text string | size int64 | token_count int64 |
|---|---|---|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "precompiled.h"
#include "ScriptEventsSystemComponent.h"
#include <AzCore/Memory/SystemAllocator.h>
#include <ScriptEvents/ScriptEventsGem.h>
#include <ScriptEvents/Components/ScriptEventReferencesComponent.h>
namespace ScriptEvents
{
ScriptEventsModule::ScriptEventsModule()
: AZ::Module()
, m_systemImpl(nullptr)
{
ScriptEventModuleConfigurationRequestBus::Handler::BusConnect();
m_descriptors.insert(m_descriptors.end(), {
ScriptEvents::ScriptEventsSystemComponent::CreateDescriptor(),
ScriptEvents::Components::ScriptEventReferencesComponent::CreateDescriptor(),
});
}
ScriptEventsSystemComponentImpl* ScriptEventsModule::GetSystemComponentImpl()
{
if (!m_systemImpl)
{
m_systemImpl = aznew ScriptEventsSystemComponentRuntimeImpl();
}
return m_systemImpl;
}
/**
* Add required SystemComponents to the SystemEntity.
*/
AZ::ComponentTypeList ScriptEventsModule::GetRequiredSystemComponents() const
{
return AZ::ComponentTypeList{
azrtti_typeid<ScriptEvents::ScriptEventsSystemComponent>(),
};
}
}
AZ_DECLARE_MODULE_CLASS(ScriptEvents_32d8ba21703e4bbbb08487366e48dd69, ScriptEvents::ScriptEventsModule)
| 1,835 | 533 |
#include "SymbolTable.hpp"
#include "foundation/ArgumentException.hpp"
namespace aapp = axis::application::parsing::preprocessing;
aapp::SymbolTable::SymbolTable(void)
{
// no op
}
aapp::SymbolTable::~SymbolTable(void)
{
// erases symbol table and call destructors of every every contained element
_table.clear();
}
void aapp::SymbolTable::AddSymbol( Symbol& symbol )
{
if (IsDefined(symbol.Name))
{
throw axis::foundation::ArgumentException();
}
_table[symbol.Name] = &symbol;
}
void aapp::SymbolTable::ClearTable( void )
{
_table.clear();
}
bool aapp::SymbolTable::IsDefined( const axis::String& name ) const
{
symbol_table::const_iterator it = _table.find(name);
return (it != _table.end());
}
const axis::String& aapp::SymbolTable::GetValue( const axis::String& name ) const
{
symbol_table::const_iterator it = _table.find(name);
if (it == _table.end())
{ // element not found
throw axis::foundation::ArgumentException();
}
return (it->second)->Value;
}
| 984 | 333 |
/*
* MIT License
*
* Copyright (c) 2017 Benjamin Zeller
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <AtlasPack/TextureAtlasPacker>
#include <AtlasPack/textureatlas_p.h>
#include <AtlasPack/JobQueue>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
namespace fs = boost::filesystem;
namespace AtlasPack {
/**
* \internal
* Represents a Node in the packing tree algorithm,
* can contain either child nodes or a image. The rect
* variable is always set.
*/
struct Node {
Node (Rect _rect = Rect())
: rect(_rect){}
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
Rect rect;
Image img;
};
class TextureAtlasPackerPrivate {
public:
Node *insertImage (const Image &img, Node *node);
bool collectNodes(TextureAtlasPrivate *atlas, std::shared_ptr<PaintDevice> painter, std::basic_ostream<char> *descStr,
Node *node, JobQueue<bool> *painterQueue, std::vector<std::future<bool> > &painterResults, std::string *err = nullptr);
Node m_root;
};
/**
* @brief TextureAtlasPrivate::insertImage
* \returns the Node the Image was inserted into, nullptr if not enough space is available
*/
Node *TextureAtlasPackerPrivate::insertImage(const Image &img, Node *node)
{
//if we have children, we are not a leaf
if (node->left || node->right) {
//first inside left:
Node *newNode = insertImage(img, node->left.get());
if (newNode)
return newNode;
//no space in left, insert right
return insertImage(img, node->right.get());
} else {
//this path is entered if we found a leaf node
//first check if the space is already filled
if (node->img.isValid())
return nullptr;
Pos nodePos = node->rect.topLeft;
Size nodeSize = node->rect.size;
//check if there is enough room
if (nodeSize.height < img.height()
|| nodeSize.width < img.width()) {
//node too small
return nullptr;
}
//check if we found a perfect fit
if (nodeSize.height == img.height()
&& nodeSize.width == img.width()) {
//perfect fit, store the image
node->img = img;
return node;
}
//At this poing the node is splitted up
//we will split in a way that we always end up with the biggest possible
//empty rectangle
size_t remainWidth = nodeSize.width - img.width();
size_t remainHeight = nodeSize.height - img.height();
if (remainWidth > remainHeight) {
node->left = std::make_shared<Node>(Rect(nodePos,
Size(img.width(), nodeSize.height)));
node->right = std::make_shared<Node>(Rect(Pos(nodePos.x+img.width(), nodePos.y),
Size(nodeSize.width - img.width(), nodeSize.height)));
} else {
node->left = std::make_shared<Node>(Rect(nodePos,
Size(nodeSize.width, img.height())));
node->right = std::make_shared<Node>(Rect(Pos(nodePos.x, nodePos.y + img.height()),
Size(nodeSize.width, nodeSize.height - img.height())));
}
//now insert into leftmost Node
return insertImage(img, node->left.get());
}
}
/**
* @internal
* @brief TextureAtlasPackerPrivate::collectNodes
* Iterates over the full tree, filling the \a atlas and painting the images using the \a painter as well as writing
* the image rectangle and filenmame into the output stream given by \a descStr.
* If a error occurs and \a err is set, a error message is put there.
*/
bool TextureAtlasPackerPrivate::collectNodes(TextureAtlasPrivate *atlas, std::shared_ptr<PaintDevice> painter,
std::basic_ostream<char> *descStr, Node *node,
JobQueue<bool> *painterQueue, std::vector<std::future<bool>> &painterResults,
std::string *err)
{
bool collected = false;
if(node->img.isValid()) {
collected = true;
// we found a Image node, lets fill the information into the given structures
Texture t(node->rect.topLeft, node->img);
atlas->m_textures[node->img.path()] = t;
// Renders the node into the atlas image, called from a async thread
auto fun = [](std::shared_ptr<PaintDevice> painter, Node *node){
// paint the texture into the cache image
if(!painter->paintImageFromFile(node->rect.topLeft, node->img.path())) {
std::cout<<"Failed to paint image "<<node->img.path();
return false;
}
return true;
};
// push the future results into a vector, so we can check if we had errors after all tasks are done
painterResults.push_back(painterQueue->addTask(std::bind(fun, painter, node)));
// the description file is written as a CSV file
// @NOTE possible room for improvement, make the description file structure modular,
// to make it easy to use another format
(*descStr) << node->img.path() <<","
<< t.pos.x<<","
<< t.pos.y<<","
<< t.image.width()<<","
<< t.image.height()<<"\n";
}
if (collected && (node->left || node->right )) {
//this should never happen, if it does at least print a warning about it
if(collected) std::cerr<<"Node has leafs AND image?"<<std::endl;
}
//recursively iterate through the child nodes, start with the left node again
if(node->left) {
if (!collectNodes(atlas, painter, descStr, node->left.get(), painterQueue, painterResults, err))
return false;
}
if(node->right){
if (!collectNodes(atlas, painter, descStr, node->right.get(), painterQueue, painterResults, err))
return false;
}
return true;
}
/**
* @class TextureAtlasPacker::TextureAtlasPacker
* Implements a packing algorithm to pack images into a bigger texture, called
* a \a AtlasPack::TextureAtlas. This can speed up image loading in applications that make use
* of a lot of small image files.
*
* This implementation makes use of the lightmap packing algorithm that can be found at http://blackpawn.com/texts/lightmaps/default.html
*/
TextureAtlasPacker::TextureAtlasPacker(Size atlasSize)
: p(new TextureAtlasPackerPrivate())
{
p->m_root.rect = Rect(Pos(0,0), atlasSize);
}
TextureAtlasPacker::~TextureAtlasPacker()
{
if (p) delete p;
}
/*!
* \brief TextureAtlasPacker::size
* Returns the current geometrical size of the texture atlas.
*/
Size TextureAtlasPacker::size() const
{
return p->m_root.rect.size;
}
/*!
* \brief TextureAtlasPacker::insertImage
* Tried to insert the \sa AtlasPack::Image given by \a img into the atlas.
* The internal algorithm will split the atlas rectangle into smaller portions
* until the image fits.
* Returns \a true on success, or \a false in case the atlas does not have enough remaining space.
*/
bool TextureAtlasPacker::insertImage(const Image &img)
{
return p->insertImage(img, &p->m_root) != nullptr;
}
/**
* \brief TextureAtlasPacker::compile
* Compiles the current in memory state of the TextureAtlas into a description and
* image file and stores them on disk. Expects \a basePath to point at a user writeable directory,
* the last part of \a basePath will be used to form the texture atlas description file and image file names.
*
* \note This can take a lot of time for a big list of images, however the implementation does run with multiple
* threads to speed the process up.
*/
TextureAtlas TextureAtlasPacker::compile(const std::string &basePath, Backend *backend, std::string *error) const
{
try {
//the basepath is used to create the filenames for the 2 output files
fs::path descFileName(basePath + ".atlas");
fs::path textureFile(basePath + ".png");
JobQueue<bool> jobs;
//check if the output directory exists
if (!fs::exists(descFileName.parent_path())
|| !fs::is_directory(descFileName.parent_path())) {
if (error)
*error = "Basepath is not a directory or does not exist";
return TextureAtlas();
}
//create atlas description text file
std::ofstream descFile(descFileName.string(), std::ios::trunc | std::ios::out);
if(!descFile.is_open()) {
if (error) {
std::stringstream s;
s << "Could not create atlas index file "<<descFileName.string()<<" "<<strerror(errno);
*error = s.str();
}
return TextureAtlas();
}
//get new painter instance from the backend
auto painter = backend->createPaintDevice(p->m_root.rect.size);
std::unique_ptr<TextureAtlasPrivate> priv = std::make_unique<TextureAtlasPrivate>();
std::vector<std::future<bool> > paintResults;
//recursively collect all nodes, write them to the desc file and give paint tasks to the
//JobQueue to run asynchronously
if(!p->collectNodes(priv.get(), painter, &descFile, &p->m_root, &jobs, paintResults, error))
return TextureAtlas();
//wait until all painters are done
jobs.waitForAllRunningTasks();
//check if we have errors in some of the painters, no need
//to print which one here, because the painters will print a error message on their
//own if required
for (std::future<bool> &res : paintResults) {
if (!res.get()) {
std::cout<<"Some images failed to paint";
return TextureAtlas();
}
}
//finally save the result to a file
if(!painter->exportToFile(textureFile.string())) {
if (error) *error = "Failed to export Texture to file";
return TextureAtlas();
}
descFile.close();
return TextureAtlas(priv.release());
} catch (const fs::filesystem_error& ex) {
std::cerr << "Filesystem error while compiling the texture atlas: "<<ex.what() << std::endl;
}
catch (const std::exception &ex) {
std::cerr << "Catched an exception when compiling the texture atlas."<<ex.what()<< std::endl;
}
catch (...) {
std::cerr << "Catched an unknown exception when compiling the texture atlas." << std::endl;
}
return TextureAtlas();
}
}
| 11,788 | 3,328 |
//$Id$
//------------------------------------------------------------------------------
// AtmosphereFactory
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2017 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number S-67573-G
//
// Author: Wendy Shoan
// Created: 2004/08/12
//
/**
* This class is the factory class for Atmospheres.
*/
//------------------------------------------------------------------------------
#ifndef AtmosphereFactory_hpp
#define AtmosphereFactory_hpp
#include "gmatdefs.hpp"
#include "Factory.hpp"
#include "AtmosphereModel.hpp"
class GMAT_API AtmosphereFactory : public Factory
{
public:
GmatBase* CreateObject(const std::string &ofType,
const std::string &withName = "");
AtmosphereModel* CreateAtmosphereModel(const std::string &ofType,
const std::string &withName = "");
// method to return list of types of objects that this factory can create
virtual StringArray GetListOfCreatableObjects(
const std::string &qualifier = "Earth");
// default constructor
AtmosphereFactory();
// constructor
AtmosphereFactory(StringArray createList);
// copy constructor
AtmosphereFactory(const AtmosphereFactory& fact);
// assignment operator
AtmosphereFactory& operator= (const AtmosphereFactory& fact);
// destructor
~AtmosphereFactory();
protected:
// protected data
private:
};
#endif // AtmosphereFactory_hpp
| 2,387 | 641 |
/*
* Copyright 2012 Open Source Robotics Foundation
*
* 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.
*
*/
/* Desc: A persepective OGRE Camera
* Author: Nate Koenig
* Date: 15 July 2003
*/
#ifndef _RENDERING_CAMERA_HH_
#define _RENDERING_CAMERA_HH_
#include <boost/enable_shared_from_this.hpp>
#include <string>
#include <utility>
#include <list>
#include <vector>
#include <deque>
#include "common/Event.hh"
#include "common/Time.hh"
#include "math/Angle.hh"
#include "math/Pose.hh"
#include "math/Plane.hh"
#include "math/Vector2i.hh"
#include "msgs/MessageTypes.hh"
#include "rendering/RenderTypes.hh"
#include "sdf/sdf.hh"
// Forward Declarations
namespace Ogre
{
class Texture;
class RenderTarget;
class Camera;
class Viewport;
class SceneNode;
class AnimationState;
class CompositorInstance;
}
namespace gazebo
{
/// \ingroup gazebo_rendering
/// \brief Rendering namespace
namespace rendering
{
class MouseEvent;
class ViewController;
class Scene;
class GaussianNoiseCompositorListener;
/// \addtogroup gazebo_rendering Rendering
/// \brief A set of rendering related class, functions, and definitions
/// \{
/// \class Camera Camera.hh rendering/rendering.hh
/// \brief Basic camera sensor
///
/// This is the base class for all cameras.
class Camera : public boost::enable_shared_from_this<Camera>
{
/// \brief Constructor
/// \param[in] _namePrefix Unique prefix name for the camera.
/// \param[in] _scene Scene that will contain the camera
/// \param[in] _autoRender Almost everyone should leave this as true.
public: Camera(const std::string &_namePrefix, ScenePtr _scene,
bool _autoRender = true);
/// \brief Destructor
public: virtual ~Camera();
/// \brief Load the camera with a set of parmeters
/// \param[in] _sdf The SDF camera info
public: virtual void Load(sdf::ElementPtr _sdf);
/// \brief Load the camera with default parmeters
public: virtual void Load();
/// \brief Initialize the camera
public: virtual void Init();
/// \brief Set the render Hz rate
/// \param[in] _hz The Hz rate
public: void SetRenderRate(double _hz);
/// \brief Get the render Hz rate
/// \return The Hz rate
public: double GetRenderRate() const;
/// \brief Render the camera
///
/// Called after the pre-render signal. This function will generate
/// camera images
public: void Render();
/// \brief Post render
///
/// Called afer the render signal.
public: virtual void PostRender();
/// \internal
/// \brief Update the camera information. This does not render images.
///
/// This function gets called automatically. There is no need for the
/// average user to call this function.
public: virtual void Update();
/// \brief Finalize the camera.
///
/// This function is called before the camera is destructed
public: virtual void Fini();
/// Deprecated.
/// \sa GetInitialized
public: inline bool IsInitialized() const GAZEBO_DEPRECATED(1.5);
/// \brief Return true if the camera has been initialized
/// \return True if initialized was successful
public: bool GetInitialized() const;
/// \internal
/// \brief Set the ID of the window this camera is rendering into.
/// \param[in] _windowId The window id of the camera.
public: void SetWindowId(unsigned int _windowId);
/// \brief Get the ID of the window this camera is rendering into.
/// \return The ID of the window.
public: unsigned int GetWindowId() const;
/// \brief Set the scene this camera is viewing
/// \param[in] _scene Pointer to the scene
public: void SetScene(ScenePtr _scene);
/// \brief Get the global pose of the camera
/// \return Pose of the camera in the world coordinate frame
public: math::Pose GetWorldPose();
/// \brief Get the camera position in the world
/// \return The world position of the camera
public: math::Vector3 GetWorldPosition() const;
/// \brief Get the camera's orientation in the world
/// \return The camera's orientation as a math::Quaternion
public: math::Quaternion GetWorldRotation() const;
/// \brief Set the global pose of the camera
/// \param[in] _pose The new math::Pose of the camera
public: virtual void SetWorldPose(const math::Pose &_pose);
/// \brief Set the world position
/// \param[in] _pos The new position of the camera
public: void SetWorldPosition(const math::Vector3 &_pos);
/// \brief Set the world orientation
/// \param[in] _quat The new orientation of the camera
public: void SetWorldRotation(const math::Quaternion &_quat);
/// \brief Translate the camera
/// \param[in] _direction The translation vector
public: void Translate(const math::Vector3 &_direction);
/// \brief Rotate the camera around the yaw axis
/// \param[in] _angle Rotation amount
public: void RotateYaw(math::Angle _angle);
/// \brief Rotate the camera around the pitch axis
/// \param[in] _angle Pitch amount
public: void RotatePitch(math::Angle _angle);
/// \brief Set the clip distances
/// \param[in] _near Near clip distance in meters
/// \param[in] _far Far clip distance in meters
public: void SetClipDist(float _near, float _far);
/// \brief Set the camera FOV (horizontal)
/// \param[in] _radians Horizontal field of view
public: void SetHFOV(math::Angle _angle);
/// \brief Get the camera FOV (horizontal)
/// \return The horizontal field of view
public: math::Angle GetHFOV() const;
/// \brief Get the camera FOV (vertical)
/// \return The vertical field of view
public: math::Angle GetVFOV() const;
/// \brief Set the image size
/// \param[in] _w Image width
/// \param[in] _h Image height
public: void SetImageSize(unsigned int _w, unsigned int _h);
/// \brief Set the image height
/// \param[in] _w Image width
public: void SetImageWidth(unsigned int _w);
/// \brief Set the image height
/// \param[in] _h Image height
public: void SetImageHeight(unsigned int _h);
/// \brief Get the width of the image
/// \return Image width
public: virtual unsigned int GetImageWidth() const;
/// \brief Get the width of the off-screen render texture
/// \return Render texture width
public: unsigned int GetTextureWidth() const;
/// \brief Get the height of the image
/// \return Image height
public: virtual unsigned int GetImageHeight() const;
/// \brief Get the depth of the image
/// \return Depth of the image
public: unsigned int GetImageDepth() const;
/// \brief Get the string representation of the image format.
/// \return String representation of the image format.
public: std::string GetImageFormat() const;
/// \brief Get the height of the off-screen render texture
/// \return Render texture height
public: unsigned int GetTextureHeight() const;
/// \brief Get the image size in bytes
/// \return Size in bytes
public: size_t GetImageByteSize() const;
/// \brief Calculate image byte size base on a few parameters.
/// \param[in] _width Width of an image
/// \param[in] _height Height of an image
/// \param[in] _format Image format
/// \return Size of an image based on the parameters
public: static size_t GetImageByteSize(unsigned int _width,
unsigned int _height,
const std::string &_format);
/// \brief Get the Z-buffer value at the given image coordinate.
/// \param[in] _x Image coordinate; (0, 0) specifies the top-left corner.
/// \param[in] _y Image coordinate; (0, 0) specifies the top-left corner.
/// \returns Image z value; note that this is abitrarily scaled and
/// is @e not the same as the depth value.
public: double GetZValue(int _x, int _y);
/// \brief Get the near clip distance
/// \return Near clip distance
public: double GetNearClip();
/// \brief Get the far clip distance
/// \return Far clip distance
public: double GetFarClip();
/// \brief Enable or disable saving
/// \param[in] _enable Set to True to enable saving of frames
public: void EnableSaveFrame(bool _enable);
/// \brief Set the save frame pathname
/// \param[in] _pathname Directory in which to store saved image frames
public: void SetSaveFramePathname(const std::string &_pathname);
/// \brief Save the last frame to disk
/// \param[in] _filename File in which to save a single frame
/// \return True if saving was successful
public: bool SaveFrame(const std::string &_filename);
/// \brief Get a pointer to the ogre camera
/// \return Pointer to the OGRE camera
public: Ogre::Camera *GetOgreCamera() const;
/// \brief Get a pointer to the Ogre::Viewport
/// \return Pointer to the Ogre::Viewport
public: Ogre::Viewport *GetViewport() const;
/// \brief Get the viewport width in pixels
/// \return The viewport width
public: unsigned int GetViewportWidth() const;
/// \brief Get the viewport height in pixels
/// \return The viewport height
public: unsigned int GetViewportHeight() const;
/// \brief Get the viewport up vector
/// \return The viewport up vector
public: math::Vector3 GetUp();
/// \brief Get the viewport right vector
/// \return The viewport right vector
public: math::Vector3 GetRight();
/// \brief Get the average FPS
/// \return The average frames per second
public: virtual float GetAvgFPS() {return 0;}
/// \brief Get the triangle count
/// \return The current triangle count
public: virtual unsigned int GetTriangleCount() {return 0;}
/// \brief Set the aspect ratio
/// \param[in] _ratio The aspect ratio (width / height) in pixels
public: void SetAspectRatio(float _ratio);
/// \brief Get the apect ratio
/// \return The aspect ratio (width / height) in pixels
public: float GetAspectRatio() const;
/// \brief Set the camera's scene node
/// \param[in] _node The scene nodes to attach the camera to
public: void SetSceneNode(Ogre::SceneNode *_node);
/// \brief Get the camera's scene node
/// \return The scene node the camera is attached to
public: Ogre::SceneNode *GetSceneNode() const;
/// \brief Get the camera's pitch scene node
/// \return The pitch node the camera is attached to
public: Ogre::SceneNode *GetPitchNode() const;
/// \brief Get a pointer to the image data
///
/// Get the raw image data from a camera's buffer.
/// \param[in] _i Index of the camera's texture (0 = RGB, 1 = depth).
/// \return Pointer to the raw data, null if data is not available.
public: virtual const unsigned char *GetImageData(unsigned int i = 0);
/// \brief Get the camera's name
/// \return The name of the camera
public: std::string GetName() const;
/// \brief Set the camera's name
/// \param[in] _name New name for the camera
public: void SetName(const std::string &_name);
/// \brief Toggle whether to view the world in wireframe
public: void ToggleShowWireframe();
/// \brief Set whether to view the world in wireframe
/// \param[in] _s Set to True to render objects as wireframe
public: void ShowWireframe(bool _s);
/// \brief Get a world space ray as cast from the camera
/// through the viewport
/// \param[in] _screenx X coordinate in the camera's viewport, in pixels.
/// \param[in] _screeny Y coordinate in the camera's viewport, in pixels.
/// \param[out] _origin Origin in the world coordinate frame of the
/// resulting ray
/// \param[out] _dir Direction of the resulting ray
public: void GetCameraToViewportRay(int _screenx, int _screeny,
math::Vector3 &_origin,
math::Vector3 &_dir);
/// \brief Set whether to capture data
/// \param[in] _value Set to true to capture data into a memory buffer.
public: void SetCaptureData(bool _value);
/// \brief Capture data once and save to disk
public: void SetCaptureDataOnce();
/// \brief Set the render target
/// \param[in] _textureName Name of the new render texture
public: void CreateRenderTexture(const std::string &_textureName);
/// \brief Get the scene this camera is in
/// \return Pointer to scene containing this camera
public: ScenePtr GetScene() const;
/// \brief Get point on a plane
/// \param[in] _x X cooridnate in camera's viewport, in pixels
/// \param[in] _y Y cooridnate in camera's viewport, in pixels
/// \param[in] _plane Plane on which to find the intersecting point
/// \param[out] _result Point on the plane
/// \return True if a valid point was found
public: bool GetWorldPointOnPlane(int _x, int _y,
const math::Plane &_plane, math::Vector3 &_result);
/// \brief Set the camera's render target
/// \param[in] _target Pointer to the render target
public: virtual void SetRenderTarget(Ogre::RenderTarget *_target);
/// \brief Attach the camera to a scene node
/// \param[in] _visualName Name of the visual to attach the camera to
/// \param[in] _inheritOrientation True means camera acquires the visual's
/// orientation
/// \param[in] _minDist Minimum distance the camera is allowed to get to
/// the visual
/// \param[in] _maxDist Maximum distance the camera is allowd to get from
/// the visual
public: void AttachToVisual(const std::string &_visualName,
bool _inheritOrientation,
double _minDist = 0.0, double _maxDist = 0.0);
/// \brief Set the camera to track a scene node
/// \param[in] _visualName Name of the visual to track
public: void TrackVisual(const std::string &_visualName);
/// \brief Get the render texture
/// \return Pointer to the render texture
public: Ogre::Texture *GetRenderTexture() const;
/// \brief Get the camera's direction vector
/// \return Direction the camera is facing
public: math::Vector3 GetDirection() const;
/// \brief Connect to the new image signal
/// \param[in] _subscriber Callback that is called when a new image is
/// generated
/// \return A pointer to the connection. This must be kept in scope.
public: template<typename T>
event::ConnectionPtr ConnectNewImageFrame(T _subscriber)
{return newImageFrame.Connect(_subscriber);}
/// \brief Disconnect from an image frame
/// \param[in] _c The connection to disconnect
public: void DisconnectNewImageFrame(event::ConnectionPtr &_c)
{newImageFrame.Disconnect(_c);}
/// \brief Save a frame using an image buffer
/// \param[in] _image The raw image buffer
/// \param[in] _width Width of the image
/// \param[in] _height Height of the image
/// \param[in] _depth Depth of the image data
/// \param[in] _format Format the image data is in
/// \param[in] _filename Name of the file in which to write the frame
/// \return True if saving was successful
public: static bool SaveFrame(const unsigned char *_image,
unsigned int _width, unsigned int _height, int _depth,
const std::string &_format,
const std::string &_filename);
/// \brief Get the last time the camera was rendered
/// \return Time the camera was last rendered
public: common::Time GetLastRenderWallTime();
/// \brief Return true if the visual is within the camera's view
/// frustum
/// \param[in] _visual The visual to check for visibility
/// \return True if the _visual is in the camera's frustum
public: bool IsVisible(VisualPtr _visual);
/// \brief Return true if the visual is within the camera's view
/// frustum
/// \param[in] _visualName Name of the visual to check for visibility
/// \return True if the _visual is in the camera's frustum
public: bool IsVisible(const std::string &_visualName);
/// \brief Return true if the camera is moving due to an animation.
public: bool IsAnimating() const;
/// \brief Move the camera to a position (this is an animated motion).
/// \sa Camera::MoveToPositions
/// \param[in] _pose End position of the camera
/// \param[in] _time Duration of the camera's movement
public: virtual bool MoveToPosition(const math::Pose &_pose,
double _time);
/// \brief Move the camera to a series of poses (this is an
/// animated motion).
/// \sa Camera::MoveToPosition
/// \param[in] _pts Vector of poses to move to
/// \param[in] _time Duration of the entire move
/// \param[in] _onComplete Callback that is called when the move is
/// complete
public: bool MoveToPositions(const std::vector<math::Pose> &_pts,
double _time,
boost::function<void()> _onComplete = NULL);
/// \brief Get the path to saved screenshots.
/// \return Path to saved screenshots.
public: std::string GetScreenshotPath() const;
/// \brief Implementation of the render call
protected: virtual void RenderImpl();
/// \brief Implementation of the Camera::TrackVisual call
/// \param[in] _visualName Name of the visual to track
/// \return True if able to track the visual
protected: bool TrackVisualImpl(const std::string &_visualName);
/// \brief Set the camera to track a scene node
/// \param[in] _visual The visual to track
/// \return True if able to track the visual
protected: virtual bool TrackVisualImpl(VisualPtr _visual);
/// \brief Attach the camera to a scene node
/// \param[in] _visualName Name of the visual to attach the camera to
/// \param[in] _inheritOrientation True means camera acquires the visual's
/// orientation
/// \param[in] _minDist Minimum distance the camera is allowed to get to
/// the visual
/// \param[in] _maxDist Maximum distance the camera is allowd to get from
/// the visual
/// \return True on success
protected: virtual bool AttachToVisualImpl(const std::string &_name,
bool _inheritOrientation,
double _minDist = 0, double _maxDist = 0);
/// \brief Attach the camera to a visual
/// \param[in] _visual The visual to attach the camera to
/// \param[in] _inheritOrientation True means camera acquires the visual's
/// orientation
/// \param[in] _minDist Minimum distance the camera is allowed to get to
/// the visual
/// \param[in] _maxDist Maximum distance the camera is allowd to get from
/// the visual
/// \return True on success
protected: virtual bool AttachToVisualImpl(VisualPtr _visual,
bool _inheritOrientation,
double _minDist = 0, double _maxDist = 0);
/// \brief Get the next frame filename based on SDF parameters
/// \return The frame's filename
protected: std::string GetFrameFilename();
/// \brief Internal function used to indicate that an animation has
/// completed.
protected: virtual void AnimationComplete();
/// \brief if user requests bayer image, post process rgb from ogre
/// to generate bayer formats
/// \param[in] _dst Destination buffer for the image data
/// \param[in] _src Source image buffer
/// \param[in] _format Format of the source buffer
/// \param[in] _width Image width
/// \param[in] _height Image height
private: void ConvertRGBToBAYER(unsigned char *_dst, unsigned char *_src,
std::string _format, int _width, int _height);
/// \brief Set the clip distance based on stored SDF values
private: void SetClipDist();
/// \brief Get the OGRE image pixel format in
/// \param[in] _format The Gazebo image format
/// \return Integer representation of the Ogre image format
private: static int GetOgrePixelFormat(const std::string &_format);
/// \brief Create the ogre camera.
private: void CreateCamera();
/// \brief Name of the camera.
protected: std::string name;
/// \brief Camera's SDF values.
protected: sdf::ElementPtr sdf;
/// \brief ID of the window that the camera is attached to.
protected: unsigned int windowId;
/// \brief Width of the render texture.
protected: unsigned int textureWidth;
/// \brief Height of the render texture.
protected: unsigned int textureHeight;
/// \brief The OGRE camera
protected: Ogre::Camera *camera;
/// \brief Viewport the ogre camera uses.
protected: Ogre::Viewport *viewport;
/// \brief Scene node that controls camera position.
protected: Ogre::SceneNode *sceneNode;
/// \brief Scene nod that controls camera pitch.
protected: Ogre::SceneNode *pitchNode;
// \brief Buffer for a single image frame.
protected: unsigned char *saveFrameBuffer;
/// \brief Buffer for a bayer image frame.
protected: unsigned char *bayerFrameBuffer;
/// \brief Number of saved frames.
protected: unsigned int saveCount;
/// \brief Path to saved screenshots.
protected: std::string screenshotPath;
/// \brief Format for saving images.
protected: int imageFormat;
/// \brief Save image width.
protected: int imageWidth;
/// \brief Save image height.
protected: int imageHeight;
/// \brief Target that renders frames.
protected: Ogre::RenderTarget *renderTarget;
/// \brief Texture that receives results from rendering.
protected: Ogre::Texture *renderTexture;
/// \brief True to capture frames into an image buffer.
protected: bool captureData;
/// \brief True to capture a frame once and save to disk.
protected: bool captureDataOnce;
/// \brief True if new data is available.
protected: bool newData;
/// \brief Time the last frame was rendered.
protected: common::Time lastRenderWallTime;
/// \brief Pointer to the scene.
protected: ScenePtr scene;
/// \brief Event triggered when a new frame is generated.
protected: event::EventT<void(const unsigned char *,
unsigned int, unsigned int, unsigned int,
const std::string &)> newImageFrame;
/// \brief The camera's event connections.
protected: std::vector<event::ConnectionPtr> connections;
/// \brief List of requests.
protected: std::list<msgs::Request> requests;
/// \brief True if initialized.
protected: bool initialized;
/// \brief Animation state, used to animate the camera.
protected: Ogre::AnimationState *animState;
/// \brief Previous time the camera animation was updated.
protected: common::Time prevAnimTime;
/// \brief User callback for when an animation completes.
protected: boost::function<void()> onAnimationComplete;
/// \brief Pointer to image SDF element.
private: sdf::ElementPtr imageElem;
/// \brief Visual that the camera is tracking.
private: VisualPtr trackedVisual;
/// \brief Counter used to create unique camera names.
private: static unsigned int cameraCounter;
/// \brief Deferred shading geometry buffer.
private: Ogre::CompositorInstance *dsGBufferInstance;
/// \brief Deferred shading merge compositor.
private: Ogre::CompositorInstance *dsMergeInstance;
/// \brief Deferred lighting geometry buffer.
private: Ogre::CompositorInstance *dlGBufferInstance;
/// \brief Deferred lighting merge compositor.
private: Ogre::CompositorInstance *dlMergeInstance;
/// \brief Screen space ambient occlusion compositor.
private: Ogre::CompositorInstance *ssaoInstance;
/// \brief Gaussian noise compositor
private: Ogre::CompositorInstance *gaussianNoiseInstance;
/// \brief Gaussian noise compositor listener
private: boost::shared_ptr<GaussianNoiseCompositorListener>
gaussianNoiseCompositorListener;
/// \brief Queue of move positions.
private: std::deque<std::pair<math::Pose, double> > moveToPositionQueue;
/// \brief Render period.
private: common::Time renderPeriod;
/// \brief Which noise type we support
private: enum NoiseModelType
{
NONE,
GAUSSIAN
};
/// \brief If true, apply the noise model specified by other
/// noise parameters
private: bool noiseActive;
/// \brief Which type of noise we're applying
private: enum NoiseModelType noiseType;
/// \brief If noiseType==GAUSSIAN, noiseMean is the mean of the
/// distibution from which we sample
private: double noiseMean;
/// \brief If noiseType==GAUSSIAN, noiseStdDev is the standard
/// devation of the distibution from which we sample
private: double noiseStdDev;
};
/// \}
}
}
#endif
| 26,612 | 7,277 |
// RUN: %clang_cc1 -fsyntax-only -verify -Wno-c++11-extensions %s
struct errc {
int v_;
operator int() const {return v_;}
};
class error_condition
{
int _val_;
public:
error_condition() : _val_(0) {}
error_condition(int _val)
: _val_(_val) {}
template <class E>
error_condition(E _e) {
// make_error_condition must not be typo corrected to error_condition
// even though the first declaration of make_error_condition has not
// yet been encountered. This was a bug in the first version of the type
// name typo correction patch that wasn't noticed until building LLVM with
// Clang failed.
*this = make_error_condition(_e);
}
};
inline error_condition make_error_condition(errc _e) {
return error_condition(static_cast<int>(_e));
}
// Prior to the introduction of a callback object to further filter possible
// typo corrections, this example would not trigger a suggestion as "base_type"
// is a closer match to "basetype" than is "BaseType" but "base_type" does not
// refer to a base class or non-static data member.
struct BaseType { };
struct Derived : public BaseType { // expected-note {{base class 'BaseType' specified here}}
static int base_type; // expected-note {{'base_type' declared here}}
Derived() : basetype() {} // expected-error{{initializer 'basetype' does not name a non-static data member or base class; did you mean the base class 'BaseType'?}}
};
// Test the improvement from passing a callback object to CorrectTypo in
// the helper function LookupMemberExprInRecord.
int get_type(struct Derived *st) {
return st->Base_Type; // expected-error{{no member named 'Base_Type' in 'Derived'; did you mean 'base_type'?}}
}
// In this example, somename should not be corrected to the cached correction
// "some_name" since "some_name" is a class and a namespace name is needed.
class some_name {}; // expected-note {{'some_name' declared here}}
somename Foo; // expected-error {{unknown type name 'somename'; did you mean 'some_name'?}}
namespace SomeName {} // expected-note {{namespace 'SomeName' defined here}}
using namespace somename; // expected-error {{no namespace named 'somename'; did you mean 'SomeName'?}}
// Without the callback object, CorrectTypo would choose "field1" as the
// correction for "fielda" as it is closer than "FieldA", but that correction
// would be later discarded by the caller and no suggestion would be given.
struct st {
struct {
int field1;
};
double FieldA; // expected-note{{'FieldA' declared here}}
};
st var = { .fielda = 0.0 }; // expected-error{{field designator 'fielda' does not refer to any field in type 'st'; did you mean 'FieldA'?}}
// Test the improvement from passing a callback object to CorrectTypo in
// Sema::BuildCXXNestedNameSpecifier. And also for the improvement by doing
// so in Sema::getTypeName.
typedef char* another_str; // expected-note{{'another_str' declared here}}
namespace AnotherStd { // expected-note{{'AnotherStd' declared here}}
class string {};
}
another_std::string str; // expected-error{{use of undeclared identifier 'another_std'; did you mean 'AnotherStd'?}}
another_str *cstr = new AnotherStr; // expected-error{{unknown type name 'AnotherStr'; did you mean 'another_str'?}}
// Test the improvement from passing a callback object to CorrectTypo in
// Sema::ActOnSizeofParameterPackExpr.
char* TireNames;
template<typename ...TypeNames> struct count { // expected-note{{parameter pack 'TypeNames' declared here}}
static const unsigned value = sizeof...(TyreNames); // expected-error{{'TyreNames' does not refer to the name of a parameter pack; did you mean 'TypeNames'?}}
};
// Test the typo-correction callback in Sema::DiagnoseUnknownTypeName.
namespace unknown_type_test {
class StreamOut {}; // expected-note 2 {{'StreamOut' declared here}}
long stream_count; // expected-note 2 {{'stream_count' declared here}}
};
unknown_type_test::stream_out out; // expected-error{{no type named 'stream_out' in namespace 'unknown_type_test'; did you mean 'StreamOut'?}}
// Demonstrate a case where using only the cached value returns the wrong thing
// when the cached value was the result of a previous callback object that only
// accepts a subset of the current callback object.
namespace {
using namespace unknown_type_test;
void bar(long i);
void before_caching_classname() {
bar((stream_out)); // expected-error{{use of undeclared identifier 'stream_out'; did you mean 'stream_count'?}}
}
stream_out out; // expected-error{{unknown type name 'stream_out'; did you mean 'StreamOut'?}}
void after_caching_classname() {
bar((stream_out)); // expected-error{{use of undeclared identifier 'stream_out'; did you mean 'stream_count'?}}
}
}
// Test the typo-correction callback in Sema::DiagnoseInvalidRedeclaration.
struct BaseDecl {
void add_in(int i);
};
struct TestRedecl : public BaseDecl {
void add_it(int i); // expected-note{{'add_it' declared here}}
};
void TestRedecl::add_in(int i) {} // expected-error{{out-of-line definition of 'add_in' does not match any declaration in 'TestRedecl'; did you mean 'add_it'?}}
// Test the improved typo correction for the Parser::ParseCastExpr =>
// Sema::ActOnIdExpression => Sema::DiagnoseEmptyLookup call path.
class SomeNetMessage;
class Message {};
void foo(Message&);
void foo(SomeNetMessage&);
void doit(void *data) {
Message somenetmsg; // expected-note{{'somenetmsg' declared here}}
foo(somenetmessage); // expected-error{{use of undeclared identifier 'somenetmessage'; did you mean 'somenetmsg'?}}
foo((somenetmessage)data); // expected-error{{use of undeclared identifier 'somenetmessage'; did you mean 'SomeNetMessage'?}}
}
// Test the typo-correction callback in BuildRecoveryCallExpr.
// Solves the main issue in PR 9320 of suggesting corrections that take the
// wrong number of arguments.
void revoke(const char*); // expected-note 2{{'revoke' declared here}}
void Test() {
Invoke(); // expected-error{{use of undeclared identifier 'Invoke'}}
Invoke("foo"); // expected-error{{use of undeclared identifier 'Invoke'; did you mean 'revoke'?}}
Invoke("foo", "bar"); // expected-error{{use of undeclared identifier 'Invoke'}}
}
void Test2(void (*invoke)(const char *, int)) { // expected-note{{'invoke' declared here}}
Invoke(); // expected-error{{use of undeclared identifier 'Invoke'}}
Invoke("foo"); // expected-error{{use of undeclared identifier 'Invoke'; did you mean 'revoke'?}}
Invoke("foo", 7); // expected-error{{use of undeclared identifier 'Invoke'; did you mean 'invoke'?}}
Invoke("foo", 7, 22); // expected-error{{use of undeclared identifier 'Invoke'}}
}
void provoke(const char *x, bool y=false) {} // expected-note 2{{'provoke' declared here}}
void Test3() {
Provoke(); // expected-error{{use of undeclared identifier 'Provoke'}}
Provoke("foo"); // expected-error{{use of undeclared identifier 'Provoke'; did you mean 'provoke'?}}
Provoke("foo", true); // expected-error{{use of undeclared identifier 'Provoke'; did you mean 'provoke'?}}
Provoke("foo", 7, 22); // expected-error{{use of undeclared identifier 'Provoke'}}
}
// PR 11737 - Don't try to typo-correct the implicit 'begin' and 'end' in a
// C++11 for-range statement.
struct R {};
bool begun(R);
void RangeTest() {
for (auto b : R()) {} // expected-error {{use of undeclared identifier 'begin'}} expected-note {{range has type}}
}
// PR 12019 - Avoid infinite mutual recursion in DiagnoseInvalidRedeclaration
// by not trying to typo-correct a method redeclaration to declarations not
// in the current record.
class Parent {
void set_types(int index, int value);
void add_types(int value);
};
class Child: public Parent {};
void Child::add_types(int value) {} // expected-error{{out-of-line definition of 'add_types' does not match any declaration in 'Child'}}
// Fix the callback based filtering of typo corrections within
// Sema::ActOnIdExpression by Parser::ParseCastExpression to allow type names as
// potential corrections for template arguments.
namespace clash {
class ConstructExpr {}; // expected-note{{'clash::ConstructExpr' declared here}}
}
class ClashTool {
bool HaveConstructExpr();
template <class T> T* getExprAs();
void test() {
ConstructExpr *expr = // expected-error{{unknown type name 'ConstructExpr'; did you mean 'clash::ConstructExpr'?}}
getExprAs<ConstructExpr>(); // expected-error{{use of undeclared identifier 'ConstructExpr'; did you mean 'clash::ConstructExpr'?}}
}
};
namespace test1 {
struct S {
struct Foobar *f; // expected-note{{'Foobar' declared here}}
};
test1::FooBar *b; // expected-error{{no type named 'FooBar' in namespace 'test1'; did you mean 'Foobar'?}}
}
| 8,693 | 2,608 |
#include <iostream>
#include <string>
int main() {
std::string str;
std::cin >> str;
for (std::string::size_type n = 0;n < str.size(); ++n) {
str[n] = 'X';
}
std::cout << str << std::endl;
return 0;
}
| 220 | 95 |
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/xpu/yolo_box_compute.h"
#include <vector>
#include "lite/backends/xpu/xpu_header_sitter.h"
#include "lite/core/op_registry.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace xpu {
void YoloBoxCompute::Run() {
auto& param = this->Param<param_t>();
auto& ctx = this->ctx_->As<XPUContext>();
auto input_dims = param.X->dims();
std::vector<int> anchors = param.anchors;
CHECK_LE(anchors.size(), 6UL);
const int n = input_dims[0];
const int h = input_dims[2];
const int w = input_dims[3];
const int box_num = param.Boxes->dims()[1];
const int an_num = anchors.size() / 2;
int downsample_ratio = param.downsample_ratio;
int class_num = param.class_num;
float scale_x_y = param.scale_x_y;
float bias = -0.5 * (scale_x_y - 1.);
CHECK_EQ(box_num, an_num * h * w);
int r = xdnn::yolo_box<float>(ctx.GetRawContext(),
param.X->data<float>(),
param.ImgSize->data<int>(),
param.Boxes->mutable_data<float>(TARGET(kXPU)),
param.Scores->mutable_data<float>(TARGET(kXPU)),
n,
h,
w,
anchors,
an_num,
class_num,
param.conf_thresh,
downsample_ratio,
scale_x_y,
bias,
false);
CHECK_EQ(r, 0);
}
} // namespace xpu
} // namespace kernels
} // namespace lite
} // namespace paddle
REGISTER_LITE_KERNEL(yolo_box,
kXPU,
kFloat,
kNCHW,
paddle::lite::kernels::xpu::YoloBoxCompute,
def)
.BindInput("X", {LiteType::GetTensorTy(TARGET(kXPU))})
.BindInput("ImgSize",
{LiteType::GetTensorTy(TARGET(kXPU), PRECISION(kInt32))})
.BindOutput("Boxes", {LiteType::GetTensorTy(TARGET(kXPU))})
.BindOutput("Scores", {LiteType::GetTensorTy(TARGET(kXPU))})
.Finalize();
| 2,854 | 924 |
/**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef imgproc_texturing_hpp_included_
#define imgproc_texturing_hpp_included_
#include <vector>
#include "math/geometry_core.hpp"
namespace imgproc { namespace tx {
/** Uv patch.
*/
struct UvPatch : math::Extents2 {
UvPatch() : math::Extents2(math::InvalidExtents{}) {}
UvPatch(const math::Extents2 &e) : math::Extents2(e) {}
void inflate(double size);
void update(const UvPatch &other);
void update(double x, double y);
template <typename T> void update(const math::Point2_<T> &point);
typedef std::vector<UvPatch> list;
};
UvPatch inflate(const UvPatch &uvPatch, double size);
/** Texture patch. Maps source region to destination region.
*/
class Patch {
public:
struct InplaceTag {};
static InplaceTag Inplace;
typedef std::vector<Patch*> list;
/** Construct default, unusable patch.
*/
Patch() = default;
/** Creates patch for given texturing coordinates bounds.
*
* \param uvPatch source UV patch
*/
Patch(const UvPatch &uvPatch);
/** Manual patch creation.
*/
Patch(int x, int y, int width, int height);
/** Places patch at given location.
*/
void place(const math::Point2i &location);
/** Maps source texturing coordinates to destination texturing coordinates.
*/
math::Point2d map(const math::Point2d &uv) const;
/** Maps source texturing coordinates to destination texturing coordinates.
*
* In place version.
*/
void map(const InplaceTag&, math::Point2d &uv) const;
/** Maps source texturing coordinates to destination texturing coordinates.
* Modifies arguments in place.
*/
template <typename T>
void map(T &x, T &y) const;
math::Point2d imap(const math::Point2d &uv) const;
/** Maps destination texturing coordinates to source texturing coordinates.
*
* In place version.
*/
void imap(const InplaceTag&, math::Point2d &uv) const;
/** Maps destination texturing coordinates to source texturing coordinates.
* Modifies arguments in place.
*/
template <typename T>
void imap(T &x, T &y) const;
/** Whole pixel rectangle circumscribed around subpixel patch.
*/
struct Rect {
math::Point2i point;
math::Size2i size;
Rect() = default;
Rect(const Rect&) = default;
Rect(const UvPatch &uvPatch);
/** Manual rectangle creation.
*/
Rect(int x, int y, int width, int height);
typedef std::vector<Rect> list;
};
const Rect& src() const { return src_; }
const Rect& dst() const { return dst_; }
const math::Size2& size() const { return src_.size; }
int width() const { return src_.size.width; }
int height() const { return src_.size.height; }
/** Clips source rectangle to given limits and updates destination one
* accordingly.
*/
Patch& srcClip(const math::Size2 &limits);
/** Clips source rectangle to given limits and updates destination one
* accordingly.
*/
Patch& srcClip(int width, int height);
/** Returns patch for source rectangle clipped to given limits.
*/
Patch srcClipped(const math::Size2 &limits) const;
/** Returns patch for source rectangle clipped to given limits.
*/
Patch srcClipped(int width, int height) const;
private:
/** Source rectangle.
*/
Rect src_;
/** Destination rectangle.
*/
Rect dst_;
/** Mapping between source and destination texturing coordinates.
*/
math::Point2 shift_;
};
/** Packs texture patches.
* Returns size of resulting texture.
*/
math::Size2 pack(Patch::list &patches);
/** Packs texture patches.
* Returns size of resulting texture.
*
* Const vector interface.
*/
math::Size2 pack(const Patch::list &patches);
/** Generate container.
* Function Patch* asPatch(*iterator) must exist.
*/
template <typename Iterator>
math::Size2 pack(Iterator begin, Iterator end);
/** Default implementaion of asPatch for, well, patch itself.
*/
Patch* asPatch(Patch &patch);
// inlines
/**
* To cover all source pixels for bilinear interpolation we have to have all 4
* pixels aroud extreme patch edges, therefore we have to fix the extens as
* follows:
*
* ll' = floor(ll - half pixel)
* ur' = ceil(ur + half pixel)
*
* +1 is to get count of pixels between ll' (inclusive) and ur' (inclusive).
*/
inline Patch::Rect::Rect(const UvPatch &uvPatch)
: point(int(std::floor(uvPatch.ll(0) - 0.5))
, int(std::floor(uvPatch.ll(1) - 0.5)))
, size(int(std::ceil(uvPatch.ur(0) + 0.5) - point(0) + 1)
, int(std::ceil(uvPatch.ur(1) + 0.5) - point(1) + 1))
{}
inline Patch::Rect::Rect(int x, int y, int width, int height)
: point(x, y), size(width, height)
{}
inline Patch::Patch(const UvPatch &uvPatch)
: src_(uvPatch), dst_(src_)
{}
inline Patch::Patch(int x, int y, int width, int height)
: src_(x, y, width, height), dst_(src_)
{}
inline void Patch::place(const math::Point2i &location)
{
dst_.point = location;
shift_(0) = dst_.point(0) - src_.point(0);
shift_(1) = dst_.point(1) - src_.point(1);
}
inline math::Point2d Patch::map(const math::Point2d &uv) const
{
return { uv(0) + shift_(0), uv(1) + shift_(1) };
}
inline void Patch::map(const InplaceTag&, math::Point2d &uv) const
{
uv(0) += shift_(0);
uv(1) += shift_(1);
}
template <typename T>
void Patch::map(T &x, T &y) const
{
x += shift_(0);
y += shift_(1);
}
inline math::Point2d Patch::imap(const math::Point2d &uv) const
{
return { uv(0) - shift_(0), uv(1) - shift_(1) };
}
inline void Patch::imap(const InplaceTag&, math::Point2d &uv) const
{
uv(0) -= shift_(0);
uv(1) -= shift_(1);
}
template <typename T>
void Patch::imap(T &x, T &y) const
{
x -= shift_(0);
y -= shift_(1);
}
inline void UvPatch::inflate(double size)
{
auto &self(static_cast<math::Extents2&>(*this));
self = self + size;
}
inline UvPatch inflate(const UvPatch &uvPatch, double size)
{
return static_cast<const math::Extents2&>(uvPatch) + size;
}
inline void UvPatch::update(double x, double y)
{
math::update(*this, double(x), double(y));
}
inline void UvPatch::update(const UvPatch &other)
{
math::update(*this, other.ll);
math::update(*this, other.ur);
}
template <typename T> void UvPatch::update(const math::Point2_<T> &point)
{
update(point(0), point(1));
}
inline math::Size2 pack(const Patch::list &patches) {
auto copy(patches);
return pack(copy);
}
template <typename Iterator>
math::Size2 pack(Iterator begin, Iterator end)
{
Patch::list patches;
for (; begin != end; ++begin) {
patches.push_back(asPatch(*begin));
}
return pack(patches);
}
inline Patch* asPatch(Patch &patch) { return &patch; }
inline Patch& Patch::srcClip(int width, int height)
{
auto &sp(src_.point);
auto &ss(src_.size);
auto &dp(dst_.point);
auto &ds(dst_.size);
// clip origin to zero, update destination accordingly
if (sp(0) < 0) {
ss.width += sp(0);
ds.width += sp(0);
dp(0) -= sp(0);
sp(0) = 0;
}
if (sp(1) < 0) {
ss.height += sp(1);
ds.height += sp(1);
dp(1) -= sp(1);
sp(1) = 0;
}
// clip length
// compute overflow in x and y
const auto xo(sp(0) + ss.width - width);
const auto yo(sp(1) + ss.height - height);
// and apply to width
if (xo > 0) {
ss.width -= xo;
ds.width -= xo;
}
if (yo > 0) {
ss.height -= yo;
ds.height -= yo;
}
return *this;
}
inline Patch& Patch::srcClip(const math::Size2 &limits)
{
return srcClip(limits.width, limits.height);
}
inline Patch Patch::srcClipped(int width, int height) const
{
return Patch(*this).srcClip(width, height);
}
inline Patch Patch::srcClipped(const math::Size2 &limits) const
{
return srcClipped(limits.width, limits.height);
}
template<typename CharT, typename Traits>
inline std::basic_ostream<CharT, Traits>&
operator<<(std::basic_ostream<CharT, Traits> &os, const Patch::Rect &r)
{
std::ios::fmtflags flags(os.flags());
os << r.size << std::showpos << r.point(0) << r.point(1);
os.flags(flags);
return os;
}
} } // namespace imgproc::tx
#endif // imgproc_texturing_hpp_included_
| 9,721 | 3,376 |
#include "ArgumentException.h"
ArgumentException::ArgumentException(string message) : invalid_argument(message.c_str())
{
}
ArgumentException::ArgumentException(const char* message) : invalid_argument(message)
{
}
| 217 | 61 |
/*
* kmp_threadprivate.cpp -- OpenMP threadprivate support library
*/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
#include "kmp.h"
#include "kmp_i18n.h"
#include "kmp_itt.h"
#define USE_CHECKS_COMMON
#define KMP_INLINE_SUBR 1
void kmp_threadprivate_insert_private_data(int gtid, void *pc_addr,
void *data_addr, size_t pc_size);
struct private_common *kmp_threadprivate_insert(int gtid, void *pc_addr,
void *data_addr,
size_t pc_size);
struct shared_table __kmp_threadprivate_d_table;
static
#ifdef KMP_INLINE_SUBR
__forceinline
#endif
struct private_common *
__kmp_threadprivate_find_task_common(struct common_table *tbl, int gtid,
void *pc_addr)
{
struct private_common *tn;
#ifdef KMP_TASK_COMMON_DEBUG
KC_TRACE(10, ("__kmp_threadprivate_find_task_common: thread#%d, called with "
"address %p\n",
gtid, pc_addr));
dump_list();
#endif
for (tn = tbl->data[KMP_HASH(pc_addr)]; tn; tn = tn->next) {
if (tn->gbl_addr == pc_addr) {
#ifdef KMP_TASK_COMMON_DEBUG
KC_TRACE(10, ("__kmp_threadprivate_find_task_common: thread#%d, found "
"node %p on list\n",
gtid, pc_addr));
#endif
return tn;
}
}
return 0;
}
static
#ifdef KMP_INLINE_SUBR
__forceinline
#endif
struct shared_common *
__kmp_find_shared_task_common(struct shared_table *tbl, int gtid,
void *pc_addr) {
struct shared_common *tn;
for (tn = tbl->data[KMP_HASH(pc_addr)]; tn; tn = tn->next) {
if (tn->gbl_addr == pc_addr) {
#ifdef KMP_TASK_COMMON_DEBUG
KC_TRACE(
10,
("__kmp_find_shared_task_common: thread#%d, found node %p on list\n",
gtid, pc_addr));
#endif
return tn;
}
}
return 0;
}
// Create a template for the data initialized storage. Either the template is
// NULL indicating zero fill, or the template is a copy of the original data.
static struct private_data *__kmp_init_common_data(void *pc_addr,
size_t pc_size) {
struct private_data *d;
size_t i;
char *p;
d = (struct private_data *)__kmp_allocate(sizeof(struct private_data));
/*
d->data = 0; // AC: commented out because __kmp_allocate zeroes the
memory
d->next = 0;
*/
d->size = pc_size;
d->more = 1;
p = (char *)pc_addr;
for (i = pc_size; i > 0; --i) {
if (*p++ != '\0') {
d->data = __kmp_allocate(pc_size);
KMP_MEMCPY(d->data, pc_addr, pc_size);
break;
}
}
return d;
}
// Initialize the data area from the template.
static void __kmp_copy_common_data(void *pc_addr, struct private_data *d) {
char *addr = (char *)pc_addr;
int i, offset;
for (offset = 0; d != 0; d = d->next) {
for (i = d->more; i > 0; --i) {
if (d->data == 0)
memset(&addr[offset], '\0', d->size);
else
KMP_MEMCPY(&addr[offset], d->data, d->size);
offset += d->size;
}
}
}
/* we are called from __kmp_serial_initialize() with __kmp_initz_lock held. */
void __kmp_common_initialize(void) {
if (!TCR_4(__kmp_init_common)) {
int q;
#ifdef KMP_DEBUG
int gtid;
#endif
__kmp_threadpriv_cache_list = NULL;
#ifdef KMP_DEBUG
/* verify the uber masters were initialized */
for (gtid = 0; gtid < __kmp_threads_capacity; gtid++)
if (__kmp_root[gtid]) {
KMP_DEBUG_ASSERT(__kmp_root[gtid]->r.r_uber_thread);
for (q = 0; q < KMP_HASH_TABLE_SIZE; ++q)
KMP_DEBUG_ASSERT(
!__kmp_root[gtid]->r.r_uber_thread->th.th_pri_common->data[q]);
/* __kmp_root[ gitd ]-> r.r_uber_thread ->
* th.th_pri_common -> data[ q ] = 0;*/
}
#endif /* KMP_DEBUG */
for (q = 0; q < KMP_HASH_TABLE_SIZE; ++q)
__kmp_threadprivate_d_table.data[q] = 0;
TCW_4(__kmp_init_common, TRUE);
}
}
/* Call all destructors for threadprivate data belonging to all threads.
Currently unused! */
void __kmp_common_destroy(void) {
if (TCR_4(__kmp_init_common)) {
int q;
TCW_4(__kmp_init_common, FALSE);
for (q = 0; q < KMP_HASH_TABLE_SIZE; ++q) {
int gtid;
struct private_common *tn;
struct shared_common *d_tn;
/* C++ destructors need to be called once per thread before exiting.
Don't call destructors for master thread though unless we used copy
constructor */
for (d_tn = __kmp_threadprivate_d_table.data[q]; d_tn;
d_tn = d_tn->next) {
if (d_tn->is_vec) {
if (d_tn->dt.dtorv != 0) {
for (gtid = 0; gtid < __kmp_all_nth; ++gtid) {
if (__kmp_threads[gtid]) {
if ((__kmp_foreign_tp) ? (!KMP_INITIAL_GTID(gtid))
: (!KMP_UBER_GTID(gtid))) {
tn = __kmp_threadprivate_find_task_common(
__kmp_threads[gtid]->th.th_pri_common, gtid,
d_tn->gbl_addr);
if (tn) {
(*d_tn->dt.dtorv)(tn->par_addr, d_tn->vec_len);
}
}
}
}
if (d_tn->obj_init != 0) {
(*d_tn->dt.dtorv)(d_tn->obj_init, d_tn->vec_len);
}
}
} else {
if (d_tn->dt.dtor != 0) {
for (gtid = 0; gtid < __kmp_all_nth; ++gtid) {
if (__kmp_threads[gtid]) {
if ((__kmp_foreign_tp) ? (!KMP_INITIAL_GTID(gtid))
: (!KMP_UBER_GTID(gtid))) {
tn = __kmp_threadprivate_find_task_common(
__kmp_threads[gtid]->th.th_pri_common, gtid,
d_tn->gbl_addr);
if (tn) {
(*d_tn->dt.dtor)(tn->par_addr);
}
}
}
}
if (d_tn->obj_init != 0) {
(*d_tn->dt.dtor)(d_tn->obj_init);
}
}
}
}
__kmp_threadprivate_d_table.data[q] = 0;
}
}
}
/* Call all destructors for threadprivate data belonging to this thread */
void __kmp_common_destroy_gtid(int gtid) {
struct private_common *tn;
struct shared_common *d_tn;
KC_TRACE(10, ("__kmp_common_destroy_gtid: T#%d called\n", gtid));
if ((__kmp_foreign_tp) ? (!KMP_INITIAL_GTID(gtid)) : (!KMP_UBER_GTID(gtid))) {
if (TCR_4(__kmp_init_common)) {
/* Cannot do this here since not all threads have destroyed their data */
/* TCW_4(__kmp_init_common, FALSE); */
for (tn = __kmp_threads[gtid]->th.th_pri_head; tn; tn = tn->link) {
d_tn = __kmp_find_shared_task_common(&__kmp_threadprivate_d_table, gtid,
tn->gbl_addr);
KMP_DEBUG_ASSERT(d_tn);
if (d_tn->is_vec) {
if (d_tn->dt.dtorv != 0) {
(void)(*d_tn->dt.dtorv)(tn->par_addr, d_tn->vec_len);
}
if (d_tn->obj_init != 0) {
(void)(*d_tn->dt.dtorv)(d_tn->obj_init, d_tn->vec_len);
}
} else {
if (d_tn->dt.dtor != 0) {
(void)(*d_tn->dt.dtor)(tn->par_addr);
}
if (d_tn->obj_init != 0) {
(void)(*d_tn->dt.dtor)(d_tn->obj_init);
}
}
}
KC_TRACE(30, ("__kmp_common_destroy_gtid: T#%d threadprivate destructors "
"complete\n",
gtid));
}
}
}
#ifdef KMP_TASK_COMMON_DEBUG
static void dump_list(void) {
int p, q;
for (p = 0; p < __kmp_all_nth; ++p) {
if (!__kmp_threads[p])
continue;
for (q = 0; q < KMP_HASH_TABLE_SIZE; ++q) {
if (__kmp_threads[p]->th.th_pri_common->data[q]) {
struct private_common *tn;
KC_TRACE(10, ("\tdump_list: gtid:%d addresses\n", p));
for (tn = __kmp_threads[p]->th.th_pri_common->data[q]; tn;
tn = tn->next) {
KC_TRACE(10,
("\tdump_list: THREADPRIVATE: Serial %p -> Parallel %p\n",
tn->gbl_addr, tn->par_addr));
}
}
}
}
}
#endif /* KMP_TASK_COMMON_DEBUG */
// NOTE: this routine is to be called only from the serial part of the program.
void kmp_threadprivate_insert_private_data(int gtid, void *pc_addr,
void *data_addr, size_t pc_size) {
struct shared_common **lnk_tn, *d_tn;
KMP_DEBUG_ASSERT(__kmp_threads[gtid] &&
__kmp_threads[gtid]->th.th_root->r.r_active == 0);
d_tn = __kmp_find_shared_task_common(&__kmp_threadprivate_d_table, gtid,
pc_addr);
if (d_tn == 0) {
d_tn = (struct shared_common *)__kmp_allocate(sizeof(struct shared_common));
d_tn->gbl_addr = pc_addr;
d_tn->pod_init = __kmp_init_common_data(data_addr, pc_size);
/*
d_tn->obj_init = 0; // AC: commented out because __kmp_allocate
zeroes the memory
d_tn->ct.ctor = 0;
d_tn->cct.cctor = 0;;
d_tn->dt.dtor = 0;
d_tn->is_vec = FALSE;
d_tn->vec_len = 0L;
*/
d_tn->cmn_size = pc_size;
__kmp_acquire_lock(&__kmp_global_lock, gtid);
lnk_tn = &(__kmp_threadprivate_d_table.data[KMP_HASH(pc_addr)]);
d_tn->next = *lnk_tn;
*lnk_tn = d_tn;
__kmp_release_lock(&__kmp_global_lock, gtid);
}
}
struct private_common *kmp_threadprivate_insert(int gtid, void *pc_addr,
void *data_addr,
size_t pc_size) {
struct private_common *tn, **tt;
struct shared_common *d_tn;
/* +++++++++ START OF CRITICAL SECTION +++++++++ */
__kmp_acquire_lock(&__kmp_global_lock, gtid);
tn = (struct private_common *)__kmp_allocate(sizeof(struct private_common));
tn->gbl_addr = pc_addr;
d_tn = __kmp_find_shared_task_common(
&__kmp_threadprivate_d_table, gtid,
pc_addr); /* Only the MASTER data table exists. */
if (d_tn != 0) {
/* This threadprivate variable has already been seen. */
if (d_tn->pod_init == 0 && d_tn->obj_init == 0) {
d_tn->cmn_size = pc_size;
if (d_tn->is_vec) {
if (d_tn->ct.ctorv != 0) {
/* Construct from scratch so no prototype exists */
d_tn->obj_init = 0;
} else if (d_tn->cct.cctorv != 0) {
/* Now data initialize the prototype since it was previously
* registered */
d_tn->obj_init = (void *)__kmp_allocate(d_tn->cmn_size);
(void)(*d_tn->cct.cctorv)(d_tn->obj_init, pc_addr, d_tn->vec_len);
} else {
d_tn->pod_init = __kmp_init_common_data(data_addr, d_tn->cmn_size);
}
} else {
if (d_tn->ct.ctor != 0) {
/* Construct from scratch so no prototype exists */
d_tn->obj_init = 0;
} else if (d_tn->cct.cctor != 0) {
/* Now data initialize the prototype since it was previously
registered */
d_tn->obj_init = (void *)__kmp_allocate(d_tn->cmn_size);
(void)(*d_tn->cct.cctor)(d_tn->obj_init, pc_addr);
} else {
d_tn->pod_init = __kmp_init_common_data(data_addr, d_tn->cmn_size);
}
}
}
} else {
struct shared_common **lnk_tn;
d_tn = (struct shared_common *)__kmp_allocate(sizeof(struct shared_common));
d_tn->gbl_addr = pc_addr;
d_tn->cmn_size = pc_size;
d_tn->pod_init = __kmp_init_common_data(data_addr, pc_size);
/*
d_tn->obj_init = 0; // AC: commented out because __kmp_allocate
zeroes the memory
d_tn->ct.ctor = 0;
d_tn->cct.cctor = 0;
d_tn->dt.dtor = 0;
d_tn->is_vec = FALSE;
d_tn->vec_len = 0L;
*/
lnk_tn = &(__kmp_threadprivate_d_table.data[KMP_HASH(pc_addr)]);
d_tn->next = *lnk_tn;
*lnk_tn = d_tn;
}
tn->cmn_size = d_tn->cmn_size;
if ((__kmp_foreign_tp) ? (KMP_INITIAL_GTID(gtid)) : (KMP_UBER_GTID(gtid))) {
tn->par_addr = (void *)pc_addr;
} else {
tn->par_addr = (void *)__kmp_allocate(tn->cmn_size);
}
__kmp_release_lock(&__kmp_global_lock, gtid);
/* +++++++++ END OF CRITICAL SECTION +++++++++ */
#ifdef USE_CHECKS_COMMON
if (pc_size > d_tn->cmn_size) {
KC_TRACE(
10, ("__kmp_threadprivate_insert: THREADPRIVATE: %p (%" KMP_UINTPTR_SPEC
" ,%" KMP_UINTPTR_SPEC ")\n",
pc_addr, pc_size, d_tn->cmn_size));
KMP_FATAL(TPCommonBlocksInconsist);
}
#endif /* USE_CHECKS_COMMON */
tt = &(__kmp_threads[gtid]->th.th_pri_common->data[KMP_HASH(pc_addr)]);
#ifdef KMP_TASK_COMMON_DEBUG
if (*tt != 0) {
KC_TRACE(
10,
("__kmp_threadprivate_insert: WARNING! thread#%d: collision on %p\n",
gtid, pc_addr));
}
#endif
tn->next = *tt;
*tt = tn;
#ifdef KMP_TASK_COMMON_DEBUG
KC_TRACE(10,
("__kmp_threadprivate_insert: thread#%d, inserted node %p on list\n",
gtid, pc_addr));
dump_list();
#endif
/* Link the node into a simple list */
tn->link = __kmp_threads[gtid]->th.th_pri_head;
__kmp_threads[gtid]->th.th_pri_head = tn;
#ifdef BUILD_TV
__kmp_tv_threadprivate_store(__kmp_threads[gtid], tn->gbl_addr, tn->par_addr);
#endif
if ((__kmp_foreign_tp) ? (KMP_INITIAL_GTID(gtid)) : (KMP_UBER_GTID(gtid)))
return tn;
/* if C++ object with copy constructor, use it;
* else if C++ object with constructor, use it for the non-master copies only;
* else use pod_init and memcpy
*
* C++ constructors need to be called once for each non-master thread on
* allocate
* C++ copy constructors need to be called once for each thread on allocate */
/* C++ object with constructors/destructors; don't call constructors for
master thread though */
if (d_tn->is_vec) {
if (d_tn->ct.ctorv != 0) {
(void)(*d_tn->ct.ctorv)(tn->par_addr, d_tn->vec_len);
} else if (d_tn->cct.cctorv != 0) {
(void)(*d_tn->cct.cctorv)(tn->par_addr, d_tn->obj_init, d_tn->vec_len);
} else if (tn->par_addr != tn->gbl_addr) {
__kmp_copy_common_data(tn->par_addr, d_tn->pod_init);
}
} else {
if (d_tn->ct.ctor != 0) {
(void)(*d_tn->ct.ctor)(tn->par_addr);
} else if (d_tn->cct.cctor != 0) {
(void)(*d_tn->cct.cctor)(tn->par_addr, d_tn->obj_init);
} else if (tn->par_addr != tn->gbl_addr) {
__kmp_copy_common_data(tn->par_addr, d_tn->pod_init);
}
}
/* !BUILD_OPENMP_C
if (tn->par_addr != tn->gbl_addr)
__kmp_copy_common_data( tn->par_addr, d_tn->pod_init ); */
return tn;
}
/* ------------------------------------------------------------------------ */
/* We are currently parallel, and we know the thread id. */
/* ------------------------------------------------------------------------ */
/*!
@ingroup THREADPRIVATE
@param loc source location information
@param data pointer to data being privatized
@param ctor pointer to constructor function for data
@param cctor pointer to copy constructor function for data
@param dtor pointer to destructor function for data
Register constructors and destructors for thread private data.
This function is called when executing in parallel, when we know the thread id.
*/
void __kmpc_threadprivate_register(ident_t *loc, void *data, kmpc_ctor ctor,
kmpc_cctor cctor, kmpc_dtor dtor) {
struct shared_common *d_tn, **lnk_tn;
KC_TRACE(10, ("__kmpc_threadprivate_register: called\n"));
#ifdef USE_CHECKS_COMMON
/* copy constructor must be zero for current code gen (Nov 2002 - jph) */
KMP_ASSERT(cctor == 0);
#endif /* USE_CHECKS_COMMON */
/* Only the global data table exists. */
d_tn = __kmp_find_shared_task_common(&__kmp_threadprivate_d_table, -1, data);
if (d_tn == 0) {
d_tn = (struct shared_common *)__kmp_allocate(sizeof(struct shared_common));
d_tn->gbl_addr = data;
d_tn->ct.ctor = ctor;
d_tn->cct.cctor = cctor;
d_tn->dt.dtor = dtor;
/*
d_tn->is_vec = FALSE; // AC: commented out because __kmp_allocate
zeroes the memory
d_tn->vec_len = 0L;
d_tn->obj_init = 0;
d_tn->pod_init = 0;
*/
lnk_tn = &(__kmp_threadprivate_d_table.data[KMP_HASH(data)]);
d_tn->next = *lnk_tn;
*lnk_tn = d_tn;
}
}
void *__kmpc_threadprivate(ident_t *loc, kmp_int32 global_tid, void *data,
size_t size) {
void *ret;
struct private_common *tn;
KC_TRACE(10, ("__kmpc_threadprivate: T#%d called\n", global_tid));
#ifdef USE_CHECKS_COMMON
if (!__kmp_init_serial)
KMP_FATAL(RTLNotInitialized);
#endif /* USE_CHECKS_COMMON */
if (!__kmp_threads[global_tid]->th.th_root->r.r_active && !__kmp_foreign_tp) {
/* The parallel address will NEVER overlap with the data_address */
/* dkp: 3rd arg to kmp_threadprivate_insert_private_data() is the
* data_address; use data_address = data */
KC_TRACE(20, ("__kmpc_threadprivate: T#%d inserting private data\n",
global_tid));
kmp_threadprivate_insert_private_data(global_tid, data, data, size);
ret = data;
} else {
KC_TRACE(
50,
("__kmpc_threadprivate: T#%d try to find private data at address %p\n",
global_tid, data));
tn = __kmp_threadprivate_find_task_common(
__kmp_threads[global_tid]->th.th_pri_common, global_tid, data);
if (tn) {
KC_TRACE(20, ("__kmpc_threadprivate: T#%d found data\n", global_tid));
#ifdef USE_CHECKS_COMMON
if ((size_t)size > tn->cmn_size) {
KC_TRACE(10, ("THREADPRIVATE: %p (%" KMP_UINTPTR_SPEC
" ,%" KMP_UINTPTR_SPEC ")\n",
data, size, tn->cmn_size));
KMP_FATAL(TPCommonBlocksInconsist);
}
#endif /* USE_CHECKS_COMMON */
} else {
/* The parallel address will NEVER overlap with the data_address */
/* dkp: 3rd arg to kmp_threadprivate_insert() is the data_address; use
* data_address = data */
KC_TRACE(20, ("__kmpc_threadprivate: T#%d inserting data\n", global_tid));
tn = kmp_threadprivate_insert(global_tid, data, data, size);
}
ret = tn->par_addr;
}
KC_TRACE(10, ("__kmpc_threadprivate: T#%d exiting; return value = %p\n",
global_tid, ret));
return ret;
}
/*!
@ingroup THREADPRIVATE
@param loc source location information
@param global_tid global thread number
@param data pointer to data to privatize
@param size size of data to privatize
@param cache pointer to cache
@return pointer to private storage
Allocate private storage for threadprivate data.
*/
void *
__kmpc_threadprivate_cached(ident_t *loc,
kmp_int32 global_tid, // gtid.
void *data, // Pointer to original global variable.
size_t size, // Size of original global variable.
void ***cache) {
KC_TRACE(10, ("__kmpc_threadprivate_cached: T#%d called with cache: %p, "
"address: %p, size: %" KMP_SIZE_T_SPEC "\n",
global_tid, *cache, data, size));
if (TCR_PTR(*cache) == 0) {
__kmp_acquire_lock(&__kmp_global_lock, global_tid);
if (TCR_PTR(*cache) == 0) {
__kmp_acquire_bootstrap_lock(&__kmp_tp_cached_lock);
__kmp_tp_cached = 1;
__kmp_release_bootstrap_lock(&__kmp_tp_cached_lock);
void **my_cache;
KMP_ITT_IGNORE(
my_cache = (void **)__kmp_allocate(
sizeof(void *) * __kmp_tp_capacity + sizeof(kmp_cached_addr_t)););
// No need to zero the allocated memory; __kmp_allocate does that.
KC_TRACE(
50,
("__kmpc_threadprivate_cached: T#%d allocated cache at address %p\n",
global_tid, my_cache));
/* TODO: free all this memory in __kmp_common_destroy using
* __kmp_threadpriv_cache_list */
/* Add address of mycache to linked list for cleanup later */
kmp_cached_addr_t *tp_cache_addr;
tp_cache_addr = (kmp_cached_addr_t *)&my_cache[__kmp_tp_capacity];
tp_cache_addr->addr = my_cache;
tp_cache_addr->next = __kmp_threadpriv_cache_list;
__kmp_threadpriv_cache_list = tp_cache_addr;
KMP_MB();
TCW_PTR(*cache, my_cache);
KMP_MB();
}
__kmp_release_lock(&__kmp_global_lock, global_tid);
}
void *ret;
if ((ret = TCR_PTR((*cache)[global_tid])) == 0) {
ret = __kmpc_threadprivate(loc, global_tid, data, (size_t)size);
TCW_PTR((*cache)[global_tid], ret);
}
KC_TRACE(10,
("__kmpc_threadprivate_cached: T#%d exiting; return value = %p\n",
global_tid, ret));
return ret;
}
/*!
@ingroup THREADPRIVATE
@param loc source location information
@param data pointer to data being privatized
@param ctor pointer to constructor function for data
@param cctor pointer to copy constructor function for data
@param dtor pointer to destructor function for data
@param vector_length length of the vector (bytes or elements?)
Register vector constructors and destructors for thread private data.
*/
void __kmpc_threadprivate_register_vec(ident_t *loc, void *data,
kmpc_ctor_vec ctor, kmpc_cctor_vec cctor,
kmpc_dtor_vec dtor,
size_t vector_length) {
struct shared_common *d_tn, **lnk_tn;
KC_TRACE(10, ("__kmpc_threadprivate_register_vec: called\n"));
#ifdef USE_CHECKS_COMMON
/* copy constructor must be zero for current code gen (Nov 2002 - jph) */
KMP_ASSERT(cctor == 0);
#endif /* USE_CHECKS_COMMON */
d_tn = __kmp_find_shared_task_common(
&__kmp_threadprivate_d_table, -1,
data); /* Only the global data table exists. */
if (d_tn == 0) {
d_tn = (struct shared_common *)__kmp_allocate(sizeof(struct shared_common));
d_tn->gbl_addr = data;
d_tn->ct.ctorv = ctor;
d_tn->cct.cctorv = cctor;
d_tn->dt.dtorv = dtor;
d_tn->is_vec = TRUE;
d_tn->vec_len = (size_t)vector_length;
/*
d_tn->obj_init = 0; // AC: commented out because __kmp_allocate
zeroes the memory
d_tn->pod_init = 0;
*/
lnk_tn = &(__kmp_threadprivate_d_table.data[KMP_HASH(data)]);
d_tn->next = *lnk_tn;
*lnk_tn = d_tn;
}
}
| 22,778 | 8,566 |
#include "timer.h"
int timer::_count = 0;
timer *timer::_timers[MAX_TIMERS];
| 78 | 35 |
//Equation to solve: 5x1 + x2 = 7 ; x1 + 5x2 = 11
#include <iostream>
int main() {
double x_1 = 0.01; // Initialize x1 = 0
double x_1_new = 0.0;
double x_2 = 0.01; // Initialize x2 = 0
double x_2_new = 0.0;
double eps = 1.0; // Tolerance limit epsilon, initialized to 1
int count_steps_jac = 0;
// Jacobi iterative method
while (eps > 0.01){
x_1_new = (7-x_2)/5.0;
x_2_new = (11-x_1)/5.0;
eps = x_1_new - x_1;
x_1 = x_1_new;
x_2 = x_2_new;
count_steps_jac++;
}
std::cout << "X1 for Jacobi method: " << x_1 << std::endl;
std::cout << "X2 for Jacobi method: " << x_2 << std::endl;
std::cout << "Number of steps taken for Jacobi method: " << count_steps_jac << std::endl;
// Gauss Siedel Iterative method
eps = 1.0; // Tolerance limit reset
int count_steps_gaus = 0;
x_1 = 0.01;
x_1_new = x_1; // Initialize x_1_new as x_1
x_2 = 0.01;
x_2_new = x_2; // Initialize x_2_new as x_2
while (eps > 0.01){
x_1_new = (7-x_2_new)/5.0;
x_2_new = (11-x_1_new)/5.0;
eps = x_1_new - x_1;
x_1 = x_1_new;
x_2 = x_2_new;
count_steps_gaus++;
}
std::cout << "X1 for Gauss Siedel method: " << x_1 << std::endl;
std::cout << "X2 for Gauss Siedel method: " << x_2 << std::endl;
std::cout << "Number of steps taken for Gauss Siedel method: " << count_steps_gaus << std::endl;
}
| 1,443 | 693 |
#include "Matrix.h"
#include "iostream"
namespace Maths
{
Matrix::Matrix()
{
// If no data is given then set as identity matrix
for (int i = 0; i < 9; i++)
{
matrixData[i] = 0;
}
matrixData[0] = matrixData[4] = matrixData[8] = 1.0f;
}
Matrix::Matrix(float matrix0, float matrix3, float matrix6, float matrix1, float matrix4, float matrix7, float matrix2, float matrix5, float matrix8)
{
matrixData[0] = matrix0;
matrixData[3] = matrix3;
matrixData[6] = matrix6;
matrixData[1] = matrix1;
matrixData[4] = matrix4;
matrixData[7] = matrix7;
matrixData[2] = matrix2;
matrixData[5] = matrix5;
matrixData[8] = matrix8;
}
Matrix & Matrix::operator=(const Matrix & matrix)
{
for (int i = 0; i <= 8; i++)
{
matrixData[i] = matrix.matrixData[i];
}
return *this;
}
Matrix::~Matrix()
{
}
void Matrix::Show()
{
std::cout << matrixData[0] << ", " << matrixData[3] << ", " << matrixData[6] << std::endl;
std::cout << matrixData[1] << ", " << matrixData[4] << ", " << matrixData[7] << std::endl;
std::cout << matrixData[2] << ", " << matrixData[5] << ", " << matrixData[8] << std::endl;
}
Matrix Matrix::operator+(const Matrix & matrix)
{
return Matrix(matrixData[0] + matrix.matrixData[0], matrixData[3] + matrix.matrixData[3], matrixData[6] + matrix.matrixData[6],
matrixData[1] + matrix.matrixData[1], matrixData[4] + matrix.matrixData[4], matrixData[7] + matrix.matrixData[7],
matrixData[2] + matrix.matrixData[2], matrixData[5] + matrix.matrixData[5], matrixData[8] + matrix.matrixData[8]);
}
void Matrix::operator+=(const Matrix & matrix)
{
for (int i = 0; i <= 8; i++)
{
matrixData[i] += matrix.matrixData[i];
}
}
Matrix Matrix::operator-(const Matrix & matrix)
{
return Matrix(matrixData[0] - matrix.matrixData[0], matrixData[3] - matrix.matrixData[3], matrixData[6] - matrix.matrixData[6],
matrixData[1] - matrix.matrixData[1], matrixData[4] - matrix.matrixData[4], matrixData[7] - matrix.matrixData[7],
matrixData[2] - matrix.matrixData[2], matrixData[5] - matrix.matrixData[5], matrixData[8] - matrix.matrixData[8]);
}
void Matrix::operator-=(const Matrix & matrix)
{
for (int i = 0; i <= 8; i++)
{
matrixData[i] -= matrix.matrixData[i];
}
}
Matrix Matrix::operator*(const float Multiplication)
{
return Matrix(matrixData[0] * Multiplication, matrixData[3] * Multiplication, matrixData[6] * Multiplication,
matrixData[1] * Multiplication, matrixData[4] * Multiplication, matrixData[7] * Multiplication,
matrixData[2] * Multiplication, matrixData[5] * Multiplication, matrixData[8] * Multiplication);
}
void Matrix::operator*=(const float Multiplication)
{
for (int i = 0; i <= 8; i++)
{
matrixData[i] *= Multiplication;
}
}
Matrix Matrix::operator/(const float Division)
{
return Matrix(matrixData[0] / Division, matrixData[3] / Division, matrixData[6] / Division,
matrixData[1] / Division, matrixData[4] / Division, matrixData[7] / Division,
matrixData[2] / Division, matrixData[5] / Division, matrixData[8] / Division);
}
void Matrix::operator/=(const float Division)
{
for (int i = 0; i <= 8; i++)
{
matrixData[i] /= Division;
}
}
Matrix Matrix::operator*(const Matrix & matrix)
{
return Matrix(matrixData[0] * matrix.matrixData[0] + matrixData[3] * matrix.matrixData[1] + matrixData[6] * matrix.matrixData[2],
matrixData[0] * matrix.matrixData[3] + matrixData[3] * matrix.matrixData[4] + matrixData[6] * matrix.matrixData[5],
matrixData[0] * matrix.matrixData[6] + matrixData[3] * matrix.matrixData[7] + matrixData[6] * matrix.matrixData[8],
matrixData[1] * matrix.matrixData[0] + matrixData[4] * matrix.matrixData[1] + matrixData[7] * matrix.matrixData[2],
matrixData[1] * matrix.matrixData[3] + matrixData[4] * matrix.matrixData[4] + matrixData[7] * matrix.matrixData[5],
matrixData[1] * matrix.matrixData[6] + matrixData[4] * matrix.matrixData[7] + matrixData[7] * matrix.matrixData[8],
matrixData[2] * matrix.matrixData[0] + matrixData[5] * matrix.matrixData[1] + matrixData[8] * matrix.matrixData[2],
matrixData[2] * matrix.matrixData[3] + matrixData[5] * matrix.matrixData[4] + matrixData[8] * matrix.matrixData[5],
matrixData[2] * matrix.matrixData[6] + matrixData[5] * matrix.matrixData[7] + matrixData[8] * matrix.matrixData[8]);
}
void Matrix::operator*=(const Matrix & matrix)
{
matrixData[0] = matrixData[0] * matrix.matrixData[0] + matrixData[3] * matrix.matrixData[1] + matrixData[6] * matrix.matrixData[2];
matrixData[3] = matrixData[0] * matrix.matrixData[3] + matrixData[3] * matrix.matrixData[4] + matrixData[6] * matrix.matrixData[5];
matrixData[6] = matrixData[0] * matrix.matrixData[6] + matrixData[3] * matrix.matrixData[7] + matrixData[6] * matrix.matrixData[8];
matrixData[1] = matrixData[1] * matrix.matrixData[0] + matrixData[4] * matrix.matrixData[1] + matrixData[7] * matrix.matrixData[2];
matrixData[4] = matrixData[1] * matrix.matrixData[3] + matrixData[4] * matrix.matrixData[4] + matrixData[7] * matrix.matrixData[5];
matrixData[7] = matrixData[1] * matrix.matrixData[6] + matrixData[4] * matrix.matrixData[7] + matrixData[7] * matrix.matrixData[8];
matrixData[2] = matrixData[2] * matrix.matrixData[0] + matrixData[5] * matrix.matrixData[1] + matrixData[8] * matrix.matrixData[2];
matrixData[5] = matrixData[2] * matrix.matrixData[3] + matrixData[5] * matrix.matrixData[4] + matrixData[8] * matrix.matrixData[5];
matrixData[8] = matrixData[2] * matrix.matrixData[6] + matrixData[5] * matrix.matrixData[7] + matrixData[8] * matrix.matrixData[8];
}
void Matrix::SetAsIdentityMatrix()
{
for (int i = 0; i <= 8; i++)
{
matrixData[i] = 0.0f;
}
matrixData[0] = matrixData[4] = matrixData[8] = 1.0f;
}
void Matrix::SetMatrixAsInverseOf(const Matrix & matrix)
{
float detCalc[6];
detCalc[0] = matrix.matrixData[0] * matrix.matrixData[4];
detCalc[1] = matrix.matrixData[0] * matrix.matrixData[7];
detCalc[2] = matrix.matrixData[3] * matrix.matrixData[1];
detCalc[3] = matrix.matrixData[6] * matrix.matrixData[1];
detCalc[4] = matrix.matrixData[3] * matrix.matrixData[2];
detCalc[5] = matrix.matrixData[6] * matrix.matrixData[2];
float determinant = (detCalc[0] * matrix.matrixData[8] - detCalc[1] * matrix.matrixData[5] - detCalc[2] * matrix.matrixData[8] + detCalc[3] * matrix.matrixData[5] +
detCalc[4] * matrix.matrixData[7] - detCalc[5] * matrix.matrixData[4]);
if (determinant == 0.0f)
{
return;
}
float invd = 1.0f / determinant;
float inverseCalc[9];
inverseCalc[0] = (matrix.matrixData[4] * matrix.matrixData[8] - matrix.matrixData[7] * matrix.matrixData[5]) * invd;
inverseCalc[3] =-(matrix.matrixData[3] * matrix.matrixData[8] - matrix.matrixData[6] * matrix.matrixData[5]) * invd;
inverseCalc[6] = (matrix.matrixData[3] * matrix.matrixData[7] - matrix.matrixData[6] * matrix.matrixData[4]) * invd;
inverseCalc[1] =-(matrix.matrixData[1] * matrix.matrixData[8] - matrix.matrixData[7] * matrix.matrixData[2]) * invd;
inverseCalc[4] = (matrix.matrixData[0] * matrix.matrixData[8] - detCalc[5]) * invd;
inverseCalc[7] =-(detCalc[1] - detCalc[3]) * invd;
inverseCalc[2] = (matrix.matrixData[1] * matrix.matrixData[5] - matrix.matrixData[4] * matrix.matrixData[2]) * invd;
inverseCalc[5] =-(matrix.matrixData[0] * matrix.matrixData[5] - detCalc[4]) * invd;
inverseCalc[8] = (detCalc[0] - detCalc[2]) * invd;
matrixData[0] = inverseCalc[0];
matrixData[3] = inverseCalc[3];
matrixData[6] = inverseCalc[6];
matrixData[1] = inverseCalc[1];
matrixData[4] = inverseCalc[4];
matrixData[7] = inverseCalc[7];
matrixData[2] = inverseCalc[2];
matrixData[5] = inverseCalc[5];
matrixData[8] = inverseCalc[8];
}
const Matrix Matrix::GetInverseOfMatrix()
{
Matrix Result;
Result.SetMatrixAsInverseOf(*this);
return Result;
}
void Matrix::InvertMatrix()
{
SetMatrixAsInverseOf(*this);
}
void Matrix::SetTranspose(const Matrix & matrix)
{
matrixData[0] = matrix.matrixData[0];
matrixData[3] = matrix.matrixData[1];
matrixData[6] = matrix.matrixData[2];
matrixData[1] = matrix.matrixData[3];
matrixData[4] = matrix.matrixData[4];
matrixData[7] = matrix.matrixData[5];
matrixData[2] = matrix.matrixData[6];
matrixData[5] = matrix.matrixData[7];
matrixData[8] = matrix.matrixData[8];
}
const Matrix Matrix::GetTranspose()
{
Matrix Result;
Result.SetTranspose(*this);
return Result;
}
Vector3D Matrix::operator*(const Vector3D & vector)
{
return Vector3D(matrixData[0] * vector.x + matrixData[3] * vector.y + matrixData[6] * vector.z,
matrixData[1] * vector.x + matrixData[4] * vector.y + matrixData[7] * vector.z,
matrixData[2] * vector.x + matrixData[5] * vector.y + matrixData[8] * vector.z);
}
Vector3D Matrix::TransformVectorByMatrix(const Vector3D & vector)
{
return(*this * vector);
}
}
| 9,176 | 3,683 |
#include <babylon/extensions/dynamicterrain/dynamic_terrain.h>
#include <babylon/babylon_stl_util.h>
#include <babylon/cameras/camera.h>
#include <babylon/core/logging.h>
#include <babylon/engines/scene.h>
#include <babylon/extensions/dynamicterrain/dynamic_terrain_options.h>
#include <babylon/meshes/builders/mesh_builder_options.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/mesh_builder.h>
#include <babylon/meshes/vertex_buffer.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/misc/file_tools.h>
namespace BABYLON {
namespace Extensions {
Vector3 DynamicTerrain::_v1 = Vector3::Zero();
Vector3 DynamicTerrain::_v2 = Vector3::Zero();
Vector3 DynamicTerrain::_v3 = Vector3::Zero();
Vector3 DynamicTerrain::_v4 = Vector3::Zero();
Vector3 DynamicTerrain::_vAvB = Vector3::Zero();
Vector3 DynamicTerrain::_vAvC = Vector3::Zero();
Vector3 DynamicTerrain::_norm = Vector3::Zero();
Vector3 DynamicTerrain::_bbMin = Vector3::Zero();
Vector3 DynamicTerrain::_bbMax = Vector3::Zero();
DynamicTerrain::DynamicTerrain(const std::string& iName, DynamicTerrainOptions& options,
Scene* scene)
: name{iName}
, _subToleranceX{1}
, _subToleranceZ{1}
, _initialLOD{1}
, _LODValue{1}
, _cameraLODCorrection{0}
, _oldCorrection{0}
, _deltaX{0.f}
, _deltaZ{0.f}
, _signX{0}
, _signZ{0}
, _deltaSubX{0}
, _deltaSubZ{0}
, _mapShiftX{0.f}
, _mapShiftZ{0.f}
, _mapFlgtNb{0}
, _needsUpdate{false}
, _updateLOD{false}
, _updateForced{false}
, _refreshEveryFrame{false}
, _useCustomVertexFunction{false}
, _computeNormals{true}
, _datamap{false}
, _uvmap{false}
, _colormap{false}
, _vertex{DynamicTerrainVertex{Vector3::Zero(), // vertex position in the terrain space
Vector2::Zero(), // vertex uv
Color4(1.0, 1.0, 1.0, 1.0), // vertex color
1, // vertex LOD value on X axis
1, // vertex LOD value on Z axis
Vector3::Zero(), // vertex World position
0}}
, _averageSubSizeX{0.f}
, _averageSubSizeZ{0.f}
, _terrainSizeX{0.f}
, _terrainSizeZ{0.f}
, _terrainHalfSizeX{0.f}
, _terrainHalfSizeZ{0.f}
, _centerWorld{Vector3::Zero()}
, _centerLocal{Vector3::Zero()}
, _mapSizeX{0.f}
, _mapSizeZ{0.f}
, _isAlwaysVisible{false}
, _precomputeNormalsFromMap{false}
{
_terrainSub = (options.terrainSub > 0) ? static_cast<unsigned>(options.terrainSub) : 60;
_mapData = options.mapData;
_terrainIdx = _terrainSub + 1;
_mapSubX = (options.mapSubX > 0) ? static_cast<unsigned>(options.mapSubX) : _terrainIdx;
_mapSubZ = (options.mapSubZ > 0) ? static_cast<unsigned>(options.mapSubZ) : _terrainIdx;
// if not defined, it will be still populated by default values
_mapUVs = options.mapUVs;
_mapColors = options.mapColors;
_scene = scene;
_terrainCamera = options.camera ? options.camera : scene->activeCamera;
// initialize the map arrays if not passed as parameters
_datamap = !_mapData.empty();
_uvmap = !_mapUVs.empty();
_colormap = !_mapColors.empty();
_mapData = _datamap ? _mapData : Float32Array(_terrainIdx * _terrainIdx * 3);
_mapUVs = _uvmap ? _mapUVs : Float32Array(_terrainIdx * _terrainIdx * 2);
if (_datamap) {
_mapNormals
= !options.mapNormals.empty() ? options.mapNormals : Float32Array(_mapSubX * _mapSubZ * 3);
}
else {
_mapNormals = Float32Array(_terrainIdx * _terrainIdx * 3);
}
// Ribbon creation
std::size_t index = 0; // current vertex index in the map array
std::size_t posIndex = 0; // current position (coords) index in the map array
std::size_t colIndex = 0; // current color index in the color array
std::size_t uvIndex = 0; // current uv index in the uv array
Color4 color; // current color
Vector2 uv; // current uv
std::size_t terIndex = 0; // current index in the terrain array
float y = 0.0; // current y coordinate
std::vector<Vector3> terrainPath; // current path
float u = 0.0; // current u of UV
float v = 0.0; // current v of UV
std::size_t lg = _terrainIdx + 1; // augmented length for the UV to finish before
std::vector<std::vector<Vector3>> terrainData;
std::vector<Color4> terrainColor;
std::vector<Vector2> terrainUV;
for (unsigned int j = 0; j <= _terrainSub; ++j) {
terrainPath.clear();
for (unsigned int i = 0; i <= _terrainSub; ++i) {
index = _mod(j * 3, _mapSubZ) * _mapSubX + _mod(i * 3, _mapSubX);
posIndex = index * 3;
colIndex = index * 3;
uvIndex = index * 2;
terIndex = j * _terrainIdx + i;
// geometry
if (_datamap) {
y = _mapData[posIndex + 1];
}
else {
y = 0.f;
_mapData[3 * terIndex] = static_cast<float>(i);
_mapData[3 * terIndex + 1] = y;
_mapData[3 * terIndex + 2] = static_cast<float>(j);
}
terrainPath.emplace_back(Vector3(static_cast<float>(i), y, static_cast<float>(j)));
// color
if (_colormap) {
color
= Color4(_mapColors[colIndex], _mapColors[colIndex + 1], _mapColors[colIndex + 2], 1.f);
}
else {
color = Color4(1.f, 1.f, 1.f, 1.f);
}
terrainColor.emplace_back(color);
// uvs
if (_uvmap) {
uv = Vector2(_mapUVs[uvIndex], _mapUVs[uvIndex + 1]);
}
else {
u = 1.f - std::abs(1.f - 2.f * i / lg);
v = 1.f - std::abs(1.f - 2.f * j / lg);
_mapUVs[2 * terIndex] = u;
_mapUVs[2 * terIndex + 1] = v;
uv = Vector2(u, v);
}
terrainUV.emplace_back(uv);
}
terrainData.emplace_back(terrainPath);
}
_mapSizeX = std::abs(_mapData[(_mapSubX - 1) * 3] - _mapData[0]);
_mapSizeZ = std::abs(_mapData[(_mapSubZ - 1) * _mapSubX * 3 + 2] - _mapData[2]);
_averageSubSizeX = _mapSizeX / _mapSubX;
_averageSubSizeZ = _mapSizeZ / _mapSubZ;
RibbonOptions ribbonOptions;
ribbonOptions.pathArray = terrainData;
ribbonOptions.sideOrientation = (options.invertSide) ? Mesh::FRONTSIDE : Mesh::BACKSIDE;
ribbonOptions.colors = terrainColor;
ribbonOptions.uvs = terrainUV;
ribbonOptions.updatable = true;
_terrain = MeshBuilder::CreateRibbon("terrain", ribbonOptions, _scene);
_indices = _terrain->getIndices();
_positions = _terrain->getVerticesData(VertexBuffer::PositionKind);
_normals = _terrain->getVerticesData(VertexBuffer::NormalKind);
_uvs = _terrain->getVerticesData(VertexBuffer::UVKind);
_colors = _terrain->getVerticesData(VertexBuffer::ColorKind);
computeNormalsFromMap();
// update it immediatly and register the update callback function in the
// render loop
update(true);
_terrain->position().x = _terrainCamera->globalPosition().x - _terrainHalfSizeX;
_terrain->position().z = _terrainCamera->globalPosition().z - _terrainHalfSizeZ;
// initialize deltaSub to make
float deltaNbSubX = (_terrain->position().x - _mapData[0]) / _averageSubSizeX;
float deltaNbSubZ = (_terrain->position().z - _mapData[2]) / _averageSubSizeZ;
_deltaSubX = (deltaNbSubX > 0.f) ? static_cast<unsigned>(std::floor(deltaNbSubX)) :
static_cast<unsigned>(std::ceil(deltaNbSubX));
_deltaSubZ = (deltaNbSubZ > 0.f) ? static_cast<unsigned>(std::floor(deltaNbSubZ)) :
static_cast<unsigned>(std::ceil(deltaNbSubZ));
_scene->registerBeforeRender([this](Scene*, EventState&) {
beforeUpdate(_refreshEveryFrame);
update(_refreshEveryFrame);
afterUpdate(_refreshEveryFrame);
});
update(true); // recompute everything once the initial deltas are calculated
}
DynamicTerrain::~DynamicTerrain() = default;
DynamicTerrain& DynamicTerrain::update(bool force)
{
_needsUpdate = false;
_updateLOD = false;
_updateForced = (force);
_deltaX = _terrainHalfSizeX + _terrain->position().x - _terrainCamera->globalPosition().x;
_deltaZ = _terrainHalfSizeZ + _terrain->position().z - _terrainCamera->globalPosition().z;
_oldCorrection = _cameraLODCorrection;
_cameraLODCorrection = updateCameraLOD(_terrainCamera);
_updateLOD = (_oldCorrection != _cameraLODCorrection);
_LODValue = _initialLOD + _cameraLODCorrection;
_LODValue = (_LODValue > 0) ? _LODValue : 1;
_mapShiftX = _averageSubSizeX * _subToleranceX * _LODValue;
_mapShiftZ = _averageSubSizeZ * _subToleranceZ * _LODValue;
if (std::abs(_deltaX) > _mapShiftX) {
_signX = (_deltaX > 0.f) ? -1 : 1;
_mapFlgtNb = static_cast<unsigned>(std::abs(_deltaX / _mapShiftX));
_terrain->position().x += _mapShiftX * _signX * _mapFlgtNb;
if (_signX == 1) {
_deltaSubX += (_subToleranceX * _LODValue * _mapFlgtNb);
}
else if (_signZ == -1) {
_deltaSubX -= (_subToleranceX * _LODValue * _mapFlgtNb);
}
_needsUpdate = true;
}
if (std::abs(_deltaZ) > _mapShiftZ) {
_signZ = (_deltaZ > 0.f) ? -1 : 1;
_mapFlgtNb = static_cast<unsigned>(std::abs(_deltaZ / _mapShiftZ));
_terrain->position().z += _mapShiftZ * _signZ * _mapFlgtNb;
if (_signZ == 1) {
_deltaSubZ += (_subToleranceZ * _LODValue * _mapFlgtNb);
}
else if (_signZ == -1) {
_deltaSubZ -= (_subToleranceZ * _LODValue * _mapFlgtNb);
}
_needsUpdate = true;
}
if (_needsUpdate || _updateLOD || _updateForced) {
_deltaSubX = _mod(_deltaSubX, _mapSubX);
_deltaSubZ = _mod(_deltaSubZ, _mapSubZ);
_updateTerrain();
}
_updateForced = false;
_updateLOD = false;
_centerLocal.x = _terrainHalfSizeX;
_centerLocal.y = _terrain->position().y;
_centerLocal.z = _terrainHalfSizeZ;
_centerWorld.x = _terrain->position().x + _terrainHalfSizeX;
_centerWorld.y = _terrain->position().y;
_centerWorld.z = _terrain->position().z + _terrainHalfSizeZ;
return *this;
}
void DynamicTerrain::_updateTerrain()
{
unsigned int stepJ = 0;
unsigned int stepI = 0;
unsigned int LODLimitDown = 0;
unsigned int LODLimitUp = 0;
unsigned int LODValue = _LODValue;
unsigned int lodI = LODValue;
unsigned int lodJ = LODValue;
unsigned int l = 0;
unsigned int index = 0; // current vertex index in the map data array
unsigned int posIndex = 0; // current position index in the map data array
unsigned int colIndex = 0; // current index in the map color array
unsigned int uvIndex = 0; // current index in the map uv array
unsigned int terIndex = 0; // current vertex index in the terrain map array
// when used as a data map
unsigned int ribbonInd = 0; // current ribbon vertex index
unsigned int ribbonPosInd = 0; // current ribbon position index (same than normal index)
unsigned int ribbonUVInd = 0; // current ribbon UV index
unsigned int ribbonColInd = 0; // current ribbon color index
unsigned int ribbonPosInd1 = 0;
unsigned int ribbonPosInd2 = 0;
unsigned int ribbonPosInd3 = 0;
// note : all the indexes are explicitly set as integers for the js optimizer
// (store them all in the stack)
if (_updateLOD || _updateForced) {
updateTerrainSize();
}
Vector3::FromFloatsToRef(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(),
std::numeric_limits<float>::max(), _bbMin);
Vector3::FromFloatsToRef(std::numeric_limits<float>::lowest(),
std::numeric_limits<float>::lowest(),
std::numeric_limits<float>::lowest(), _bbMax);
for (unsigned int j = 0; j <= _terrainSub; ++j) {
// LOD Z
LODValue = _LODValue;
for (l = 0; l < _LODLimits.size(); ++l) {
LODLimitDown = _LODLimits[l];
LODLimitUp = _terrainSub - LODLimitDown - 1;
if (j < LODLimitDown || j > LODLimitUp) {
LODValue = l + 1 + _LODValue;
}
lodJ = LODValue;
}
for (unsigned int i = 0; i <= _terrainSub; ++i) {
// LOD X
LODValue = _LODValue;
for (l = 0; l < _LODLimits.size(); ++l) {
LODLimitDown = _LODLimits[l];
LODLimitUp = _terrainSub - LODLimitDown - 1;
if (i < LODLimitDown || i > LODLimitUp) {
LODValue = l + 1 + _LODValue;
}
lodI = LODValue;
}
// map current index
index = _mod(_deltaSubZ + stepJ, _mapSubZ) * _mapSubX + _mod(_deltaSubX + stepI, _mapSubX);
terIndex = _mod(_deltaSubZ + stepJ, _terrainIdx) * _terrainIdx
+ _mod(_deltaSubX + stepI, _terrainIdx);
// related index in the array of positions (data map)
if (_datamap) {
posIndex = 3 * index;
}
else {
posIndex = 3 * terIndex;
}
// related index in the UV map
if (_uvmap) {
uvIndex = 2 * index;
}
else {
uvIndex = 2 * terIndex;
}
// related index in the color map
if (_colormap) {
colIndex = 3 * index;
}
else {
colIndex = 3 * terIndex;
}
// ribbon indexes
ribbonPosInd = 3 * ribbonInd;
ribbonColInd = 4 * ribbonInd;
ribbonUVInd = 2 * ribbonInd;
ribbonPosInd1 = ribbonPosInd;
ribbonPosInd2 = ribbonPosInd + 1;
ribbonPosInd3 = ribbonPosInd + 2;
ribbonInd += 1;
// geometry
_positions[ribbonPosInd1] = _averageSubSizeX * stepI;
_positions[ribbonPosInd2] = _mapData[posIndex + 1];
_positions[ribbonPosInd3] = _averageSubSizeZ * stepJ;
if (!_computeNormals) {
_normals[ribbonPosInd1] = _mapNormals[posIndex];
_normals[ribbonPosInd2] = _mapNormals[posIndex + 1];
_normals[ribbonPosInd3] = _mapNormals[posIndex + 2];
}
// bbox internal update
if (_positions[ribbonPosInd1] < _bbMin.x) {
_bbMin.x = _positions[ribbonPosInd1];
}
if (_positions[ribbonPosInd1] > _bbMax.x) {
_bbMax.x = _positions[ribbonPosInd1];
}
if (_positions[ribbonPosInd2] < _bbMin.y) {
_bbMin.y = _positions[ribbonPosInd2];
}
if (_positions[ribbonPosInd2] > _bbMax.y) {
_bbMax.y = _positions[ribbonPosInd2];
}
if (_positions[ribbonPosInd3] < _bbMin.z) {
_bbMin.z = _positions[ribbonPosInd3];
}
if (_positions[ribbonPosInd3] > _bbMax.z) {
_bbMax.z = _positions[ribbonPosInd3];
}
// color
if (_colormap) {
_colors[ribbonColInd] = _mapColors[colIndex];
_colors[ribbonColInd + 1] = _mapColors[colIndex + 1];
_colors[ribbonColInd + 2] = _mapColors[colIndex + 2];
}
// uv : the array _mapUVs is always populated
_uvs[ribbonUVInd] = _mapUVs[uvIndex];
_uvs[ribbonUVInd + 1] = _mapUVs[uvIndex + 1];
// call to user custom function with the current updated vertex object
if (_useCustomVertexFunction) {
_vertex.position.copyFromFloats(_positions[ribbonPosInd1], _positions[ribbonPosInd2],
_positions[ribbonPosInd3]);
_vertex.worldPosition.x = _mapData[posIndex];
_vertex.worldPosition.y = _vertex.position.y;
_vertex.worldPosition.z = _mapData[posIndex + 2];
_vertex.lodX = lodI;
_vertex.lodZ = lodJ;
_vertex.color.r = _colors[ribbonColInd];
_vertex.color.g = _colors[ribbonColInd + 1];
_vertex.color.b = _colors[ribbonColInd + 2];
_vertex.color.a = _colors[ribbonColInd + 3];
_vertex.uvs.x = _uvs[ribbonUVInd];
_vertex.uvs.y = _uvs[ribbonUVInd + 1];
_vertex.mapIndex = index;
updateVertex(_vertex, i,
j); // the user can modify the array values here
_colors[ribbonColInd] = _vertex.color.r;
_colors[ribbonColInd + 1] = _vertex.color.g;
_colors[ribbonColInd + 2] = _vertex.color.b;
_colors[ribbonColInd + 3] = _vertex.color.a;
_uvs[ribbonUVInd] = _vertex.uvs.x;
_uvs[ribbonUVInd + 1] = _vertex.uvs.y;
_positions[ribbonPosInd1] = _vertex.position.x;
_positions[ribbonPosInd2] = _vertex.position.y;
_positions[ribbonPosInd3] = _vertex.position.z;
}
stepI += lodI;
}
stepI = 0;
stepJ += lodJ;
}
// ribbon update
_terrain->updateVerticesData(VertexBuffer::PositionKind, _positions, false, false);
if (_computeNormals) {
VertexData::ComputeNormals(_positions, _indices, _normals);
}
_terrain->updateVerticesData(VertexBuffer::NormalKind, _normals, false, false);
_terrain->updateVerticesData(VertexBuffer::UVKind, _uvs, false, false);
_terrain->updateVerticesData(VertexBuffer::ColorKind, _colors, false, false);
_terrain->_boundingInfo = std::make_unique<BoundingInfo>(_bbMin, _bbMax);
_terrain->_boundingInfo->update(_terrain->_worldMatrix);
}
DynamicTerrain& DynamicTerrain::updateTerrainSize()
{
unsigned int remainder = _terrainSub; // the remaining cells at the general current LOD value
unsigned int nb = 0; // nb of cells in the current LOD limit interval
unsigned int next = 0; // next cell index, if it exists
unsigned int lod; // lod value in the current LOD limit interval
float tsx = 0.0; // current sum of cell sizes on x
float tsz = 0.0; // current sum of cell sizes on z
for (unsigned int l = 0; l < _LODLimits.size(); ++l) {
lod = _LODValue + l + 1;
next = (l >= _LODLimits.size() - 1) ? 0 : _LODLimits[l + 1];
nb = 2 * (_LODLimits[l] - next);
tsx += _averageSubSizeX * lod * nb;
tsz += _averageSubSizeZ * lod * nb;
remainder -= nb;
}
tsx += remainder * _averageSubSizeX * _LODValue;
tsz += remainder * _averageSubSizeZ * _LODValue;
_terrainSizeX = tsx;
_terrainSizeZ = tsz;
_terrainHalfSizeX = tsx * 0.5f;
_terrainHalfSizeZ = tsz * 0.5f;
return *this;
}
float DynamicTerrain::getHeightFromMap(float x, float z, const Vector3& normal) const
{
return DynamicTerrain::_GetHeightFromMap(x, z, _mapData, _mapSubX, _mapSubZ, _mapSizeX, _mapSizeZ,
normal);
}
float DynamicTerrain::GetHeightFromMap(float x, float z, const Float32Array& mapData,
unsigned int mapSubX, unsigned int mapSubZ,
const Vector3& normal)
{
const float mapSizeX = std::abs(mapData[(mapSubX - 1) * 3] - mapData[0]);
const float mapSizeZ = std::abs(mapData[(mapSubZ - 1) * mapSubX * 3 + 2] - mapData[2]);
return DynamicTerrain::_GetHeightFromMap(x, z, mapData, mapSubX, mapSubZ, mapSizeX, mapSizeZ,
normal);
}
float DynamicTerrain::_GetHeightFromMap(float x, float z, const Float32Array& mapData,
unsigned int mapSubX, unsigned int mapSubZ, float mapSizeX,
float mapSizeZ, const Vector3& normal)
{
const float x0 = mapData[0];
const float z0 = mapData[2];
// reset x and z in the map space so they are between 0 and the axis map size
x = x - std::floor((x - x0) / mapSizeX) * mapSizeX;
z = z - std::floor((z - z0) / mapSizeZ) * mapSizeZ;
const auto col1 = static_cast<unsigned>(std::floor((x - x0) * mapSubX / mapSizeX));
const auto row1 = static_cast<unsigned>(std::floor((z - z0) * mapSubZ / mapSizeZ));
const unsigned int col2 = (col1 + 1) % mapSubX;
const unsigned int row2 = (row1 + 1) % mapSubZ;
// starting indexes of the positions of 4 vertices defining a quad on the map
const unsigned int idx1 = 3 * (row1 * mapSubX + col1);
const unsigned int idx2 = 3 * (row1 * mapSubX + col2);
const unsigned int idx3 = 3 * ((row2)*mapSubX + col1);
const unsigned int idx4 = 3 * ((row2)*mapSubX + col2);
DynamicTerrain::_v1.copyFromFloats(mapData[idx1], mapData[idx1 + 1], mapData[idx1 + 2]);
DynamicTerrain::_v2.copyFromFloats(mapData[idx2], mapData[idx2 + 1], mapData[idx2 + 2]);
DynamicTerrain::_v3.copyFromFloats(mapData[idx3], mapData[idx3 + 1], mapData[idx3 + 2]);
DynamicTerrain::_v4.copyFromFloats(mapData[idx4], mapData[idx4 + 1], mapData[idx4 + 2]);
Vector3 vA = DynamicTerrain::_v1;
Vector3 vB;
Vector3 vC;
Vector3 v;
const float xv4v1 = DynamicTerrain::_v4.x - DynamicTerrain::_v1.x;
const float zv4v1 = DynamicTerrain::_v4.z - DynamicTerrain::_v1.z;
if (stl_util::almost_equal(xv4v1, 0.f) || stl_util::almost_equal(zv4v1, 0.f)) {
return DynamicTerrain::_v1.y;
}
const float cd = zv4v1 / xv4v1;
const float h = DynamicTerrain::_v1.z - cd * DynamicTerrain::_v1.x;
if (z < cd * x + h) {
vB = DynamicTerrain::_v4;
vC = DynamicTerrain::_v2;
v = vA;
}
else {
vB = DynamicTerrain::_v3;
vC = DynamicTerrain::_v4;
v = vB;
}
vB.subtractToRef(vA, DynamicTerrain::_vAvB);
vC.subtractToRef(vA, DynamicTerrain::_vAvC);
Vector3::CrossToRef(DynamicTerrain::_vAvB, DynamicTerrain::_vAvC, DynamicTerrain::_norm);
DynamicTerrain::_norm.normalize();
if (normal != Vector3::Zero()) {
auto tmpVector = normal;
tmpVector.copyFrom(DynamicTerrain::_norm);
}
const float d = -(DynamicTerrain::_norm.x * v.x + DynamicTerrain::_norm.y * v.y
+ DynamicTerrain::_norm.z * v.z);
float y = v.y;
if (!stl_util::almost_equal(DynamicTerrain::_norm.y, 0.f)) {
y = -(DynamicTerrain::_norm.x * x + DynamicTerrain::_norm.z * z + d) / DynamicTerrain::_norm.y;
}
return y;
}
void DynamicTerrain::ComputeNormalsFromMapToRef(const Float32Array& mapData, unsigned int mapSubX,
unsigned int mapSubZ, Float32Array& normals)
{
Uint32Array mapIndices;
auto tmp1Normal = Vector3::Zero();
auto tmp2Normal = Vector3::Zero();
unsigned int l = mapSubX * (mapSubZ - 1);
for (unsigned int i = 0; i < l; i++) {
stl_util::concat(mapIndices, {i + 1, i + mapSubX, i});
stl_util::concat(mapIndices, {i + mapSubX, i + 1, i + mapSubX + 1});
}
VertexData::ComputeNormals(mapData, mapIndices, normals);
// seam process
unsigned int lastIdx = (mapSubX - 1) * 3;
unsigned int colStart = 0;
unsigned int colEnd = 0;
for (unsigned int i = 0; i < mapSubZ; ++i) {
colStart = i * mapSubX * 3;
colEnd = colStart + lastIdx;
DynamicTerrain::GetHeightFromMap(mapData[colStart], mapData[colStart + 2], mapData, mapSubX,
mapSubZ, tmp1Normal);
DynamicTerrain::GetHeightFromMap(mapData[colEnd], mapData[colEnd + 2], mapData, mapSubX,
mapSubZ, tmp2Normal);
tmp1Normal.addInPlace(tmp2Normal).scaleInPlace(0.5f);
normals[colStart] = tmp1Normal.x;
normals[colStart + 1] = tmp1Normal.y;
normals[colStart + 2] = tmp1Normal.z;
normals[colEnd] = tmp1Normal.x;
normals[colEnd + 1] = tmp1Normal.y;
normals[colEnd + 2] = tmp1Normal.z;
}
}
DynamicTerrain& DynamicTerrain::computeNormalsFromMap()
{
DynamicTerrain::ComputeNormalsFromMapToRef(_mapData, _mapSubX, _mapSubZ, _mapNormals);
return *this;
}
bool DynamicTerrain::contains(float x, float z)
{
if (x < _positions[0] + mesh()->position().x
|| x > _positions[3 * _terrainIdx] + mesh()->position().x) {
return false;
}
if (z < _positions[2] + mesh()->position().z
|| z > _positions[3 * _terrainIdx * _terrainIdx + 2] + mesh()->position().z) {
return false;
}
return true;
}
Float32Array DynamicTerrain::CreateMapFromHeightMap(const std::string& heightmapURL,
const HeightMapOptions& options, Scene* scene)
{
const auto subX = options.subX;
const auto subZ = options.subZ;
Float32Array data(subX * subZ * 3);
DynamicTerrain::CreateMapFromHeightMapToRef(heightmapURL, options, data, scene);
return data;
}
void DynamicTerrain::CreateMapFromHeightMapToRef(const std::string& heightmapURL,
const HeightMapOptions& options,
Float32Array& data, Scene* /*scene*/)
{
const auto& width = options.width;
const auto& height = options.height;
const auto& subX = options.subX;
const auto& subZ = options.subZ;
const auto& minHeight = options.minHeight;
const auto& maxHeight = options.maxHeight;
const auto& offsetX = options.offsetX;
const auto& offsetZ = options.offsetZ;
const auto& filter = options.colorFilter;
const auto& onReady = options.onReady;
const auto onload = [&](const Image& img) {
// Getting height map data
// var canvas = document.createElement("canvas");
// var context = canvas.getContext("2d");
int bufferWidth = img.width;
int bufferHeight = img.height;
// canvas.width = bufferWidth;
// canvas.height = bufferHeight;
// context.drawImage(img, 0, 0);
// Cast is due to wrong definition in lib.d.ts from ts 1.3 -
// https://github.com/Microsoft/TypeScript/issues/949
// var buffer = <Uint8Array>(<any>context.getImageData(0, 0, bufferWidth,
// bufferHeight).data);
const Uint8Array& buffer = img.data;
float x = 0.0;
float y = 0.0;
float z = 0.0;
for (unsigned int row = 0; row < subZ; row++) {
for (unsigned int col = 0; col < subX; col++) {
x = col * width / subX - width * 0.5f;
z = row * height / subZ - height * 0.5f;
float heightmapX = ((x + width * 0.5f) / width * (bufferWidth - 1));
float heightmapY = (bufferHeight - 1) - ((z + height * 0.5f) / height * (bufferHeight - 1));
unsigned int pos = static_cast<unsigned>(heightmapX + heightmapY * bufferWidth) * 4;
float gradient
= (buffer[pos] * filter.r + buffer[pos + 1] * filter.g + buffer[pos + 2] * filter.b)
/ 255.f;
y = minHeight + (maxHeight - minHeight) * gradient;
unsigned int idx = (row * subX + col) * 3;
data[idx] = x + offsetX;
data[idx + 1] = y;
data[idx + 2] = z + offsetZ;
}
}
// callback function if any
if (onReady) {
onReady(data, subX, subZ);
}
};
const auto onError = [](const std::string& msg, const std::string& /*exception*/) {
BABYLON_LOG_ERROR("Tools", msg)
};
FileTools::LoadImageFromUrl(heightmapURL, onload, onError);
}
void DynamicTerrain::CreateUVMapToRef(float subX, float subZ, Float32Array& mapUVs)
{
for (float h = 0; h < subZ; h++) {
for (float w = 0; w < subX; w++) {
mapUVs[static_cast<std::size_t>(h * subX + w) * 2] = w / subX;
mapUVs[static_cast<std::size_t>(h * subX + w) * 2 + 1] = h / subZ;
}
}
}
Float32Array DynamicTerrain::CreateUVMap(float subX, float subZ)
{
Float32Array mapUVs(static_cast<std::size_t>(subX * subZ * 2));
DynamicTerrain::CreateUVMapToRef(subX, subZ, mapUVs);
return mapUVs;
}
/**
* Computes and sets the terrain UV map with values to fit the whole map.
* Returns the terrain.
*/
DynamicTerrain& DynamicTerrain::createUVMap()
{
setMapUVs(
DynamicTerrain::CreateUVMap(static_cast<float>(_mapSubX), static_cast<float>(_mapSubZ)));
return *this;
}
bool DynamicTerrain::refreshEveryFrame() const
{
return _refreshEveryFrame;
}
void DynamicTerrain::setRefreshEveryFrame(bool val)
{
_refreshEveryFrame = val;
}
MeshPtr& DynamicTerrain::mesh()
{
return _terrain;
}
CameraPtr& DynamicTerrain::camera()
{
return _terrainCamera;
}
void DynamicTerrain::setCamera(const CameraPtr& val)
{
_terrainCamera = val;
}
unsigned int DynamicTerrain::subToleranceX() const
{
return _subToleranceX;
}
void DynamicTerrain::setSubToleranceX(unsigned int val)
{
_subToleranceX = (val > 0) ? val : 1;
}
unsigned int DynamicTerrain::subToleranceZ() const
{
return _subToleranceZ;
}
void DynamicTerrain::setSubToleranceZ(unsigned int val)
{
_subToleranceZ = (val > 0) ? val : 1;
}
unsigned int DynamicTerrain::initialLOD() const
{
return _initialLOD;
}
void DynamicTerrain::setInitialLOD(unsigned int val)
{
_initialLOD = (val > 0) ? val : 1;
}
unsigned int DynamicTerrain::LODValue() const
{
return _LODValue;
}
unsigned int DynamicTerrain::cameraLODCorrection() const
{
return _cameraLODCorrection;
}
void DynamicTerrain::setCameraLODCorrection(unsigned int val)
{
_cameraLODCorrection = val;
}
float DynamicTerrain::averageSubSizeX() const
{
return _averageSubSizeX;
}
float DynamicTerrain::averageSubSizeZ() const
{
return _averageSubSizeZ;
}
float DynamicTerrain::terrainSizeX() const
{
return _terrainSizeX;
}
float DynamicTerrain::terrainHalfSizeX() const
{
return _terrainHalfSizeX;
}
float DynamicTerrain::terrainSizeZ() const
{
return _terrainSizeZ;
}
float DynamicTerrain::terrainHalfSizeZ()
{
return _terrainHalfSizeZ;
}
const Vector3& DynamicTerrain::centerLocal() const
{
return _centerLocal;
}
const Vector3& DynamicTerrain::centerWorld() const
{
return _centerWorld;
}
const Uint32Array& DynamicTerrain::LODLimits() const
{
return _LODLimits;
}
void DynamicTerrain::LODLimits(Uint32Array ar)
{
std::sort(ar.begin(), ar.end(), std::greater<std::uint32_t>());
_LODLimits = std::move(ar);
}
const Float32Array& DynamicTerrain::mapData() const
{
return _mapData;
}
void DynamicTerrain::setMapData(const Float32Array& val)
{
_mapData = val;
_datamap = true;
_mapSizeX = std::abs(_mapData[(_mapSubX - 1) * 3] - _mapData[0]);
_mapSizeZ = std::abs(_mapData[(_mapSubZ - 1) * _mapSubX * 3 + 2] - _mapData[2]);
_averageSubSizeX = _mapSizeX / _mapSubX;
_averageSubSizeZ = _mapSizeZ / _mapSubZ;
if (_precomputeNormalsFromMap) {
computeNormalsFromMap();
}
update(true);
}
unsigned int DynamicTerrain::mapSubX() const
{
return _mapSubX;
}
void DynamicTerrain::setMapSubX(unsigned int val)
{
_mapSubX = val;
}
unsigned int DynamicTerrain::mapSubZ() const
{
return _mapSubZ;
}
void DynamicTerrain::setMapSubZ(unsigned int val)
{
_mapSubZ = val;
}
const Float32Array& DynamicTerrain::mapColors() const
{
return _mapColors;
}
void DynamicTerrain::setMapColors(const Float32Array& val)
{
_colormap = true;
_mapColors = val;
}
const Float32Array& DynamicTerrain::mapUVs() const
{
return _mapUVs;
}
void DynamicTerrain::setMapUVs(const Float32Array& val)
{
_uvmap = true;
_mapUVs = val;
}
const Float32Array& DynamicTerrain::mapNormals() const
{
return _mapNormals;
}
void DynamicTerrain::setMapNormals(const Float32Array& val)
{
_mapNormals = val;
}
bool DynamicTerrain::computeNormals() const
{
return _computeNormals;
}
void DynamicTerrain::setComputeNormals(bool val)
{
_computeNormals = val;
}
bool DynamicTerrain::useCustomVertexFunction() const
{
return _useCustomVertexFunction;
}
void DynamicTerrain::useCustomVertexFunction(bool val)
{
_useCustomVertexFunction = val;
}
bool DynamicTerrain::isAlwaysVisible() const
{
return _isAlwaysVisible;
}
void DynamicTerrain::setIsAlwaysVisible(bool val)
{
mesh()->alwaysSelectAsActiveMesh = val;
_isAlwaysVisible = val;
}
bool DynamicTerrain::precomputeNormalsFromMap() const
{
return _precomputeNormalsFromMap;
}
void DynamicTerrain::setPrecomputeNormalsFromMap(bool val)
{
_precomputeNormalsFromMap = val;
}
void DynamicTerrain::updateVertex(DynamicTerrainVertex& /*vertex*/, unsigned int /*i*/,
unsigned /*j*/)
{
}
unsigned int DynamicTerrain::updateCameraLOD(const CameraPtr& /*terrainCamera*/)
{
// LOD value increases with camera altitude
unsigned int camLOD = 0;
return camLOD;
}
void DynamicTerrain::beforeUpdate(bool /*refreshEveryFrame*/)
{
}
void DynamicTerrain::afterUpdate(bool /*refreshEveryFrame*/)
{
}
} // end of namespace Extensions
} // end of namespace BABYLON
| 32,447 | 11,862 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <ostream>
#include <set>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/cxx20_erase.h"
#include "base/macros.h"
#include "base/strings/string_util.h"
#include "chrome/browser/ash/login/existing_user_controller.h"
#include "chrome/browser/ash/login/session/user_session_manager.h"
#include "chrome/browser/ash/login/session/user_session_manager_test_api.h"
#include "chrome/browser/ash/login/test/device_state_mixin.h"
#include "chrome/browser/ash/login/test/fake_gaia_mixin.h"
#include "chrome/browser/ash/login/test/login_manager_mixin.h"
#include "chrome/browser/ash/login/test/oobe_base_test.h"
#include "chrome/browser/ash/login/test/session_manager_state_waiter.h"
#include "chrome/browser/ash/login/test/user_policy_mixin.h"
#include "chrome/browser/ash/login/ui/login_display_host.h"
#include "chrome/browser/ash/login/users/chrome_user_manager_impl.h"
#include "chrome/browser/ash/login/wizard_controller.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/site_isolation/about_flags.h"
#include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chromeos/cryptohome/cryptohome_parameters.h"
#include "chromeos/dbus/session_manager/fake_session_manager_client.h"
#include "chromeos/settings/cros_settings_names.h"
#include "components/flags_ui/pref_service_flags_storage.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/session_manager/core/session_manager.h"
#include "components/session_manager/core/session_manager_observer.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/switches/chrome_switches.h"
namespace policy {
namespace {
namespace em = ::enterprise_management;
struct Params {
Params(std::string login_screen_isolate_origins,
std::string user_policy_isolate_origins,
bool user_policy_site_per_process,
std::vector<std::string> user_flag_internal_names,
bool ephemeral_users,
bool expected_request_restart,
std::vector<std::string> expected_switches_for_user,
std::vector<std::string> expected_isolated_origins = {})
: login_screen_isolate_origins(login_screen_isolate_origins),
user_policy_isolate_origins(user_policy_isolate_origins),
user_policy_site_per_process(user_policy_site_per_process),
user_flag_internal_names(std::move(user_flag_internal_names)),
ephemeral_users(ephemeral_users),
expected_request_restart(expected_request_restart),
expected_switches_for_user(expected_switches_for_user),
expected_isolated_origins(expected_isolated_origins) {}
friend std::ostream& operator<<(std::ostream& os, const Params& p) {
os << "{" << std::endl
<< " login_screen_isolate_origins: " << p.login_screen_isolate_origins
<< std::endl
<< " user_policy_site_per_process: " << p.user_policy_site_per_process
<< std::endl
<< " user_policy_isolate_origins: " << p.user_policy_isolate_origins
<< std::endl
<< " user_flag_internal_names: "
<< base::JoinString(p.user_flag_internal_names, ", ") << std::endl
<< " ephemeral_users: " << p.ephemeral_users << std::endl
<< " expected_request_restart: " << p.expected_request_restart
<< std::endl
<< " expected_switches_for_user: "
<< base::JoinString(p.expected_switches_for_user, ", ") << std::endl
<< " expected_isolated_origins: "
<< base::JoinString(p.expected_isolated_origins, ", ") << std::endl
<< "}";
return os;
}
// If non-empty, --isolate-origins=|login_screen_isolate_origins| will be
// passed to the login manager chrome instance between policy flag sentinels.
// Note: On Chrome OS, login_manager evaluates device policy and does this.
std::string login_screen_isolate_origins;
// If non-empty, the IsolateOrigins user policy will be simulated to be set
// |user_policy_isolate_origins|.
std::string user_policy_isolate_origins;
// If true, the SitePerProcess user policy will be simulated to be set to
// true.
bool user_policy_site_per_process;
std::vector<std::string> user_flag_internal_names;
// If true, ephemeral users are enabled.
bool ephemeral_users;
// If true, the test case will expect that AttemptRestart has been called by
// UserSessionManager.
bool expected_request_restart;
// When a restart was requested, the test case verifies that the flags passed
// to |SessionManagerClient::SetFlagsForUser| match
// |expected_switches_for_user|.
std::vector<std::string> expected_switches_for_user;
// List of origins that should be isolated (via policy or via cmdline flag).
std::vector<std::string> expected_isolated_origins;
};
// Defines the test cases that will be executed.
const Params kTestCases[] = {
// 0. No site isolation in device or user policy - no restart expected.
Params(std::string() /* login_screen_isolate_origins */,
std::string() /* user_policy_isolate_origins */,
false /* user_policy_site_per_process */,
{} /* user_flag_internal_names */,
false /* ephemeral_users */,
false /* expected_request_restart */,
{} /* expected_switches_for_user */),
// 1. SitePerProcess opt-out through about://flags - restart expected.
Params(
std::string() /* login_screen_isolate_origins */,
std::string() /* user_policy_isolate_origins */,
false /* user_policy_site_per_process */,
/* user_flag_internal_names */
{about_flags::SiteIsolationTrialOptOutChoiceEnabled()},
false /* ephemeral_users */,
true /* expected_request_restart */,
{"--disable-site-isolation-trials"} /* expected_switches_for_user */),
// 2. SitePerProcess forced through user policy - opt-out through
// about://flags entry expected to be ignored.
Params(std::string() /* login_screen_isolate_origins */,
std::string() /* user_policy_isolate_origins */,
true /* user_policy_site_per_process */,
/* user_flag_internal_names */
{about_flags::SiteIsolationTrialOptOutChoiceEnabled()},
false /* ephemeral_users */,
false /* expected_request_restart */,
{} /* expected_switches_for_user */),
// 3. IsolateOrigins in user policy only - no restart expected, because
// IsolateOrigins from the user policy should be picked up by
// SiteIsolationPrefsObserver (without requiring injection of the
// --isolate-origins cmdline switch).
Params(std::string() /* login_screen_isolate_origins */,
"https://example.com" /* user_policy_isolate_origins */,
false /* user_policy_site_per_process */,
{} /* user_flag_internal_names */,
false /* ephemeral_users */,
false /* expected_request_restart */,
{} /* expected_switches_for_user */,
{"https://example.com"} /* expected_isolated_origins */)};
class SiteIsolationFlagHandlingTest
: public ash::OobeBaseTest,
public ::testing::WithParamInterface<Params> {
public:
SiteIsolationFlagHandlingTest(const SiteIsolationFlagHandlingTest&) = delete;
SiteIsolationFlagHandlingTest& operator=(
const SiteIsolationFlagHandlingTest&) = delete;
protected:
SiteIsolationFlagHandlingTest()
: account_id_(AccountId::FromUserEmailGaiaId("username@examle.com",
"1111111111")) {}
void SetUpInProcessBrowserTestFixture() override {
chromeos::SessionManagerClient::InitializeFakeInMemory();
// Mark that chrome restart can be requested.
// Note that AttemptRestart() is mocked out in UserSessionManager through
// |SetAttemptRestartClosureInTests| (set up in SetUpOnMainThread).
ash::FakeSessionManagerClient::Get()->set_supports_browser_restart(true);
std::unique_ptr<ash::ScopedDevicePolicyUpdate> update =
device_state_.RequestDevicePolicyUpdate();
update->policy_payload()
->mutable_ephemeral_users_enabled()
->set_ephemeral_users_enabled(GetParam().ephemeral_users);
update.reset();
std::unique_ptr<ash::ScopedUserPolicyUpdate> user_policy_update =
user_policy_.RequestPolicyUpdate();
if (GetParam().user_policy_site_per_process) {
user_policy_update->policy_payload()
->mutable_siteperprocess()
->mutable_policy_options()
->set_mode(em::PolicyOptions::MANDATORY);
user_policy_update->policy_payload()->mutable_siteperprocess()->set_value(
true);
}
if (!GetParam().user_policy_isolate_origins.empty()) {
user_policy_update->policy_payload()
->mutable_isolateorigins()
->mutable_policy_options()
->set_mode(em::PolicyOptions::MANDATORY);
user_policy_update->policy_payload()->mutable_isolateorigins()->set_value(
GetParam().user_policy_isolate_origins);
}
user_policy_update.reset();
OobeBaseTest::SetUpInProcessBrowserTestFixture();
}
void SetUpOnMainThread() override {
fake_gaia_.SetupFakeGaiaForLogin(account_id_.GetUserEmail(),
account_id_.GetGaiaId(),
ash::FakeGaiaMixin::kFakeRefreshToken);
OobeBaseTest::SetUpOnMainThread();
// Mock out chrome restart.
ash::test::UserSessionManagerTestApi session_manager_test_api(
ash::UserSessionManager::GetInstance());
session_manager_test_api.SetAttemptRestartClosureInTests(
base::BindRepeating(
&SiteIsolationFlagHandlingTest::AttemptRestartCalled,
base::Unretained(this)));
// Observe for user session start.
user_session_started_observer_ =
std::make_unique<ash::SessionStateWaiter>();
}
ash::ChromeUserManagerImpl* GetChromeUserManager() const {
return static_cast<ash::ChromeUserManagerImpl*>(
user_manager::UserManager::Get());
}
bool HasAttemptRestartBeenCalled() const { return attempt_restart_called_; }
// Called when chrome requests a restarted.
void AttemptRestartCalled() {
user_session_started_observer_.reset();
attempt_restart_called_ = true;
}
void LogIn() {
// Start user sign-in. We can't use |LoginPolicyTestBase::LogIn|, because
// it waits for a user session start unconditionally, which will not happen
// if chrome requests a restart to set user-session flags.
ash::WizardController::SkipPostLoginScreensForTesting();
OobeBaseTest::WaitForSigninScreen();
login_manager_.LoginWithDefaultContext(user_);
// Wait for either the user session to start, or for restart to be requested
// (whichever happens first).
user_session_started_observer_->Wait();
}
const AccountId account_id_;
// This will be set to |true| when chrome has requested a restart.
bool attempt_restart_called_ = false;
// This is important because ephemeral users only work on enrolled machines.
ash::DeviceStateMixin device_state_{
&mixin_host_,
ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED};
ash::UserPolicyMixin user_policy_{&mixin_host_, account_id_};
const ash::LoginManagerMixin::TestUserInfo user_{account_id_};
ash::LoginManagerMixin login_manager_{&mixin_host_, {user_}};
ash::FakeGaiaMixin fake_gaia_{&mixin_host_};
// Observes for user session start.
std::unique_ptr<ash::SessionStateWaiter> user_session_started_observer_;
};
} // namespace
IN_PROC_BROWSER_TEST_P(SiteIsolationFlagHandlingTest, PRE_FlagHandlingTest) {
LogIn();
if (!GetParam().user_flag_internal_names.empty()) {
Profile* profile = chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(
user_manager::UserManager::Get()->GetActiveUser());
ASSERT_TRUE(profile);
flags_ui::PrefServiceFlagsStorage flags_storage(profile->GetPrefs());
std::set<std::string> flags_to_set;
for (const std::string& flag_to_set : GetParam().user_flag_internal_names)
flags_to_set.insert(flag_to_set);
EXPECT_TRUE(flags_storage.SetFlags(flags_to_set));
flags_storage.CommitPendingWrites();
}
}
IN_PROC_BROWSER_TEST_P(SiteIsolationFlagHandlingTest, FlagHandlingTest) {
// Skip tests where expected_request_restart is true.
// See crbug.com/990817 for more details.
if (GetParam().expected_request_restart)
return;
// Log in and wait for either the user session to start, or for the restart
// to be requested (whichever happens first).
LogIn();
EXPECT_EQ(GetParam().expected_request_restart, HasAttemptRestartBeenCalled());
// Verify that expected origins are isolated...
auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
for (const std::string& origin_str : GetParam().expected_isolated_origins) {
url::Origin origin = url::Origin::Create(GURL(origin_str));
EXPECT_TRUE(policy->IsGloballyIsolatedOriginForTesting(origin));
}
if (!HasAttemptRestartBeenCalled())
return;
// Also verify flags if chrome was restarted.
std::vector<std::string> switches_for_user;
bool has_switches_for_user =
ash::FakeSessionManagerClient::Get()->GetFlagsForUser(
cryptohome::CreateAccountIdentifierFromAccountId(account_id_),
&switches_for_user);
EXPECT_TRUE(has_switches_for_user);
// Remove flag sentinels. Keep whatever is between those sentinels, to
// verify that we don't pass additional parameters in there.
base::EraseIf(switches_for_user, [](const std::string& flag) {
return flag == "--flag-switches-begin" || flag == "--flag-switches-end";
});
EXPECT_EQ(GetParam().expected_switches_for_user, switches_for_user);
}
INSTANTIATE_TEST_SUITE_P(All,
SiteIsolationFlagHandlingTest,
::testing::ValuesIn(kTestCases));
} // namespace policy
| 14,696 | 4,658 |
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and
* others. For conditions of distribution and use see copyright notice in license.txt */
/*lines_continuum put energetics, H, and He lines into line intensity stack */
#include "cddefines.h"
#include "taulines.h"
#include "iso.h"
#include "geometry.h"
#include "heavy.h"
#include "dense.h"
#include "prt.h"
#include "opacity.h"
#include "coolheavy.h"
#include "phycon.h"
#include "rfield.h"
#include "predcont.h"
#include "radius.h"
#include "continuum.h"
#include "lines.h"
#include "freebound.h"
#include "lines_service.h"
void lines_continuum(void)
{
double f1,
f2 ,
bac ,
flow;
long i,nBand;
DEBUG_ENTRY( "lines_continuum()" );
/* code has all local emissivities zeroed out with cryptic comment about being
* situation dependent. Why? this is option to turn back on */
const bool KILL_CONT = false;
i = StuffComment( "continua" );
linadd( 0., (realnum)i , "####", 'i',
" start continua");
/* these entries only work correctly if the APERTURE command is not in effect */
if( geometry.iEmissPower == 2 )
{
/***********************************************************************
* stuff in Bac ratio - continuum above the Balmer Jump
* this is trick, zeroing out saved continuum integrated so far,
* and adding the current version, so that the line array gives the
* value in the final continuum
*
* reflected continuum is different from others since relative to inner
* radius, others for for this radius
*************************************************************************/
/** \todo 2 this block of lines should have nInu, InwT, InwC like main vector of continuum points */
/***************************************************************************
* "Bac " , 3646, this is residual continuum at peak of Balmer Jump
* flux below - flux above
***************************************************************************/
/* >>chng 00 dec 02, remove opac.tmn */
/* >>chng 00 dec 19, remove / radius.GeoDil */
/* extrapolated continuum above head */
/* >>chng 01 jul 13, from ConInterOut to ConEmitOut */
f1 = (rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1] +
rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/radius.r1r0sq )/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1);
/* extrapolated continuum below head */
/* >>chng 00 dec 19, remove / radius.GeoDil */
f2 = (rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]+
rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/radius.r1r0sq )/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2);
/* convert to nuFnu units */
f1 = f1*0.250*0.250*EN1RYD*radius.r1r0sq;
f2 = f2*0.250*0.250*EN1RYD*radius.r1r0sq;
bac = (f1 - f2);
/* memory not allocated until ipass >= 0
* clear summed intrinsic and emergent intensity of following
* entry - following call to linadd will enter the total and
* keep entering the total but is done for each zone hence need to
* keep resetting to zero*/
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd(MAX2(0.,bac)/radius.dVeffAper,3646,"Bac ",'i',
"residual flux at head of Balmer continuum, nuFnu ");
/* >>chng 03 feb 06, set to zero */
/* emslin saves the per unit vol emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity which was set
* FOR THE PREVIOUS LINE since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/* memory not allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd(f1/radius.dVeffAper,3645,"nFnu",'i',
"total flux above head of Balmer continuum, nuFnu ");
/* >>chng 03 feb 06, set to zero */
/* emslin saves the per unit vol emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity which was set
* FOR THE PREVIOUS LINE since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/* memory not allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd(f2/radius.dVeffAper,3647,"nFnu",'i',
"total flux above head of Balmer continuum, nuFnu ");
/* >>chng 03 feb 06, set to zero */
/* emslin saves the per unit vol emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity which was set
* FOR THE PREVIOUS LINE since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/******************************************************************************
* "cout" , 3646, this is outward residual continuum at peak of Balmer Jump *
* equal to total in spherical geometry, half in opt thin open geometry *
******************************************************************************/
/* >>chng 00 dec 02, remove opac.tmn */
/* >>chng 00 dec 19, remove / radius.GeoDil */
f1 = rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1);
/* >>chng 00 dec 19, remove / radius.GeoDil */
f2 = rfield.ConEmitOut[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2);
/* net Balmer jump */
bac = (f1 - f2)*0.250*0.250*EN1RYD*radius.r1r0sq;
/* memory not allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd(MAX2(0.,bac)/radius.dVeffAper,3646,"cout",'i',
"residual flux in Balmer continuum, nuFnu ");
/* >>chng 03 feb 06, set to zero */
/* emslin saves the per unit vol emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity which was set
* FOR THE PREVIOUS LINE since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/*********************************************************************
* "cref" , 3646, this is reflected continuum at peak of Balmer Jump*
* equal to zero in spherical geometry, half of total in op thin opn *
*********************************************************************/
/* >>chng 00 dec 02, remove opac.tmn */
/* >>chng 00 dec 19, remove / radius.GeoDil */
f1 = rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1);
f2 = rfield.ConEmitReflec[0][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2);
/* net Balmer jump */
bac = (f1 - f2)*0.250*0.250*EN1RYD;
/* memory not allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd(MAX2(0.,bac)/radius.dVeffAper,3646,"cref",'i',
"residual flux in Balmer continuum, nuFnu ");
/* >>chng 03 feb 06, set to zero */
/* emslin saves the per unit vol emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity which was set
* FOR THE PREVIOUS LINE since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/*********************************************************************
* "thin" , 3646, tot optically thin continuum at peak of Balmer Jump*/
if( nzone > 0 )
{
/* rfield.ConEmitLocal is not defined initially, only evaluate when into model */
f1 = rfield.ConEmitLocal[nzone][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1]/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-1);
f2 = rfield.ConEmitLocal[nzone][iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2]/
rfield.widflx(iso_sp[ipH_LIKE][ipHYDROGEN].fb[2].ipIsoLevNIonCon-2);
}
else
{
f1 = 0.;
f2 = 0.;
}
bac = (f1 - f2)*0.250*0.250*EN1RYD;
linadd(MAX2(0.,bac),3646,"thin",'i',
"residual flux in Balmer continuum, nuFnu ");
linadd(continuum.cn4861/radius.dVeffAper,4860,"Inci",'i',
"incident continuum nu*f_nu at H-beta, at illuminated face of cloud ");
linadd(continuum.cn1367/radius.dVeffAper,1367,"Inci",'i',
"incident continuum nu*f_nu in FUV 1367A but out of Lya damping wings, at illuminated face of cloud");
linadd(continuum.cn2066/radius.dVeffAper,2066,"Inci",'i',
"incident continuum nu*f_nu in FUV 2066A at illuminated face of cloud");
linadd(continuum.cn1216/radius.dVeffAper,1215,"Inci",'i',
"incident continuum nu*f_nu near Ly-alpha, at illuminated face of cloud");
if( LineSave.ipass > 0 )
{
continuum.cn4861 = 0.;
continuum.cn1216 = 0.;
continuum.cn1367 = 0.;
continuum.cn2066 = 0.;
}
}
flow = (iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH2p].RadRecomb[ipRecRad] +
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH2s].RadRecomb[ipRecRad])*
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH2p].RadRecomb[ipRecEsc]*
dense.eden*dense.xIonDense[ipHYDROGEN][1]* 5.45e-12;
linadd(flow,0,"Ba C",'i',
"integrated Balmer continuum emission");
if( iso_sp[ipH_LIKE][ipHYDROGEN].n_HighestResolved_max >= 3 )
{
flow = ( iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3s].RadRecomb[ipRecRad]*
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3s].RadRecomb[ipRecEsc] +
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3p].RadRecomb[ipRecRad]*
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3p].RadRecomb[ipRecEsc] +
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3d].RadRecomb[ipRecRad]*
iso_sp[ipH_LIKE][ipHYDROGEN].fb[ipH3d].RadRecomb[ipRecEsc] ) *
dense.eden*dense.xIonDense[ipHYDROGEN][1]*3.53e-12;
}
else
{
flow = iso_sp[ipH_LIKE][ipHYDROGEN].fb[3].RadRecomb[ipRecRad]*
iso_sp[ipH_LIKE][ipHYDROGEN].fb[3].RadRecomb[ipRecEsc]*
dense.eden*dense.xIonDense[ipHYDROGEN][1]*3.53e-12;
}
linadd(flow,0,"PA C",'i',
"Paschen continuum emission ");
/* these are a series of continuum bands defined in the file
* continuum_bands.ini - this makes it possible to enter any
* integrated total emission into the emission-line stack */
/* these entries only work correctly if the APERTURE command is not in effect */
if( geometry.iEmissPower == 2 )
{
for( nBand=0; nBand < continuum.nContBand; ++nBand )
{
double EmergentContinuum = 0.;
double DiffuseEmission = 0.;
if( LineSave.ipass > 0 )
{
/* find total emission over band - units will be erg cm-2 s-1 */
for( i=continuum.ipContBandLow[nBand]; i<=continuum.ipContBandHi[nBand]; ++i )
{
// correction for fraction of low or hi cell
// that lies within the band
double EdgeCorrection = 1.;
if( i==continuum.ipContBandLow[nBand] )
EdgeCorrection = continuum.BandEdgeCorrLow[nBand];
else if( i==continuum.ipContBandHi[nBand])
EdgeCorrection = continuum.BandEdgeCorrHi[nBand];
double xIntenOut =
/* the attenuated incident continuum */
flux_correct_isotropic( 0, i-1 ) +
// the outward emitted continuous radiation field
(rfield.ConEmitOut[0][i-1] +
/* outward emitted lines */
rfield.outlin[0][i-1])*geometry.covgeo;
xIntenOut *= EdgeCorrection;
/* div by opac.E2TauAbsFace[i] because ConEmitReflec has already
* been corrected for this - emergent_line will introduce a
* further correction so this will cancel the extra factor */
/* NB: Comparison to 1e-37 suppresses overflows when realnum
* is double (FLT_IS_DBL). */
double xIntenIn = 0.;
if( opac.E2TauAbsFace[i-1] > 1e-37 )
xIntenIn = (double)rfield.ConEmitReflec[0][i-1]/
(double)opac.E2TauAbsFace[i-1]*geometry.covgeo;
/* outward emitted lines */
xIntenIn += rfield.reflin[0][i-1]*geometry.covgeo;
xIntenIn *= EdgeCorrection;
/* the fraction of this that gets out */
EmergentContinuum += rfield.anu(i-1) *
emergent_line( xIntenIn , xIntenOut , i )
/ SDIV(opac.tmn[i-1]);
// diffuse local emission
DiffuseEmission += (rfield.ConEmitLocal[nzone][i-1] +
rfield.DiffuseLineEmission[i-1])*rfield.anu(i-1)*
EdgeCorrection;
}
}
/* we will call lindst with an energy half way between the two
* ends of the band. This will make an extinction correction that
* has already been applied above by multiplying by emergent_line.
* Find this factor and remove it before the call */
double corr = emergent_line( 0.5 , 0.5 ,
(continuum.ipContBandLow[nBand]+continuum.ipContBandHi[nBand])/2 );
/* NB: Comparison to 1e-37 suppresses overflows when realnum
* is double (FLT_IS_DBL). */
if( corr < 1e-37 )
EmergentContinuum = 0.;
else
EmergentContinuum /= corr;
/* convert to physical units */
EmergentContinuum *= EN1RYD*radius.r1r0sq/radius.dVeffAper;
DiffuseEmission *= EN1RYD;
/* memory not allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
lindst( EmergentContinuum,
// the negative wavelength is a sentinel that the wavelength
// may be bogus - very often the "center" of the band, as defined
// by observers, is far to the blue end of the range. use the
// observed definition of the wavelength. This introduces an error
// since the wavelength is used to determine the transfer of the
// band against background opacities
-continuum.ContBandWavelength[nBand],
continuum.chContBandLabels[nBand].c_str(),
(continuum.ipContBandLow[nBand]+continuum.ipContBandHi[nBand])/2,
't', false,
"continuum bands defined in continuum_bands.ini");
// emissivity has no meaning for these bands - quantity is net
// transmitted radiation field
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinSet(0,DiffuseEmission);
LineSave.lines[LineSave.nsum-1].emslinThin();
}
}
}
linadd(MAX2(0.,CoolHeavy.brems_cool_net),0,"HFFc",'c',
"net free-free cooling, ALL species, free-free heating subtracted, so nearly cancels with cooling in LTE ");
linadd(MAX2(0.,-CoolHeavy.brems_cool_net),0,"HFFh",'h',
"net free-free heating, nearly cancels with cooling in LTE ");
linadd(CoolHeavy.brems_cool_h,0,"H FF",'i',
" H brems (free-free) cooling ");
linadd(CoolHeavy.brems_heat_total,0,"FF H",'i',
"total free-free heating ");
linadd(CoolHeavy.brems_cool_he,0,"HeFF",'i',
"He brems emission ");
linadd(CoolHeavy.heavfb,0,"MeFB",'c',
"heavy element recombination cooling ");
linadd(CoolHeavy.brems_cool_metals,0,"MeFF",'i',
"heavy elements (metals) brems cooling, heat not subtracted ");
linadd(CoolHeavy.brems_cool_h+CoolHeavy.brems_cool_he+CoolHeavy.brems_cool_metals,0,"ToFF",'i',
"total brems emission - total cooling but not minus heating ");
linadd((CoolHeavy.brems_cool_h+CoolHeavy.brems_cool_he)*sexp(5.8e6/phycon.te),0,"FF X",'i',
"part of H brems, in x-ray beyond 0.5KeV ");
linadd(CoolHeavy.eebrm,0,"eeff",'c',
"electron - electron brems ");
linadd(CoolHeavy.colmet,0,"Mion",'c',
" cooling due to collisional ionization of heavy elements" );
/* predict emitted continuum at series of continuum points */
/* class is located in predcont.h,
* PredCont - contains vector of pair of Energy and ip where
* we want to predict the continuum,
*
* the entry nFnu will only be printed if the command
* print diffuse continuum
* is entered -
*
* this code should be kept parallel with that in dopunch, where
* save continuum is produced, since two must agree */
t_PredCont& PredCont = t_PredCont::Inst();
if( LineSave.ipass == 0 )
PredCont.set_offset(LineSave.nsum);
/* these entries only work correctly if the APERTURE command is not in effect */
if( geometry.iEmissPower == 2 )
{
for( i=0; i < long(PredCont.size()); i++ )
{
double SourceTransmitted , Cont_nInu;
double SourceReflected, DiffuseOutward, DiffuseInward;
double renorm;
/* put wavelength in Angstroms into dummy structure, so that we can use iWavLen
* to get a proper wavelength with units, continuum energies are stored in PredCont */
(*TauDummy).WLAng() = (realnum)PredCont[i].Angstrom();
/*lambda = iWavLen(TauDummy , &chUnits , &chShift );*/
/* >>chng 00 dec 02, there were three occurrences of /opac.tmn which had the
* effect of raising the summed continuum by the local opacity correction factor.
* in the case of the Lyman continuum this raised the reported value by orders
* of magnitude. There have been commented out in the following for now. */
/* reflected total continuum (diff+incident emitted inward direction) */
/* >>chng 00 dec 08, implement the "set nFnu [SOURCE_REFLECTED] ... command, PvH */
/* >>chng 00 dec 19, remove / radius.GeoDil */
renorm = rfield.anu2(PredCont[i].ip_C())*EN1RYD/rfield.widflx(PredCont[i].ip_C());
/* this is the reflected diffuse continuum */
if( prt.lgDiffuseInward )
{
DiffuseInward = rfield.ConEmitReflec[0][PredCont[i].ip_C()]*renorm;
}
else
{
DiffuseInward = 0.;
}
/* the outward diffuse continuum */
if( prt.lgDiffuseOutward )
{
DiffuseOutward = rfield.ConEmitOut[0][PredCont[i].ip_C()]*renorm*radius.r1r0sq;
}
else
{
DiffuseOutward = 0.;
}
/* reflected part of INCIDENT continuum (only incident, not diffuse, which was above) */
if( prt.lgSourceReflected )
{
SourceReflected = rfield.ConRefIncid[0][PredCont[i].ip_C()]*renorm;
}
else
{
SourceReflected = 0.;
}
/* the attenuated incident continuum */
if( prt.lgSourceTransmitted )
{
SourceTransmitted = rfield.flux[0][PredCont[i].ip_C()]*renorm*radius.r1r0sq;
}
else
{
SourceTransmitted = 0.;
}
/* memory has not been allocated until ipass >= 0, so must not access this element,
* this element will be used to save the following quantity */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd((DiffuseInward+SourceReflected+DiffuseOutward+SourceTransmitted)/radius.dVeffAper,
(*TauDummy).WLAng(),"nFnu",'i',
"total continuum at selected energy points " );
/* emslin saves the per unit vol emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity which was set
* FOR THE PREVIOUS LINE since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/* this is the normal set to zero to trick the NEXT line into going in properly */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
/* the nsum-1 -- emslin and nsum -- SumLine is not a bug, look above - they do
* different things to different saves */
Cont_nInu = rfield.flux[0][PredCont[i].ip_C()]*renorm*radius.r1r0sq +
rfield.ConRefIncid[0][PredCont[i].ip_C()]*renorm;
# if 0
/* this code can be used to create assert statements for the continuum shape */
if( !i )
fprintf(ioQQQ,"\n");
string chWL;
sprt_wl( chWL , (*TauDummy).WLAng() );
fprintf( ioQQQ,"assert line luminosity \"nInu\" %s %.3f\n",
chWL.c_str(),
log10(SDIV(Cont_nInu/radius.dVeffAper) * radius.Conv2PrtInten) );
# endif
linadd( Cont_nInu/radius.dVeffAper,(*TauDummy).WLAng(),"nInu",'i',
"transmitted and reflected incident continuum at selected energy points " );
/* emslin saves the per unit volume emissivity of a line, which is normally
* what goes into linadd. We zero this unit emissivity since it is so situation dependent */
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/* memory has not been allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd( (DiffuseInward+SourceReflected)/radius.dVeffAper,(*TauDummy).WLAng(),"InwT",'i',
"total reflected continuum, total inward emission plus reflected (diffuse) total continuum ");
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
/* memory has not been allocated until ipass >= 0 */
if( LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum].SumLineZero();
}
linadd(SourceReflected/radius.dVeffAper,(*TauDummy).WLAng(),"InwC",'i',
"reflected incident continuum (only incident) ");
if( KILL_CONT && LineSave.ipass > 0 )
{
LineSave.lines[LineSave.nsum-1].emslinZero();
}
}
}
i = StuffComment( "RRC" );
linadd( 0., (realnum)i , "####", 'i',"radiative recombination continua");
// radiative recombination continua, RRC, for iso sequences
for( long ipISO=ipH_LIKE; ipISO<NISO; ++ipISO )
{
for( long nelem=ipISO; nelem < LIMELM; nelem++ )
{
if( nelem < 2 || dense.lgElmtOn[nelem] )
{
for( long n=0; n < iso_sp[ipISO][nelem].numLevels_max; n++ )
{
if( LineSave.ipass < 0 )
// this pass only counting lines
linadd(0.,0.,"dumy",'i',"radiative recombination continuum");
else if( LineSave.ipass == 0 )
{
// save wavelength and label
/* chIonLbl generates a null terminated 4 char string, of form "C 2"
* the result, chLable, is only used when ipass == 0, can be undefined otherwise */
realnum wl = (realnum)(RYDLAM / iso_sp[ipISO][nelem].fb[n].xIsoLevNIonRyd);
wl /= (realnum)RefIndex( 1e8/wl );
linadd( 0. , wl ,chIonLbl(iso_sp[ipISO][nelem].trans(1,0)).c_str(),'i',
"radiative recombination continuum");
}
else
{
// save intensity
linadd(iso_sp[ipISO][nelem].fb[n].RadRecCon,0,"dumy",'i',
"radiative recombination continuum");
}
}
}
}
}
// RRC for non iso sequence ions
/* add recombination continua for elements heavier than those done with iso seq */
for( long nelem=NISO; nelem < LIMELM; nelem++ )
{
/* do not include species with iso-sequence in following */
/* >>chng 03 sep 09, upper bound was wrong, did not include NISO */
for( long ion=0; ion < nelem-NISO+1; ion++ )
{
if( dense.lgElmtOn[nelem] )
{
if( LineSave.ipass < 0 )
// this pass only counting lines
linadd(0.,0.,"dumy",'i',"radiative recombination continuum");
else if( LineSave.ipass == 0 )
{
string chLabel = chIonLbl( nelem+1, ion+1 );
realnum wl = (realnum)(RYDLAM / Heavy.Valence_IP_Ryd[nelem][ion]);
wl /= (realnum)RefIndex( 1e8/wl );
linadd( 0. , wl ,chLabel.c_str(),'i',
"radiative recombination continuum");
}
else
{
// save intensity
linadd(Heavy.RadRecCon[nelem][ion],0,"dumy",'i',
"radiative recombination continuum");
}
}
}
}
return;
}
| 23,154 | 9,985 |
#define _YY_APPLY_TO_LATE_BOUND_MODULES(_APPLY) \
_APPLY(ntdll, "ntdll" , USING_UNSAFE_LOAD ) \
_APPLY(kernel32, "kernel32" , USING_UNSAFE_LOAD ) \
_APPLY(psapi, "psapi" , 0 ) \
_APPLY(version, "version" , 0 ) \
_APPLY(advapi32, "advapi32" , 0 ) \
_APPLY(user32, "user32" , 0 ) \
_APPLY(ws2_32, "ws2_32" , 0 ) \
_APPLY(shell32, "shell32" , 0 ) \
_APPLY(shcore, "shcore" , 0 ) \
_APPLY(shlwapi, "shlwapi" , 0 ) \
_APPLY(setupapi, "setupapi" , 0 ) \
_APPLY(api_ms_win_core_winrt_l1_1_0, "api-ms-win-core-winrt-l1-1-0" , 0 ) \
_APPLY(api_ms_win_core_winrt_string_l1_1_0, "api-ms-win-core-winrt-string-l1-1-0", 0 ) \
_APPLY(api_ms_win_core_winrt_error_l1_1_0, "api-ms-win-core-winrt-error-l1-1-0" , 0 ) \
_APPLY(api_ms_win_core_path_l1_1_0, "api-ms-win-core-path-l1-1-0" , 0 )
//全局可能使用到的函数
#define _YY_APPLY_TO_LATE_BOUND_FUNCTIONS(_APPLY) \
_APPLY(NtCreateFile, ntdll ) \
_APPLY(NtClose, ntdll ) \
_APPLY(NtQueryDirectoryFile, ntdll ) \
_APPLY(NtQueryInformationFile, ntdll ) \
_APPLY(NtSetInformationFile, ntdll ) \
_APPLY(RtlNtStatusToDosError, ntdll ) \
_APPLY(RtlDetermineDosPathNameType_U, ntdll ) \
_APPLY(RtlDosPathNameToNtPathName_U, ntdll ) \
_APPLY(RtlDosPathNameToNtPathName_U_WithStatus, ntdll ) \
_APPLY(RtlFreeUnicodeString, ntdll ) \
_APPLY(NtQueryObject, ntdll ) \
_APPLY(NtQueryInformationThread, ntdll ) \
_APPLY(NtQueryInformationProcess, ntdll ) \
_APPLY(NtOpenKeyedEvent, ntdll ) \
_APPLY(NtWaitForKeyedEvent, ntdll ) \
_APPLY(NtReleaseKeyedEvent, ntdll ) \
_APPLY(RtlAdjustPrivilege, ntdll ) \
_APPLY(RtlPcToFileHeader, ntdll ) \
_APPLY(LdrAddRefDll, ntdll ) \
_APPLY(RtlWow64EnableFsRedirectionEx, ntdll ) \
_APPLY(LdrLoadDll, ntdll ) \
_APPLY(RtlDllShutdownInProgress, ntdll ) \
_APPLY(AddDllDirectory, kernel32 )
#include <sdkddkver.h>
#ifndef YY_Thunks_Support_Version
#define YY_Thunks_Support_Version WDK_NTDDI_VERSION
#endif
#define _WINSOCKAPI_
#define PSAPI_VERSION 1
#if (YY_Thunks_Support_Version < NTDDI_WIN6)
#define INITKNOWNFOLDERS
#endif
#define _Disallow_YY_KM_Namespace
#include "km.h"
#include <Shlwapi.h>
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <psapi.h>
#include <winnls.h>
#include "YY_Thunks.h"
#if (YY_Thunks_Support_Version < NTDDI_WS03SP1)
#pragma comment(lib, "Advapi32.lib")
#endif
#if (YY_Thunks_Support_Version < NTDDI_WIN6)
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "version.lib")
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "shell32.lib")
#endif
#if (YY_Thunks_Support_Version < NTDDI_WIN7)
#pragma comment(lib, "psapi.lib")
#endif
#if (YY_Thunks_Support_Version >= NTDDI_WINBLUE)
#pragma comment(lib, "Shcore.lib")
#endif
#if (YY_Thunks_Support_Version < NTDDI_WINBLUE)
#pragma comment(lib, "Gdi32.lib")
#endif
//展开函数的所有的 声明 以及 try_get_ 函数
#define __DEFINE_THUNK(_MODULE, _SIZE, _RETURN_, _CONVENTION_, _FUNCTION, ...) \
__APPLY_UNIT_TEST_BOOL(_FUNCTION); \
EXTERN_C _RETURN_ _CONVENTION_ _FUNCTION(__VA_ARGS__); \
static decltype(_FUNCTION)* __cdecl _CRT_CONCATENATE(try_get_, _FUNCTION)() noexcept \
{ \
__CHECK_UNIT_TEST_BOOL(_FUNCTION); \
__declspec(allocate(".YYThr$AAA")) static void* _CRT_CONCATENATE(pInit_ ,_FUNCTION) = \
reinterpret_cast<void*>(&_CRT_CONCATENATE(try_get_, _FUNCTION)); \
/*为了避免编译器将 YYThr$AAA 节优化掉*/ \
__foreinclude(_CRT_CONCATENATE(pInit_ ,_FUNCTION)); \
__declspec(allocate(".YYThu$AAB")) static void* _CRT_CONCATENATE(pFun_, _FUNCTION); \
return reinterpret_cast<decltype(_FUNCTION)*>(try_get_function( \
&_CRT_CONCATENATE(pFun_ ,_FUNCTION), \
_CRT_STRINGIZE(_FUNCTION), \
&_CRT_CONCATENATE(try_get_module_, _MODULE))); \
} \
__if_not_exists(_CRT_CONCATENATE(try_get_, _FUNCTION))
#include "src/YY_Thunks_List.hpp"
#undef __DEFINE_THUNK
namespace YY
{
namespace Thunks
{
namespace internal
{
static DWORD __fastcall NtStatusToDosError(
_In_ NTSTATUS Status
)
{
if (STATUS_TIMEOUT == Status)
{
/*
https://github.com/Chuyu-Team/YY-Thunks/issues/10
用户报告,Windows XP 无法转换 STATUS_TIMEOUT。实际结果也是rubin,因此,特殊处理一下。
*/
return ERROR_TIMEOUT;
}
else if (auto pRtlNtStatusToDosError = try_get_RtlNtStatusToDosError())
{
return pRtlNtStatusToDosError(Status);
}
else
{
//如果没有RtlNtStatusToDosError就直接设置Status代码吧,反正至少比没有错误代码强
return Status;
}
}
static DWORD __fastcall BaseSetLastNTError(
_In_ NTSTATUS Status
)
{
auto lStatus = NtStatusToDosError(Status);
SetLastError(lStatus);
return lStatus;
}
static void __fastcall RaiseStatus(NTSTATUS Status)
{
RaiseException(Status, EXCEPTION_NONCONTINUABLE, 0, NULL);
}
static LARGE_INTEGER* __fastcall BaseFormatTimeOut(LARGE_INTEGER* Timeout, DWORD dwMilliseconds)
{
if (dwMilliseconds == INFINITE)
return nullptr;
Timeout->QuadPart = -10000ll * dwMilliseconds;
return Timeout;
}
static LSTATUS __fastcall Basep8BitStringToStaticUnicodeString(UNICODE_STRING* pDst, LPCSTR Src)
{
const UINT CodePage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
auto cchDst = MultiByteToWideChar(CodePage, MB_ERR_INVALID_CHARS, Src, -1, pDst->Buffer, pDst->MaximumLength / sizeof(wchar_t));
if (cchDst == 0)
{
return GetLastError();
}
pDst->Length = cchDst * sizeof(wchar_t);
return ERROR_SUCCESS;
}
static BOOL __fastcall BasepGetVolumeGUIDFromNTName(const UNICODE_STRING* NtName, wchar_t szVolumeGUID[MAX_PATH])
{
#define __szVolumeMountPointPrefix__ L"\\\\?\\GLOBALROOT"
//一个设备名称 512 长度够多了吧?
wchar_t szVolumeMountPoint[512];
//检查缓冲区是否充足
auto cbBufferNeed = sizeof(__szVolumeMountPointPrefix__) + NtName->Length;
if (cbBufferNeed > sizeof(szVolumeMountPoint))
{
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
memcpy(szVolumeMountPoint, __szVolumeMountPointPrefix__, sizeof(__szVolumeMountPointPrefix__) - sizeof(__szVolumeMountPointPrefix__[0]));
memcpy((char*)szVolumeMountPoint + sizeof(__szVolumeMountPointPrefix__) - sizeof(__szVolumeMountPointPrefix__[0]), NtName->Buffer, NtName->Length);
szVolumeMountPoint[cbBufferNeed / 2 - 1] = L'\0';
return GetVolumeNameForVolumeMountPointW(szVolumeMountPoint, szVolumeGUID, MAX_PATH);
#undef __szVolumeMountPointPrefix__
}
static BOOL __fastcall BasepGetVolumeDosLetterNameFromNTName(const UNICODE_STRING* NtName, wchar_t szVolumeDosLetter[MAX_PATH])
{
wchar_t szVolumeName[MAX_PATH];
if (!BasepGetVolumeGUIDFromNTName(NtName, szVolumeName))
{
return FALSE;
}
DWORD cchVolumePathName = 0;
if (!GetVolumePathNamesForVolumeNameW(szVolumeName, szVolumeDosLetter + 4, MAX_PATH - 4, &cchVolumePathName))
{
return FALSE;
}
szVolumeDosLetter[0] = L'\\';
szVolumeDosLetter[1] = L'\\';
szVolumeDosLetter[2] = L'?';
szVolumeDosLetter[3] = L'\\';
return TRUE;
}
}
}//namespace Thunks
} //namespace YY
//导入实际的实现
#define YY_Thunks_Implemented
#define __DEFINE_THUNK(_MODULE, _SIZE, _RETURN_, _CONVENTION_, _FUNCTION, ...) \
_LCRT_DEFINE_IAT_SYMBOL(_FUNCTION, _SIZE); \
EXTERN_C _RETURN_ _CONVENTION_ _FUNCTION(__VA_ARGS__)
#include "YY_Thunks_List.hpp"
#undef __DEFINE_THUNK
#undef YY_Thunks_Implemented | 10,686 | 3,821 |
#include "LightStreaksPostEffect/LightStreaksPostEffect.hpp"
#include <Castor3D/Engine.hpp>
#include <Castor3D/Buffer/GpuBuffer.hpp>
#include <Castor3D/Model/Vertex.hpp>
#include <Castor3D/Material/Texture/Sampler.hpp>
#include <Castor3D/Material/Texture/TextureLayout.hpp>
#include <Castor3D/Miscellaneous/Parameter.hpp>
#include <Castor3D/Render/RenderSystem.hpp>
#include <Castor3D/Render/RenderTarget.hpp>
#include <Castor3D/Shader/Program.hpp>
#include <Castor3D/Shader/Shaders/GlslUtils.hpp>
#include <CastorUtils/Design/ResourceCache.hpp>
#include <CastorUtils/Graphics/Image.hpp>
#include <ashespp/Buffer/VertexBuffer.hpp>
#include <ashespp/Image/Image.hpp>
#include <ashespp/Image/ImageView.hpp>
#include <ashespp/RenderPass/RenderPass.hpp>
#include <ashespp/RenderPass/RenderPassCreateInfo.hpp>
#include <ShaderWriter/Source.hpp>
#include <RenderGraph/RunnablePasses/RenderQuad.hpp>
#include <numeric>
namespace light_streaks
{
castor::String const PostEffect::Type = cuT( "light_streaks" );
castor::String const PostEffect::Name = cuT( "LightStreaks PostEffect" );
PostEffect::PostEffect( castor3d::RenderTarget & renderTarget
, castor3d::RenderSystem & renderSystem
, castor3d::Parameters const & params )
: castor3d::PostEffect{ PostEffect::Type
, PostEffect::Name
, renderTarget
, renderSystem
, params
, Count + 2u }
, m_kawaseUbo{ renderSystem.getRenderDevice() }
{
}
castor3d::PostEffectSPtr PostEffect::create( castor3d::RenderTarget & renderTarget
, castor3d::RenderSystem & renderSystem
, castor3d::Parameters const & params )
{
return std::make_shared< PostEffect >( renderTarget
, renderSystem
, params );
}
void PostEffect::accept( castor3d::PipelineVisitorBase & visitor )
{
m_hiPass->accept( visitor );
m_kawasePass->accept( visitor );
m_combinePass->accept( visitor );
for ( auto & view : m_hiImage.subViewsId )
{
visitor.visit( "PostFX: LS - Hi " + std::to_string( view.data->info.subresourceRange.baseArrayLayer )
, view
, m_renderTarget.getGraph().getFinalLayout( view ).layout
, castor3d::TextureFactors{}.invert( true ) );
}
for ( auto & view : m_kawaseImage.subViewsId )
{
visitor.visit( "PostFX: LS - Kawase " + std::to_string( view.data->info.subresourceRange.baseArrayLayer )
, view
, m_renderTarget.getGraph().getFinalLayout( view ).layout
, castor3d::TextureFactors{}.invert( true ) );
}
}
crg::ImageViewId const * PostEffect::doInitialise( castor3d::RenderDevice const & device
, crg::FramePass const & previousPass )
{
auto extent = castor3d::getSafeBandedExtent3D( m_renderTarget.getSize() );
auto & graph = m_renderTarget.getGraph();
auto size = castor3d::makeExtent2D( extent );
size.width >>= 2;
size.height >>= 2;
uint32_t index = 0u;
static float constexpr factor = 0.2f;
static std::array< castor::Point2f, Count > directions
{
{
castor::Point2f{ factor, factor },
castor::Point2f{ -factor, -factor },
castor::Point2f{ -factor, factor },
castor::Point2f{ factor, -factor }
}
};
m_hiImage = { device
, graph.getHandler()
, "LSHi"
, 0u
, VkExtent3D{ size.width, size.height, 1u }
, Count + 1u
, 1u
, m_target->data->info.format
, ( VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
| VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) };
m_kawaseImage = { device
, graph.getHandler()
, "LSKaw"
, 0u
, VkExtent3D{ size.width, size.height, 1u }
, Count
, 1u
, m_target->data->info.format
, ( VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT
| VK_IMAGE_USAGE_SAMPLED_BIT
| VK_IMAGE_USAGE_TRANSFER_DST_BIT
| VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) };
for ( auto i = 0u; i < Count; ++i )
{
for ( uint32_t j = 0u; j < 3u; ++j )
{
m_kawaseUbo.update( index
, size
, directions[i]
, j );
++index;
}
}
m_hiPass = std::make_unique< HiPass >( graph
, previousPass
, device
, *m_target
, m_hiImage.subViewsId
, size
, &isEnabled() );
m_kawasePass = std::make_unique< KawasePass >( graph
, m_hiPass->getLastPass()
, device
, m_hiImage.subViewsId
, m_kawaseImage.subViewsId
, m_kawaseUbo
, size
, &isEnabled() );
m_combinePass = std::make_unique< CombinePass >( graph
, m_kawasePass->getLastPass()
, device
, *m_target
, m_kawaseImage.subViewsId
, castor3d::makeExtent2D( extent )
, &isEnabled() );
m_pass = &m_combinePass->getPass();
m_hiImage.create();
m_kawaseImage.create();
return &m_combinePass->getResult();
}
void PostEffect::doCleanup( castor3d::RenderDevice const & device )
{
m_combinePass.reset();
m_kawasePass.reset();
m_hiPass.reset();
}
bool PostEffect::doWriteInto( castor::StringStream & file, castor::String const & tabs )
{
file << ( tabs + cuT( "postfx \"" ) + Type + cuT( "\"" ) );
return true;
}
}
| 4,924 | 2,116 |
#include <iostream>
#include <numeric>
#include <vector>
#include <climits>
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(unsigned v)
{
std::cout << v << '\n';
}
void solve(const std::vector<std::vector<unsigned>>& m)
{
const size_t n = m.size();
unsigned min = INT_MAX;
for (const auto& x : m) {
const unsigned k = x.size();
min = std::min(min, k * 15 + std::accumulate(x.cbegin(), x.cend(), 0u) * 5);
}
answer(min);
}
int main()
{
size_t n;
std::cin >> n;
std::vector<size_t> k(n);
std::cin >> k;
std::vector<std::vector<unsigned>> m(n);
for (size_t i = 0; i < n; ++i) {
m[i].resize(k[i]);
std::cin >> m[i];
}
solve(m);
return 0;
}
| 854 | 349 |
/* Red-Black tree via pb_ds. */
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int main(){
ordered_set<int> s;
s.insert(1);
s.insert(3);
cout << s.order_of_key(2) << endl; // the number of elements in the s less than 2
cout << *s.find_by_order(0) << endl; // print the 0-th smallest number in s(0-based)
}
| 535 | 212 |
//****************************************************************************
// Copyright © 2017 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 23.02.2017.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "ParseNumber.hpp"
#include <cmath>
#include <cstdint>
#include <limits>
#include <optional>
#include <type_traits>
namespace GridLib
{
namespace
{
template <typename IntT>
IntT fromDigit(char c)
{
if ('0' <= c && c <= '9')
return IntT(c - '0');
auto u = uint8_t(c);
u &= 0xDFu;
if ('A' <= u && u <= 'Z')
return IntT(10 + u - 'A');
return std::numeric_limits<IntT>::max();
}
template <typename T, T Base>
constexpr T maxPrecedingValueNegative()
{
if constexpr (std::is_signed<T>::value)
{
using U = typename std::make_unsigned<T>::type;
return T((U(1) << (sizeof(T) * 8 - 1)) / U(Base));
}
else
{
return T(0);
}
}
template <typename T, T Base>
constexpr T maxFinalDigitNegative()
{
if constexpr (std::is_signed<T>::value)
{
using U = typename std::make_unsigned<T>::type;
return T((U(1) << (sizeof(T) * 8 - 1)) % U(Base));
}
else
{
return T(0);
}
}
template <typename T, T Base>
constexpr T maxPrecedingValuePositive()
{
if constexpr (std::is_signed<T>::value)
{
using U = typename std::make_unsigned<T>::type;
return T(U(~(U(1) << (sizeof(T) * 8 - 1))) / U(Base));
}
else
{
return T(~T(0)) / Base;
}
}
template <typename T, T Base>
constexpr T maxFinalDigitPositive()
{
if constexpr (std::is_signed<T>::value)
{
using U = typename std::make_unsigned<T>::type;
return T(U(~(U(1) << (sizeof(T) * 8 - 1))) % U(Base));
}
else
{
return T(~T(0)) % Base;
}
}
template <typename IntT, IntT Base>
std::optional<IntT> parsePositiveIntegerImpl(std::string_view str)
{
if (str.empty())
return {};
IntT value = fromDigit<IntT>(str[0]);
if (value >= Base)
return {};
for (size_t i = 1; i < str.size(); ++i)
{
auto digit = fromDigit<IntT>(str[i]);
if (digit < Base
&& (value < maxPrecedingValuePositive<IntT, Base>()
|| (value == maxPrecedingValuePositive<IntT, Base>()
&& digit <= maxFinalDigitPositive<IntT, Base>())))
{
value *= Base;
value += digit;
}
else if (str[i] != '_' || i == str.size() - 1
|| str[i - 1] == '_')
{
return {};
}
}
return value;
}
template <typename IntT, IntT Base>
std::optional<IntT> parseNegativeIntegerImpl(std::string_view str)
{
if constexpr (std::is_signed<IntT>::value)
{
if (str.empty())
return {};
IntT value = fromDigit<IntT>(str[0]);
if (value >= Base)
return {};
for (size_t i = 1; i < str.size(); ++i)
{
auto digit = fromDigit<IntT>(str[i]);
if (digit < Base
&& (value < maxPrecedingValueNegative<IntT, Base>()
|| (value == maxPrecedingValueNegative<IntT, Base>()
&& digit <= maxFinalDigitNegative<IntT, Base>())))
{
value *= Base;
value += digit;
}
else if (str[i] != '_' || i == str.size() - 1
|| str[i - 1] == '_')
{
return {};
}
}
return IntT(-value);
}
else
{
if (str.empty())
return {};
for (char c : str)
{
auto digit = fromDigit<IntT>(c);
if (digit > 0)
return {};
}
return IntT(0);
}
}
template <typename IntT>
std::optional<IntT> parseInteger(std::string_view str, bool detectBase)
{
static_assert(std::is_integral<IntT>());
if (str.empty())
return {};
bool positive = true;
if (str[0] == '-')
{
positive = false;
str = str.substr(1);
}
else if (str[0] == '+')
{
str = str.substr(1);
}
if (str.empty())
return {};
if (str[0] == '0' && str.size() >= 3 && detectBase)
{
auto str2 = str.substr(2);
switch (uint8_t(str[1]) | 0x20u)
{
case 'b':
return positive ? parsePositiveIntegerImpl<IntT, 2>(str2)
: parseNegativeIntegerImpl<IntT, 2>(str2);
case 'o':
return positive ? parsePositiveIntegerImpl<IntT, 8>(str2)
: parseNegativeIntegerImpl<IntT, 8>(str2);
case 'x':
return positive ? parsePositiveIntegerImpl<IntT, 16>(str2)
: parseNegativeIntegerImpl<IntT, 16>(str2);
default:
break;
}
}
if ('0' <= str[0] && str[0] <= '9')
{
return positive ? parsePositiveIntegerImpl<IntT, 10>(str)
: parseNegativeIntegerImpl<IntT, 10>(str);
}
if (str == "false" || str == "null")
return IntT(0);
if (str == "true")
return IntT(1);
return {};
}
template <typename T>
bool parseImpl(std::string_view str, T& value, bool detectBase)
{
auto parsedValue = parseInteger<T>(str, detectBase);
if (parsedValue)
{
value = *parsedValue;
return true;
}
return false;
}
}
bool parse(std::string_view str, char& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, int8_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, int16_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, int32_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, int64_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, uint8_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, uint16_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, uint32_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
bool parse(std::string_view str, uint64_t& value, bool detectBase)
{
return parseImpl(str, value, detectBase);
}
namespace
{
int getDigit(char c)
{
return int(uint8_t(c) ^ 0x30u);
}
template <typename T>
std::optional<T> parseFloatingPoint(std::string_view str)
{
if (str.empty())
return {};
size_t i = 0;
// Get the sign of the number
bool negative = false;
if (str[0] == '-')
{
negative = true;
if (++i == str.size())
return {};
}
else if (str[0] == '+')
{
if (++i == str.size())
return {};
}
// Get the integer value
auto value = T(getDigit(str[i]));
if (value > 9)
{
if (str == "Infinity" || str == "null" || str == "+Infinity")
return std::numeric_limits<T>::infinity();
if (str == "-Infinity")
return -std::numeric_limits<T>::infinity();
if (str == "NaN")
return std::numeric_limits<T>::quiet_NaN();
return {};
}
bool underscore = false;
for (++i; i < str.size(); ++i)
{
auto digit = getDigit(str[i]);
if (digit <= 9)
{
value *= 10;
value += digit;
underscore = false;
}
else if (str[i] != '_' || underscore)
{
break;
}
else
{
underscore = true;
}
}
if (underscore)
return {};
if (i == str.size())
return !negative ? value : -value;
// Get the fraction
underscore = true; // Makes underscore after point illegal.
int decimals = 0;
T fraction = {};
if (str[i] == '.')
{
for (++i; i < str.size(); ++i)
{
auto digit = getDigit(str[i]);
if (digit <= 9)
{
fraction *= 10;
fraction += digit;
underscore = false;
++decimals;
}
else if (str[i] != '_' || underscore)
{
break;
}
else
{
underscore = true;
}
}
}
// Get the exponent
int exponent = 0;
if (i != str.size())
{
// Accept both e/E and d/D (FORTRAN) as exponent character.
if ((uint8_t(str[i]) & 0xDEu) != 'D')
return {};
if (++i == str.size())
return {};
bool negativeExponent = false;
if (str[i] == '-')
{
negativeExponent = true;
if (++i == str.size())
return {};
}
else if (str[i] == '+')
{
if (++i == str.size())
return {};
}
exponent += getDigit(str[i]);
if (exponent > 9)
return {};
for (++i; i != str.size(); ++i)
{
auto digit = getDigit(str[i]);
if (digit <= 9)
{
exponent *= 10;
exponent += digit;
underscore = false;
}
else if (str[i] != '_' || underscore)
{
return {};
}
else
{
underscore = true;
}
if (exponent > std::numeric_limits<T>::max_exponent10)
return {};
}
if (negativeExponent)
exponent = -exponent;
}
if (exponent)
value *= pow(T(10), exponent);
if (fraction != 0)
value += fraction * pow(T(10), exponent - decimals);
// Add the sign
if (negative)
value = -value;
return value;
}
template <typename T>
bool parseImpl(std::string_view str, T& value)
{
if (auto parsedValue = parseFloatingPoint<T>(str))
{
value = *parsedValue;
return true;
}
return false;
}
}
bool parse(std::string_view str, float& value)
{
return parseImpl(str, value);
}
bool parse(std::string_view str, double& value)
{
return parseImpl(str, value);
}
bool parse(std::string_view str, long double& value)
{
return parseImpl(str, value);
}
}
| 13,609 | 3,660 |
/**
* (C) Copyright 2020 IBM. All Rights Reserved.
*
* This code is licensed under the Apache License, Version 2.0. You may
* obtain a copy of this license in the LICENSE.txt file in the root directory
* of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
*
* Any modifications or derivative works of this code must retain this
* copyright notice, and modified files need to carry a notice indicating
* that they have been altered from the originals.
*/
#include "dense_bit_line_maker.h"
#include "rpu_pulsed_device.h"
#include "utility_functions.h"
namespace RPU {
// init and memory
template <typename T> void DenseBitLineMaker<T>::initialize(int x_size, int d_size) {
if (x_size != x_size_ || d_size != d_size_ || !containers_allocated_) {
x_size_ = x_size;
d_size_ = d_size;
allocateContainers();
}
}
template <typename T> void DenseBitLineMaker<T>::allocateContainers() {
freeContainers();
rw_rng_ = make_unique<RealWorldRNG<T>>(0);
x_counts_ = new int[x_size_];
d_counts_ = new int[d_size_];
x_values_ = new T[x_size_];
d_values_ = new T[d_size_];
coincidences_ = new int[d_size_ * x_size_];
containers_allocated_ = true;
}
template <typename T> void DenseBitLineMaker<T>::freeContainers() {
if (containers_allocated_) {
delete[] d_counts_;
delete[] x_counts_;
delete[] d_values_;
delete[] x_values_;
delete[] coincidences_;
d_counts_ = nullptr;
x_counts_ = nullptr;
d_values_ = nullptr;
x_values_ = nullptr;
coincidences_ = nullptr;
rw_rng_ = nullptr;
containers_allocated_ = false;
}
}
// ctor
template <typename T>
DenseBitLineMaker<T>::DenseBitLineMaker(int x_size, int d_size)
: x_size_(x_size), d_size_(d_size), containers_allocated_(false) {}
// dtor
template <typename T> DenseBitLineMaker<T>::~DenseBitLineMaker() { freeContainers(); }
// copy construcutor
template <typename T> DenseBitLineMaker<T>::DenseBitLineMaker(const DenseBitLineMaker<T> &other) {
x_size_ = other.x_size_;
d_size_ = other.d_size_;
if (other.containers_allocated_) {
initialize(other.x_size_, other.d_size_);
for (int k = 0; k < d_size_; ++k) {
d_counts_[k] = other.d_counts_[k];
d_values_[k] = other.d_values_[k];
}
for (int k = 0; k < x_size_; ++k) {
x_counts_[k] = other.x_counts_[k];
x_values_[k] = other.x_values_[k];
}
for (int k = 0; k < d_size_ * x_size_; ++k) {
coincidences_[k] = other.coincidences_[k];
}
}
}
// copy assignment
template <typename T>
DenseBitLineMaker<T> &DenseBitLineMaker<T>::operator=(const DenseBitLineMaker<T> &other) {
DenseBitLineMaker<T> tmp(other);
swap(*this, tmp);
return *this;
}
// move constructor
template <typename T> DenseBitLineMaker<T>::DenseBitLineMaker(DenseBitLineMaker<T> &&other) {
*this = std::move(other);
}
// move assignment
template <typename T>
DenseBitLineMaker<T> &DenseBitLineMaker<T>::operator=(DenseBitLineMaker<T> &&other) {
// pointers
d_counts_ = other.d_counts_;
x_counts_ = other.x_counts_;
d_values_ = other.d_values_;
x_values_ = other.x_values_;
coincidences_ = other.coincidences_;
// set pointers to null
other.d_counts_ = nullptr;
other.x_counts_ = nullptr;
other.d_values_ = nullptr;
other.x_values_ = nullptr;
other.coincidences_ = nullptr;
// other values
x_size_ = other.x_size_;
d_size_ = other.d_size_;
rw_rng_ = std::move(other.rw_rng_);
containers_allocated_ = other.containers_allocated_;
return *this;
}
/**************************************************************************************/
/* Take the mean of the probability as counts. No variation in the count number. */
template <typename T>
inline void DenseBitLineMaker<T>::generateCountsMean(
int *counts,
const T *v,
const int v_inc,
const int v_size,
const T p,
RNG<T> *rng,
const int BL,
const T res,
const bool sto_round,
const T lr) {
int j_v = 0;
for (int j = 0; j < v_size; j++) {
T v_value = lr < 0 ? -v[j_v] : v[j_v];
j_v += v_inc;
if (v_value == 0) {
counts[j] = 0;
continue;
}
T pp = getDiscretizedValue((T)fabs(v_value) * p, res, sto_round, *rng);
int ntimes = (int)MAX(MIN(RPU_ROUNDFUN(BL * pp), BL), 0);
counts[j] = (v_value >= 0) ? ntimes : -ntimes;
}
}
/** generates coincidences by just multiplying the respective count
prob. no random fluctuations. Coincidences might be pos of
negative, depending on the direction of update**/
template <typename T>
void DenseBitLineMaker<T>::generateCoincidences(
int *coincidences,
const int *x_counts,
const int x_size,
const int *d_counts,
const int d_size,
const int BL) {
T bl = (T)BL;
int idx = 0;
for (int i = 0; i < d_size; ++i) {
T dc = (T)d_counts[i];
if (dc != 0.0) {
dc /= bl;
PRAGMA_SIMD
for (int j = 0; j < x_size; ++j) {
coincidences[idx++] = (int)RPU_ROUNDFUN(dc * x_counts[j]);
}
} else {
// need to set to zero
PRAGMA_SIMD
for (int j = 0; j < x_size; ++j) {
coincidences[idx++] = 0;
}
}
}
}
// makeCounts
template <typename T>
int *DenseBitLineMaker<T>::makeCoincidences(
const T *x_in,
const int x_inc,
const T *d_in,
const int d_inc,
RNG<T> *rng,
const T lr,
const T dw_min,
const PulsedUpdateMetaParameter<T> &up) {
T A = 0;
T B = 0;
int BL = 0;
if (up.update_bl_management || up.update_management) {
T x_abs_max = Find_Absolute_Max<T>(x_in, x_size_, x_inc);
T d_abs_max = Find_Absolute_Max<T>(d_in, d_size_, d_inc);
up.performUpdateManagement(BL, A, B, up.desired_BL, x_abs_max, d_abs_max, lr, dw_min);
} else {
up.calculateBlAB(BL, A, B, lr, dw_min);
}
if (!containers_allocated_) {
initialize(x_size_, d_size_);
}
switch (up.pulse_type) {
case PulseType::MeanCount:
// x counts
generateCountsMean(x_counts_, x_in, x_inc, x_size_, B, rng, BL, up.res, up.sto_round, lr);
// d counts
generateCountsMean(d_counts_, d_in, d_inc, d_size_, A, rng, BL, up.res, up.sto_round, lr);
generateCoincidences(coincidences_, x_counts_, x_size_, d_counts_, d_size_, BL);
break;
default:
RPU_FATAL("PulseType not supported");
}
return coincidences_;
}
template <typename T> bool DenseBitLineMaker<T>::supports(RPU::PulseType pulse_type) const {
return PulseType::MeanCount == pulse_type;
}
template <typename T> void DenseBitLineMaker<T>::printCounts(int max_n) const {
if (!containers_allocated_) {
RPU_FATAL("Containter not yet allocated");
}
std::cout << "\n\nX_counts:\n";
for (int k = 0; k < MIN(x_size_, max_n); k++) {
std::cout << x_counts_[k] << ", ";
}
std::cout << "\n\nD_counts:\n";
for (int k = 0; k < MIN(d_size_, max_n); k++) {
std::cout << d_counts_[k] << ", ";
}
std::cout << std::endl;
}
template class DenseBitLineMaker<float>;
#ifdef RPU_USE_DOUBLE
template class DenseBitLineMaker<double>;
#endif
} // namespace RPU
| 7,052 | 2,844 |
/// @copyright (c) 2007 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
#include <measurementequation/NormWienerPreconditioner.h>
#include <askap_synthesis.h>
#include <askap/AskapLogging.h>
ASKAP_LOGGER(logger, ".measurementequation.normwienerpreconditioner");
#include <askap/AskapError.h>
#include <measurementequation/SynthesisParamsHelper.h>
#include <utils/PaddingUtils.h>
#include <profile/AskapProfiler.h>
#include <casacore/casa/aips.h>
#include <casacore/casa/Arrays/Array.h>
#include <casacore/casa/Arrays/ArrayMath.h>
#include <casacore/casa/Arrays/Matrix.h>
#include <casacore/casa/Arrays/MatrixMath.h>
#include <casacore/casa/Arrays/Vector.h>
#include <casacore/lattices/Lattices/SubLattice.h>
#include <casacore/lattices/Lattices/ArrayLattice.h>
#include <casacore/lattices/LatticeMath/LatticeFFT.h>
#include <casacore/lattices/LEL/LatticeExpr.h>
using namespace casa;
#include <iostream>
#include <cmath>
using std::abs;
namespace askap
{
namespace synthesis
{
NormWienerPreconditioner::NormWienerPreconditioner() :
itsRobust(0.0)
{
}
NormWienerPreconditioner::NormWienerPreconditioner(const float& noisepower) :
itsRobust(noisepower)
{
}
IImagePreconditioner::ShPtr NormWienerPreconditioner::clone()
{
return IImagePreconditioner::ShPtr(new NormWienerPreconditioner(*this));
}
bool NormWienerPreconditioner::doPreconditioning(casa::Array<float>& psf,
casa::Array<float>& dirty,
casa::Array<float>& pcf) const
{
{
ASKAPTRACE("NormWienerPreconditioner::doPreconditioning");
ASKAPLOG_INFO_STR(logger, "Applying Normalised Wiener filter with robustness parameter " << itsRobust);
float maxPSFBefore=casa::max(psf);
ASKAPLOG_INFO_STR(logger, "Peak of PSF before Normalised Wiener filtering = " << maxPSFBefore);
casa::ArrayLattice<float> lpsf(psf);
casa::ArrayLattice<float> ldirty(dirty);
const casa::IPosition shape = lpsf.shape();
casa::ArrayLattice<casa::Complex> scratch(shape);
//scratch.set(0.);
scratch.copyData(casa::LatticeExpr<casa::Complex>(toComplex(lpsf)));
LatticeFFT::cfft2d(scratch, True);
// Construct a Wiener filter
casa::ArrayLattice<casa::Complex> wienerfilter(shape);
//wienerfilter.set(0.);
// Normalize relative to the average weight
const double noisepower(pow(10.0, 2*itsRobust));
const double np(noisepower*maxPSFBefore);
wienerfilter.copyData(casa::LatticeExpr<casa::Complex>(maxPSFBefore*conj(scratch)/(real(scratch*conj(scratch)) + np*np)));
// Apply the filter to the lpsf
// (reuse the ft(lpsf) currently held in 'scratch')
// need to rebuild ft(lpsf) with padding, otherwise there is a scaling error
//scratch.set(0.);
scratch.copyData(casa::LatticeExpr<casa::Complex>(toComplex(lpsf)));
LatticeFFT::cfft2d(scratch, True);
//
scratch.copyData(casa::LatticeExpr<casa::Complex> (wienerfilter * scratch));
/*
SynthesisParamsHelper::saveAsCasaImage("dbg.img",casa::amplitude(scratch.asArray()));
//SynthesisParamsHelper::saveAsCasaImage("dbg.img",lpsf.asArray());
throw AskapError("This is a debug exception");
*/
LatticeFFT::cfft2d(scratch, False);
lpsf.copyData(casa::LatticeExpr<float>(real(scratch)));
float maxPSFAfter=casa::max(psf);
ASKAPLOG_INFO_STR(logger, "Peak of PSF after Normalised Wiener filtering = " << maxPSFAfter);
psf*=maxPSFBefore/maxPSFAfter;
ASKAPLOG_INFO_STR(logger, "Normalized to unit peak");
// Apply the filter to the dirty image
//scratch.set(0.);
scratch.copyData(casa::LatticeExpr<casa::Complex>(toComplex(ldirty)));
LatticeFFT::cfft2d(scratch, True);
scratch.copyData(casa::LatticeExpr<casa::Complex> (wienerfilter * scratch));
LatticeFFT::cfft2d(scratch, False);
ldirty.copyData(casa::LatticeExpr<float>(real(scratch)));
dirty*=maxPSFBefore/maxPSFAfter;
return true;
}
}
}
}
| 5,300 | 1,780 |
/* Copyright (C) 2012-2019 IBM Corp.
* This program is 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. See accompanying LICENSE file.
*/
#include <NTL/ZZ.h>
#include "FHEContext.h"
#include "Ctxt.h"
#include "permutations.h"
#include "EncryptedArray.h"
namespace helib {
std::ostream& operator<< (std::ostream &s, const PermNetwork &net)
{
s << "[";
for (long i=0; i< net.layers.length(); i++) {
const PermNetLayer& lyr = net.layers[i];
s << "[" << lyr.genIdx << " " << lyr.e << " " << lyr.isID << " "
<< lyr.shifts << "]\n";
}
return s << "]";
}
// Compute one or more layers corresponding to one network of one leaf
void PermNetwork::setLayers4Leaf(long lyrIdx, const ColPerm& p,
const NTL::Vec<long>& benesLvls, long gIdx,
const SubDimension& leafData,
const Permut& map2cube)
{
#ifdef DEBUG_PRINTOUT
std::cerr << "Layer "<<lyrIdx<<", column-permutation="<< p << std::endl;
#endif
// Compute the shift amounts for all the layers in this network
NTL::Vec<bool> isID;
NTL::Vec<Permut> shifts;
if (benesLvls.length()==1) {// Special case for a "trivial" 1-layer network
shifts.SetLength(1);
isID.SetLength(1);
isID[0] = !p.getShiftAmounts(shifts[0]);
}
else // The general case of a multi-layer Benes network
p.getBenesShiftAmounts(shifts,isID,benesLvls);
// Copy the shift amounts to the right place in the bigger network,
// renaming the slots from a linear array to the hyper cube
for (long i=0; i<benesLvls.length(); i++) {
PermNetLayer& lyr = layers[lyrIdx+i];
lyr.genIdx = gIdx;
lyr.isID = isID[i];
lyr.e = leafData.e;
if (!lyr.isID) {
#ifdef DEBUG_PRINTOUT
std::cerr << "layer "<<lyrIdx+i<<": "<<shifts[i]<<std::endl;
#endif
if (leafData.good) // For good leaves, shift by -x is the same as size-x
for (long k=0; k<shifts[i].length(); k++)
if (shifts[i][k]<0) shifts[i][k] += leafData.size;
applyPermToVec(lyr.shifts, shifts[i], map2cube); // do the renaming
#ifdef DEBUG_PRINTOUT
std::cerr << " : "<<lyr.shifts<<std::endl;
#endif
}
// else std::cerr << "layer "<<lyrIdx+i<<"= identity\n";
}
}
// Build a full permutation network
void PermNetwork::buildNetwork(const Permut& pi, const GeneratorTrees& trees)
{
if (trees.numTrees()==0) { // the identity permutation, nothing to do
layers.SetLength(0);
return;
}
NTL::Vec<long> dims;
trees.getCubeSubDims(dims);
// std::cerr << "pi = "<<pi<<std::endl;
// std::cerr << "map2cube ="<<trees.mapToCube()<<std::endl;
// std::cerr << "map2array="<<trees.mapToArray()<<std::endl;
// Compute the permutation on the cube, rho = map2cube o pi o map2array
Permut rho;
applyPermsToVec(rho, trees.mapToCube(), pi, trees.mapToArray());
// std::cerr << "rho = "<<rho<<std::endl;
// Break rho along the different dimensions
CubeSignature sig(dims); // make a cube-signature object
std::vector<ColPerm> perms;
breakPermByDim(perms, rho, sig);
// for (long i=0; i<(long)perms.size(); i++) { // debugging printouts
// Permut tmp;
// perms[i].makeExplicit(tmp);
// std::cerr << " prems["<<i<<"]="<<tmp<<std::endl;
// }
layers.SetLength(trees.numLayers()); // allocate space
// Go over the different permutations and build the corresponding layers
long dimIdx =0;
long frntLyr=0, backLyr=layers.length();
for (long g=0; g<trees.numTrees(); g++) { // go over all the generators/trees
const OneGeneratorTree &T = trees[g];
// In each tree, go over all the leaves
for (long leaf=T.firstLeaf(); leaf>=0; leaf=T.nextLeaf(leaf)) {
const SubDimension& leafData = T[leaf].getData();
// This leaf determines layers frntLyer...frntLey+frst.length()-1, and
// if it isn't the middle then also backLyr-scnd.length()...backLyr-1
// handle the first Benes network
setLayers4Leaf(/*1st-layer-index=*/frntLyr,
/*permutation =*/perms[dimIdx],
/*Benes levels =*/leafData.frstBenes,
/*generator index=*/T.getAuxKey(),
/*(size,good,e) =*/leafData,
/*hypercube renaming permutation=*/trees.mapToCube());
frntLyr += leafData.frstBenes.length(); // how many layers were used
dimIdx++;
if (leafData.scndBenes.length()>0) { // Also a second Benes network
long dimIdx2 = perms.size() -dimIdx; // dimIdx was incremented above
backLyr -= leafData.scndBenes.length();
setLayers4Leaf(/*1st-layer-index=*/backLyr,
/*permutation =*/perms[dimIdx2],
/*Benes levels =*/leafData.scndBenes,
/*generator index=*/T.getAuxKey(),
/*(size,good,e) =*/leafData,
/*hypercube renaming permutation=*/trees.mapToCube());
}
}
}
}
// Apply a permutation network to a hypercube, used mostly for debugging
void PermNetwork::applyToCube(HyperCube<long>& cube) const
{
if (layers.length()==0) return;
long n = cube.getSize();
NTL::Vec<long> tmp(NTL::INIT_SIZE, n); // temporary vector
// Apply the layers, one at a time
for (long i=0; i<layers.length(); i++) {
const PermNetLayer& lyr = layers[i];
if (lyr.isID) continue; // this layer is the identity permutation
//OLD: assert(lyr.shifts.length()==n);
helib::assertEq(lyr.shifts.length(), n, "layer has incorrect size");
// This layer shift elements along the dimension lyr.genIdx
long dim = lyr.genIdx;
// Move elements as dictated by this layer
for (long j=0; j<n; j++) {
long shamt = lyr.e * lyr.shifts[j]; // how much to shift this slot
if (shamt<0) shamt += cube.getDim(dim); // addCoord expects shamt>=0
long j2 = cube.addCoord(j, dim, shamt); // new index for this slot
tmp[j2] = cube[j];
}
// Copy back to cube
for (long j=0; j<n; j++)
cube[j] = tmp[j];
#ifdef DEBUG_PRINTOUT
std::cerr << " after layer "<< i << ", cube=" << cube.getData()<<std::endl;
#endif
}
}
void PermNetwork::applyToPtxt(NTL::ZZX& p, const EncryptedArray& ea) const
{
throw helib::LogicError("PermNetwork::applyToPtxt is not implemented");
}
// Upon return, mask[i]=1 if haystack[i]=needle, 0 otherwise.
// Also set to 0 all the entries in haystack where mask[i]=1.
// Return the index of the first nonzero entry in haystack at the end
// of the pass (-1 if they are all zero). Also return a flag saying if
// any entries of the mask are nonzero.
static std::pair<long,bool>
makeMask(std::vector<long>& mask, NTL::Vec<long>& haystack, long needle)
{
long found = false;
long fstNonZeroIdx = -1;
for (long i=0; i<(long)mask.size(); i++) {
if (haystack[i] == needle) { // found a needle
found = true;
mask[i]=1;
haystack[i]=0; // remove this needle from haystack
} else { // no needle here
mask[i]=0;
if (haystack[i]!=0 && fstNonZeroIdx<0)
fstNonZeroIdx = i; // first nonzero entry in haystack
}
}
return std::make_pair(fstNonZeroIdx,found);
}
// Apply a permutation network to a ciphertext
void PermNetwork::applyToCtxt(Ctxt& c, const EncryptedArray& ea) const
{
const PAlgebra& al = ea.getPAlgebra();
// Apply the layers, one at a time
for (long i=0; i<layers.length(); i++) {
const PermNetLayer& lyr = layers[i];
if (lyr.isID) continue; // this layer is the identity permutation
// This layer is shifted via powers of g^e mod m
long g2e = NTL::PowerMod(al.ZmStarGen(lyr.genIdx), lyr.e, al.getM());
NTL::Vec<long> unused = lyr.shifts; // copy to a new vector
std::vector<long> mask(lyr.shifts.length()); // buffer to hold masks
Ctxt sum(c.getPubKey(), c.getPtxtSpace()); // an empty ciphertext
long shamt = 0;
bool frst = true;
while (true) {
std::pair<long,bool> ret=makeMask(mask, unused, shamt); // compute mask
if (ret.second) { // non-empty mask
Ctxt tmp = c;
NTL::ZZX maskPoly;
ea.encode(maskPoly, mask); // encode mask as polynomial
tmp.multByConstant(maskPoly); // multiply by mask
if (shamt!=0) // rotate if the shift amount is nonzero
tmp.smartAutomorph(NTL::PowerMod(g2e, shamt, al.getM()));
if (frst) {
sum = tmp;
frst = false;
}
else
sum += tmp;
}
if (ret.first >= 0)
shamt = unused[ret.first]; // next shift amount to use
else break; // unused is all-zero, done with this layer
}
c = sum; // update the cipehrtext c before the next layer
}
}
}
| 8,862 | 3,259 |
#include <libusb.h>
#include <iostream>
using namespace std;
struct plv::usb::UsbList::Opaque
{
libusb_device **list = nullptr;
};
auto plv::usb::UsbList::~UsbList() -> void
{
libusb_free_device_lisit(o_->list, this->size());
}
| 239 | 97 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/notification_helper/notification_helper_crash_reporter_client.h"
#include <memory>
#include "base/check.h"
#include "base/debug/leak_annotations.h"
#include "base/file_version_info.h"
#include "base/notreached.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_version.h"
#include "chrome/install_static/install_util.h"
#include "chrome/install_static/user_data_dir.h"
#include "components/crash/core/app/crashpad.h"
#include "components/version_info/channel.h"
NotificationHelperCrashReporterClient::NotificationHelperCrashReporterClient() =
default;
NotificationHelperCrashReporterClient::
~NotificationHelperCrashReporterClient() = default;
// static
void NotificationHelperCrashReporterClient::
InitializeCrashReportingForProcessWithHandler(
const base::FilePath& exe_path) {
DCHECK(!exe_path.empty());
static NotificationHelperCrashReporterClient* instance = nullptr;
if (instance)
return;
instance = new NotificationHelperCrashReporterClient();
ANNOTATE_LEAKING_OBJECT_PTR(instance);
crash_reporter::SetCrashReporterClient(instance);
base::string16 user_data_dir;
install_static::GetUserDataDirectory(&user_data_dir, nullptr);
crash_reporter::InitializeCrashpadWithEmbeddedHandler(
true, "notification-helper", install_static::UTF16ToUTF8(user_data_dir),
exe_path);
}
bool NotificationHelperCrashReporterClient::ShouldCreatePipeName(
const base::string16& process_type) {
return true;
}
bool NotificationHelperCrashReporterClient::GetAlternativeCrashDumpLocation(
base::string16* crash_dir) {
return false;
}
void NotificationHelperCrashReporterClient::GetProductNameAndVersion(
const base::string16& exe_path,
base::string16* product_name,
base::string16* version,
base::string16* special_build,
base::string16* channel_name) {
// Report crashes under the same product name as the browser. This string
// MUST match server-side configuration.
*product_name = base::ASCIIToUTF16(PRODUCT_SHORTNAME_STRING);
std::unique_ptr<FileVersionInfo> version_info(
FileVersionInfo::CreateFileVersionInfo(base::FilePath(exe_path)));
if (version_info) {
*version = version_info->product_version();
*special_build = version_info->special_build();
} else {
*version = L"0.0.0.0-devel";
*special_build = L"";
}
*channel_name = install_static::GetChromeChannelName();
}
bool NotificationHelperCrashReporterClient::ShouldShowRestartDialog(
base::string16* title,
base::string16* message,
bool* is_rtl_locale) {
// There is no UX associated with notification_helper, so no dialog should be
// shown.
return false;
}
bool NotificationHelperCrashReporterClient::AboutToRestart() {
// The notification_helper should never be restarted after a crash.
return false;
}
bool NotificationHelperCrashReporterClient::GetIsPerUserInstall() {
return !install_static::IsSystemInstall();
}
bool NotificationHelperCrashReporterClient::GetShouldDumpLargerDumps() {
// Use large dumps for all but the stable channel.
return install_static::GetChromeChannel() != version_info::Channel::STABLE;
}
int NotificationHelperCrashReporterClient::GetResultCodeRespawnFailed() {
// The restart dialog is never shown for the notification_helper.
NOTREACHED();
return 0;
}
bool NotificationHelperCrashReporterClient::GetCrashDumpLocation(
base::string16* crash_dir) {
*crash_dir = install_static::GetCrashDumpLocation();
return !crash_dir->empty();
}
bool NotificationHelperCrashReporterClient::GetCrashMetricsLocation(
base::string16* metrics_dir) {
install_static::GetUserDataDirectory(metrics_dir, nullptr);
return !metrics_dir->empty();
}
bool NotificationHelperCrashReporterClient::IsRunningUnattended() {
return install_static::HasEnvironmentVariable16(install_static::kHeadless);
}
bool NotificationHelperCrashReporterClient::GetCollectStatsConsent() {
return install_static::GetCollectStatsConsent();
}
bool NotificationHelperCrashReporterClient::GetCollectStatsInSample() {
return install_static::GetCollectStatsInSample();
}
bool NotificationHelperCrashReporterClient::ReportingIsEnforcedByPolicy(
bool* enabled) {
return install_static::ReportingIsEnforcedByPolicy(enabled);
}
bool NotificationHelperCrashReporterClient::
ShouldMonitorCrashHandlerExpensively() {
// The expensive mechanism dedicates a process to be crashpad_handler's own
// crashpad_handler.
return false;
}
bool NotificationHelperCrashReporterClient::EnableBreakpadForProcess(
const std::string& process_type) {
// This is not used by Crashpad (at least on Windows).
NOTREACHED();
return true;
}
| 4,882 | 1,501 |
/**
* MK4duo Firmware for 3D Printer, Laser and CNC
*
* Based on Marlin, Sprinter and grbl
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
* Copyright (C) 2019 Alberto Cotronei @MagoKimbra
*
* 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/>.
*
*/
//
// Advanced Settings Menus
//
#include "../../../MK4duo.h"
#if HAS_LCD_MENU
void menu_tmc();
#if ENABLED(WORKSPACE_OFFSETS)
//
// Set the home offset based on the current_position
//
void _lcd_set_home_offsets() {
commands.enqueue_and_echo_P(PSTR("M428"));
lcdui.return_to_status();
}
#endif
#if ENABLED(VOLUMETRIC_EXTRUSION)
bool lcd_volumetric_enabled = printer.isVolumetric();
void lcd_set_volumetric() {
printer.setVolumetric(lcd_volumetric_enabled);
tools.calculate_volumetric_multipliers;
}
#endif
#if ENABLED(VOLUMETRIC_EXTRUSION) || ENABLED(ADVANCED_PAUSE_FEATURE)
//
// Advanced Settings > Filament
//
void menu_advanced_filament() {
START_MENU();
MENU_BACK(MSG_ADVANCED_SETTINGS);
#if ENABLED(LIN_ADVANCE)
MENU_ITEM_EDIT(float3, MSG_ADVANCE_K, &planner.extruder_advance_K, 0, 999);
#endif
#if ENABLED(VOLUMETRIC_EXTRUSION)
lcd_volumetric_enabled = printer.isVolumetric();
MENU_ITEM_EDIT_CALLBACK(bool, MSG_VOLUMETRIC_ENABLED, &lcd_volumetric_enabled, lcd_set_volumetric);
if (printer.isVolumetric()) {
#if EXTRUDERS == 1
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM, &tools.filament_size[0], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
#else // EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM, &tools.filament_size[tools.active_extruder], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E1, &tools.filament_size[0], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E2, &tools.filament_size[1], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E3, &tools.filament_size[2], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E4, &tools.filament_size[3], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E5, &tools.filament_size[4], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float43, MSG_FILAMENT_DIAM MSG_DIAM_E6, &tools.filament_size[5], 1.5f, 3.5f, tools.calculate_volumetric_multipliers);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
}
#endif // ENABLED(VOLUMETRIC_EXTRUSION)
#if ENABLED(ADVANCED_PAUSE_FEATURE)
constexpr float extrude_maxlength =
#if ENABLED(PREVENT_LENGTHY_EXTRUDE)
EXTRUDE_MAXLENGTH
#else
999
#endif
;
#if EXTRUDERS == 1
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD, &advancedpause.data[0].unload_length, 0, extrude_maxlength);
#else // EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD, &advancedpause.data[tools.active_extruder].unload_length, 0, extrude_maxlength);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E1, &advancedpause.data[0].unload_length, 0, extrude_maxlength);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E2, &advancedpause.data[1].unload_length, 0, extrude_maxlength);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E3, &advancedpause.data[2].unload_length, 0, extrude_maxlength);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E4, &advancedpause.data[3].unload_length, 0, extrude_maxlength);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E5, &advancedpause.data[4].unload_length, 0, extrude_maxlength);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_UNLOAD MSG_DIAM_E6, &advancedpause.data[5].unload_length, 0, extrude_maxlength);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
#if EXTRUDERS == 1
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD, &advancedpause.data[0].load_length, 0, extrude_maxlength);
#else // EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD, &advancedpause.data[tools.active_extruder].load_length, 0, extrude_maxlength);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E1, &advancedpause.data[0].load_length, 0, extrude_maxlength);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E2, &advancedpause.data[1].load_length, 0, extrude_maxlength);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E3, &advancedpause.data[2].load_length, 0, extrude_maxlength);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E4, &advancedpause.data[3].load_length, 0, extrude_maxlength);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E5, &advancedpause.data[4].load_length, 0, extrude_maxlength);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_FILAMENT_LOAD MSG_DIAM_E6, &advancedpause.data[5].load_length, 0, extrude_maxlength);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
#endif
END_MENU();
}
#endif // ENABLED(VOLUMETRIC_EXTRUSION) || ENABLED(ADVANCED_PAUSE_FEATURE)
//
// Advanced Settings > Temperature helpers
//
#if ENABLED(PID_AUTOTUNE_MENU)
#if HOTENDS > 0
int16_t autotune_temp[HOTENDS] = ARRAY_BY_HOTENDS(200);
#endif
#if BEDS > 0
int16_t autotune_temp_bed[BEDS] = ARRAY_BY_BEDS(60);
#endif
#if CHAMBERS > 0
int16_t autotune_temp_chambers[CHAMBERS] = ARRAY_BY_CHAMBERS(60);
#endif
#if HOTENDS > 0
void _lcd_autotune(const int8_t h) {
char cmd[30];
sprintf_P(cmd, PSTR("M303 U1 H%i S%i"), h, autotune_temp[h]);
lcd_enqueue_command(cmd);
}
#endif
#if BEDS > 0
void _lcd_autotune_bed(const int8_t t) {
char cmd[30];
sprintf_P(cmd, PSTR("M303 U1 H-1 T%i S%i"), t, autotune_temp_bed[t]);
lcd_enqueue_command(cmd);
}
#endif
#if CHAMBERS > 0
void _lcd_autotune_chamber(const int8_t t) {
char cmd[30];
sprintf_P(cmd, PSTR("M303 U1 H-2 T%i S%i"), t, autotune_temp_chambers[t]);
lcd_enqueue_command(cmd);
}
#endif
#endif //PID_AUTOTUNE_MENU
#define _DEFINE_PIDTEMP_BASE_FUNCS(N) void updatePID_H ## N() { hotends[N].pid.update(); }
#define _DEFINE_BED_PIDTEMP_BASE_FUNCS(N) void updatePID_BED ## N() { beds[N].pid.update(); }
#define _DEFINE_CHAMBER_PIDTEMP_BASE_FUNCS(N) void updatePID_CHAMBER ## N() { chambers[N].pid.update(); }
#if ENABLED(PID_AUTOTUNE_MENU)
#if HOTENDS > 0
#define DEFINE_PIDTEMP_FUNCS(N) \
_DEFINE_PIDTEMP_BASE_FUNCS(N); \
void lcd_autotune_callback_H ## N() { _lcd_autotune(N); }
#endif
#if BEDS > 0
#define DEFINE_PIDBED_FUNCS(N) \
_DEFINE_BED_PIDTEMP_BASE_FUNCS(N); \
void lcd_autotune_callback_BED ## N() { _lcd_autotune_bed(N); }
#endif
#if CHAMBERS > 0
#define DEFINE_PIDCHAMBER_FUNCS(N) \
_DEFINE_CHAMBER_PIDTEMP_BASE_FUNCS(N); \
void lcd_autotune_callback_CHAMBER ## N() { _lcd_autotune_chamber(N); }
#endif
#else
#if HOTENDS > 0
#define DEFINE_PIDTEMP_FUNCS(N) _DEFINE_PIDTEMP_BASE_FUNCS(N)
#endif
#if BEDS > 0
#define DEFINE_PIDBED_FUNCS(N) _DEFINE_BED_PIDTEMP_BASE_FUNCS(N)
#endif
#if CHAMBERS > 0
#define DEFINE_PIDCHAMBER_FUNCS(N) _DEFINE_CHAMBER_PIDTEMP_BASE_FUNCS(N)
#endif
#endif
#if HOTENDS > 0
DEFINE_PIDTEMP_FUNCS(0);
#if HOTENDS > 1
DEFINE_PIDTEMP_FUNCS(1);
#if HOTENDS > 2
DEFINE_PIDTEMP_FUNCS(2);
#if HOTENDS > 3
DEFINE_PIDTEMP_FUNCS(3);
#if HOTENDS > 4
DEFINE_PIDTEMP_FUNCS(4);
#if HOTENDS > 5
DEFINE_PIDTEMP_FUNCS(5);
#endif // HOTENDS > 5
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#endif // HOTENDS > 0
#if BEDS > 0
DEFINE_PIDBED_FUNCS(0);
#if BEDS > 1
DEFINE_PIDBED_FUNCS(1);
#if BEDS > 2
DEFINE_PIDBED_FUNCS(2);
#if BEDS > 3
DEFINE_PIDBED_FUNCS(3);
#endif // BEDS > 3
#endif // BEDS > 2
#endif // BEDS > 1
#endif // BEDS > 0
#if CHAMBERS > 0
DEFINE_PIDCHAMBER_FUNCS(0);
#if CHAMBERS > 1
DEFINE_PIDCHAMBER_FUNCS(1);
#if CHAMBERS > 2
DEFINE_PIDCHAMBER_FUNCS(2);
#if CHAMBERS > 3
DEFINE_PIDCHAMBER_FUNCS(3);
#endif // CHAMBERS > 3
#endif // CHAMBERS > 2
#endif // CHAMBERS > 1
#endif // CHAMBERS > 0
//
// Advanced Settings > Temperature
//
void menu_advanced_temperature() {
START_MENU();
MENU_BACK(MSG_ADVANCED_SETTINGS);
//
// Autotemp, Min, Max, Fact
//
#if ENABLED(AUTOTEMP) && HAS_TEMP_HE0
MENU_ITEM_EDIT(bool, MSG_AUTOTEMP, &planner.autotemp_enabled);
MENU_ITEM_EDIT(float3, MSG_MIN, &planner.autotemp_min, 0, hotends[0].data.maxtemp - 10);
MENU_ITEM_EDIT(float3, MSG_MAX, &planner.autotemp_max, 0, hotends[0].data.maxtemp - 10);
MENU_ITEM_EDIT(float52, MSG_FACTOR, &planner.autotemp_factor, 0, 1);
#endif
//
// PID-P H0, PID-I H0, PID-D H0, PID-C H0, PID Autotune H0
// PID-P H1, PID-I H1, PID-D H1, PID-C H1, PID Autotune H1
// PID-P H2, PID-I H2, PID-D H2, PID-C H2, PID Autotune H2
// PID-P H3, PID-I H3, PID-D H3, PID-C H3, PID Autotune H3
// PID-P H4, PID-I H4, PID-D H4, PID-C H4, PID Autotune H4
// PID-P H5, PID-I H5, PID-D H5, PID-C H5, PID Autotune H5
//
#define _PID_BASE_MENU_ITEMS(HLABEL, hindex) \
MENU_ITEM_EDIT(float52, MSG_PID_P HLABEL, &hotends[hindex].pid.Kp, 1, 9990); \
MENU_ITEM_EDIT_CALLBACK(float52, MSG_PID_I HLABEL, &hotends[hindex].pid.Ki, 0.01f, 9990, updatePID_H ## hindex); \
MENU_ITEM_EDIT(float52, MSG_PID_D HLABEL, &hotends[hindex].pid.Kd, 1, 9990)
#define _PID_BED_BASE_MENU_ITEMS(HLABEL, hindex) \
MENU_ITEM_EDIT(float52, "Bed " MSG_PID_P HLABEL, &beds[hindex].pid.Kp, 1, 9990); \
MENU_ITEM_EDIT_CALLBACK(float52, "Bed " MSG_PID_I HLABEL, &beds[hindex].pid.Ki, 0.01f, 9990, updatePID_BED ## hindex); \
MENU_ITEM_EDIT(float52, "Bed " MSG_PID_D HLABEL, &beds[hindex].pid.Kd, 1, 9990)
#define _PID_CHAMBER_BASE_MENU_ITEMS(HLABEL, hindex) \
MENU_ITEM_EDIT(float52, "Chamber " MSG_PID_P HLABEL, &chambers[hindex].pid.Kp, 1, 9990); \
MENU_ITEM_EDIT_CALLBACK(float52, "Chamber " MSG_PID_I HLABEL, &chambers[hindex].pid.Ki, 0.01f, 9990, updatePID_CHAMBER ## hindex); \
MENU_ITEM_EDIT(float52, "Chamber " MSG_PID_D HLABEL, &chambers[hindex].pid.Kd, 1, 9990)
#if ENABLED(PID_ADD_EXTRUSION_RATE)
#define _PID_MENU_ITEMS(HLABEL, hindex) \
_PID_BASE_MENU_ITEMS(HLABEL, hindex); \
MENU_ITEM_EDIT(float3, MSG_PID_C HLABEL, &hotends[hindex].pid.Kc, 1, 9990)
#else
#define _PID_MENU_ITEMS(HLABEL, hindex) _PID_BASE_MENU_ITEMS(HLABEL, hindex)
#endif
#if ENABLED(PID_AUTOTUNE_MENU)
#define PID_MENU_ITEMS(HLABEL, hindex) \
_PID_MENU_ITEMS(HLABEL, hindex); \
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(int3, MSG_PID_AUTOTUNE HLABEL, &autotune_temp[hindex], 150, hotends[hindex].data.maxtemp - 10, lcd_autotune_callback_H ## hindex)
#if BEDS > 0
#define PID_BED_MENU_ITEMS(HLABEL, hindex) \
_PID_BED_BASE_MENU_ITEMS(HLABEL, hindex); \
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(int3, "Bed " MSG_PID_AUTOTUNE HLABEL, &autotune_temp_bed[hindex], 30, beds[hindex].data.maxtemp - 10, lcd_autotune_callback_BED ## hindex)
#endif
#if CHAMBERS > 0
#define PID_CHAMBER_MENU_ITEMS(HLABEL, hindex) \
_PID_CHAMBER_BASE_MENU_ITEMS(HLABEL, hindex); \
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(int3, "Chamber " MSG_PID_AUTOTUNE HLABEL, &autotune_temp_chamber[hindex], 30, chambers[hindex].data.maxtemp - 10, lcd_autotune_callback_CHAMBER ## hindex)
#endif
#else
#define PID_MENU_ITEMS(HLABEL, hindex) _PID_MENU_ITEMS(HLABEL, hindex)
#if BEDS > 0
#define PID_BED_MENU_ITEMS() _PID_BED_BASE_MENU_ITEMS(HLABEL, hindex)
#endif
#if CHAMBERS > 0
#define PID_CHAMBER_MENU_ITEMS() _PID_CHAMBER_BASE_MENU_ITEMS(HLABEL, hindex)
#endif
#endif
#if HOTENDS > 0
if (hotends[0].isUsePid()) { PID_MENU_ITEMS(MSG_H0, 0); }
#if HOTENDS > 1
if (hotends[1].isUsePid()) { PID_MENU_ITEMS(MSG_H1, 1); }
#if HOTENDS > 2
if (hotends[2].isUsePid()) { PID_MENU_ITEMS(MSG_H2, 2); }
#if HOTENDS > 3
if (hotends[3].isUsePid()) { PID_MENU_ITEMS(MSG_H3, 3); }
#if HOTENDS > 4
if (hotends[4].isUsePid()) { PID_MENU_ITEMS(MSG_H4, 4); }
#if HOTENDS > 5
if (hotends[5].isUsePid()) { PID_MENU_ITEMS(MSG_H5, 5); }
#endif // HOTENDS > 5
#endif // HOTENDS > 4
#endif // HOTENDS > 3
#endif // HOTENDS > 2
#endif // HOTENDS > 1
#endif // HOTENDS > 0
#if BEDS > 0
if (beds[0].isUsePid()) { PID_BED_MENU_ITEMS("", 0); }
#if BEDS > 1
if (beds[1].isUsePid()) { PID_BED_MENU_ITEMS(MSG_H1, 1); }
#if BEDS > 2
if (beds[2].isUsePid()) { PID_BED_MENU_ITEMS(MSG_H2, 2); }
#if BEDS > 3
if (beds[3].isUsePid()) { PID_BED_MENU_ITEMS(MSG_H3, 3); }
#endif // BEDS > 3
#endif // BEDS > 2
#endif // BEDS > 1
#endif // BEDS > 0
#if CHAMBERS > 0
if (chambers[0].isUsePid()) { PID_CHAMBER_MENU_ITEMS("", 0); }
#if CHAMBERS > 1
if (chambers[1].isUsePid()) { PID_CHAMBER_MENU_ITEMS(MSG_H1, 1); }
#if CHAMBERS > 2
if (chambers[2].isUsePid()) { PID_CHAMBER_MENU_ITEMS(MSG_H2, 2); }
#if CHAMBERS > 3
if (chambers[3].isUsePid()) { PID_CHAMBER_MENU_ITEMS(MSG_H3, 3); }
#endif // CHAMBERS > 3
#endif // CHAMBERS > 2
#endif // CHAMBERS > 1
#endif // CHAMBERS > 0
END_MENU();
}
#if DISABLED(SLIM_LCD_MENUS)
void _reset_acceleration_rates() {
#if MECH(DELTA)
mechanics.data.max_acceleration_mm_per_s2[Y_AXIS] = mechanics.data.max_acceleration_mm_per_s2[Z_AXIS] = mechanics.data.max_acceleration_mm_per_s2[X_AXIS];
#endif
planner.reset_acceleration_rates();
}
#if EXTRUDERS > 1
void _reset_e_acceleration_rate(const uint8_t e) { if (e == tools.active_extruder) _reset_acceleration_rates(); }
void _reset_e0_acceleration_rate() { _reset_e_acceleration_rate(0); }
void _reset_e1_acceleration_rate() { _reset_e_acceleration_rate(1); }
#if EXTRUDERS > 2
void _reset_e2_acceleration_rate() { _reset_e_acceleration_rate(2); }
#if EXTRUDERS > 3
void _reset_e3_acceleration_rate() { _reset_e_acceleration_rate(3); }
#if EXTRUDERS > 4
void _reset_e4_acceleration_rate() { _reset_e_acceleration_rate(4); }
#if EXTRUDERS > 5
void _reset_e5_acceleration_rate() { _reset_e_acceleration_rate(5); }
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
void _mechanics_refresh_positioning() {
#if MECH(DELTA)
mechanics.data.axis_steps_per_mm[Y_AXIS] = mechanics.data.axis_steps_per_mm[Z_AXIS] = mechanics.data.axis_steps_per_mm[X_AXIS];
#endif
planner.refresh_positioning();
}
#if EXTRUDERS > 1
void _mechanics_refresh_e_positioning(const uint8_t e) {
if (e == tools.active_extruder)
_mechanics_refresh_positioning();
else
mechanics.steps_to_mm[E_AXIS + e] = RECIPROCAL(mechanics.data.axis_steps_per_mm[E_AXIS + e]);
}
void _mechanics_refresh_e0_positioning() { _mechanics_refresh_e_positioning(0); }
void _mechanics_refresh_e1_positioning() { _mechanics_refresh_e_positioning(1); }
#if EXTRUDERS > 2
void _mechanics_refresh_e2_positioning() { _mechanics_refresh_e_positioning(2); }
#if EXTRUDERS > 3
void _mechanics_refresh_e3_positioning() { _mechanics_refresh_e_positioning(3); }
#if EXTRUDERS > 4
void _mechanics_refresh_e4_positioning() { _mechanics_refresh_e_positioning(4); }
#if EXTRUDERS > 5
void _mechanics_refresh_e5_positioning() { _mechanics_refresh_e_positioning(5); }
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#endif // EXTRUDERS > 1
#if MECH(DELTA)
void _mechanics_set_feedrate() {
mechanics.data.max_feedrate_mm_s[Y_AXIS] = mechanics.data.max_feedrate_mm_s[Z_AXIS] = mechanics.data.max_feedrate_mm_s[X_AXIS];
}
#endif
// M203 / M205 Velocity options
void menu_advanced_velocity() {
START_MENU();
MENU_BACK(MSG_ADVANCED_SETTINGS);
// M203 Max Feedrate
#if MECH(DELTA)
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float3, MSG_VMAX, &mechanics.data.max_feedrate_mm_s[X_AXIS], 1, 999, _mechanics_set_feedrate);
#else
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_X, &mechanics.data.max_feedrate_mm_s[X_AXIS], 1, 999);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_Y, &mechanics.data.max_feedrate_mm_s[Y_AXIS], 1, 999);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_Z, &mechanics.data.max_feedrate_mm_s[Z_AXIS], 1, 999);
#endif
#if EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E, &mechanics.data.max_feedrate_mm_s[E_AXIS + tools.active_extruder], 1, 999);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E1, &mechanics.data.max_feedrate_mm_s[E_AXIS], 1, 999);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E2, &mechanics.data.max_feedrate_mm_s[E_AXIS + 1], 1, 999);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E3, &mechanics.data.max_feedrate_mm_s[E_AXIS + 2], 1, 999);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E4, &mechanics.data.max_feedrate_mm_s[E_AXIS + 3], 1, 999);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E5, &mechanics.data.max_feedrate_mm_s[E_AXIS + 4], 1, 999);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E6, &mechanics.data.max_feedrate_mm_s[E_AXIS + 5], 1, 999);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#else
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMAX MSG_E, &mechanics.data.max_feedrate_mm_s[E_AXIS], 1, 999);
#endif
// M205 S Min Feedrate
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VMIN, &mechanics.data.min_feedrate_mm_s, 0, 999);
// M205 T Min Travel Feedrate
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VTRAV_MIN, &mechanics.data.min_travel_feedrate_mm_s, 0, 999);
END_MENU();
}
// M201 / M204 Accelerations
void menu_advanced_acceleration() {
START_MENU();
MENU_BACK(MSG_ADVANCED_SETTINGS);
// M204 P Acceleration
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_ACC, &mechanics.data.acceleration, 10, 99000);
// M204 R Retract Acceleration
#if EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E, &mechanics.data.retract_acceleration[tools.active_extruder], 100, 99000);
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E1, &mechanics.data.retract_acceleration[0], 100, 99000);
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E2, &mechanics.data.retract_acceleration[1], 100, 99000);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E3, &mechanics.data.retract_acceleration[2], 100, 99000);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E4, &mechanics.data.retract_acceleration[3], 100, 99000);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E5, &mechanics.data.retract_acceleration[4], 100, 99000);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E6, &mechanics.data.retract_acceleration[5], 100, 99000);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#else
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_RETRACT MSG_E, &mechanics.data.retract_acceleration[0], 100, 99000);
#endif
// M204 T Travel Acceleration
MENU_MULTIPLIER_ITEM_EDIT(float5, MSG_A_TRAVEL, &mechanics.data.travel_acceleration, 100, 99000);
// M201 settings
#if MECH(DELTA)
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX, &mechanics.data.max_acceleration_mm_per_s2[X_AXIS], 100, 99000, _reset_acceleration_rates);
#else
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_X, &mechanics.data.max_acceleration_mm_per_s2[X_AXIS], 100, 99000, _reset_acceleration_rates);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_Y, &mechanics.data.max_acceleration_mm_per_s2[Y_AXIS], 100, 99000, _reset_acceleration_rates);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_Z, &mechanics.data.max_acceleration_mm_per_s2[Z_AXIS], 10, 99000, _reset_acceleration_rates);
#endif
#if EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + tools.active_extruder], 100, 99000, _reset_acceleration_rates);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E1, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS], 100, 99000, _reset_e0_acceleration_rate);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E2, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 1], 100, 99000, _reset_e1_acceleration_rate);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E3, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 2], 100, 99000, _reset_e2_acceleration_rate);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E4, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 3], 100, 99000, _reset_e3_acceleration_rate);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E5, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 4], 100, 99000, _reset_e4_acceleration_rate);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E6, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS + 5], 100, 99000, _reset_e5_acceleration_rate);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#else
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(long5, MSG_AMAX MSG_E, &mechanics.data.max_acceleration_mm_per_s2[E_AXIS], 100, 99000, _reset_acceleration_rates);
#endif
END_MENU();
}
#if HAS_CLASSIC_JERK
void _mechanics_set_jerk() {
mechanics.data.max_jerk[Y_AXIS] = mechanics.data.max_jerk[Z_AXIS] = mechanics.data.max_jerk[X_AXIS];
}
#endif
// M205 Jerk
void menu_advanced_jerk() {
START_MENU();
MENU_BACK(MSG_MOTION);
#if ENABLED(JUNCTION_DEVIATION)
#if ENABLED(LIN_ADVANCE)
MENU_ITEM_EDIT_CALLBACK(float43, MSG_JUNCTION_MM, &mechanics.data.junction_deviation_mm, 0.01f, 0.3f, mechanics.recalculate_max_e_jerk);
#else
MENU_ITEM_EDIT(float43, MSG_JUNCTION_MM, &mechanics.data.junction_deviation_mm, 0.01f, 0.3f);
#endif
#endif
#if HAS_CLASSIC_JERK
#if MECH(DELTA)
MENU_ITEM_EDIT_CALLBACK(float3, MSG_JERK, &mechanics.data.max_jerk[X_AXIS], 1, 990, _mechanics_set_jerk);
#else
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VA_JERK, &mechanics.data.max_jerk[X_AXIS], 1, 990);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VB_JERK, &mechanics.data.max_jerk[Y_AXIS], 1, 990);
MENU_MULTIPLIER_ITEM_EDIT(float52sign, MSG_VC_JERK, &mechanics.data.max_jerk[Z_AXIS], 0.1, 990);
#endif
#if DISABLED(JUNCTION_DEVIATION) || DISABLED(LIN_ADVANCE)
#if EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E, &mechanics.data.max_jerk[E_AXIS + tools.active_extruder], 1, 990);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E1, &mechanics.data.max_jerk[E_AXIS], 1, 990);
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E2, &mechanics.data.max_jerk[E_AXIS + 1], 1, 990);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E3, &mechanics.data.max_jerk[E_AXIS + 2], 1, 990);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E4, &mechanics.data.max_jerk[E_AXIS + 3], 1, 990);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E5, &mechanics.data.max_jerk[E_AXIS + 4], 1, 990);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK MSG_E6, &mechanics.data.max_jerk[E_AXIS + 5], 1, 990);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#else
MENU_MULTIPLIER_ITEM_EDIT(float3, MSG_VE_JERK, &mechanics.data.max_jerk[E_AXIS], 1, 990);
#endif
#endif // DISABLED(JUNCTION_DEVIATION) || DISABLED(LIN_ADVANCE)
#endif // AS_CLASSIC_JERK
END_MENU();
}
// M92 Steps-per-mm
void menu_advanced_steps_per_mm() {
START_MENU();
MENU_BACK(MSG_ADVANCED_SETTINGS);
#if MECH(DELTA)
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_STEPS_PER_MM, &mechanics.data.axis_steps_per_mm[X_AXIS], 5, 9999, _mechanics_refresh_positioning);
#else
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_ASTEPS, &mechanics.data.axis_steps_per_mm[X_AXIS], 5, 9999, _mechanics_refresh_positioning);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_BSTEPS, &mechanics.data.axis_steps_per_mm[Y_AXIS], 5, 9999, _mechanics_refresh_positioning);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_CSTEPS, &mechanics.data.axis_steps_per_mm[Z_AXIS], 5, 9999, _mechanics_refresh_positioning);
#endif
#if EXTRUDERS > 1
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_ESTEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + tools.active_extruder], 5, 9999, _mechanics_refresh_positioning);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E1STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS], 5, 9999, _mechanics_refresh_e0_positioning);
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E2STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 1], 5, 9999, _mechanics_refresh_e1_positioning);
#if EXTRUDERS > 2
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E3STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 2], 5, 9999, _mechanics_refresh_e2_positioning);
#if EXTRUDERS > 3
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E4STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 3], 5, 9999, _mechanics_refresh_e3_positioning);
#if EXTRUDERS > 4
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E5STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 4], 5, 9999, _mechanics_refresh_e4_positioning);
#if EXTRUDERS > 5
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_E6STEPS, &mechanics.data.axis_steps_per_mm[E_AXIS + 5], 5, 9999, _mechanics_refresh_e4_positioning);
#endif // EXTRUDERS > 5
#endif // EXTRUDERS > 4
#endif // EXTRUDERS > 3
#endif // EXTRUDERS > 2
#else
MENU_MULTIPLIER_ITEM_EDIT_CALLBACK(float62, MSG_ESTEPS, &mechanics.data.axis_steps_per_mm[E_AXIS], 5, 9999, _mechanics_refresh_positioning);
#endif
END_MENU();
}
#if ENABLED(EEPROM_SETTINGS)
static void lcd_init_eeprom() {
sound.feedback(eeprom.Init());
lcdui.goto_previous_screen();
}
static void lcd_init_eeprom_confirm() {
START_MENU();
MENU_BACK(MSG_ADVANCED_SETTINGS);
MENU_ITEM(function, MSG_INIT_EEPROM, lcd_init_eeprom);
END_MENU();
}
#endif
#endif // !SLIM_LCD_MENUS
void menu_advanced_settings() {
START_MENU();
MENU_BACK(MSG_CONFIGURATION);
#if ENABLED(BABYSTEP_ZPROBE_OFFSET)
MENU_ITEM(submenu, MSG_ZPROBE_ZOFFSET, lcd_babystep_zoffset);
#elif HAS_BED_PROBE
MENU_ITEM_EDIT(float52, MSG_ZPROBE_ZOFFSET, &probe.data.offset[Z_AXIS], Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX);
#endif
#if DISABLED(SLIM_LCD_MENUS)
#if ENABLED(WORKSPACE_OFFSETS)
//
// Set Home Offsets
//
MENU_ITEM(function, MSG_SET_HOME_OFFSETS, _lcd_set_home_offsets);
#endif
// M203 / M205 - Feedrate items
MENU_ITEM(submenu, MSG_VELOCITY, menu_advanced_velocity);
// M201 - Acceleration items
MENU_ITEM(submenu, MSG_ACCELERATION, menu_advanced_acceleration);
// M205 - Junction Deviation or Max Jerk
#if ENABLED(JUNCTION_DEVIATION)
MENU_ITEM(submenu, MSG_JUNCTION_DEVIATION, menu_advanced_jerk);
#else
MENU_ITEM(submenu, MSG_JERK, menu_advanced_jerk);
#endif
if (!printer.isPrinting()) {
// M92 - Steps Per mm
MENU_ITEM(submenu, MSG_STEPS_PER_MM, menu_advanced_steps_per_mm);
}
#endif // !SLIM_LCD_MENUS
#if HAS_TRINAMIC
MENU_ITEM(submenu, MSG_TMC_DRIVERS, menu_tmc);
#endif
if (printer.mode == PRINTER_MODE_FFF) {
MENU_ITEM(submenu, MSG_TEMPERATURE, menu_advanced_temperature);
#if ENABLED(VOLUMETRIC_EXTRUSION) || ENABLED(ADVANCED_PAUSE_FEATURE)
MENU_ITEM(submenu, MSG_FILAMENT, menu_advanced_filament);
#elif ENABLED(LIN_ADVANCE)
MENU_ITEM_EDIT(float52, MSG_ADVANCE_K, &planner.extruder_advance_K, 0, 999);
#endif
}
// M540 S - Abort on endstop hit when SD printing
#if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
MENU_ITEM_EDIT(bool, MSG_ENDSTOP_ABORT, &planner.abort_on_endstop_hit);
#endif
//
// BLTouch Self-Test and Reset
//
#if ENABLED(BLTOUCH)
MENU_ITEM(gcode, MSG_BLTOUCH_SELFTEST, PSTR("M280 P" STRINGIFY(Z_PROBE_SERVO_NR) " S" STRINGIFY(BLTOUCH_SELFTEST)));
if (!endstops.isProbeEnabled() && bltouch.test())
MENU_ITEM(gcode, MSG_BLTOUCH_RESET, PSTR("M280 P" STRINGIFY(Z_PROBE_SERVO_NR) " S" STRINGIFY(BLTOUCH_RESET)));
#endif
#if ENABLED(EEPROM_SETTINGS) && DISABLED(SLIM_LCD_MENUS)
MENU_ITEM(submenu, MSG_INIT_EEPROM, lcd_init_eeprom_confirm);
#endif
END_MENU();
}
#endif // HAS_LCD_MENU
| 31,861 | 15,269 |
// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "helpers.hpp"
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/document/view.hpp>
#include <bsoncxx/test_util/catch.hh>
#include <mongocxx/exception/logic_error.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/private/conversions.hh>
#include <mongocxx/read_preference.hpp>
namespace {
using namespace bsoncxx;
using namespace mongocxx;
using builder::basic::kvp;
using builder::basic::make_document;
TEST_CASE("Read preference", "[read_preference]") {
instance::current();
read_preference rp;
SECTION("Defaults to mode primary, empty tags, and no max staleness") {
REQUIRE(rp.mode() == read_preference::read_mode::k_primary);
REQUIRE_FALSE(rp.tags());
REQUIRE_FALSE(rp.max_staleness());
}
SECTION("Can have mode changed") {
rp.mode(read_preference::read_mode::k_nearest);
REQUIRE(libmongoc::conversions::read_mode_t_from_read_mode(rp.mode()) ==
MONGOC_READ_NEAREST);
}
SECTION("Can have tags changed") {
auto tags = make_document(kvp("tag_key", "tag_value"));
rp.tags(tags.view());
REQUIRE(rp.tags().value() == tags);
}
SECTION("Can have max_staleness changed") {
std::chrono::seconds max_staleness{120};
rp.max_staleness(max_staleness);
REQUIRE(rp.max_staleness().value() == max_staleness);
}
SECTION("Max staleness of -1 returns nullopt") {
rp.max_staleness(std::chrono::seconds{-1});
REQUIRE(!rp.max_staleness());
}
SECTION("Rejects invalid max_staleness") {
REQUIRE_THROWS_AS(rp.max_staleness(std::chrono::seconds{0}), logic_error);
REQUIRE_THROWS_AS(rp.max_staleness(std::chrono::seconds{-2}), logic_error);
}
}
TEST_CASE("Read preference can be constructed with another read_mode", "[read_preference]") {
instance::current();
read_preference rp(read_preference::read_mode::k_secondary, read_preference::deprecated_tag{});
REQUIRE(rp.mode() == read_preference::read_mode::k_secondary);
REQUIRE_FALSE(rp.tags());
}
TEST_CASE("Read preference can be constructed with a read_mode and tags", "[read_preference]") {
instance::current();
auto tags = make_document(kvp("tag_key", "tag_value"));
read_preference rp(
read_preference::read_mode::k_secondary, tags.view(), read_preference::deprecated_tag{});
REQUIRE(rp.mode() == read_preference::read_mode::k_secondary);
REQUIRE(rp.tags().value() == tags);
}
TEST_CASE("Read preference equality operator works", "[read_preference]") {
instance::current();
read_preference rp_a;
read_preference rp_b;
SECTION("default-constructed read_preference objects are equal") {
REQUIRE(rp_a == rp_b);
}
SECTION("mode is compared") {
rp_a.mode(read_preference::read_mode::k_nearest);
REQUIRE_FALSE(rp_a == rp_b);
rp_b.mode(read_preference::read_mode::k_nearest);
REQUIRE(rp_a == rp_b);
}
SECTION("tags are compared") {
auto tags = make_document(kvp("tag_key", "tag_value"));
rp_a.tags(tags.view());
REQUIRE_FALSE(rp_a == rp_b);
rp_b.tags(tags.view());
REQUIRE(rp_a == rp_b);
}
SECTION("max_staleness is compared") {
std::chrono::seconds max_staleness{120};
rp_a.max_staleness(max_staleness);
REQUIRE_FALSE(rp_a == rp_b);
rp_b.max_staleness(max_staleness);
REQUIRE(rp_a == rp_b);
}
}
TEST_CASE("Read preference inequality operator works", "[read_preference]") {
instance::current();
read_preference rp_a;
read_preference rp_b;
REQUIRE_FALSE(rp_a != rp_b);
rp_a.mode(read_preference::read_mode::k_nearest);
REQUIRE(rp_a != rp_b);
}
TEST_CASE("Read preference methods call underlying mongoc methods", "[read_preference]") {
instance::current();
MOCK_READ_PREFERENCE
read_preference rp;
bool called = false;
SECTION("mode() calls mongoc_read_prefs_set_mode()") {
read_preference::read_mode expected_mode = read_preference::read_mode::k_nearest;
read_prefs_set_mode->interpose([&](mongoc_read_prefs_t*, mongoc_read_mode_t mode) {
called = true;
REQUIRE(mode == libmongoc::conversions::read_mode_t_from_read_mode(expected_mode));
});
rp.mode(expected_mode);
REQUIRE(called);
}
SECTION("tags() calls mongoc_read_prefs_set_tags()") {
auto expected_tags = make_document(kvp("foo", "bar"));
read_prefs_set_tags->interpose([&](mongoc_read_prefs_t*, const bson_t* tags) {
called = true;
REQUIRE(bson_get_data(tags) == expected_tags.view().data());
});
rp.tags(expected_tags.view());
REQUIRE(called);
}
SECTION("max_staleness() calls mongoc_read_prefs_set_max_staleness_seconds()") {
std::chrono::seconds expected_max_staleness_sec{150};
read_prefs_set_max_staleness_seconds->interpose(
[&](mongoc_read_prefs_t*, int64_t max_staleness_sec) {
called = true;
REQUIRE(std::chrono::seconds{max_staleness_sec} == expected_max_staleness_sec);
});
rp.max_staleness(expected_max_staleness_sec);
REQUIRE(called);
}
SECTION("hedge() calls mongoc_read_prefs_set_hedge") {
/* No hedge should return a disengaged optional. */
REQUIRE(!rp.hedge());
read_prefs_set_hedge->visit([&](mongoc_read_prefs_t*, const bson_t* doc) {
bson_iter_t iter;
REQUIRE(bson_iter_init_find(&iter, doc, "hedge"));
REQUIRE(bson_iter_as_bool(&iter) == true);
called = true;
});
rp.hedge(make_document(kvp("hedge", true)));
REQUIRE((*rp.hedge())["hedge"].get_bool().value == true);
REQUIRE(called);
}
}
} // namespace
| 6,444 | 2,309 |
#include "SequenceTextFile.h"
#include "SystemApis.h"
#include "Variables.h"
using namespace Utau;
Q_CHARSET_DECLARE(SequenceTextFile)
// Project File Reader
SequenceTextFile::SequenceTextFile() : BaseFile(Qs::Default) {
m_codec = defaultCodec;
reset();
}
SequenceTextFile::SequenceTextFile(const QString &filename) : BaseFile(Qs::Default) {
m_codec = defaultCodec;
setFilename(filename);
}
SequenceTextFile::~SequenceTextFile() {
}
SequenceTextFile::SequenceTextFile(Qs::VariableSource source) : BaseFile(source) {
}
bool SequenceTextFile::loadCore(bool *valid) {
QFile file(m_filename);
QByteArray data;
bool isUnicode = false;
if (!file.open(QFile::ReadOnly | QIODevice::Text)) {
if (*valid) {
*valid = true;
}
return false;
}
data = file.readAll();
file.close();
// Detect Code
QTextCodec *codec = GetUtfCodec(data);
QTextStream in(&data);
if (codec) {
m_codec = codec;
}
in.setCodec(m_codec);
// Read File
QStringList currentSection;
QString line;
QString sectionName;
QString sectionHead;
QLinkNote curNote;
int curLength;
bool result = true;
bool num = false;
bool projectValid = true;
bool findVersion, findSetting, findNote;
findVersion = findSetting = findNote = false;
curLength = 0;
try {
while (!in.atEnd()) {
line = in.readLine();
if (line.isEmpty() && !in.atEnd()) {
continue;
}
// Continue to add until meet the start of section or end
if (!line.startsWith(SECTION_BEGIN_MARK) && !in.atEnd()) {
currentSection.push_back(line);
continue;
}
// If meet end, append without continue
if (!line.isEmpty() && in.atEnd()) {
currentSection.push_back(line);
}
// Previous section is empty
if (currentSection.size() <= 1) {
} else {
sectionHead = currentSection[0];
// If Section Name is invalid
if (!parseSectionName(sectionHead, sectionName)) {
currentSection.clear();
continue;
}
// If Section Name is a number
num = false;
sectionName.toInt(&num);
if (num) {
// Parse Note
findNote = true;
curNote.clear();
if (parseSectionNote(currentSection, curNote)) {
// curNote.tick = curLength;
// Ignore note whose length is invalid
if (curNote.length > 0) {
m_sectionNotes.push_back(curNote);
curLength += curNote.length; // Add to main tick count
}
} else {
projectValid = false;
}
} else if (sectionName == SECTION_NAME_VERSION) {
// Parse Version Sequence
findVersion = true;
if (!parseSectionVersion(currentSection, m_sectionVersion)) {
projectValid = false;
}
// Not Unicode
QString charset = m_sectionVersion.charset;
if (!isUnicode) {
if (!charset.isEmpty()) {
QTextCodec *newCodec =
QTextCodec::codecForName(m_sectionVersion.charset.toLatin1());
if (newCodec) {
in.setCodec(newCodec);
}
} else {
}
}
} else if (sectionName == SECTION_NAME_SETTING) {
// Parse global settings
findSetting = true;
if (!parseSectionSettings(currentSection, m_sectionSettings)) {
projectValid = false;
}
}
}
currentSection.clear();
currentSection.push_back(line);
}
if (!(findVersion || findSetting || findNote)) {
result = false;
projectValid = false;
}
} catch (...) {
result = false;
projectValid = false;
}
if (valid) {
*valid = projectValid;
}
return result;
}
bool SequenceTextFile::saveCore() {
QFile file(m_filename);
if (!file.open(QFile::WriteOnly | QIODevice::Text)) {
return false;
}
QTextStream out(&file);
QString charset = m_sectionVersion.charset;
if (!charset.isEmpty()) {
m_codec = QTextCodec::codecForName(charset.toLatin1()); // Write UTF-8
}
out.setCodec(m_codec);
writeSectionVersion(out); // Write Version
writeSectionSettings(out); // Write Global Settings
// Write Notes
for (int i = 0; i < m_sectionNotes.size(); ++i) {
writeSectionNote(i, m_sectionNotes.at(i), out);
}
writeSectionName(SECTION_NAME_TRACKEND, out); // Write End Sign
file.close();
return true;
}
void SequenceTextFile::resetCore() {
m_sectionVersion.clear();
m_sectionSettings.clear();
m_sectionNotes.clear();
}
SectionVersion SequenceTextFile::sectionVersion() const {
return m_sectionVersion;
}
SectionVersion &SequenceTextFile::sectionVersion() {
return m_sectionVersion;
}
void SequenceTextFile::setSectionVersion(const SectionVersion &value) {
m_sectionVersion = value;
}
QList<QLinkNote> SequenceTextFile::sectionNotes() const {
return m_sectionNotes;
}
QList<QLinkNote> &SequenceTextFile::sectionNotes() {
return m_sectionNotes;
}
void SequenceTextFile::setSectionNotes(const QList<QLinkNote> &value) {
m_sectionNotes = value;
}
void SequenceTextFile::clearSectionNotes() {
m_sectionNotes.clear();
}
void SequenceTextFile::appendSectionNote(const QLinkNote &oNote) {
m_sectionNotes.push_back(oNote);
}
QLinkNote SequenceTextFile::popSectionNote() {
QLinkNote aNote = m_sectionNotes.back();
m_sectionNotes.pop_back();
return aNote;
}
SectionSettings SequenceTextFile::sectionSettings() const {
return m_sectionSettings;
}
SectionSettings &SequenceTextFile::sectionSettings() {
return m_sectionSettings;
}
void SequenceTextFile::setSectionSettings(const SectionSettings &value) {
m_sectionSettings = value;
}
bool SequenceTextFile::parseSectionName(const QString &oName, QString &oResult) {
if (oName.startsWith(SECTION_BEGIN_MARK) && oName.endsWith(SECTION_END_MARK)) {
oResult = oName.mid(SECTION_BEGIN_MARK.size(),
oName.size() - SECTION_BEGIN_MARK.size() - SECTION_END_MARK.size());
return true;
} else {
return false;
}
}
bool SequenceTextFile::parseSectionNote(const QStringList §ionList, QLinkNote ¬e) {
QStringList::size_type i;
bool isValid = true;
int eq;
QString line;
QString key, value;
int valueInt;
double valueDouble;
bool isInt, isDouble;
PBStrings mode2;
QString strEnv;
for (i = 0; i < sectionList.size(); ++i) {
line = sectionList.at(i);
eq = line.indexOf('=');
if (eq <= 0) {
continue;
}
key = line.left(eq);
value = line.mid(eq + 1);
valueInt = value.toInt(&isInt);
valueDouble = value.toDouble(&isDouble);
if (key == KEY_NAME_LYRIC) {
note.lyric = value; // Lyric
} else if (key == KEY_NAME_NOTE_NUM) {
if (isInt) {
note.noteNum = valueInt; // Note Num
}
} else if (key == KEY_NAME_LENGTH) {
if (isInt) {
note.length = valueInt; // Length
}
} else if (key == KEY_NAME_FLAGS) {
note.flags = value; // Flags
} else if (key == KEY_NAME_INTENSITY) {
if (isDouble) {
note.intensity = valueDouble; // Volume
}
} else if (key == KEY_NAME_MODULATION || key == KEY_NAME_MODURATION) {
if (isDouble) {
note.modulation = valueDouble; // Modulation
}
} else if (key == KEY_NAME_PRE_UTTERANCE) {
if (isDouble) {
note.preUttr = valueDouble; // PreUtterence
}
} else if (key == KEY_NAME_VOICE_OVERLAP) {
if (isDouble) {
note.overlap = valueDouble; // Voice Overlap
}
} else if (key == KEY_NAME_VELOCITY) {
if (isDouble) {
note.velocity = valueDouble; // Consonant Velocity
}
} else if (key == KEY_NAME_START_POINT) {
if (isDouble) {
note.stp = valueDouble; // StartPoint
}
} else if (key == KEY_NAME_TEMPO) {
if (isDouble) {
note.tempo = valueDouble; // Tempo
}
} else if (key == KEY_NAME_REGION_START) {
note.region = value; // Start of region
} else if (key == KEY_NAME_REGION_END) {
note.regionEnd = value; // End of region
} else if (key == KEY_NAME_PB_START) {
if (isDouble) {
note.pbstart = valueDouble; // Mode1 Start
}
} else if (key == KEY_NAME_PBS) {
mode2.PBS = value; // Mode2 Start
} else if (key == KEY_NAME_PBW) {
mode2.PBW = value; // Mode2 Intervals
} else if (key == KEY_NAME_PBY) {
mode2.PBY = value; // Mode2 Offsets
} else if (key == KEY_NAME_PBM) {
mode2.PBM = value; // Mode2 Types
} else if (key == KEY_NAME_PB_START) {
if (isDouble) {
note.pbstart = valueDouble; // Mode1 Start
}
} else if (key == KEY_NAME_PICHES || key == KEY_NAME_PITCHES ||
key == KEY_NAME_PITCH_BEND) {
note.pitches = StringsToDoubles(value.split(COMMA)); // Mode1 Pitch
} else if (key == KEY_NAME_VBR) {
note.vibrato = StringsToDoubles(value.split(COMMA)); // Vibrato
} else if (key == KEY_NAME_ENVELOPE) {
strEnv = value; // Envelope
} else if (!key.startsWith('@')) {
note.customData.append(qMakePair(key, value)); // Custom Values
}
}
note.Mode2Pitch = StringToPortamento(mode2); // Mode2 Pitch
note.envelope = StringToEnvelope(strEnv);
return isValid;
}
bool SequenceTextFile::parseSectionVersion(const QStringList §ionList,
SectionVersion &version) {
int i;
bool flag = false;
int eq;
QString line;
QString key, value;
for (i = 0; i < sectionList.size(); ++i) {
line = sectionList.at(i);
eq = line.indexOf('=');
if (eq >= 0) {
key = line.left(eq);
value = line.mid(eq + 1);
if (key == KEY_NAME_CHARSET) {
m_sectionVersion.charset = value;
}
continue;
}
if (line.indexOf(UST_VERSION_PREFIX_NOSPACE) == 0) {
version.version = line.mid(UST_VERSION_PREFIX_NOSPACE.size()).simplified();
flag = true;
}
}
return flag;
}
bool SequenceTextFile::parseSectionSettings(const QStringList §ionList,
SectionSettings &settings) {
QStringList::size_type i;
bool isValid = true;
int eq;
QString key, value;
double num;
bool isNum;
for (i = 0; i < sectionList.size(); ++i) {
eq = sectionList[i].indexOf("=");
if (eq <= 0) {
continue;
}
key = sectionList[i].left(eq);
value = sectionList[i].mid(eq + 1);
if (key == KEY_NAME_PROJECT_NAME) {
settings.projectName = value; // Project Name
} else if (key == KEY_NAME_OUTPUT_FILE) {
settings.outputFileName = value; // Output File Name
} else if (key == KEY_NAME_VOICE_DIR) {
settings.voiceDirectory = fromUSTVoiceDir(value, AppPath); // Voice Directory
} else if (key == KEY_NAME_CACHE_DIR) {
settings.cacheDirectory = value; // Cache Directory
} else if (key == KEY_NAME_TOOL1) {
settings.wavtoolPath = fromUSTToolsDir(value, AppPath); // Wavtool
} else if (key == KEY_NAME_TOOL2) {
settings.resamplerPath = fromUSTToolsDir(value, AppPath); // Resampler
} else if (key == KEY_NAME_MODE2) {
if (value != "True") {
isValid = false;
}
settings.isMode2 = true; // Mode2
} else if (key == KEY_NAME_TEMPO) {
num = value.toDouble(&isNum);
if (!isNum) {
isValid = false;
} else {
settings.globalTempo = num; // Global Tempo
}
} else if (key == KEY_NAME_FLAGS) {
settings.globalFlags = value; // Flags
}
}
return isValid;
}
void SequenceTextFile::writeSectionName(const int &name, QTextStream &out) {
QString newName = QString::number(name);
int nums = newName.size();
for (int i = 0; i < 4 - nums; ++i) {
newName.prepend("0");
}
writeSectionName(newName, out);
}
void SequenceTextFile::writeSectionName(const QString &name, QTextStream &out) {
out << SECTION_BEGIN_MARK + name + SECTION_END_MARK << Qt::endl;
}
void SequenceTextFile::writeSectionNote(int num, const QLinkNote ¬e, QTextStream &out) {
writeSectionName(num, out);
// Items maybe not exist
QString aVibrato = DoublesToStrings(note.vibrato).join(COMMA);
QString aPitchBend = DoublesToStrings(note.pitches).join(COMMA);
// Complex items
PBStrings mode2;
QString strEnvelope;
mode2 = PortamentoToString(note.Mode2Pitch);
strEnvelope = EnvelopeToString(note.envelope);
// Items always exists
out << KEY_NAME_LENGTH << "=" << note.length << Qt::endl;
out << KEY_NAME_LYRIC << "=" << note.lyric << Qt::endl;
out << KEY_NAME_NOTE_NUM << "=" << note.noteNum << Qt::endl;
// Items can be omitted
if (note.preUttr != NODEF_DOUBLE) {
out << KEY_NAME_PRE_UTTERANCE << "=" << note.preUttr << Qt::endl;
}
if (note.overlap != NODEF_DOUBLE) {
out << KEY_NAME_VOICE_OVERLAP << "=" << note.overlap << Qt::endl;
}
if (note.velocity != NODEF_DOUBLE) {
out << KEY_NAME_VELOCITY << "=" << QString::number(note.velocity) << Qt::endl;
}
if (note.intensity != NODEF_DOUBLE) {
out << KEY_NAME_INTENSITY << "=" << note.intensity << Qt::endl;
}
if (note.modulation != NODEF_DOUBLE) {
out << KEY_NAME_MODULATION << "=" << note.modulation << Qt::endl;
}
if (note.stp != NODEF_DOUBLE) {
out << KEY_NAME_START_POINT << "=" << note.stp << Qt::endl;
}
if (!note.flags.isEmpty()) {
out << KEY_NAME_FLAGS << "=" << note.flags << Qt::endl;
}
// Items may not exist
if (!note.pitches.isEmpty()) {
out << KEY_NAME_PB_TYPE << "=" << VALUE_PITCH_TYPE << Qt::endl;
out << KEY_NAME_PB_START << "=" << note.pbstart << Qt::endl;
out << KEY_NAME_PITCH_BEND << "=" << aPitchBend << Qt::endl;
}
if (!note.Mode2Pitch.isEmpty()) {
out << KEY_NAME_PBS << "=" << mode2.PBS << Qt::endl;
out << KEY_NAME_PBW << "=" << mode2.PBW << Qt::endl;
if (!mode2.PBY.isEmpty()) {
out << KEY_NAME_PBY << "=" << mode2.PBY << Qt::endl;
}
if (!mode2.PBS.isEmpty()) {
out << KEY_NAME_PBM << "=" << mode2.PBM << Qt::endl;
}
}
if (!note.envelope.isEmpty()) {
out << KEY_NAME_ENVELOPE << "=" << strEnvelope << Qt::endl;
}
if (!note.vibrato.isEmpty()) {
out << KEY_NAME_VBR << "=" << aVibrato << Qt::endl;
}
if (note.tempo != NODEF_DOUBLE) {
out << KEY_NAME_TEMPO << "=" << note.tempo << Qt::endl;
}
if (note.region != NODEF_STRING) {
out << KEY_NAME_REGION_START << "=" << note.region << Qt::endl;
}
if (note.regionEnd != NODEF_STRING) {
out << KEY_NAME_REGION_END << "=" << note.regionEnd << Qt::endl;
}
// Custom Values
for (int i = 0; i < note.customData.size(); ++i) {
out << note.customData[i].first << "=" << note.customData[i].second << Qt::endl;
}
}
void SequenceTextFile::writeSectionVersion(QTextStream &out) {
writeSectionName(SECTION_NAME_VERSION, out);
out << UST_VERSION_PREFIX_NOSPACE << m_sectionVersion.version << Qt::endl;
// UTF-8 UST File?
QString charset = m_sectionVersion.charset;
if (!charset.isEmpty()) {
out << KEY_NAME_CHARSET << "=" << charset << Qt::endl;
}
}
void SequenceTextFile::writeSectionSettings(QTextStream &oStream) {
writeSectionName(SECTION_NAME_SETTING, oStream);
oStream << KEY_NAME_TEMPO << "=" << m_sectionSettings.globalTempo << Qt::endl;
oStream << KEY_NAME_TRACKS << "=" << VALUE_TRACKS_SINGLE << Qt::endl;
oStream << KEY_NAME_PROJECT_NAME << "=" << m_sectionSettings.projectName << Qt::endl;
oStream << KEY_NAME_VOICE_DIR << "=" << toUSTVoiceDir(m_sectionSettings.voiceDirectory, AppPath)
<< Qt::endl;
oStream << KEY_NAME_OUTPUT_FILE << "=" << m_sectionSettings.outputFileName << Qt::endl;
oStream << KEY_NAME_CACHE_DIR << "=" << m_sectionSettings.cacheDirectory << Qt::endl;
oStream << KEY_NAME_TOOL1 << "=" << toUSTToolsDir(m_sectionSettings.wavtoolPath, AppPath)
<< Qt::endl;
oStream << KEY_NAME_TOOL2 << "=" << toUSTToolsDir(m_sectionSettings.resamplerPath, AppPath)
<< Qt::endl;
if (m_sectionSettings.isMode2) {
oStream << KEY_NAME_MODE2 << "=" << VALUE_MODE2_ON << Qt::endl;
}
if (!m_sectionSettings.globalFlags.isEmpty()) {
oStream << KEY_NAME_FLAGS << "=" << m_sectionSettings.globalFlags << Qt::endl;
}
}
| 18,160 | 5,711 |
// Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlApprLineFit3.h"
#include "WmlContSphere3.h"
#include "WmlIntrSph3Sph3.h"
#include "WmlMatrix3.h"
#include "WmlSphereBV.h"
using namespace Wml;
WmlImplementBV(SphereBV,BV_SPHERE);
//----------------------------------------------------------------------------
void SphereBV::CopyTo (BoundingVolume* pkTargetBV) const
{
assert( GetType() == pkTargetBV->GetType() );
((SphereBV*)pkTargetBV)->m_kSphere = m_kSphere;
}
//----------------------------------------------------------------------------
void SphereBV::TransformTo (BoundingVolume* pkTargetBV,
const Matrix3f& rkRot, const Vector3f& rkTrn, float fScale) const
{
assert( GetType() == pkTargetBV->GetType() );
Sphere3f& rkTarget = ((SphereBV*)pkTargetBV)->m_kSphere;
rkTarget.Center() = fScale*(rkRot*m_kSphere.Center()) + rkTrn;
rkTarget.Radius() = fScale*m_kSphere.Radius();
}
//----------------------------------------------------------------------------
bool SphereBV::Contains (const Vector3f& rkPoint, float fEpsilon) const
{
return InSphere(rkPoint,m_kSphere,fEpsilon);
}
//----------------------------------------------------------------------------
bool SphereBV::TestIntersection (const BoundingVolume* pkBV) const
{
assert( GetType() == pkBV->GetType() );
return Wml::TestIntersection(m_kSphere,((SphereBV*)pkBV)->m_kSphere);
}
//----------------------------------------------------------------------------
BoundingVolume* SphereBV::Create ()
{
return new SphereBV;
}
//----------------------------------------------------------------------------
BoundingVolume* SphereBV::Create (int iVertexCount, const Vector3f* akVertex,
const int* aiConnect, int i0, int i1, int* aiISplit, Vector3f& rkOrigin,
Vector3f& rkDirection)
{
// tag vertices that are used in the submesh
bool* abValid = new bool[iVertexCount];
memset(abValid,0,iVertexCount*sizeof(bool));
for (int i = i0; i <= i1; i++)
{
int iIndex = 3*aiISplit[i];
abValid[aiConnect[iIndex++]] = true;
abValid[aiConnect[iIndex++]] = true;
abValid[aiConnect[iIndex++]] = true;
}
SphereBV* pkSphereBV = new SphereBV;
ContSphereAverage(iVertexCount,akVertex,abValid,pkSphereBV->m_kSphere);
OrthogonalLineFit(iVertexCount,akVertex,abValid,rkOrigin,rkDirection);
delete[] abValid;
return pkSphereBV;
}
//----------------------------------------------------------------------------
| 2,893 | 957 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/panorama/model/S3Location.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Panorama
{
namespace Model
{
S3Location::S3Location() :
m_bucketNameHasBeenSet(false),
m_objectKeyHasBeenSet(false),
m_regionHasBeenSet(false)
{
}
S3Location::S3Location(JsonView jsonValue) :
m_bucketNameHasBeenSet(false),
m_objectKeyHasBeenSet(false),
m_regionHasBeenSet(false)
{
*this = jsonValue;
}
S3Location& S3Location::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("BucketName"))
{
m_bucketName = jsonValue.GetString("BucketName");
m_bucketNameHasBeenSet = true;
}
if(jsonValue.ValueExists("ObjectKey"))
{
m_objectKey = jsonValue.GetString("ObjectKey");
m_objectKeyHasBeenSet = true;
}
if(jsonValue.ValueExists("Region"))
{
m_region = jsonValue.GetString("Region");
m_regionHasBeenSet = true;
}
return *this;
}
JsonValue S3Location::Jsonize() const
{
JsonValue payload;
if(m_bucketNameHasBeenSet)
{
payload.WithString("BucketName", m_bucketName);
}
if(m_objectKeyHasBeenSet)
{
payload.WithString("ObjectKey", m_objectKey);
}
if(m_regionHasBeenSet)
{
payload.WithString("Region", m_region);
}
return payload;
}
} // namespace Model
} // namespace Panorama
} // namespace Aws
| 1,535 | 580 |
#include "rollkit/characteristic.hpp"
#include <algorithm>
#include "rollkit/utils.hpp"
using namespace std;
namespace rollkit {
nlohmann::json Characteristic::serialize() const {
nlohmann::json ret;
bool is_readable = find(_perms.begin(), _perms.end(), "pr") != _perms.end();
ret["type"] = _hap_type;
ret["iid"] = _instance_id;
ret["perms"] = _perms;
ret["format"] = _format;
if(is_readable) {
ret["value"] = handle_read();
}
return ret;
}
} // namespace rollkit
| 496 | 191 |
/**
* @Author: Alcwyn Parker <alcwynparker>
* @Date: 2017-04-28T21:06:23+01:00
* @Email: alcwynparker@gmail.com
* @Project: Anemone
* @Filename: Anemone.cpp
* @Last modified by: alcwynparker
* @Last modified time: 2017-05-10T00:00:10+01:00
*/
#include "Arduino.h"
#include "Anemone.h"
Anemone::Anemone(int pin)
{
ssout = pin;
// put your setup code here, to run once:
pinMode(ssout, OUTPUT);
for (int i = 0; i < BITNUMBER; i++){
}
}
void Anemone::start(){
clear();
saveSwitchStates();
delay(1000);
}
/**
* void ledsOff - Loop thorugh the char array and set of the char
* back to zero
*
*/
void Anemone::clear(){
// loop through all sendBytes and set the bits to on (OFF for the bus);
for (int i=0; i < BYTENUMBER; i++)
{
sendBytes[i] = 255;
}
updateLEDs();
}
/**
* void updateLEDa - Handles the SPI transaction. Sends each byte individually
* and receives a byte each time (the switch state);
*
*/
void Anemone::updateLEDs()
{
// Start transaction
SPI.beginTransaction(SPISettings(150000, MSBFIRST, SPI_MODE3));
digitalWrite(ssout, LOW);
// loop through and send each byte
for (int i = 0; i < BYTENUMBER; i++){
byte sendByte = sendBytes[i];
// flip bits
sendByte = ((sendByte >> 1) & 0x55) | ((sendByte << 1) & 0xaa);
sendByte = ((sendByte >> 2) & 0x33) | ((sendByte << 2) & 0xcc);
sendByte = ((sendByte >> 4) & 0x0f) | ((sendByte << 4) & 0xf0);
returnBytes[i] = SPI.transfer(sendByte);
}
// end transaction
SPI.endTransaction();
digitalWrite(ssout, HIGH);
processReturnBytes();
}
/**
* void Anemone - reverses the returnBytes array so that it is in the
* right order / flips each byte at the same time!
*
* FOUND: http://forum.arduino.cc/index.php?topic=70463.0
*/
void Anemone::processReturnBytes(){
for (int i=0, j = BYTENUMBER-1; i< BYTENUMBER/2; i++, j--)
{
byte iByte = returnBytes[i];
byte jByte = returnBytes[j];
/*
// flip bits
iByte = ((iByte >> 1) & 0x55) | ((iByte << 1) & 0xaa);
iByte = ((iByte >> 2) & 0x33) | ((iByte << 2) & 0xcc);
iByte = ((iByte >> 4) & 0x0f) | ((iByte << 4) & 0xf0);
jByte = ((jByte >> 1) & 0x55) | ((jByte << 1) & 0xaa);
jByte = ((jByte >> 2) & 0x33) | ((jByte << 2) & 0xcc);
jByte = ((jByte >> 4) & 0x0f) | ((jByte << 4) & 0xf0);
*/
returnBytes[i] = jByte;
returnBytes[j] = iByte;
}
}
/**
* void saveSwitchStates - save this frames switch states for the debounce
* process in the next frame
*
*/
void Anemone::saveSwitchStates(){
// Save returnBytes to prevReturnBytes for debounce processing
for (int i = 0; i < BYTENUMBER; i++){
prevReturnBytes[i] = returnBytes[i];
}
}
/**
* void ledWrite - alter a single LED in the char array
*
* @param {int} index of the LED to change
* @param {int} the state to change | 0 on / 1 off
*
*/
void Anemone::ledWrite(int index, int state){
// invert the index to allow for right to left declaration
//index = BITNUMBER - index - 1;
int nodeByte = index / 8; // which byte
int nodeBit = index % 8; // which bit
// update char to bit
bitWrite(sendBytes[nodeByte], nodeBit, state);
}
/**
* ledRead - returns true if the led is on or false if it is off
*
* @param {int} index of the led
* @return {bool} state of the led
*/
bool Anemone::ledRead(int index){
int nodeByte = index / 8; // which byte
int nodeBit = index % 8; // which bit
// update char to bit
int val = bitRead(sendBytes[nodeByte], nodeBit);
if (val == 0){
return true;
}else{
return false;
}
}
/**
* void checkActiveSwitches - loops through and compares the returnBytes to the
* prevBytes and updates the activeSwitches byte array.
* TODO: Eventually this should be done with a bit operator to speed things up
*
* processBytes must be called prior to returnActiveSwitches
* @return {type} description
*/
void Anemone::checkActiveSwitches(){
for (int i = 0; i < BITNUMBER; i++){
int nodeByte = i / 8; // which byte
int nodeBit = i % 8; // which bit
int prevBit = bitRead(prevReturnBytes[nodeByte], nodeBit);
int currentBit = bitRead(returnBytes[nodeByte], nodeBit);
if (prevBit != currentBit){
bitWrite(activeSwitches[nodeByte], nodeBit, 0);
}else{
bitWrite(activeSwitches[nodeByte], nodeBit, 1);
}
}
}
/**
* bool checkSwitch - returns true or false depending on whether the switch Handles
* been toggled
*
* @param {type} int index of the switch
* @return {bool} a flag for if the switch has been toggled
*/
bool Anemone::checkSwitch(int index){
int nodeByte = index / 8; // which byte
int nodeBit = index % 8; // which bit
int switchToggleState = bitRead(activeSwitches[nodeByte], nodeBit);
if (switchToggleState == 0){
return true;
}else{
return false;
}
}
/**
* void toggleLED - simply toggles an LEDs bit
*
* TODO: Replace this operation with a bit operator
*
* @param {int} index of the LED
*/
void Anemone::toggleLED(int index){
int nodeByte = index / 8; // which byte
int nodeBit = index % 8; // which bit
int ledState = bitRead(sendBytes[nodeByte], nodeBit);
if (ledState == 1){
bitWrite(sendBytes[nodeByte], nodeBit, 0);
}else{
bitWrite(sendBytes[nodeByte], nodeBit, 1);
}
}
/**
* getSwitchTimer - returns the timer from a specific switchTimers
* used to implement the debounce timer.
*
* @param {int}
* @return {type} timer value - counting down to activate
*/
uint8_t Anemone::getSwitchTimer(int index){
return switchTimers[index];
}
/**
* setSwitchTimer - sets the switch timer
* used to implement the debounce timer.
* @param {int} index of the switch
* @param {type} value to start the timer at
*/
void Anemone::setSwitchTimer(int index, int val){
switchTimers[index] = val;
}
/**
* stepSwitchTimer - counts the timer down a step
* used to implement the debounce timer.
* @param {int} index of the switch
*/
void Anemone::stepSwitchTimer(int index){
switchTimers[index]--;
}
/**
* overrideActiveSwitch - used for debounce to stop misreadings
*
* @param {int} index of switch
* @param {int} value to set the active switch to
*
*/
void Anemone::overrideActiveSwitch(int index, int val){
int nodeByte = index / 8; // which byte
int nodeBit = index % 8; // which bit
bitWrite(activeSwitches[nodeByte], nodeBit, val);
}
/**
* void clearDebounce - reset the debounce from the next frame
*
*
*/
void Anemone::clearDebounce(){
for (int i = 0; i < BYTENUMBER; i++){
debounce[i] = 255;
}
}
/**
* node - This is the public facing function that returns the result of the debounce
* for interaction with the switches
*
* @param {int} index of the switch
* @return {bool} is the switch on or off
*/
bool Anemone::node(int index){
int switchByte = index / 8; // which byte
int switchBit = index % 8; // which bit
if (bitRead(debounce[switchByte], switchBit) == 0){
return true;
}else{
return false;
}
}
/**
* void update - this is called everyframe to update everything
*
*/
void Anemone::update(){
clearDebounce();
updateLEDs();
checkActiveSwitches();
// debounce process (BYTES 1 OFF / 0 ON)
for (int i = 0; i < BITNUMBER; i++){
// Find position in the byte array
int switchByte = i / 8; // which byte
int switchBit = i % 8; // which bit
// Get debounce specific values
bool stateChange = checkSwitch(i);
int timerVal = getSwitchTimer(i);
// check for cancellation through noise
if (stateChange == true && timerVal > 0) {
setSwitchTimer(i, 0);
overrideActiveSwitch(i, 1);
//Serial.println("RESET");
}
if(stateChange == true && timerVal == 0){
setSwitchTimer(i, 9);
//Serial.println("START");
}
// count down to trigger
if (timerVal > 1 && stateChange == false) {
stepSwitchTimer(i);
//Serial.println("COUNT DOWN");
}
// Trigger Action
if (timerVal == 1) {
setSwitchTimer(i, 0);
bitWrite(debounce[switchByte], switchBit, 0);
//Serial.println("ACTIVATE");
}
}
// save for next time
saveSwitchStates();
}
/**
* getRingStart - Returns the first index of a node in a ring
*
* @param {int} the number of the ring (bottom=0 top =8)
* @return {int} indec of first node
*/
int Anemone::getRingStart(int ring){
return ringStarts[ring];
}
/**
* getRingEnd - Returns the last index of a node in a ring
*
* @param {int} the number of the ring (bottom=0 top =8)
* @return {int} index of last node
*/
int Anemone::getRingEnd(int ring){
return ringEnds[ring];
}
/**
* void lightRing - set all the LEDs in a ring to be on when the next update
* is called
*
* @param {int} index of the ring
*/
void Anemone::lightRing(int ring){
int start = getRingStart(ring);
int end = getRingEnd(ring);
for (int i = start; i <= end; i++){
ledWrite(i, 0);
}
}
/**
* void clearRing - set all the LEDs in a ring to be off when the next update
* is called
*
* @param {int} index of the ring
*/
void Anemone::clearRing(int ring){
int start = getRingStart(ring);
int end = getRingEnd(ring);
for (int i = start; i <= end; i++){
ledWrite(i, 1);
}
}
/**
* void getRingNodeCount - returns the number of leds in the ring
*
* @param {int} number of leds
*/
int Anemone::getRingNodeCount(int ring){
return ringNodeCount[ring];
}
void Anemone::debugArray(byte *a) {
for (int i = 0; i < BITNUMBER; i++) {
int switchByte = i / 8; // which byte
int switchBit = i % 8; // which bit
int val = bitRead(a[switchByte], switchBit);
Serial.print(val);
if (switchBit == 7) Serial.print("-");
}
Serial.println("");
}
void Anemone::debugByte(byte b) {
for (int i = 0; i < 8; i++) {
int val = bitRead(b, i);
Serial.print(val);
}
}
| 10,014 | 3,623 |
// mckay.cpp
//
// solver due to Brendan McKay
// C++ translation by Volker Widor 2003
// adapted by Anton Betten
// 1/16/2009
#include "foundations.h"
using namespace std;
namespace orbiter {
namespace foundations {
mckay::tMCKAY::tMCKAY() {
nb_calls_to_solve = 0;
first_moved = 0;
second_moved = 0;
problem_label = NULL;
_eqnanz = 0;
_varanz = 0;
//vector<bool> unitcoeffs;
//vector<bool> active;
rekurs = 0;
_break = false;
D = NULL;
//tLGS *_lgs;
#ifdef MCKAY_DEBUG
//vector<int> range, split, branch;
ticks0 = 0;
#endif
};
void mckay::tMCKAY::Init(diophant *lgs,
const char *label, int aEqnAnz, int aVarAnz)
{
os_interface Os;
_varanz=aVarAnz;
_eqnanz=aEqnAnz;
nb_calls_to_solve = 0;
D = lgs;
//_lgs = aLgs;
rekurs=0;
unitcoeffs.resize(_eqnanz);
active.resize(_eqnanz);
problem_label = label;
#ifdef MCKAY_DEBUG
int m;
m = MAXIMUM(_eqnanz, _varanz) + 1;
range.resize(m);
split.resize(m);
branch.resize(m);
ticks0 = Os.os_ticks();
#endif
}
void mckay::tMCKAY::possolve(vector<int> &lo, vector<int> &hi,
vector<equation> &eqn, vector<int> &lorhs, vector<int> &hirhs,
vector<int> &neqn, int numeqn, int numvar, int verbose_level)
{
int f_v = (verbose_level >= 1);
int f_v4 = (verbose_level >= 4);
int i,j;
bool hopeless;
if (f_v) {
cout << "possolve" << endl;
}
nb_calls_to_solve = 0;
first_moved = INT_MAX;
second_moved = INT_MAX;
if (numeqn > _eqnanz || numvar > _varanz) {
cerr<<"*** >E intsolve: limits exceeded\n";
throw this;
}
/* First step:
If for one equation there is no coefficient different from
zero, this equation is \"not" active.
Further mark in \|unitcoeffs| the equations with coefficients
solely $\in\{0,1\}$.
*/
hopeless = false;
for (i = 0; i < numeqn; ++i) {
if (neqn[i] == 0) {
active[i] = false;
if (lorhs[i] > 0 || hirhs[i] < 0) hopeless = true;
}
else {
active[i] = true;
}
for (j = neqn[i]; --j >= 0;) if (eqn[i][j].coeff != 1) break;
unitcoeffs[i] = (j < 0);
}
/* More output. */
if (f_v4) {
puteqns(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn);
}
/* Finally the recursion starts. */
if (!hopeless)
_break = false;
if (f_v) {
cout << "mckay::tMCKAY::possolve: calling solve" << endl;
}
solve(0,lo,hi,active,numvar,lorhs,hirhs,eqn,neqn,numeqn, verbose_level);
if (f_v) {
cout << "mckay::tMCKAY::possolve done" << endl;
}
return;
}
/* \subsection{subtract}
subtract equation e1 from e2 if possible ---
return success.
It is used in function \|pruneqn|.
*/
bool mckay::tMCKAY::subtract(
int eqn1, equation &e1, int l1, int lors1, int hirs1,
int eqn2, equation &e2, int *pl2, int *plors2, int *phirs2,
int verbose_level)
{
int f_v = (verbose_level >= 1);
int i,j,k;
term e1i;
int l2,factor,minfactor;
/* First test if subtraction is possible. */
minfactor = 999999;
l2 = *pl2;
if (l1 > l2 || hirs1 > lors1) return false;
/* Second test if subtraction is possible. */
j = 0;
for (i = 0; i < l1; ++i) {
e1i = e1[i];
for (; j < l2 && e2[j].var != e1i.var; ++j) {}
if (j == l2 || e2[j].coeff < e1i.coeff) return false;
factor = e2[j].coeff / e1i.coeff;
if (factor < minfactor) minfactor = factor;
}
/* Do subtraction */
k = 0;
for (i = j = 0; i < l1; ++i, ++j)
{
e1i = e1[i];
for (; j < l2 && e2[j].var != e1i.var; ++j) e2[k++] = e2[j];
if (j < l2 && e2[j].coeff > minfactor*e1i.coeff) {
e2[k].var = e2[j].var;
e2[k].coeff = e2[j].coeff - minfactor*e1i.coeff;
++k;
}
}
for (; j < l2; ++j) e2[k++] = e2[j];
*pl2 = k;
*plors2 -= minfactor*lors1;
*phirs2 -= minfactor*hirs1;
/* end of subtraction. */
if (f_v) {
cout << "subtract: subtracted equation " << eqn1
<< " from equation " << eqn2 << endl;
}
return true;
}
/* \subsection{pruneqn --- remove equations}
prune equations by subtraction.
*/
void mckay::tMCKAY::pruneqn(vector<int> &lo, vector<int> &hi,
int numvar,
vector<int> &lorhs, vector<int> &hirhs,
vector<equation> &eqn, vector<int> &neqn,
int numeqn, int verbose_level)
{
int f_v = (verbose_level >= 1);
bool ok;
vector<bool> done;
done.resize(_eqnanz);
int i,j;
/* \|done| is always \|false|. Why? */
for (i = 0; i < numeqn; ++i) {
done[i] = false;
}
do {
ok = true;
for (i = 0; i < numeqn; ++i) {
if (!done[i] && neqn[i] > 0) {
for (j = 0; j < numeqn; ++j) {
if (i != j &&
subtract(i, eqn[i],neqn[i],
lorhs[i],hirhs[i],j, eqn[j],
&neqn[j],&lorhs[j],&hirhs[j],
verbose_level)) {
if (f_v) {
cout << "mckay::tMCKAY::pruneqn after subtract:" << endl;
puteqns(lo, hi,
numvar, lorhs, hirhs, eqn, neqn, numeqn);
}
ok = false;
done[j] = false;
} // if
} // for
} // if
} // for
} while (!ok);
return;
}
/*
\subsection{varprune --- remove variables}
Try to remove free variables by testing if variables are already
fixed. This is the case if the lower bound on a variable is equal to its
upper bound.
*/
void mckay::tMCKAY::varprune(vector<int> &lo, vector<int> &hi,
vector<int> &lorhs, vector<int> &hirhs,
vector<equation> &eqn, vector<int> &neqn,
int numeqn, int verbose_level)
{
int f_v = (verbose_level >= 1);
int i,j,sum,len;
for (j = 0; j < numeqn; ++j) {
len = neqn[j];
sum = 0;
// simple test whether the lower bound
// of a variable meets its upper bound:
for (i = 0; i < len;) {
if (lo[eqn[j][i].var] == hi[eqn[j][i].var]) {
sum += eqn[j][i].coeff*lo[eqn[j][i].var];
if (f_v && sum) {
cout << "varprune: equation " << j << " variable "
<< eqn[j][i].var << " is not free any more, "
"sum += " << eqn[j][i].coeff * lo[eqn[j][i].var]
<< endl;
}
eqn[j][i] = eqn[j][--len];
}
else {
++i;
}
}
lorhs[j] -= sum;
hirhs[j] -= sum;
if (f_v && sum) {
cout << "varprune: equation " << j << " reducing RHS by "
<< sum << " to lorhs[j]=" << lorhs[j] << " hirhs[j]="
<< hirhs[j] << endl;
}
neqn[j] = len;
}
}
void mckay::tMCKAY::puteqns(vector<int> &lo, vector<int> &hi,
int numvar, vector<int> &lorhs, vector<int> &hirhs,
vector<equation> &eqn, vector<int> &neqn, int numeqn)
{
int i,j;
// First the lower and upper bounds on the variable are written:
cout << "CON" << endl;
for (i = 0; i < numvar; ++i) {
if (i > 0) cout << "," << endl;
if (lo[i] > 0) cout << "x" << i << " >= " << lo[i] << ", ";
cout << "x" << i << " <= " << hi[i];
}
// print the equations:
for (i = 0; i < numeqn; ++i) {
cout << "," << endl;
cout << "Equation " << i << " : ";
for (j = 0; j < neqn[i]; ++j) {
if (j % 16 == 15) cout << endl << " ";
cout << (j == 0 ? "" : "+") << eqn[i][j].coeff
<< "*x" << eqn[i][j].var;
}
cout << (lorhs[i] < hirhs[i] ? " >= " : " = ") << lorhs[i];
if (lorhs[i] == hirhs[i]) continue;
// inequalities:
cout << "," << endl;
for (j = 0; j < neqn[i]; ++j) {
if (j % 16 == 15) cout << endl << " ";
cout << (j == 0 ? "" : "+") << eqn[i][j].coeff
<< "*x" << eqn[i][j].var;
}
cout << " <= " << hirhs[i];
}
cout << ";" << endl;
}
/*
\subsection{divideeqns}
take out common factors, return bad eqn number.
It is only used in the main program.
*/
int mckay::tMCKAY::divideeqns(vector<int> &lorhs,
vector<int> &hirhs, vector<equation> &eqn,
vector<int> &neqn, int numeqn)
{
int i,j,g,len;
for (j = 0; j < numeqn; ++j)
{
len = neqn[j];
if (len == 0) continue;
g = eqn[j][0].coeff;
i = 1;
for (i = 1; i < len && g > 1; ++i) g = gcd(g,eqn[j][i].coeff);
/* $g = \gcd$ of all coefficients of the left hand side of equation $i$.
If $g=1$ step to the next equation.
*/
if (g == 1) continue;
for (i = 0; i < len; ++i) eqn[j][i].coeff /= g;
lorhs[j] = lorhs[j] < 0 ? 0 : (lorhs[j] + g - 1) / g;
hirhs[j] = hirhs[j] < 0 ? -1 : hirhs[j] / g;
/* Write some information.*/
cerr<<"eqn "<<j<<": g="<<g<<" lorhs="<<lorhs[j]
<<" hirhs="<<hirhs[j]<<"\n";
if (lorhs[j] > hirhs[j]) return j;
}
return -1;
}
/*
\subsection{gcd}
used in \|divideeqns|.
*/
int mckay::tMCKAY::gcd(int n1,int n2)
{
int a,b,c;
if (n1 > n2) {
a = n1; b = n2;
}
else {
a = n2; b = n1;
}
while ((c = a % b) > 0) {
a = b; b = c;
}
return(b);
}
/*
\section{solve --- brute force recursion}
This procedure is called recursively.
*/
void mckay::tMCKAY::solve(int level,
vector<int> &alo, vector<int> &ahi,
vector<bool> &aactive, int numvar,
vector<int> &lorhs, vector<int> &hirhs,
vector<equation> &eqn, vector<int> &neqn,
int numeqn, int verbose_level)
{
int f_v = (verbose_level >= 1);
//int f_vv = (verbose_level >= 2);
int f_vvv = (verbose_level >= 3);
int i,j;
vector<int> lo, hi;
lo.resize(_varanz);
hi.resize(_varanz);
int isplit, mindiff;
vector<bool> active;
active.resize(_eqnanz);
//int current_node;
int f_restriction_made;
//current_node = nb_calls_to_solve;
nb_calls_to_solve++;
#if 0
if (f_vv) {
log_12l(nb_calls_to_solve, level);
//log_12l(current_node, level);
cout << "mckay::tMCKAY::solve " << problem_label
//<< " node " << current_node
<< " first_moved " << first_moved
<< " second_moved " << second_moved
<< " level " << level << endl;
}
#ifdef MCKAY_DEBUG
if (f_vvv) {
cout << " : ";
for (i = 0; i < level; ++i) {
cout << "x_" << split[i] << "=" << branch[i];
if (i < level - 1) {
cout << ", ";
}
}
}
#endif
if (f_vv) {
cout << endl;
}
#endif
#ifdef MCKAY_DEBUG
if (f_vvv) {
cout << "level=" << level << endl;
cout << "i : split[i] : range[i] : branch[i]" << endl;
for (i = 0; i < level; ++i) {
cout << i << " : " << split[i] << " : " << range[i]
<< " : " << branch[i] << " : " << endl;
}
cout << "low and high:" << endl;
for (j = 0; j < numvar; j++) {
cout << j << " : " << alo[j] << " : " << ahi[j] << endl;
}
}
#endif
#if 0
if (f_vvv) {
log_12l(current_node, level);
cout << " current system:" << endl;
puteqns(alo,ahi,numvar,lorhs,hirhs,eqn,neqn,numeqn);
}
#endif
//f_debug = FALSE;
//f_debug = (verbose_level >= 10);
if (_break) {
return;
}
if (FALSE) {
int nacc = 0;
cout << " SOLVE level "<<level<< endl;
cout<<"Number of active equations: ";
for (i = numeqn; --i >= 0;) if (aactive[i]) ++nacc;
cout<<":"<<nacc<<endl;
for (i = 0; i < numeqn; i++) {
if (aactive[i])
cout << i << " ";
}
cout << endl;
cout << "low and high:" << endl;
for (j = 0; j < numvar; j++) {
cout << j << " : " << alo[j] << " : " << ahi[j] << endl;
}
#ifdef MCKAY_DEBUG
os_interface Os;
if (((Os.os_ticks() - ticks0) / Os.os_ticks_per_second())
> INTERVAL_IN_SECONDS) {
ticks0 = Os.os_ticks();
//f_debug = TRUE;
puteqns(alo,ahi,numvar,lorhs,hirhs,eqn,neqn,numeqn);
cout << "level=" << level << endl;
cout << "range[] : branch[] :" << endl;
for (i = 0; i < level; ++i)
cout << range[i] << " : " << branch[i] << " : " << endl;
}
#endif
}
/* \|lo|, \|hi| and \|active| are local arrays. */
for (i = 0; i < numvar; ++i) {
lo[i] = alo[i];
hi[i] = ahi[i];
}
for (i = 0; i < numeqn; ++i) {
active[i] = aactive[i];
}
if (!restrict_variables(level, lo, hi, active, numvar,
lorhs, hirhs,
eqn, neqn,
numeqn, f_restriction_made, verbose_level - 1)) {
#if 0
if (f_vv) {
log_12l(nb_calls_to_solve, level);
//log_12l(current_node, level);
cout << "solve restrict_variables returns FALSE, "
"backtracking" << endl;
}
#endif
return;
}
#if 0
if (f_vvv && f_restriction_made) {
log_12l(nb_calls_to_solve, level);
//log_12l(current_node, level);
cout << " after restriction: low and high:" << endl;
for (i = 0; i < numvar; i++) {
cout << i << " : " << lo[i] << " : " << hi[i] << endl;
}
}
#endif
// Here comes the searching part.
// \|mindiff| gives the smallest
// difference between lower and upper bound of a variable.
// \|isplit|
// is the corresponding variable number.
#if 0
if (f_vv) {
log_12l(nb_calls_to_solve, level);
//log_12l(current_node, level);
cout << "searching part" << endl;
}
#endif
mindiff = INT_MAX;
isplit = -1;
for (i = 0; i < numvar; ++i) {
if (hi[i] != lo[i] && hi[i] - lo[i] < mindiff) {
isplit = i;
mindiff = hi[i] - lo[i];
}
}
// If \|isplit| $< 0$ we have found a solution.
// Otherwise we try to delete variables by
// \|varprune| and we try to delete equations
// by \|pruneqn|.
if (isplit < 0) {
if (f_v) {
log_12l(nb_calls_to_solve, level);
cout << " solution " << D->_resultanz << endl;
}
D->_results.push_back(lo);
D->_resultanz++;
if (D->_resultanz < D->_maxresults) {
_break = false;
}
else {
_break = true;
}
}
else {
if (level == 0) {
varprune(lo,hi,lorhs,hirhs,eqn,neqn,numeqn, verbose_level);
//#if VERBOSE > 2
//puteqns(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn);
//#endif
pruneqn(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn, verbose_level);
//#if VERBOSE > 2
#if 0
if (f_vvv) {
log_12l(nb_calls_to_solve, level);
//log_12l(current_node, level);
cout << " after varprune and pruneqn:" << endl;
puteqns(lo,hi,numvar,lorhs,hirhs,eqn,neqn,numeqn);
}
#endif
//#endif
}
/*
Finally we start the recursion.
the variable with the number \|isplit| runs from
\|lo[isplit]| to \|hi[isplit]| and for each step we call \|solve|
with this fixed value.
\|branch|, \|split| and \|range| are collected for debugging purposes.
*/
#if 0
if (TRUE /*(f_v && (current_node % 10000) == 0) || f_vv*/) {
//log_12l(current_node, level);
log_12l(nb_calls_to_solve, level);
cout << "solve choosing variable " << isplit
<< " lo=" << lo[isplit] << " hi=" << hi[isplit] << endl;
}
#endif
for (i = 0; i <= mindiff; ++i) {
int first_moved_orig = first_moved;
int second_moved_orig = second_moved;
int f_first_moved_has_changed = FALSE;
int f_second_moved_has_changed = FALSE;
if (i) {
if (level < first_moved) {
first_moved = level;
second_moved = INT_MAX;
}
else if (level < second_moved) {
second_moved = level;
}
if (first_moved != first_moved_orig) {
f_first_moved_has_changed = TRUE;
}
if (second_moved != second_moved_orig) {
f_second_moved_has_changed = TRUE;
}
}
if (f_first_moved_has_changed || f_second_moved_has_changed ||
(nb_calls_to_solve % 10000000) == 0) {
log_12l(nb_calls_to_solve, level);
cout << " x_" << isplit << " = " << lo[isplit] << endl;
}
hi[isplit] = lo[isplit];
#ifdef MCKAY_DEBUG
split[level] = isplit;
branch[level] = lo[isplit];
range[level] = mindiff+1;
#endif
// here comes the recursion:
if (f_v) {
cout << "solve level " << level << " isplit=" << isplit << " before solve i=" << i << " / " << mindiff << endl;
for (j = 0; j < numeqn; j++) {
if (aactive[i])
cout << j << " ";
}
cout << endl;
cout << "low and high:" << endl;
for (j = 0; j <= level; j++) {
cout << j << " : " << alo[j] << " : " << ahi[j] << endl;
}
#if 0
#ifdef MCKAY_DEBUG
if (TRUE/*((os_ticks() - ticks0) / os_ticks_per_second())
> INTERVAL_IN_SECONDS*/) {
ticks0 = os_ticks();
//f_debug = TRUE;
puteqns(alo,ahi,numvar,lorhs,hirhs,eqn,neqn,numeqn);
cout << "level=" << level << endl;
cout << "range[] : branch[] :" << endl;
for (j = 0; j <= level; j++) {
cout << range[j] << " : " << branch[j] << " : " << endl;
}
}
#else
// cout << "MCKAY_DEBUG is FALSE" << endl;
#endif
#endif
}
solve(level + 1, lo, hi, active, numvar,
lorhs, hirhs, eqn, neqn, numeqn,
verbose_level);
if (f_v) {
cout << "solve level " << level << " isplit=" << isplit << " after solve" << endl;
}
++lo[isplit];
} // next i
} // else
#if 0
if (f_vv) {
log_12l(nb_calls_to_solve, level);
//log_12l(current_node, level);
cout << " done" << endl;
}
#endif
}
int mckay::tMCKAY::restrict_variables(int level,
vector<int> &lo, vector<int> &hi,
vector<bool> &active, int numvar,
vector<int> &lorhs, vector<int> &hirhs,
vector<equation> &eqn, vector<int> &neqn,
int numeqn, int &f_restriction_made, int verbose_level)
{
int f_v = (verbose_level >= 1);
int f_vv = (verbose_level >= 2);
//int f_vvv = (verbose_level >= 3);
//int f_debug;
int i, j;
long int current_node;
int losum,hisum,eic,eiv,lx,hx;
int nfree,ok, xlo,xhi;
int save;
int f_restriction_made_in_this_eqn;
if (f_v) {
cout << "mckay::tMCKAY::restrict_variables" << endl;
}
if (f_vv) {
cout << "low and high:" << endl;
for (j = 0; j <= level; j++) {
cout << j << " : " << lo[j] << " : " << hi[j] << endl;
}
puteqns(lo, hi, numvar, lorhs, hirhs, eqn, neqn, numeqn);
cout << "level=" << level << endl;
cout << "range[] : branch[] :" << endl;
for (j = 0; j <= level; j++) {
cout << range[j] << " : " << branch[j] << " : " << endl;
}
}
current_node = nb_calls_to_solve;
/* The following line seems to be a relict from another problem. */
/* *< if (level == 8 && lo[22] == 1 && lo[19] == 1) nul(); >* */
/* The following loop through the equations tries to restrict the lower
and upper bounds on the variables.
We only have to handle active equations.
*/
ok = 0;
/* ok = number of equations that have been
* checked since the last change of any
* lo[] or hi[] was made.
* the aim is to check all equations once
* without reducing hi[] - lo[];
* so that we have reached stability */
f_restriction_made = FALSE;
for (j = 0; ok < numeqn; j = (j == numeqn-1 ? 0 : j+1)) {
// j is the next equation to check;
// j wraps around all equation indices
if (f_vv /*f_debug*/) {
cout << "mckay::tMCKAY::restrict_variables checking equation " << j << endl;
}
++ok;
if (active[j]) {
f_restriction_made_in_this_eqn = FALSE;
// we check equation j:
// We distinguish two cases:
// First, if there are only $\{0,1\}$-coefficients.
if (FALSE /*unitcoeffs[j]*/) {
// The lower and upper bounds on the variables
// (belonging to nonzero coefficients) are summed up
// in \|losum| and \|hisum|.
if (f_vv /*f_debug*/) {
cout << "checking equation " << j
<< " with unitcoeffs" << endl;
}
losum = 0;
hisum = 0;
for (i = neqn[j]; --i >= 0;) {
losum += lo[eqn[j][i].var];
// lowest possible lhs
hisum += hi[eqn[j][i].var];
// highest possible lhs
}
if (losum > hirhs[j]) {
if (f_v) {
cout << "solve " << problem_label << " node "
<< current_node << " level " << level
<< "return b/c for equation " << j
<< " with unitcoeffs "
"we have losum = " << losum << " > "
<< hirhs[j] << " = hirhs[j]" << endl;
}
return FALSE;
}
if (hisum < lorhs[j]) {
if (f_v) {
cout << "solve " << problem_label << " node "
<< current_node << " level " << level
<< "return b/c for equation " << j
<< " with unitcoeffs "
" we have hisum = " << hisum << " < "
<< lorhs[j] << " = lorhs[j]" << endl;
}
return FALSE;
}
// If possible the lower or upper bounds on the
// variables are restricted further.
// count the number of remaining free
// variables in nfree.
nfree = 0;
for (i = neqn[j]; --i >= 0;) {
eiv = eqn[j][i].var;
hx = hi[eiv];
lx = lo[eiv];
if (hx != lx) {
xlo = lorhs[j] + hx - hisum;
// = lorhs[j] - (hisum - hx), i.e.,
// lorhs[j] minus hisum of all the
// other variables.
// This is a lower bound on the amount
// that the current variable contributes.
xhi = hirhs[j] + lx - losum;
// = hirhs[j] - (losum - lx), i.e.
// hirhs[j] minus losum of all the
// other variables.
// This is an upper bound on the amount
// that the current variable contributes.
if (xlo > lx) {
save = lo[eiv];
lo[eiv] = xlo;
if (lo[eiv] != save) {
f_restriction_made = TRUE;
f_restriction_made_in_this_eqn = TRUE;
if (f_v) {
cout << "increasing lo[" << eiv
<< "] from " << save << " to "
<< lo[eiv] << endl;
}
}
ok = 0;
// a change was made;
// loop through all
// equations again.
}
if (xhi < hx) {
save = hi[eiv];
hi[eiv] = xhi;
if (lo[eiv] != save) {
f_restriction_made = TRUE;
f_restriction_made_in_this_eqn = TRUE;
if (f_v) {
cout << "reducing hi[" << eiv
<< "] from " << save << " to "
<< hi[eiv] << endl;
}
}
ok = 0;
}
if (lo[eiv] != hi[eiv]) {
++nfree;
}
} // if (hx != lx)
} // next i
} // if (unitcoeffs[j])
// Now the slightly more complicated case
// if there are coefficents greater than $1$.
// If the lower bound of a variable becomes greater
// than its upper bound, the procedure is stopped at once.
else {
// Again the lower and upper bounds on the variables
// (belonging to nonzero coefficients) are summed
// up in \|losum| and \|hisum|.
if (f_v /*f_debug*/) {
cout << "mckay::tMCKAY::restrict_variables checking equation " << j
<< " without unitcoeffs" << endl;
}
losum = 0;
hisum = 0;
for (i = neqn[j]; --i >= 0;) {
losum += eqn[j][i].coeff * lo[eqn[j][i].var];
hisum += eqn[j][i].coeff * hi[eqn[j][i].var];
}
if (losum > hirhs[j]) {
if (f_v) {
cout << "mckay::tMCKAY::restrict_variables "
<< problem_label << " node "
<< current_node << " level " << level
<< "return b/c for equation " << j
<< " without unitcoeffs "
"we have losum = " << losum << " > "
<< hirhs[j] << " = hirhs[j]" << endl;
}
return FALSE;
}
if (hisum < lorhs[j]) {
if (f_v) {
cout << "mckay::tMCKAY::restrict_variables "
<< problem_label << " node "
<< current_node << " level " << level
<< "return b/c for equation " << j
<< " without unitcoeffs "
"we have hisum = " << hisum << " < "
<< lorhs[j] << " = lorhs[j]" << endl;
}
return FALSE;
}
if (f_vv && f_restriction_made_in_this_eqn) {
cout << "mckay::tMCKAY::restrict_variables "
"equation " << j << ", after restriction: "
"low and high:" << endl;
for (i = 0; i < numvar; i++) {
cout << i << " : " << lo[i] << " : "
<< hi[i] << endl;
}
cout << "hisum=" << hisum << endl;
cout << "losum=" << losum << endl;
}
// And if possible the lower or upper bounds
// on the variables
// are restricted further.
f_restriction_made_in_this_eqn = FALSE;
nfree = 0;
for (i = neqn[j]; --i >= 0;) {
if (FALSE /*f_debug*/) {
cout << "restricting lower and upper "
"bounds equation " << j << endl;
}
if (hi[eqn[j][i].var] != lo[eqn[j][i].var]) {
eic = eqn[j][i].coeff;
eiv = eqn[j][i].var;
hx = eic * hi[eiv];
lx = eic * lo[eiv];
xlo = lorhs[j] + hx - hisum;
// = lorhs[j] - (hisum - hx), i.e.,
// lorhs[j] minus hisum of all the other variables.
// This is a lower bound on the amount
// that the current variable contributes.
xhi = hirhs[j] + lx - losum;
// = hirhs[j] - (losum - lx), i.e.
// hirhs[j] minus losum of all the other variables.
// This is an upper bound on the amount
// that the current variable contributes.
if (xlo > lx) {
save = lo[eiv];
lo[eiv] = (xlo + eic - 1) / eic;
if (lo[eiv] != save) {
f_restriction_made = TRUE;
f_restriction_made_in_this_eqn = TRUE;
if (f_v) {
cout << "increasing lo[" << eiv
<< "] from "
<< save << " to " << lo[eiv] << " : "
<< "eqn j=" << j << " variable "
<< eiv << " coeff=" << eic
<< " lorhs[j]=" << lorhs[j]
<< " hisum=" << hisum
<< " hx=" << hx
<< " hisum - hx=" << hisum - hx
<< endl;
}
}
if (lo[eiv] > hi[eiv]) {
if (f_v) {
cout << "return bc for eqn " << j
<< " term " << i << " xlo > lx "
"and lo[eiv] > hi[eiv]" << endl;
}
return FALSE;
}
ok = 0;
}
if (xhi < hx) {
save = hi[eiv];
hi[eiv] = xhi / eic;
if (hi[eiv] < save) {
f_restriction_made = TRUE;
f_restriction_made_in_this_eqn = TRUE;
if (f_v) {
cout << "reducing hi[" << eiv << "] from "
<< save << " to " << hi[eiv] << " : "
<< "eqn j=" << j << " variable "
<< eiv << " coeff=" << eic
<< " hirhs[j]=" << hirhs[j]
<< " losum=" << losum
<< " lx=" << lx
<< " losum - lx=" << losum - lx
<< endl;
}
}
if (lo[eiv] > hi[eiv]) {
if (f_v) {
cout << "return bc for eqn " << j
<< " term " << i << " xhi < hx "
"and lo[eiv] > hi[eiv]" << endl;
cout << "xlo=" << xlo << endl;
cout << "xhi=" << xhi << endl;
cout << "lx=" << lx << endl;
cout << "hx=" << hx << endl;
cout << "eic=" << eic << endl;
cout << "eiv=" << eiv << endl;
cout << "lo[eiv]=" << lo[eiv] << endl;
cout << "hi[eiv]=" << hi[eiv] << endl;
}
return FALSE;
}
ok = 0;
}
if (lo[eiv] != hi[eiv]) {
++nfree;
}
} // if hi[eqn[j][i]
} // next i
if (f_vv && f_restriction_made_in_this_eqn) {
cout << "mckay::tMCKAY::restrict_variables "
"equation " << j << ", after restriction: "
"low and high:" << endl;
for (i = 0; i < numvar; i++) {
cout << i << " : " << lo[i] << " : "
<< hi[i] << endl;
}
cout << "hisum=" << hisum << endl;
cout << "losum=" << losum << endl;
}
} // else
// Now hopefully the variables are in each
// case further restricted.
// The equation becomes inactive if
// \item{(1)} there are no free variables in
// this equation \"and
// \item{(2)} if it was not possible to further
// restrict the variables in the last try.
if (ok > 0 && nfree == 0) {
active[j] = false;
}
} // if (active[j])
} // next j
return TRUE;
}
void mckay::tMCKAY::log_12l(long int current_node, int level)
{
cout << "solve " << problem_label
<< " node " << current_node
<< " first_moved ";
if (first_moved < INT_MAX) {
cout << first_moved;
}
else {
cout << "infinity";
}
cout << " second_moved ";
if (second_moved < INT_MAX) {
cout << second_moved;
}
else {
cout << "infinity";
}
cout << " level " << level;
cout << " nb_sol=" << D->_resultanz;
}
}
}
| 28,005 | 13,549 |
#include <string>
#include <utility>
#include <vector>
#include <memory>
#include <iostream>
#include <ssc/sscapi.h>
#include "SAM_api.h"
#include "ErrorHandler.h"
#include "SAM_TroughPhysicalProcessHeat.h"
SAM_EXPORT int SAM_TroughPhysicalProcessHeat_execute(SAM_table data, int verbosity, SAM_error* err){
return SAM_module_exec("trough_physical_process_heat", data, verbosity, err);
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_azimuth_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "azimuth", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_file_name_sset(SAM_table ptr, const char* str, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_string(ptr, "file_name", str);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_solar_resource_data_tset(SAM_table ptr, SAM_table tab, SAM_error *err){
SAM_table_set_table(ptr, "solar_resource_data", tab, err);
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_tilt_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "tilt", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Weather_track_mode_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "track_mode", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_A_aperture_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "A_aperture", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_AbsorberMaterial_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "AbsorberMaterial", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_AnnulusGas_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "AnnulusGas", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Ave_Focal_Length_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "Ave_Focal_Length", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_ColperSCA_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "ColperSCA", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_2_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "D_2", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_3_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "D_3", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_4_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "D_4", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_5_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "D_5", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "D_cpnt", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_D_p_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "D_p", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Design_loss_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Design_loss", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Dirt_HCE_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Dirt_HCE", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Dirt_mirror_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "Dirt_mirror", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Distance_SCA_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "Distance_SCA", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_4_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "EPSILON_4", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_5_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "EPSILON_5", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Error_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "Error", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_FieldConfig_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "FieldConfig", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Flow_type_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Flow_type", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Fluid_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "Fluid", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_GeomEffects_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "GeomEffects", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_GlazingIntactIn_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "GlazingIntactIn", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_HCE_FieldFrac_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "HCE_FieldFrac", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_HDR_rough_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "HDR_rough", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_IAM_matrix_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "IAM_matrix", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_I_bn_des_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "I_bn_des", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_K_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "K_cpnt", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_SCA_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "L_SCA", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_aperture_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "L_aperture", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "L_cpnt", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_heat_sink_piping_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "L_heat_sink_piping", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_rnr_per_xpan_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "L_rnr_per_xpan", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_hdr_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "L_xpan_hdr", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_rnr_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "L_xpan_rnr", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Min_rnr_xpans_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "Min_rnr_xpans", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_N_hdr_per_xpan_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "N_hdr_per_xpan", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_N_max_hdr_diams_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "N_max_hdr_diams", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_P_a_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "P_a", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Pipe_hl_coef_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "Pipe_hl_coef", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Rho_mirror_clean_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "Rho_mirror_clean", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Rough_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Rough", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Row_Distance_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "Row_Distance", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_SCA_drives_elec_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "SCA_drives_elec", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Shadowing_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Shadowing", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_T_fp_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "T_fp", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_T_loop_in_des_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "T_loop_in_des", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_T_loop_out_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "T_loop_out", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Tau_envelope_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Tau_envelope", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_TrackingError_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "TrackingError", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_Type_cpnt_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "Type_cpnt", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_max_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "V_hdr_cold_max", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_min_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "V_hdr_cold_min", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_max_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "V_hdr_hot_max", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_min_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "V_hdr_hot_min", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_W_aperture_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "W_aperture", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_accept_init_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "accept_init", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_accept_loc_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "accept_loc", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_accept_mode_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "accept_mode", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_alpha_abs_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "alpha_abs", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_alpha_env_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "alpha_env", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_calc_design_pipe_vals_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "calc_design_pipe_vals", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_custom_sf_pipe_sizes_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "custom_sf_pipe_sizes", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_11_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_11", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_12_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_12", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_13_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_13", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_14_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_14", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_21_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_21", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_22_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_22", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_23_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_23", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_24_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_24", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_31_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_31", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_32_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_32", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_33_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_33", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_34_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_34", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_41_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_41", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_42_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_42", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_43_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_43", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_44_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "epsilon_3_44", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_eta_pump_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "eta_pump", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_is_model_heat_sink_piping_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_model_heat_sink_piping", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmax_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "m_dot_htfmax", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmin_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "m_dot_htfmin", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_cold_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "mc_bal_cold", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_hot_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "mc_bal_hot", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_sca_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "mc_bal_sca", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nColt_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "nColt", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nHCEVar_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "nHCEVar", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nHCEt_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "nHCEt", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nLoops_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "nLoops", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_nSCA_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "nSCA", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_northsouth_field_sep_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "northsouth_field_sep", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_offset_xpan_hdr_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "offset_xpan_hdr", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_diams_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "sf_hdr_diams", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_lengths_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "sf_hdr_lengths", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_wallthicks_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "sf_hdr_wallthicks", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_diams_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "sf_rnr_diams", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_lengths_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "sf_rnr_lengths", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_wallthicks_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "sf_rnr_wallthicks", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_theta_dep_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "theta_dep", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_theta_stow_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "theta_stow", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_washing_frequency_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "washing_frequency", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_water_usage_per_wash_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "water_usage_per_wash", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SolarField_wind_stow_speed_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "wind_stow_speed", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_disp_wlim_maxspec_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_wlim_maxspec", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_field_fl_props_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "field_fl_props", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_non_solar_field_land_area_multiplier_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "non_solar_field_land_area_multiplier", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_pb_pump_coef_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "pb_pump_coef", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_q_pb_design_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "q_pb_design", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_specified_solar_multiple_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "specified_solar_multiple", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_tanks_in_parallel_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "tanks_in_parallel", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Controller_trough_loop_control_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "trough_loop_control", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SystemDesign_tshours_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "tshours", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_cold_tank_Thtr_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "cold_tank_Thtr", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_cold_tank_max_heat_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "cold_tank_max_heat", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_h_tank_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "h_tank", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_init_hot_htf_percent_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "init_hot_htf_percent", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_tank_pairs_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "tank_pairs", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES_u_tank_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "u_tank", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES2tank_h_tank_min_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "h_tank_min", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_Thtr_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "hot_tank_Thtr", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_max_heat_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "hot_tank_max_heat", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_ampl_data_dir_sset(SAM_table ptr, const char* str, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_string(ptr, "ampl_data_dir", str);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_ampl_exec_call_sset(SAM_table ptr, const char* str, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_string(ptr, "ampl_exec_call", str);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_csu_cost_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_csu_cost", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_frequency_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_frequency", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_horizon_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_horizon", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_max_iter_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_max_iter", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_mip_gap_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_mip_gap", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_pen_delta_w_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_pen_delta_w", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_reporting_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_reporting", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_rsu_cost_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_rsu_cost", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_spec_bb_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_spec_bb", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_spec_presolve_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_spec_presolve", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_spec_scaling_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_spec_scaling", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_steps_per_hour_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_steps_per_hour", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_time_weighting_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_time_weighting", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_disp_timeout_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_timeout", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor1_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor1", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor2_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor2", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor3_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor3", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor4_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor4", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor5_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor5", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor6_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor6", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor7_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor7", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor8_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor8", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor9_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "dispatch_factor9", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_factors_ts_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "dispatch_factors_ts", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekday_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "dispatch_sched_weekday", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekend_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "dispatch_sched_weekend", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_dispatch_series_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "dispatch_series", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_f_turb_tou_periods_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "f_turb_tou_periods", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_ampl_engine_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_ampl_engine", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_dispatch", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_series_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_dispatch_series", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_tod_pc_target_also_pc_max_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_tod_pc_target_also_pc_max", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_wlim_series_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_wlim_series", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_is_write_ampl_dat_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "is_write_ampl_dat", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_ppa_multiplier_model_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "ppa_multiplier_model", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_q_rec_heattrace_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "q_rec_heattrace", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_q_rec_standby_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "q_rec_standby", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_timestep_load_fractions_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "timestep_load_fractions", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_weekday_schedule_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "weekday_schedule", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_weekend_schedule_mset(SAM_table ptr, double* mat, int nrows, int ncols, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_matrix(ptr, "weekend_schedule", mat, nrows, ncols);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Tou_wlim_series_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "wlim_series", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_SystemControl_disp_inventory_incentive_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "disp_inventory_incentive", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_System_aux_array_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "aux_array", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_System_bop_array_aset(SAM_table ptr, double* arr, int length, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_array(ptr, "bop_array", arr, length);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_System_pb_fixed_par_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "pb_fixed_par", number);
});
}
SAM_EXPORT void SAM_TroughPhysicalProcessHeat_Powerblock_L_rnr_pb_nset(SAM_table ptr, double number, SAM_error *err){
translateExceptions(err, [&]{
ssc_data_set_number(ptr, "L_rnr_pb", number);
});
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Weather_azimuth_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "azimuth", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "azimuth");
});
return result;
}
SAM_EXPORT const char* SAM_TroughPhysicalProcessHeat_Weather_file_name_sget(SAM_table ptr, SAM_error *err){
const char* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_string(ptr, "file_name");
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "file_name");
});
return result;
}
SAM_EXPORT SAM_table SAM_TroughPhysicalProcessHeat_Weather_solar_resource_data_tget(SAM_table ptr, SAM_error *err){
SAM_table result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_table(ptr, "solar_resource_data");
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "solar_resource_data");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Weather_tilt_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "tilt", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "tilt");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Weather_track_mode_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "track_mode", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "track_mode");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_A_aperture_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "A_aperture", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "A_aperture");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_AbsorberMaterial_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "AbsorberMaterial", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "AbsorberMaterial");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_AnnulusGas_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "AnnulusGas", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "AnnulusGas");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Ave_Focal_Length_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "Ave_Focal_Length", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Ave_Focal_Length");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_ColperSCA_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "ColperSCA", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "ColperSCA");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_2_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "D_2", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "D_2");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_3_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "D_3", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "D_3");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_4_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "D_4", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "D_4");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_5_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "D_5", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "D_5");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "D_cpnt", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "D_cpnt");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_D_p_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "D_p", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "D_p");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Design_loss_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Design_loss", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Design_loss");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Dirt_HCE_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Dirt_HCE", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Dirt_HCE");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Dirt_mirror_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "Dirt_mirror", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Dirt_mirror");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Distance_SCA_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "Distance_SCA", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Distance_SCA");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_4_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "EPSILON_4", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "EPSILON_4");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_EPSILON_5_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "EPSILON_5", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "EPSILON_5");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Error_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "Error", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Error");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_FieldConfig_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "FieldConfig", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "FieldConfig");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Flow_type_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Flow_type", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Flow_type");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Fluid_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "Fluid", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "Fluid");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_GeomEffects_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "GeomEffects", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "GeomEffects");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_GlazingIntactIn_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "GlazingIntactIn", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "GlazingIntactIn");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_HCE_FieldFrac_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "HCE_FieldFrac", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "HCE_FieldFrac");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_HDR_rough_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "HDR_rough", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "HDR_rough");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_IAM_matrix_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "IAM_matrix", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "IAM_matrix");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_I_bn_des_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "I_bn_des", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "I_bn_des");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_K_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "K_cpnt", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "K_cpnt");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_L_SCA_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "L_SCA", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "L_SCA");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_L_aperture_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "L_aperture", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "L_aperture");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_L_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "L_cpnt", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "L_cpnt");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_heat_sink_piping_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "L_heat_sink_piping", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "L_heat_sink_piping");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_rnr_per_xpan_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "L_rnr_per_xpan", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "L_rnr_per_xpan");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_hdr_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "L_xpan_hdr", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "L_xpan_hdr");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_L_xpan_rnr_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "L_xpan_rnr", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "L_xpan_rnr");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Min_rnr_xpans_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "Min_rnr_xpans", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "Min_rnr_xpans");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_N_hdr_per_xpan_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "N_hdr_per_xpan", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "N_hdr_per_xpan");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_N_max_hdr_diams_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "N_max_hdr_diams", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "N_max_hdr_diams");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_P_a_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "P_a", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "P_a");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Pipe_hl_coef_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "Pipe_hl_coef", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "Pipe_hl_coef");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Rho_mirror_clean_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "Rho_mirror_clean", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Rho_mirror_clean");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Rough_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Rough", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Rough");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_Row_Distance_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "Row_Distance", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "Row_Distance");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_SCA_drives_elec_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "SCA_drives_elec", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "SCA_drives_elec");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Shadowing_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Shadowing", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Shadowing");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_T_fp_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "T_fp", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "T_fp");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_T_loop_in_des_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "T_loop_in_des", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "T_loop_in_des");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_T_loop_out_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "T_loop_out", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "T_loop_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Tau_envelope_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Tau_envelope", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Tau_envelope");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_TrackingError_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "TrackingError", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "TrackingError");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_Type_cpnt_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "Type_cpnt", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Type_cpnt");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_max_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "V_hdr_cold_max", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_cold_max");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_cold_min_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "V_hdr_cold_min", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_cold_min");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_max_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "V_hdr_hot_max", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_hot_max");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_V_hdr_hot_min_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "V_hdr_hot_min", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "V_hdr_hot_min");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_W_aperture_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "W_aperture", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "W_aperture");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_accept_init_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "accept_init", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "accept_init");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_accept_loc_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "accept_loc", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "accept_loc");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_accept_mode_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "accept_mode", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "accept_mode");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_alpha_abs_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "alpha_abs", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "alpha_abs");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_alpha_env_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "alpha_env", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "alpha_env");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_calc_design_pipe_vals_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "calc_design_pipe_vals", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "calc_design_pipe_vals");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_custom_sf_pipe_sizes_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "custom_sf_pipe_sizes", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "custom_sf_pipe_sizes");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_11_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_11", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_11");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_12_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_12", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_12");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_13_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_13", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_13");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_14_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_14", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_14");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_21_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_21", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_21");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_22_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_22", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_22");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_23_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_23", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_23");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_24_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_24", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_24");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_31_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_31", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_31");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_32_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_32", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_32");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_33_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_33", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_33");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_34_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_34", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_34");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_41_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_41", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_41");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_42_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_42", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_42");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_43_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_43", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_43");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_epsilon_3_44_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "epsilon_3_44", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "epsilon_3_44");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_eta_pump_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "eta_pump", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "eta_pump");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_is_model_heat_sink_piping_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_model_heat_sink_piping", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_model_heat_sink_piping");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmax_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "m_dot_htfmax", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_htfmax");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_m_dot_htfmin_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "m_dot_htfmin", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_htfmin");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_cold_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "mc_bal_cold", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "mc_bal_cold");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_hot_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "mc_bal_hot", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "mc_bal_hot");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_mc_bal_sca_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "mc_bal_sca", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "mc_bal_sca");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nColt_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "nColt", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "nColt");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nHCEVar_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "nHCEVar", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "nHCEVar");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nHCEt_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "nHCEt", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "nHCEt");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nLoops_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "nLoops", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "nLoops");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_nSCA_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "nSCA", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "nSCA");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_northsouth_field_sep_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "northsouth_field_sep", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "northsouth_field_sep");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_offset_xpan_hdr_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "offset_xpan_hdr", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "offset_xpan_hdr");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_diams_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "sf_hdr_diams", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "sf_hdr_diams");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_lengths_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "sf_hdr_lengths", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "sf_hdr_lengths");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_hdr_wallthicks_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "sf_hdr_wallthicks", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "sf_hdr_wallthicks");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_diams_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "sf_rnr_diams", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "sf_rnr_diams");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_lengths_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "sf_rnr_lengths", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "sf_rnr_lengths");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_SolarField_sf_rnr_wallthicks_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "sf_rnr_wallthicks", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "sf_rnr_wallthicks");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_theta_dep_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "theta_dep", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "theta_dep");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_theta_stow_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "theta_stow", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "theta_stow");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_washing_frequency_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "washing_frequency", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "washing_frequency");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_water_usage_per_wash_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "water_usage_per_wash", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "water_usage_per_wash");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SolarField_wind_stow_speed_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "wind_stow_speed", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "wind_stow_speed");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_disp_wlim_maxspec_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_wlim_maxspec", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_wlim_maxspec");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Controller_field_fl_props_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "field_fl_props", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "field_fl_props");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_non_solar_field_land_area_multiplier_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "non_solar_field_land_area_multiplier", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "non_solar_field_land_area_multiplier");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_pb_pump_coef_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "pb_pump_coef", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "pb_pump_coef");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_q_pb_design_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "q_pb_design", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "q_pb_design");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_specified_solar_multiple_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "specified_solar_multiple", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "specified_solar_multiple");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Controller_tanks_in_parallel_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "tanks_in_parallel", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "tanks_in_parallel");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Controller_trough_loop_control_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "trough_loop_control", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "trough_loop_control");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SystemDesign_tshours_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "tshours", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "tshours");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_cold_tank_Thtr_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "cold_tank_Thtr", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "cold_tank_Thtr");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_cold_tank_max_heat_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "cold_tank_max_heat", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "cold_tank_max_heat");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_h_tank_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "h_tank", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "h_tank");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_init_hot_htf_percent_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "init_hot_htf_percent", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "init_hot_htf_percent");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_tank_pairs_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "tank_pairs", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "tank_pairs");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES_u_tank_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "u_tank", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "u_tank");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES2tank_h_tank_min_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "h_tank_min", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "h_tank_min");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_Thtr_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "hot_tank_Thtr", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "hot_tank_Thtr");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_TES2tank_hot_tank_max_heat_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "hot_tank_max_heat", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "hot_tank_max_heat");
});
return result;
}
SAM_EXPORT const char* SAM_TroughPhysicalProcessHeat_Tou_ampl_data_dir_sget(SAM_table ptr, SAM_error *err){
const char* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_string(ptr, "ampl_data_dir");
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "ampl_data_dir");
});
return result;
}
SAM_EXPORT const char* SAM_TroughPhysicalProcessHeat_Tou_ampl_exec_call_sget(SAM_table ptr, SAM_error *err){
const char* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_string(ptr, "ampl_exec_call");
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "ampl_exec_call");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_csu_cost_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_csu_cost", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_csu_cost");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_frequency_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_frequency", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_frequency");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_horizon_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_horizon", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_horizon");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_max_iter_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_max_iter", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_max_iter");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_mip_gap_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_mip_gap", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_mip_gap");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_pen_delta_w_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_pen_delta_w", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_pen_delta_w");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_reporting_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_reporting", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_reporting");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_rsu_cost_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_rsu_cost", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_rsu_cost");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_spec_bb_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_spec_bb", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_spec_bb");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_spec_presolve_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_spec_presolve", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_spec_presolve");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_spec_scaling_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_spec_scaling", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_spec_scaling");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_steps_per_hour_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_steps_per_hour", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_steps_per_hour");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_time_weighting_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_time_weighting", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_time_weighting");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_disp_timeout_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_timeout", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_timeout");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor1_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor1", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor1");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor2_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor2", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor2");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor3_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor3", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor3");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor4_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor4", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor4");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor5_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor5", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor5");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor6_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor6", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor6");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor7_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor7", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor7");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor8_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor8", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor8");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_dispatch_factor9_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "dispatch_factor9", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factor9");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_factors_ts_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "dispatch_factors_ts", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_factors_ts");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekday_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "dispatch_sched_weekday", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_sched_weekday");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_sched_weekend_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "dispatch_sched_weekend", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_sched_weekend");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_dispatch_series_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "dispatch_series", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "dispatch_series");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_f_turb_tou_periods_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "f_turb_tou_periods", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "f_turb_tou_periods");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_ampl_engine_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_ampl_engine", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_ampl_engine");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_dispatch", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_dispatch");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_dispatch_series_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_dispatch_series", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_dispatch_series");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_tod_pc_target_also_pc_max_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_tod_pc_target_also_pc_max", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_tod_pc_target_also_pc_max");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_wlim_series_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_wlim_series", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_wlim_series");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_is_write_ampl_dat_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "is_write_ampl_dat", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "is_write_ampl_dat");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_ppa_multiplier_model_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "ppa_multiplier_model", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "ppa_multiplier_model");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_q_rec_heattrace_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "q_rec_heattrace", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "q_rec_heattrace");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Tou_q_rec_standby_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "q_rec_standby", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "q_rec_standby");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_timestep_load_fractions_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "timestep_load_fractions", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "timestep_load_fractions");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_weekday_schedule_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "weekday_schedule", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "weekday_schedule");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_weekend_schedule_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "weekend_schedule", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "weekend_schedule");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Tou_wlim_series_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wlim_series", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "wlim_series");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_SystemControl_disp_inventory_incentive_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "disp_inventory_incentive", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "disp_inventory_incentive");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_System_aux_array_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "aux_array", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "aux_array");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_System_bop_array_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "bop_array", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "bop_array");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_System_pb_fixed_par_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "pb_fixed_par", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "pb_fixed_par");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Powerblock_L_rnr_pb_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "L_rnr_pb", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "L_rnr_pb");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_CosTh_ave_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "CosTh_ave", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "CosTh_ave");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_EndLoss_ave_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "EndLoss_ave", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "EndLoss_ave");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_EqOpteff_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "EqOpteff", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "EqOpteff");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_IAM_ave_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "IAM_ave", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "IAM_ave");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_RowShadow_ave_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "RowShadow_ave", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "RowShadow_ave");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_SCAs_def_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "SCAs_def", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "SCAs_def");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_field_cold_in_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_field_cold_in", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_field_cold_in");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_field_hot_out_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_field_hot_out", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_field_hot_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_heat_sink_in_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_heat_sink_in", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_heat_sink_in");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_heat_sink_out_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_heat_sink_out", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_heat_sink_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_rec_cold_in_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_rec_cold_in", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_rec_cold_in");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_rec_hot_out_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_rec_hot_out", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_rec_hot_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_tes_cold_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_tes_cold", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_tes_cold");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_T_tes_hot_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "T_tes_hot", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "T_tes_hot");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_Theta_ave_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "Theta_ave", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "Theta_ave");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_field_pump_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "W_dot_field_pump", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_field_pump");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_parasitic_tot_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "W_dot_parasitic_tot", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_parasitic_tot");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_pc_pump_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "W_dot_pc_pump", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_pc_pump");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_W_dot_sca_track_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "W_dot_sca_track", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "W_dot_sca_track");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_electricity_consumption_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_electricity_consumption", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_electricity_consumption");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_energy_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_energy", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_energy");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_annual_energy_distribution_time_mget(SAM_table ptr, int* nrows, int* ncols, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_matrix(ptr, "annual_energy_distribution_time", nrows, ncols);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_energy_distribution_time");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_field_freeze_protection_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_field_freeze_protection", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_field_freeze_protection");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_gross_energy_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_gross_energy", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_gross_energy");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_tes_freeze_protection_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_tes_freeze_protection", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_tes_freeze_protection");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_thermal_consumption_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_thermal_consumption", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_thermal_consumption");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_annual_total_water_use_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "annual_total_water_use", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "annual_total_water_use");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_beam_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "beam", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "beam");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_capacity_factor_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "capacity_factor", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "capacity_factor");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_deltaP_field_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "deltaP_field", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "deltaP_field");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_dni_costh_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "dni_costh", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "dni_costh");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_e_ch_tes_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "e_ch_tes", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "e_ch_tes");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_e_dot_field_int_energy_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "e_dot_field_int_energy", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "e_dot_field_int_energy");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_gen_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "gen", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "gen");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_hour_day_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "hour_day", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "hour_day");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_kwh_per_kw_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "kwh_per_kw", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "kwh_per_kw");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_balance_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_balance", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_balance");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_cr_to_tes_hot_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_cr_to_tes_hot", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_cr_to_tes_hot");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_cycle_to_field_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_cycle_to_field", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_cycle_to_field");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_field_delivered_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_field_delivered", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_field_delivered");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_field_recirc_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_field_recirc", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_field_recirc");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_field_to_cycle_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_field_to_cycle", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_field_to_cycle");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_htf_heat_sink_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_htf_heat_sink", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_htf_heat_sink");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_loop_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_loop", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_loop");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_pc_to_tes_cold_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_pc_to_tes_cold", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_pc_to_tes_cold");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_tes_cold_out_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_tes_cold_out", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_tes_cold_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_m_dot_tes_hot_out_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "m_dot_tes_hot_out", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "m_dot_tes_hot_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_mass_tes_cold_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "mass_tes_cold", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "mass_tes_cold");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_mass_tes_hot_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "mass_tes_hot", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "mass_tes_hot");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_month_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "month", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "month");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_op_mode_1_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "op_mode_1", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "op_mode_1");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_op_mode_2_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "op_mode_2", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "op_mode_2");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_op_mode_3_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "op_mode_3", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "op_mode_3");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_pres_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "pres", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "pres");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_balance_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_balance", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_balance");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_ch_tes_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_ch_tes", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_ch_tes");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dc_tes_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dc_tes", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dc_tes");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_freeze_prot_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_freeze_prot", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_freeze_prot");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_htf_sf_out_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_htf_sf_out", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_htf_sf_out");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_piping_loss_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_piping_loss", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_piping_loss");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_rec_abs_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_rec_abs", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_rec_abs");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_rec_inc_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_rec_inc", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_rec_inc");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_rec_thermal_loss_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_rec_thermal_loss", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_rec_thermal_loss");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_dot_to_heat_sink_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_dot_to_heat_sink", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_dot_to_heat_sink");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_inc_sf_tot_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_inc_sf_tot", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_inc_sf_tot");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_q_tes_heater_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "q_tes_heater", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "q_tes_heater");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_qinc_costh_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "qinc_costh", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "qinc_costh");
});
return result;
}
SAM_EXPORT double SAM_TroughPhysicalProcessHeat_Outputs_solar_multiple_actual_nget(SAM_table ptr, SAM_error *err){
double result;
translateExceptions(err, [&]{
if (!ssc_data_get_number(ptr, "solar_multiple_actual", &result))
make_access_error("SAM_TroughPhysicalProcessHeat", "solar_multiple_actual");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_solazi_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "solazi", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "solazi");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_solzen_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "solzen", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "solzen");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_tank_losses_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "tank_losses", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "tank_losses");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_tdry_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "tdry", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "tdry");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_time_hr_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "time_hr", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "time_hr");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_twet_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "twet", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "twet");
});
return result;
}
SAM_EXPORT double* SAM_TroughPhysicalProcessHeat_Outputs_wspd_aget(SAM_table ptr, int* length, SAM_error *err){
double* result = nullptr;
translateExceptions(err, [&]{
result = ssc_data_get_array(ptr, "wspd", length);
if (!result)
make_access_error("SAM_TroughPhysicalProcessHeat", "wspd");
});
return result;
}
| 123,412 | 50,539 |
/**
* @brief defines newton raphman power flow solver
*
* @file newtonSolver.cpp
* @author Luiz Victor Linhares Rocha
* @date 2018-09-22
* @copyright 2018
*/
#include <cmath>
#include "newtonSolver.hpp"
#include "barra.hpp"
#include "branch.hpp"
#include "powerNet.hpp"
namespace neuralFlux {
NewtonSolver::NewtonSolver():PowerFlowSolver() {
}
NewtonSolver::NewtonSolver(PowerNetPtr net):
PowerFlowSolver(net) {
}
NewtonSolver::~NewtonSolver() {
}
const Eigen::MatrixXd& NewtonSolver::getJacobian(const bool calculate) {
if (calculate)
return calculateJacobian();
return m_jacobian;
}
const Eigen::VectorXd& NewtonSolver::getDeltas(const bool calculate) {
if (calculate)
return calculateDeltas();
return m_deltas;
}
void NewtonSolver::solve() {
cacheBars();
calculateJacobian();
calculateDeltas();
while (!reachedMaxIt() && !reachMinError(getTotalError())) {
step();
calculateJacobian();
calculateDeltas();
addIt();
}
}
const Eigen::MatrixXd& NewtonSolver::calculateJacobian() {
calculateH();
calculateM();
calculateN();
calculateL();
return m_jacobian;
}
const Eigen::VectorXd& NewtonSolver::calculateDeltas() {
for (size_t i = 0 ; i < m_nPQ ; i++) {
m_deltas(i) = getDeltaP(m_PQBars[i]);
m_deltas(i+m_nPQ+m_nPV) = getDeltaQ(m_PQBars[i]);
}
for (size_t i = 0 ; i < m_nPV ; i++) {
m_deltas(i+m_nPQ) = getDeltaP(m_PVBars[i]);
}
return m_deltas;
}
void NewtonSolver::applyCorrection() {
for (size_t i = 0 ; i < m_nPQ ; i++) {
BarPtr bar = getNet()->getBarByIndex(m_PQBars[i]);
bar->setTeta(bar->getTeta() + m_correction(i));
bar->setV(bar->getV() + m_correction(i+m_nPQ+m_nPV));
}
for (size_t i = 0 ; i < m_nPV ; i++) {
BarPtr bar = getNet()->getBarByIndex(m_PVBars[i]);
bar->setTeta(bar->getTeta() + m_correction(i+m_nPQ));
}
}
double NewtonSolver::getTotalError() {
double erroMax = 0;
for (size_t i = 0, n = m_deltas.rows() ; i < n; i++) {
if (std::fabs(m_deltas[i]) > erroMax)
erroMax = std::fabs(m_deltas[i]);
}
return erroMax;
}
void NewtonSolver::cacheBars() {
PowerNetPtr net = getNet();
size_t nBars = net->getNBars();
for (size_t i = 0 ; i < nBars ; i++) {
if (net->getBarByIndex(i)->getType() == Bar::PQ) {
m_PQBars.push_back(i);
} else if (net->getBarByIndex(i)->getType() == Bar::PV) {
m_PVBars.push_back(i);
}
}
m_nPQ = m_PQBars.size();
m_nPV = m_PVBars.size();
m_jacobian.setZero(2*m_nPQ+m_nPV, 2*m_nPQ+m_nPV);
m_deltas.setZero(2*m_nPQ+m_nPV);
m_correction.setZero(2*m_nPQ+m_nPV);
}
double NewtonSolver::getH(const size_t i, const size_t j) {
PowerNetPtr net = getNet();
if (i != j) {
const double Vk = net->getBarByIndex(i)->getV();
const double Vm = net->getBarByIndex(j)->getV();
const double Gkm = net->getY(i, j).real();
const double Bkm = net->getY(i, j).imag();
const double sinkm = sin(net->getTetaKmByIndex(i, j));
const double coskm = cos(net->getTetaKmByIndex(i, j));
return Vk*Vm*(Gkm*sinkm-Bkm*coskm);
} else {
const double Vk = net->getBarByIndex(i)->getV();
const double Bkk = net->getY(i, i).imag();
const double soma = getSumConjugate(i);
return -Vk*Vk*Bkk - Vk*soma;
}
}
double NewtonSolver::getL(const size_t i, const size_t j) {
PowerNetPtr net = getNet();
if (i != j) {
const double Vk = net->getBarByIndex(i)->getV();
const double Gkm = net->getY(i, j).real();
const double Bkm = net->getY(i, j).imag();
const double sinkm = sin(net->getTetaKmByIndex(i, j));
const double coskm = cos(net->getTetaKmByIndex(i, j));
return Vk*(Gkm*sinkm-Bkm*coskm);
} else {
const double Vk = net->getBarByIndex(i)->getV();
const double Bkk = net->getY(i, i).imag();
const double soma = getSumConjugate(i);
return -2*Vk*Bkk + soma;
}
}
double NewtonSolver::getM(const size_t i, const size_t j) {
PowerNetPtr net = getNet();
if (i != j) {
const double Vk = net->getBarByIndex(i)->getV();
const double Vm = net->getBarByIndex(j)->getV();
const double Gkm = net->getY(i, j).real();
const double Bkm = net->getY(i, j).imag();
const double sinkm = sin(net->getTetaKmByIndex(i, j));
const double coskm = cos(net->getTetaKmByIndex(i, j));
return -Vk*Vm*(Gkm*coskm+Bkm*sinkm);
} else {
const double Vk = net->getBarByIndex(i)->getV();
const double Gkk = net->getY(i, i).real();
const double soma = getSum(i);
return -(Vk*Vk)*Gkk+Vk*soma;
}
}
double NewtonSolver::getN(const size_t i, const size_t j) {
PowerNetPtr net = getNet();
if (i != j) {
const double Vk = net->getBarByIndex(i)->getV();
const double Gkm = net->getY(i, j).real();
const double Bkm = net->getY(i, j).imag();
const double sinkm = sin(net->getTetaKmByIndex(i, j));
const double coskm = cos(net->getTetaKmByIndex(i, j));
return Vk*(Gkm*coskm+Bkm*sinkm);
} else {
const double Vk = net->getBarByIndex(i)->getV();
const double Gkk = net->getY(i, i).real();
const double soma = getSum(i);
return Vk*Gkk + soma;
}
}
double NewtonSolver::getSum(const size_t i) {
double sum = 0;
PowerNetPtr net = getNet();
for (size_t j = 0, n = net->getNBars() ; j < n ; j++) {
if (i == j || net->areConnectedByIndex(i, j)) {
const double vm = net->getBarByIndex(j)->getV();
const double gkm = net->getY(i, j).real();
const double bkm = net->getY(i, j).imag();
const double sinkm = sin(net->getTetaKmByIndex(i, j));
const double coskm = cos(net->getTetaKmByIndex(i, j));
sum += vm*(gkm*coskm+bkm*sinkm);
}
}
return sum;
}
double NewtonSolver::getSumConjugate(const size_t i) {
double sum = 0;
PowerNetPtr net = getNet();
for (size_t j = 0 , n = net->getNBars() ; j < n ; j++) {
if (i == j || net->areConnectedByIndex(i, j)) {
const double vm = net->getBarByIndex(j)->getV();
const double gkm = net->getY(i, j).real();
const double bkm = net->getY(i, j).imag();
const double sinkm = sin(net->getTetaKmByIndex(i, j));
const double coskm = cos(net->getTetaKmByIndex(i, j));
sum += vm*(gkm*sinkm-bkm*coskm);
}
}
return sum;
}
double NewtonSolver::getDeltaP(const size_t i) {
BarPtr bar = getNet()->getBarByIndex(i);
return bar->getP()-bar->getV()*getSum(i);
}
double NewtonSolver::getDeltaQ(const size_t i) {
BarPtr bar = getNet()->getBarByIndex(i);
return bar->getQ()-bar->getV()*getSumConjugate(i);
}
void NewtonSolver::calculateH() {
for (size_t i = 0; i < m_nPQ ; i++) {
// primeiro, adiciona as barras pq em relação as correções de pq
for (size_t j = 0 ; j < m_nPQ ; j++) {
m_jacobian(i, j) = getH(m_PQBars[i], m_PQBars[j]);
}
// barras pq em relação a correções de pv
for (size_t j = 0 ; j < m_nPV ; j++) {
m_jacobian(i, j+m_nPQ) = getH(m_PQBars[i], m_PVBars[j]);
}
}
for (size_t i = 0 ; i < m_nPV ; i++) {
// barras pv em relação a correções de pq
for (size_t j = 0 ; j < m_nPQ ; j++) {
m_jacobian(i+m_nPQ, j) = getH(m_PVBars[i], m_PQBars[j]);
}
// barras pv em relação a correções de pv
for (size_t j = 0 ; j < m_nPV ; j++) {
m_jacobian(i+m_nPQ, j+m_nPQ) = getH(m_PVBars[i], m_PVBars[j]);
}
}
}
void NewtonSolver::calculateL() {
// apenas pq com relação de correções de pq
for (size_t i = 0 ; i < m_nPQ ; i++) {
for (size_t j = 0; j < m_nPQ; j++) {
m_jacobian(i + m_nPQ + m_nPV, j + m_nPQ + m_nPV) = getL(m_PQBars[i], m_PQBars[j]);
}
}
}
void NewtonSolver::calculateM() {
for (size_t i = 0 ; i < m_nPQ ; i++) {
// barras pq em relação a correções de pq
for (size_t j = 0 ; j < m_nPQ ; j++) {
m_jacobian(i+m_nPQ+m_nPV, j) = getM(m_PQBars[i], m_PQBars[j]);
}
// barras pv em relação a correções de pq
for (size_t j = 0 ; j < m_nPV ; j++) {
m_jacobian(i + m_nPQ + m_nPV, j + m_nPQ) = getM(m_PQBars[i], m_PVBars[j]);
}
}
}
void NewtonSolver::calculateN() {
// pq com relação a correções de PQ
for (size_t i = 0 ; i < m_nPQ ; i++) {
for (size_t j = 0 ; j < m_nPQ ; j++) {
m_jacobian(i, j + m_nPQ + m_nPV) = getN(m_PQBars[i], m_PQBars[j]);
}
}
// pv com relação a correções de PQ
for (size_t i = 0; i < m_nPV; i++) {
for (size_t j = 0 ; j < m_nPQ ; j++) {
m_jacobian(i + m_nPQ, j + m_nPQ + m_nPV) = getN(m_PVBars[i], m_PQBars[j]);
}
}
}
void NewtonSolver::step() {
m_correction = m_jacobian.colPivHouseholderQr().solve(m_deltas);
applyCorrection();
}
} // namespace neuralFlux
| 9,198 | 3,797 |
/* Copyright (C) 2021 Gleb Bezborodov - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the MIT license.
*
* You should have received a copy of the MIT license with
* this file. If not, please write to: bezborodoff.gleb@gmail.com, or visit : https://github.com/glensand/hope
*/
#include "gtest/gtest.h"
#include "hope/concurrency/async_worker_pool.h"
struct change final {
std::atomic_bool changed;
change(bool val) {
changed = val;
}
change(change&& rhs) noexcept {
changed = rhs.changed.load();
}
};
TEST(WorkerPoolTest, ChangeTest)
{
return;
constexpr unsigned TestCount{ 1000 };
std::vector<change> test_v;
for(unsigned i = 0; i < TestCount; ++i) {
test_v.emplace_back(false);
}
hope::concurrency::async_worker_pool pool;
pool.run();
for(auto&& c : test_v) {
pool.add_job([&] { c.changed = true; });
}
pool.wait();
for (auto&& c : test_v)
ASSERT_TRUE(c.changed == true);
pool.stop();
}
TEST(WorkerPoolTest, Stress)
{
return;
std::vector<int> ints;
for (auto i = 0; i < 1000; ++i)
ints.push_back(i);
hope::concurrency::async_worker_pool pool;
pool.run();
for (auto i = 0; i < 300; ++i)
pool.add_job([&] {
int sum = 0;
for (auto i : ints)
sum += i;
});
pool.wait();
pool.stop();
}
| 1,425 | 521 |
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include "popups/Popups.hpp"
#include <service-appmgr/Actions.hpp>
#include <PhoneModes/Common.hpp>
namespace gui
{
class BluetoothModeParams : public app::manager::actions::ActionParams
{
public:
explicit BluetoothModeParams(sys::bluetooth::BluetoothMode mode) : bluetoothMode{mode}
{}
[[nodiscard]] auto getBluetoothMode() const noexcept
{
return bluetoothMode;
}
private:
sys::bluetooth::BluetoothMode bluetoothMode;
};
} // namespace gui
| 680 | 231 |
// Copyright (c) 2021 The worldwideweb Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <random.h>
#include <fs.h>
#include <util/strencodings.h>
fs::path GetUniquePath(const fs::path& base)
{
FastRandomContext rnd;
fs::path tmpFile = base / HexStr(rnd.randbytes(8));
return tmpFile;
} | 414 | 148 |
#include <gtest/gtest.h>
#include <platform.h>
#include <../libponyrt/mem/pool.h>
#include <../libponyrt/sched/scheduler.h>
#include "util.h"
#include <memory>
#define TEST_COMPILE(src, pass) DO(test_compile(src, pass))
#define TEST_COMPILE_RESUME(pass) DO(test_compile_resume(pass))
class CompilerSerialisationTest : public PassTest
{
public:
void test_pass_ast(const char* pass);
void test_pass_reach(const char* pass);
};
static const char* const src =
"use @pony_exitcode[None](code: I32)\n"
"actor Main\n"
" new create(env: Env) =>\n"
" let x = recover Array[U8] end\n"
" x.push(42)\n"
" foo(consume x)\n"
" be foo(x: Array[U8] val) =>\n"
" try\n"
" if x(0)? == 42 then\n"
" @pony_exitcode(1)\n"
" end\n"
" end";
static void* s_alloc_fn(pony_ctx_t* ctx, size_t size)
{
(void)ctx;
return ponyint_pool_alloc_size(size);
}
static void s_throw_fn()
{
throw std::exception{};
}
struct pool_size_deleter
{
size_t size;
void operator()(void* ptr)
{
ponyint_pool_free_size(size, ptr);
}
};
std::unique_ptr<char, pool_size_deleter> manage_array(ponyint_array_t& array)
{
std::unique_ptr<char, pool_size_deleter> p{array.ptr};
p.get_deleter().size = array.alloc;
return p;
}
struct pool_deleter
{
size_t size;
void operator()(void* ptr)
{
ponyint_pool_free_size(size, ptr);
}
};
struct ast_deleter
{
void operator()(ast_t* ptr)
{
ast_free(ptr);
}
};
struct reach_deleter
{
void operator()(reach_t* ptr)
{
reach_free(ptr);
}
};
void CompilerSerialisationTest::test_pass_ast(const char* pass)
{
set_builtin(NULL);
TEST_COMPILE(src, pass);
pony_ctx_t ctx;
memset(&ctx, 0, sizeof(pony_ctx_t));
ponyint_array_t array;
memset(&array, 0, sizeof(ponyint_array_t));
pony_serialise(&ctx, program, ast_pony_type(), &array, s_alloc_fn, s_throw_fn);
auto array_guard = manage_array(array);
std::unique_ptr<ast_t, ast_deleter> new_guard{
(ast_t*)pony_deserialise(&ctx, ast_pony_type(), &array, s_alloc_fn,
s_alloc_fn, s_throw_fn)};
ast_t* new_program = new_guard.get();
ASSERT_NE(new_program, (void*)NULL);
DO(check_ast_same(program, new_program));
new_guard.release();
new_guard.reset(program);
program = new_program;
package = ast_child(program);
module = ast_child(package);
TEST_COMPILE_RESUME("ir");
}
void CompilerSerialisationTest::test_pass_reach(const char* pass)
{
set_builtin(NULL);
TEST_COMPILE(src, pass);
ASSERT_NE(compile, (void*)NULL);
reach_t* r = compile->reach;
pony_ctx_t ctx;
memset(&ctx, 0, sizeof(pony_ctx_t));
ponyint_array_t array;
memset(&array, 0, sizeof(ponyint_array_t));
pony_serialise(&ctx, r, reach_pony_type(), &array, s_alloc_fn, s_throw_fn);
auto array_guard = manage_array(array);
array_guard.get_deleter().size = array.size;
std::unique_ptr<reach_t, reach_deleter> new_guard{
(reach_t*)pony_deserialise(&ctx, reach_pony_type(), &array, s_alloc_fn,
s_alloc_fn, s_throw_fn)};
reach_t* new_r = new_guard.get();
ASSERT_NE(new_r, (void*)NULL);
new_guard.release();
new_guard.reset(r);
compile->reach = new_r;
TEST_COMPILE_RESUME("ir");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterSugar)
{
test_pass_ast("sugar");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterScope)
{
test_pass_ast("scope");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterImport)
{
test_pass_ast("import");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterName)
{
test_pass_ast("name");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterFlatten)
{
test_pass_ast("flatten");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterTraits)
{
test_pass_ast("traits");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterRefer)
{
test_pass_ast("refer");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterExpr)
{
test_pass_ast("expr");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterVerify)
{
test_pass_ast("verify");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterFinal)
{
test_pass_ast("final");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterReach)
{
test_pass_reach("reach");
}
TEST_F(CompilerSerialisationTest, SerialiseAfterPaint)
{
test_pass_reach("paint");
}
| 4,240 | 1,757 |
#include <boost/asio/system_timer.hpp>
| 39 | 16 |
// This is a part of the Active Template Library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.
// Client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#import "..\ATLCollections.tlb"
using namespace ATLCOLLECTIONSLib;
// Outputs all the items in a collection using the Count and Item properties
template <class T>
HRESULT OutputLoopedItems(T sp)
{
// Get the count of items
long lCount = sp->GetCount();
// The collection indexes are 1-based
for (long i = 1; i <= lCount; ++i)
{
_bstr_t bstrTemp = static_cast<_variant_t>(sp->GetItem(i));
std::cout << static_cast<const char*>(bstrTemp) << "\n";
}
return S_OK;
}
// Outputs all the items in a collection using the enumerator
template <class T>
HRESULT OutputEnumeratedItems(T sp)
{
// Get the VARIANT enumerator from the collection
IEnumVARIANTPtr spEnum = sp->Get_NewEnum();
// nBatchSize is the number of items that we request in each call to IEnumVARIANT::Next.
// The actual number of items returned may not equal nBatchSize.
const ULONG nBatchSize = 5;
// nReturned will store the number of items returned by a call to IEnumVARIANT::Next
ULONG nReturned = 0;
// arrVariant is the array used to hold the returned items
VARIANT arrVariant[nBatchSize] = {0};
HRESULT hr = E_UNEXPECTED;
do
{
hr = spEnum->Next(nBatchSize, &arrVariant[0], &nReturned);
if (FAILED(hr))
return hr;
for (ULONG i = 0; i < nReturned; ++i)
{
_bstr_t bstrTemp = static_cast<_variant_t>(arrVariant[i]);
std::cout << static_cast<const char*>(bstrTemp) << "\n";
::VariantClear(&arrVariant[i]);
}
} while (hr != S_FALSE); // S_FALSE indicates end of collection
return hr;
}
int main()
{
CoInitialize(NULL);
try
{
// Words is a read-only collection
IWordsPtr spWords(__uuidof(Words));
std::cout << "** The contents of the Words collection obtained via Count/Item **\n";
OutputLoopedItems(spWords);
std::cout << "** The contents of the Words collection obtained via the enumerator **\n";
OutputEnumeratedItems(spWords);
// Items is a read-write collection
IItemsPtr spItems(__uuidof(Items));
std::cout << "** The contents of the Items collection obtained via Count/Item ****\n";
OutputLoopedItems(spItems);
std::cout << "** The contents of the Items collection obtained via the enumerator **\n";
OutputEnumeratedItems(spItems);
// Update display
std::cout << "** Testing Add, Remove and Clear methods **\n";
// Get the current item count
std::cout << "Count: " << spItems->GetCount() << "\n";
// Define the key and the value for a new item
const wchar_t* wszKey = L"a key";
const wchar_t* wszValue = L"a value";
// Add the item
spItems->Add(wszKey, wszValue);
// Get the item
_bstr_t bstrItem = spItems->GetItem(wszKey);
// Display the item
std::cout << "Added item: " << static_cast<const char*>(bstrItem) << "\n";
// Get the current item count
std::cout << "Count: " << spItems->GetCount() << "\n";
// Remove the item
spItems->Remove(wszKey);
// Update display
std::cout << "Removed item: " << static_cast<const char*>(bstrItem) << "\n";
// Get the current item count
std::cout << "Count: " << spItems->GetCount() << "\n";
// Clear all items
spItems->Clear();
// Update display
std::cout << "Cleared all items\n";
// Get the current item count
std::cout << "Count: " << spItems->GetCount() << "\n";
}
catch (const _com_error& Err)
{
std::cout << "Error: " << Err.ErrorMessage() << "\n";
}
catch (...)
{
std::cout << "Unexpected Error\n";
}
CoUninitialize();
return 0;
}
| 3,912 | 1,388 |
// Copyright 2008 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Exhaustive testing of regular expression matching.
#include <schwa/third-party/re2/util/test.h>
#include <schwa/third-party/re2/testing/exhaustive_tester.h>
namespace schwa { namespace third_party { namespace re2 {
// Test simple character classes by themselves.
TEST(CharacterClasses, Exhaustive) {
vector<string> atoms = Split(" ",
"[a] [b] [ab] [^bc] [b-d] [^b-d] []a] [-a] [a-] [^-a] [a-b-c] a b .");
ExhaustiveTest(2, 1, atoms, RegexpGenerator::EgrepOps(),
5, Explode("ab"), "", "");
}
// Test simple character classes inside a___b (for example, a[a]b).
TEST(CharacterClasses, ExhaustiveAB) {
vector<string> atoms = Split(" ",
"[a] [b] [ab] [^bc] [b-d] [^b-d] []a] [-a] [a-] [^-a] [a-b-c] a b .");
ExhaustiveTest(2, 1, atoms, RegexpGenerator::EgrepOps(),
5, Explode("ab"), "a%sb", "");
}
// Returns UTF8 for Rune r
static string UTF8(Rune r) {
char buf[UTFmax+1];
buf[runetochar(buf, &r)] = 0;
return string(buf);
}
// Returns a vector of "interesting" UTF8 characters.
// Unicode is now too big to just return all of them,
// so UTF8Characters return a set likely to be good test cases.
static const vector<string>& InterestingUTF8() {
static bool init;
static vector<string> v;
if (init)
return v;
init = true;
// All the Latin1 equivalents are interesting.
for (int i = 1; i < 256; i++)
v.push_back(UTF8(i));
// After that, the codes near bit boundaries are
// interesting, because they span byte sequence lengths.
for (int j = 0; j < 8; j++)
v.push_back(UTF8(256 + j));
for (int i = 512; i < Runemax; i <<= 1)
for (int j = -8; j < 8; j++)
v.push_back(UTF8(i + j));
// The codes near Runemax, including Runemax itself, are interesting.
for (int j = -8; j <= 0; j++)
v.push_back(UTF8(Runemax + j));
return v;
}
// Test interesting UTF-8 characters against character classes.
TEST(InterestingUTF8, SingleOps) {
vector<string> atoms = Split(" ",
". ^ $ \\a \\f \\n \\r \\t \\v \\d \\D \\s \\S \\w \\W \\b \\B "
"[[:alnum:]] [[:alpha:]] [[:blank:]] [[:cntrl:]] [[:digit:]] "
"[[:graph:]] [[:lower:]] [[:print:]] [[:punct:]] [[:space:]] "
"[[:upper:]] [[:xdigit:]] [\\s\\S] [\\d\\D] [^\\w\\W] [^\\d\\D]");
vector<string> ops; // no ops
ExhaustiveTest(1, 0, atoms, ops,
1, InterestingUTF8(), "", "");
}
// Test interesting UTF-8 characters against character classes,
// but wrap everything inside AB.
TEST(InterestingUTF8, AB) {
vector<string> atoms = Split(" ",
". ^ $ \\a \\f \\n \\r \\t \\v \\d \\D \\s \\S \\w \\W \\b \\B "
"[[:alnum:]] [[:alpha:]] [[:blank:]] [[:cntrl:]] [[:digit:]] "
"[[:graph:]] [[:lower:]] [[:print:]] [[:punct:]] [[:space:]] "
"[[:upper:]] [[:xdigit:]] [\\s\\S] [\\d\\D] [^\\w\\W] [^\\d\\D]");
vector<string> ops; // no ops
vector<string> alpha = InterestingUTF8();
for (int i = 0; i < alpha.size(); i++)
alpha[i] = "a" + alpha[i] + "b";
ExhaustiveTest(1, 0, atoms, ops,
1, alpha, "a%sb", "");
}
} } } // namespace
| 3,221 | 1,267 |
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <iostream>
#include <stdlib.h>
#include <dali/public-api/dali-core.h>
#include <dali-test-suite-utils.h>
#include <mesh-builder.h>
using namespace Dali;
void utc_dali_shader_startup(void)
{
test_return_value = TET_UNDEF;
}
void utc_dali_shader_cleanup(void)
{
test_return_value = TET_PASS;
}
namespace
{
static const char* VertexSource =
"This is a custom vertex shader\n"
"made on purpose to look nothing like a normal vertex shader inside dali\n";
static const char* FragmentSource =
"This is a custom fragment shader\n"
"made on purpose to look nothing like a normal fragment shader inside dali\n";
void TestConstraintNoBlue( Vector4& current, const PropertyInputContainer& inputs )
{
current.b = 0.0f;
}
} // anon namespace
int UtcDaliShaderMethodNew01(void)
{
TestApplication application;
Shader shader = Shader::New( VertexSource, FragmentSource );
DALI_TEST_EQUALS((bool)shader, true, TEST_LOCATION);
END_TEST;
}
int UtcDaliShaderMethodNew02(void)
{
TestApplication application;
Shader shader;
DALI_TEST_EQUALS((bool)shader, false, TEST_LOCATION);
END_TEST;
}
int UtcDaliShaderAssignmentOperator(void)
{
TestApplication application;
Shader shader1 = Shader::New(VertexSource, FragmentSource);
Shader shader2;
DALI_TEST_CHECK(!(shader1 == shader2));
shader2 = shader1;
DALI_TEST_CHECK(shader1 == shader2);
shader2 = Shader::New(VertexSource, FragmentSource);;
DALI_TEST_CHECK(!(shader1 == shader2));
END_TEST;
}
int UtcDaliShaderDownCast01(void)
{
TestApplication application;
Shader shader = Shader::New(VertexSource, FragmentSource);
BaseHandle handle(shader);
Shader shader2 = Shader::DownCast(handle);
DALI_TEST_EQUALS( (bool)shader2, true, TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderDownCast02(void)
{
TestApplication application;
Handle handle = Handle::New(); // Create a custom object
Shader shader = Shader::DownCast(handle);
DALI_TEST_EQUALS( (bool)shader, false, TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderDefaultProperties(void)
{
TestApplication application;
// from shader-impl.cpp
// DALI_PROPERTY( "program", MAP, true, false, false, Dali::Shader::Property::PROGRAM )
Shader shader = Shader::New(VertexSource, FragmentSource);
DALI_TEST_EQUALS( shader.GetPropertyCount(), 1, TEST_LOCATION );
DALI_TEST_EQUALS( shader.GetPropertyName( Shader::Property::PROGRAM ), "program", TEST_LOCATION );
DALI_TEST_EQUALS( shader.GetPropertyIndex( "program" ), (Property::Index)Shader::Property::PROGRAM, TEST_LOCATION );
DALI_TEST_EQUALS( shader.GetPropertyType( Shader::Property::PROGRAM ), Property::MAP, TEST_LOCATION );
DALI_TEST_EQUALS( shader.IsPropertyWritable( Shader::Property::PROGRAM ), true, TEST_LOCATION );
DALI_TEST_EQUALS( shader.IsPropertyAnimatable( Shader::Property::PROGRAM ), false, TEST_LOCATION );
DALI_TEST_EQUALS( shader.IsPropertyAConstraintInput( Shader::Property::PROGRAM ), false, TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderConstraint01(void)
{
TestApplication application;
tet_infoline("Test that a non-uniform shader property can be constrained");
Shader shader = Shader::New(VertexSource, FragmentSource);
Geometry geometry = CreateQuadGeometry();
Renderer renderer = Renderer::New( geometry, shader );
Actor actor = Actor::New();
actor.AddRenderer(renderer);
actor.SetSize(400, 400);
Stage::GetCurrent().Add(actor);
Vector4 initialColor = Color::WHITE;
Property::Index colorIndex = shader.RegisterProperty( "uFadeColor", initialColor );
application.SendNotification();
application.Render(0);
DALI_TEST_EQUALS( shader.GetProperty<Vector4>(colorIndex), initialColor, TEST_LOCATION );
// Apply constraint
Constraint constraint = Constraint::New<Vector4>( shader, colorIndex, TestConstraintNoBlue );
constraint.Apply();
application.SendNotification();
application.Render(0);
// Expect no blue component in either buffer - yellow
DALI_TEST_EQUALS( shader.GetCurrentProperty< Vector4 >( colorIndex ), Color::YELLOW, TEST_LOCATION );
application.Render(0);
DALI_TEST_EQUALS( shader.GetCurrentProperty< Vector4 >( colorIndex ), Color::YELLOW, TEST_LOCATION );
shader.RemoveConstraints();
shader.SetProperty(colorIndex, Color::WHITE );
application.SendNotification();
application.Render(0);
DALI_TEST_EQUALS( shader.GetCurrentProperty< Vector4 >( colorIndex ), Color::WHITE, TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderConstraint02(void)
{
TestApplication application;
tet_infoline("Test that a uniform map shader property can be constrained");
Shader shader = Shader::New(VertexSource, FragmentSource);
Geometry geometry = CreateQuadGeometry();
Renderer renderer = Renderer::New( geometry, shader );
Actor actor = Actor::New();
actor.AddRenderer(renderer);
actor.SetSize(400, 400);
Stage::GetCurrent().Add(actor);
application.SendNotification();
application.Render(0);
Vector4 initialColor = Color::WHITE;
Property::Index colorIndex = shader.RegisterProperty( "uFadeColor", initialColor );
TestGlAbstraction& gl = application.GetGlAbstraction();
application.SendNotification();
application.Render(0);
Vector4 actualValue(Vector4::ZERO);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, initialColor, TEST_LOCATION );
// Apply constraint
Constraint constraint = Constraint::New<Vector4>( shader, colorIndex, TestConstraintNoBlue );
constraint.Apply();
application.SendNotification();
application.Render(0);
// Expect no blue component in either buffer - yellow
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, Color::YELLOW, TEST_LOCATION );
application.Render(0);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, Color::YELLOW, TEST_LOCATION );
shader.RemoveConstraints();
shader.SetProperty(colorIndex, Color::WHITE );
application.SendNotification();
application.Render(0);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, Color::WHITE, TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderAnimatedProperty01(void)
{
TestApplication application;
tet_infoline("Test that a non-uniform shader property can be animated");
Shader shader = Shader::New(VertexSource, FragmentSource);
Geometry geometry = CreateQuadGeometry();
Renderer renderer = Renderer::New( geometry, shader );
Actor actor = Actor::New();
actor.AddRenderer(renderer);
actor.SetSize(400, 400);
Stage::GetCurrent().Add(actor);
Vector4 initialColor = Color::WHITE;
Property::Index colorIndex = shader.RegisterProperty( "uFadeColor", initialColor );
application.SendNotification();
application.Render(0);
DALI_TEST_EQUALS( shader.GetProperty<Vector4>(colorIndex), initialColor, TEST_LOCATION );
Animation animation = Animation::New(1.0f);
KeyFrames keyFrames = KeyFrames::New();
keyFrames.Add(0.0f, initialColor);
keyFrames.Add(1.0f, Color::TRANSPARENT);
animation.AnimateBetween( Property( shader, colorIndex ), keyFrames );
animation.Play();
application.SendNotification();
application.Render(500);
DALI_TEST_EQUALS( shader.GetCurrentProperty< Vector4 >( colorIndex ), Color::WHITE * 0.5f, TEST_LOCATION );
application.Render(500);
DALI_TEST_EQUALS( shader.GetCurrentProperty< Vector4 >( colorIndex ), Color::TRANSPARENT, TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderAnimatedProperty02(void)
{
TestApplication application;
tet_infoline("Test that a uniform map shader property can be animated");
Shader shader = Shader::New(VertexSource, FragmentSource);
Geometry geometry = CreateQuadGeometry();
Renderer renderer = Renderer::New( geometry, shader );
Actor actor = Actor::New();
actor.AddRenderer(renderer);
actor.SetSize(400, 400);
Stage::GetCurrent().Add(actor);
application.SendNotification();
application.Render(0);
Vector4 initialColor = Color::WHITE;
Property::Index colorIndex = shader.RegisterProperty( "uFadeColor", initialColor );
TestGlAbstraction& gl = application.GetGlAbstraction();
application.SendNotification();
application.Render(0);
Vector4 actualValue(Vector4::ZERO);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, initialColor, TEST_LOCATION );
Animation animation = Animation::New(1.0f);
KeyFrames keyFrames = KeyFrames::New();
keyFrames.Add(0.0f, initialColor);
keyFrames.Add(1.0f, Color::TRANSPARENT);
animation.AnimateBetween( Property( shader, colorIndex ), keyFrames );
animation.Play();
application.SendNotification();
application.Render(500);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, Color::WHITE * 0.5f, TEST_LOCATION );
application.Render(500);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, Color::TRANSPARENT, TEST_LOCATION );
// change shader program
Property::Map map;
map["vertex"] = VertexSource;
map["fragment"] = FragmentSource;
map["hints"] = "MODIFIES_GEOMETRY";
shader.SetProperty( Shader::Property::PROGRAM, Property::Value(map) );
application.SendNotification();
application.Render(100);
// register another custom property as well
Property::Index customIndex = shader.RegisterProperty( "uCustom", Vector3(1,2,3) );
DALI_TEST_EQUALS( shader.GetProperty<Vector3>( customIndex ), Vector3(1,2,3), TEST_LOCATION );
application.SendNotification();
application.Render(100);
DALI_TEST_CHECK( gl.GetUniformValue<Vector4>( "uFadeColor", actualValue ) );
DALI_TEST_EQUALS( actualValue, Color::TRANSPARENT, TEST_LOCATION );
Vector3 customValue;
DALI_TEST_CHECK( gl.GetUniformValue<Vector3>( "uCustom", customValue ) );
DALI_TEST_EQUALS( customValue, Vector3(1,2,3), TEST_LOCATION );
END_TEST;
}
int UtcDaliShaderProgramProperty(void)
{
TestApplication application;
tet_infoline("Test get/set progam property");
Shader shader = Shader::New("", "");
std::string hintSet = "MODIFIES_GEOMETRY";
Property::Map map;
map["vertex"] = VertexSource;
map["fragment"] = FragmentSource;
map["hints"] = hintSet;
shader.SetProperty( Shader::Property::PROGRAM, Property::Value(map) );
// register a custom property as well
Property::Index customIndex = shader.RegisterProperty( "custom", Vector3(1,2,3) );
DALI_TEST_EQUALS( shader.GetProperty<Vector3>( customIndex ), Vector3(1,2,3), TEST_LOCATION );
Property::Value value = shader.GetProperty(Shader::Property::PROGRAM);
DALI_TEST_CHECK( value.GetType() == Property::MAP);
const Property::Map* outMap = value.GetMap();
std::string v = (*outMap)["vertex"].Get<std::string>();
std::string f = (*outMap)["fragment"].Get<std::string>();
std::string h = (*outMap)["hints"].Get<std::string>();
DALI_TEST_CHECK( v == VertexSource );
DALI_TEST_CHECK( f == FragmentSource );
DALI_TEST_CHECK( h == hintSet );
value = shader.GetCurrentProperty( Shader::Property::PROGRAM );
DALI_TEST_CHECK( value.GetType() == Property::MAP);
outMap = value.GetMap();
// check that changing the shader did not cause us to loose custom property
DALI_TEST_EQUALS( shader.GetProperty<Vector3>( customIndex ), Vector3(1,2,3), TEST_LOCATION );
using Dali::Animation;
Animation animation = Animation::New( 0.1f );
animation.AnimateTo( Property( shader, customIndex ), Vector3(4,5,6) );
animation.Play();
application.SendNotification();
application.Render(100);
DALI_TEST_EQUALS( shader.GetProperty<Vector3>( customIndex ), Vector3(4,5,6), TEST_LOCATION );
v = (*outMap)["vertex"].Get<std::string>();
f = (*outMap)["fragment"].Get<std::string>();
h = (*outMap)["hints"].Get<std::string>();
DALI_TEST_CHECK( v == VertexSource );
DALI_TEST_CHECK( f == FragmentSource );
DALI_TEST_CHECK( h == hintSet );
std::string hintGot;
hintSet = "OUTPUT_IS_TRANSPARENT,MODIFIES_GEOMETRY";
map["hints"] = hintSet;
shader.SetProperty( Shader::Property::PROGRAM, Property::Value(map) );
value = shader.GetProperty(Shader::Property::PROGRAM);
hintGot = (*value.GetMap())["hints"].Get<std::string>();
DALI_TEST_CHECK( hintGot == hintSet );
hintSet = "OUTPUT_IS_TRANSPARENT";
map["hints"] = hintSet;
shader.SetProperty( Shader::Property::PROGRAM, Property::Value(map) );
value = shader.GetProperty(Shader::Property::PROGRAM);
hintGot = (*value.GetMap())["hints"].Get<std::string>();
DALI_TEST_CHECK( hintGot == hintSet );
hintSet = "NONE";
map["hints"] = hintSet;
shader.SetProperty( Shader::Property::PROGRAM, Property::Value(map) );
value = shader.GetProperty(Shader::Property::PROGRAM);
hintGot = (*value.GetMap())["hints"].Get<std::string>();
DALI_TEST_CHECK( hintGot == hintSet );
hintSet = "";
map["hints"] = hintSet;
shader.SetProperty( Shader::Property::PROGRAM, Property::Value(map) );
value = shader.GetProperty(Shader::Property::PROGRAM);
hintGot = (*value.GetMap())["hints"].Get<std::string>();
DALI_TEST_CHECK( hintGot == "NONE" );
END_TEST;
}
| 13,848 | 4,907 |
/****************************************************************************************
Program: PictureDesigner
Author: Görkem Tok
Language: C++
Platform: Qt Creator
Contact: ceng.gorkem.tok@gmail.com
License: MIT
****************************************************************************************/
#include "opencv_.h"
#include <QDebug>
#include <QPixmap>
#include <QMessageBox>
#include "fileoperations.h"
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgcodecs.hpp"
#include <opencv2/photo/photo.hpp>
#include "pictureoperations.h"
#include <QString>
#include "mainwindow.h"
#include <QLabel>
#include <QImage>
#include <QtMath>
Opencv_::Opencv_(MainWindow *mw, QLabel *mainLabel, QLabel *processLabel, QLabel *lbx, QLabel *lby, QLabel *lbinch, QLabel *lbch,
QLabel *lbx1, QLabel *lby1, QLabel *lbinch1, QLabel *lbch1, QLabel *statusLabel)
{
this->mw = mw;
this->fileOperations = new FileOperations();
this->poLoaded = new PictureOperations();
this->poProcess = new PictureOperations();
this->mainImageLabel = mainLabel;
this->processImageLabel = processLabel;
this->lbx = lbx;
this->lbx1 = lbx1;
this->lby = lby;
this->lby1 = lby1;
this->lbinc = lbinch;
this->lbinc1 = lbinch1;
this->lbch = lbch;
this->lbch1 = lbch1;
this->statusLabel = statusLabel;
}
void Opencv_::LoadImage(QString filepath)
{
loadedImage = cv::imread(filepath.toStdString(), cv::IMREAD_ANYCOLOR|cv::IMREAD_ANYDEPTH);
cv::Mat tempLoaded;
if(loadedImage.data)
{
loadedImage.copyTo(originalImage);
if(loadedImage.channels() > 1)
{
loadedImage.copyTo(OriginalColoredImage);
cv::cvtColor(loadedImage, tempLoaded,CV_BGR2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
}
else if(loadedImage.channels() == 1)
{
cv::cvtColor(loadedImage, tempLoaded,CV_GRAY2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
}
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug() << "LoadImage: Succes";
return;
}
qDebug() << "Failed To Load Image From "<<filePath;
QMessageBox::information(mw,"Resim Yükleme Hatası","Üzgünüm, yüklemeye çalıştığınız resim açılamıyor. Resmin dosya yolunun ve adının Türkçe karakter içermediğinden emin olun ve tekrar deneyin.");
return;
}
void Opencv_::SaveImage()
{
filePath = fileOperations->SaveImage(mw);
if(filePath != "")
{
cv::imwrite(filePath.toStdString(),loadedImage);
QMessageBox::information(mw,"Kaydetme Sonucu","Resim "+filePath+" dizinine kaydedildi !");
}
}
void Opencv_::OpenImage()
{
filePath = fileOperations->LoadImageFromFile(mw);
if( filePath != "")
LoadImage(filePath);
}
void Opencv_::BluredApply()
{
if(bluredImage.data)
{
bluredImage.copyTo(loadedImage);
cv::Mat tempLoaded;
cv::cvtColor(loadedImage, tempLoaded,CV_BGR2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug()<<"Blured Done";
}
else
QMessageBox::information(mw,"Resim bulunamadı","bu işlemi yapabilmek için resim seçmeniz gerekmektedir.");
}
void Opencv_::EdgeApply()
{
if(afterProcessImage.data)
{
afterProcessImage.copyTo(loadedImage);
cv::Mat tempLoaded;
cv::cvtColor(loadedImage, tempLoaded, CV_BGR2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug()<<"Edge Done";
}
else
QMessageBox::information(mw,"Resim bulunamadı","bu işlemi yapabilmek için resim seçmeniz gerekmektedir.");
}
void Opencv_::Filter2DApply()
{
if(filter2dImage.data)
{
filter2dImage.copyTo(loadedImage);
cv::Mat tempLoaded;
if(loadedImage.channels()>1)
cv::cvtColor(loadedImage, tempLoaded, CV_BGR2RGB);
else
cv::cvtColor(loadedImage, tempLoaded, CV_GRAY2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug()<<"Filter2D Done";
}
else
QMessageBox::information(mw,"Resim bulunamadı","bu işlemi yapabilmek için resim seçmeniz gerekmektedir.");
}
void Opencv_::ApplyMorphology()
{
if(morphologyImage.data)
{
morphologyImage.copyTo(loadedImage);
cv::Mat tempLoaded;
if(loadedImage.channels()>1)
cv::cvtColor(loadedImage, tempLoaded, CV_BGR2RGB);
else
cv::cvtColor(loadedImage, tempLoaded, CV_GRAY2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug()<<"Morphology Done";
}
else
QMessageBox::information(mw,"Resim bulunamadı","bu işlemi yapabilmek için resim seçmeniz ve resim üzerinde değişiklik yapmanız gerekmektedir.");
}
void Opencv_::ApplyColorFilter()
{
if(colorFilteredImage.data)
{
colorFilteredImage.copyTo(loadedImage);
cv::Mat tempLoaded;
if(loadedImage.channels()>1)
cv::cvtColor(loadedImage, tempLoaded, CV_BGR2RGB);
else
cv::cvtColor(loadedImage, tempLoaded, CV_GRAY2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug()<<"ColorFilter Done";
return;
}
QMessageBox::information(mw,"Resim bulunamadı","bu işlemi yapabilmek için resim seçmeniz ve resim üzerinde değişiklik yapmanız gerekmektedir.");
return;
}
void Opencv_::findContoursApply(bool t)
{
if(grayImage.data)
{
if(!t)
grayImage.copyTo(loadedImage);
else if(t)
{
cv::cvtColor(tempdrawcontoursImage,tempdrawcontoursImage,CV_RGB2BGR);
tempdrawcontoursImage.copyTo(loadedImage);
}
cv::Mat tempLoaded;
cv::cvtColor(loadedImage, tempLoaded,CV_BGR2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug()<<"findContours Done";
}
else
QMessageBox::information(mw,"Resim bulunamadı","bu işlemi yapabilmek için resim seçmeniz gerekmektedir.");
return;
}
bool Opencv_::Filter2D(int index, int kernel, int anchorX, int anchorY, double delta,int adaptiveType, int threshType, int deltaMin, int deltaMax, int size)
{
if(loadedImage.data)
{
if(index == 0)
{
float *kernelData = nullptr;
if(kernel == 0)
{
float Data[] = {0,0,0,0,1,0,0,0,0};
kernelData = Data;
}
else if(kernel == 1)
{
float Data[] = {1,0,-1,0,0,0,-1,0,1};
kernelData = Data;
}
else if(kernel == 2)
{
float Data[] = {0,-1,0,-1,4,-1,0,-1,0};
kernelData = Data;
}
else if(kernel == 3)
{
float Data[] = {-1,-1,-1,-1,8,-1,-1,-1,-1};
kernelData = Data;
}
else if(kernel == 4)
{
float Data[] = {0,-1,0,-1,5,-1,0,-1,0};
kernelData = Data;
}
cv::Size arraySize(3,3);
cv::Mat kernel=cv::Mat(arraySize, CV_32F, kernelData);
cv::Point anchor(anchorX,anchorY);
cv::filter2D(loadedImage,filter2dImage,-1,kernel,anchor,delta);
statusLabel->setText("Anchor(x,y) = "+ QString::number(anchor.x)+","+QString::number(anchor.y)+","+"Delta = "+QString::number(delta));
}
else if(index == 1)
{
cv::Mat tempthImage;
loadedImage.copyTo(tempthImage);
if(tempthImage.channels()>1)
cv::cvtColor(tempthImage, tempthImage, CV_BGR2GRAY);
cv::threshold(tempthImage, filter2dImage,deltaMin,deltaMax,threshType | cv::THRESH_OTSU);
statusLabel->setText("Thresh min:"+QString::number(deltaMin)+",Thresh max:"+QString::number(deltaMin));
}
else if(index == 2)
{
cv::Mat tempthImage;
loadedImage.copyTo(tempthImage);
if(tempthImage.channels()>1)
cv::cvtColor(tempthImage, tempthImage, CV_BGR2GRAY);
if(threshType != 0 && threshType != 1)
threshType = 0;
cv::adaptiveThreshold(tempthImage,filter2dImage, deltaMax, adaptiveType, threshType, size, 1);
statusLabel->setText("Delta Max:"+QString::number(deltaMax)+",Size:"+QString::number(size));
}
SetLoadedImageInfo(filter2dImage);
cv::Mat temp;
if(filter2dImage.channels()>1)
cv::cvtColor(filter2dImage, temp, CV_BGR2RGB);
else
cv::cvtColor(filter2dImage, temp, CV_GRAY2RGB);
QImageLoaded = new QImage(temp.data,temp.cols,temp.rows, temp.step,QImage::Format_RGB888);
poProcess->PutImageIntoLabel(*QImageLoaded, processImageLabel);
qDebug()<<"Filter2D: Success";
return true;
}
qDebug()<<"Filter2D: Exception: Image data is empty";
QMessageBox::information(mw,"Resim Yükleme Hatası","Filtreleme işlemini gerçekleştirmek için lütfen resim seçin.");
return false;
}
bool Opencv_::EdgeDetection(int index, bool dxS, bool dyS, int ksize, double scale, double delta,int thressMin, int thressMax)
{
if(loadedImage.data)
{
if(index == 0) //SOBEL
{
int dx = 0, dy = 0;
if(dxS)
dx=1;
else if(!dxS)
dx = 0;
if(dyS)
dy = 1;
else if(!dyS)
dy = 0;
cv::Sobel(loadedImage, afterProcessImage,-1,dx,dy,ksize,scale,delta);
qDebug()<<"Sobel success";
statusLabel->setText("dx:"+QString::number(dx)+",dy:"+QString::number(dy)+",Size:"+QString::number(ksize));
}
else if(index == 1) //LAPLACIAN
{
cv::Laplacian(loadedImage,afterProcessImage,-1,ksize,scale,delta);
qDebug()<<"Laptacian Success";
statusLabel->setText("Ksize:"+QString::number(ksize)+",Scale:"+QString::number(scale));
}
else if(index == 2) //SCHARR
{
int dx = 0, dy = 0;
if(dxS)
dx=1;
else if(!dxS)
dx = 0;
if(dyS)
dy = 1;
else if(!dyS)
dy = 0;
cv::Scharr(loadedImage,afterProcessImage,-1,dx,dy,scale,delta);
qDebug()<<"Scharr success";
statusLabel->setText("dx:"+QString::number(dx)+",dy:"+QString::number(dy)+",Scale:"+QString::number(scale));
}
else if(index == 3) // CANNY
{
cv::Mat temp;
loadedImage.copyTo(temp);
cv::cvtColor(temp,temp,CV_BGR2GRAY);
cv::Canny(temp,afterProcessImage,thressMin,thressMax,3,false);
statusLabel->setText("Thresh min:"+QString::number(thressMin)+",Thresh max:"+QString::number(thressMax));
}
cv::Mat iafterProcessImage;
afterProcessImage.copyTo(iafterProcessImage);
SetLoadedImageInfo(iafterProcessImage);
if(iafterProcessImage.channels()>1)
cv::cvtColor(iafterProcessImage, iafterProcessImage, CV_BGR2RGB);
else
cv::cvtColor(iafterProcessImage, iafterProcessImage, CV_GRAY2RGB);
QImageLoaded = new QImage(iafterProcessImage.data,iafterProcessImage.cols,iafterProcessImage.rows,iafterProcessImage.step,QImage::Format_RGB888);
poProcess->PutImageIntoLabel(*QImageLoaded, processImageLabel);
return true;
}
qDebug()<<"Function: EdgeDetection Exception: Image data is empty !";
return false;
}
bool Opencv_::Blur(int index, int kSizeX, int kSizeY, int ancX, int ancY, int sigmaX, int sigmaY, int k_size, int sigmaColor, int sigmaSpace)
{
if(loadedImage.data)
{
loadedImage.copyTo(TemploadedImage);
if(loadedImage.channels()==1)
cv::cvtColor(TemploadedImage,TemploadedImage, CV_GRAY2BGR);
if(index == 0)
{
cv::blur(TemploadedImage, bluredImage, cv::Size(kSizeX,kSizeY) , cv::Point(ancX,ancY));
statusLabel->setText("SizeX:"+QString::number(kSizeX)+",SizeY:"+QString::number(kSizeY));
}
else if(index == 1)
{
cv::GaussianBlur(TemploadedImage, bluredImage, cv::Size(kSizeX, kSizeY),sigmaX, sigmaY);
statusLabel->setText("SizeX:"+QString::number(kSizeX)+",SizeY:"+QString::number(kSizeY)+",Sigma(x,y):"+QString::number(sigmaX)+","+QString::number(sigmaY));
}
else if(index == 2)
{
cv::medianBlur(TemploadedImage, bluredImage, k_size);
statusLabel->setText("Size:"+QString::number(k_size));
}
else if(index == 3)
{
cv::boxFilter(TemploadedImage, bluredImage, -1, cv::Size(kSizeX, kSizeY),cv::Point(ancX,ancY));
statusLabel->setText("SizeX:"+QString::number(kSizeX)+",SizeY:"+QString::number(kSizeY));
}
else if(index == 4)
{
cv::bilateralFilter(TemploadedImage, bluredImage, k_size, sigmaColor, sigmaSpace);
statusLabel->setText("Size:"+QString::number(k_size)+",SigmaCol:"+QString::number(sigmaColor)+",SigmaSpa:"+QString::number(sigmaSpace));
}
cv::Mat ibluredImage;
bluredImage.copyTo(ibluredImage);
SetLoadedImageInfo(ibluredImage);
cv::cvtColor(ibluredImage, ibluredImage, CV_BGR2RGB);
QImageLoaded = new QImage(ibluredImage.data,ibluredImage.cols,ibluredImage.rows,ibluredImage.step,QImage::Format_RGB888);
poProcess->PutImageIntoLabel(*QImageLoaded, processImageLabel);
qDebug()<<"Function Blur: Success";
return true;
}
qDebug()<<"Funciton Blur: Image data is empty !";
return false;
}
bool Opencv_::Morphology(int index, int shape, int sizeX, int sizeY, int ancX, int ancY, int time)
{
if(loadedImage.data)
{
cv::Mat kernel = cv::getStructuringElement(shape,cv::Size(sizeX, sizeY), cv::Point(ancX,ancY));
cv::morphologyEx(loadedImage, morphologyImage, index, kernel, cv::Point(-1,-1),time);
statusLabel->setText("SizeX:"+QString::number(sizeX)+",SizeY:"+QString::number(sizeY)+", Time:"+QString::number(time));
cv::Mat imorphologyImage;
morphologyImage.copyTo(imorphologyImage);
SetLoadedImageInfo(imorphologyImage);
if(imorphologyImage.channels()>1)
cv::cvtColor(imorphologyImage, imorphologyImage, CV_BGR2RGB);
else
cv::cvtColor(imorphologyImage, imorphologyImage, CV_GRAY2RGB);
QImageLoaded = new QImage(imorphologyImage.data, imorphologyImage.cols, imorphologyImage.rows, imorphologyImage.step,QImage::Format_RGB888);
poProcess->PutImageIntoLabel(*QImageLoaded, processImageLabel);
return true;
}
qDebug()<<"Function Morphology Excepiton: Loaded image is empty !";
return false;
}
void Opencv_::SetLoadedImageInfo()
{
if(loadedImage.data)
{
lbx->setText(QString::number(loadedImage.cols));
lby->setText(QString::number(loadedImage.rows));
lbch->setText(QString::number(loadedImage.channels()));
if(loadedImage.channels() > 1)
lbinc->setText("RGB");
else
lbinc->setText("GRAY");
qDebug()<<"SetImageInfo Success";
return;
}
qDebug()<<"SetImageInfo Excepiton: Loaded image is empty !";
return;
}
void Opencv_::SetLoadedImageInfo(cv::Mat image)
{
if(image.data)
{
lbx1->setText(QString::number(image.cols));
lby1->setText(QString::number(image.rows));
lbch1->setText(QString::number(image.channels()));
if(image.channels() > 1)
lbinc1->setText("RGB");
else
lbinc1->setText("GRAY");
qDebug()<<"SetImageInfo Success";
return;
}
qDebug()<<"SetImageInfo 1/ Excepiton: Loaded image is empty !";
return;
}
bool Opencv_::GetLoadedQImage(QImage &image)
{
if(loadedImage.data)
{
cv::Mat temp;
loadedImage.copyTo(temp);
if(temp.channels()>1)
cv::cvtColor(temp,temp,CV_BGR2RGB);
else
cv::cvtColor(temp,temp,CV_GRAY2RGB);
QImage *imageTemp = new QImage(temp.data, temp.cols, temp.rows, temp.step,QImage::Format_RGB888);
image = *imageTemp;
return true;
}
QMessageBox::information(mw,"Yazdırma Hatası","Yazdırma işlemini gerçekleştirebilmek için resim seçilmiş olmalıdır !");
return false;
}
void Opencv_::ColorFilter(QLabel *imageLabel, int hmin, int smin, int vmin, int hm, int sm, int vm)
{
if(loadedImage.data)
{
if(loadedImage.channels()>1)
{
loadedImage.copyTo(colorFilteredImage);
cv::Mat hsvImage;
cv::Mat grayScale;
cv::Mat rgbImage;
cv::Mat rgbImage2;
cv::cvtColor(loadedImage, hsvImage, CV_BGR2HSV);
cv::inRange(hsvImage, cv::Scalar(hmin,smin,vmin),cv::Scalar(hm,sm,vm),grayScale);
cv::cvtColor(grayScale, grayScale, CV_GRAY2BGR);
cv::cvtColor(grayScale, rgbImage, CV_BGR2RGB);
QImage *qimage = new QImage(rgbImage.data,rgbImage.cols, rgbImage.rows,rgbImage.step,QImage::Format_RGB888);
imageLabel->setPixmap(QPixmap::fromImage(*qimage).scaled(imageLabel->size(),Qt::KeepAspectRatio));
colorFilteredImage = colorFilteredImage & grayScale;
cv::cvtColor(colorFilteredImage, rgbImage2, CV_BGR2RGB);
QImage *q2image = new QImage(rgbImage2.data,rgbImage2.cols, rgbImage2.rows,rgbImage2.step,QImage::Format_RGB888);
poProcess->PutImageIntoLabel(*q2image, processImageLabel);
SetLoadedImageInfo(hsvImage);
statusLabel->setText("(min,max)|H:"+QString::number(hmin)+","+QString::number(hm)+",S:"+QString::number(smin)+","+QString::number(sm)+",V:"+QString::number(vmin)+","+QString::number(vm));
}
else
{
QMessageBox::information(mw,"Renk Uzayı Hatası","Tek kanallı(siyah-beyaz) görüntüler üzerinde renk filtreleme işlemi yapılamaz.");
}
return;
}
QMessageBox::information(mw,"Resim Seçilmemiş","Bu işlemi yapabilmeniz için resim seçmiş olmanız gerekmektedir.");
return;
}
void Opencv_::ColorizeImageMethodNormal()
{
if(!loadedImage.empty())
{
if(OriginalColoredImage.channels()>1)
{
if(loadedImage.channels()==1)
cv::cvtColor(loadedImage,loadedImage, CV_GRAY2BGR);
tempImColoredAndOlded = loadedImage & OriginalColoredImage;
cv::cvtColor(tempImColoredAndOlded, tempImColoredAndOlded, CV_BGR2RGB);
QImage *qim = new QImage(tempImColoredAndOlded.data, tempImColoredAndOlded.cols,tempImColoredAndOlded.rows,tempImColoredAndOlded.step,QImage::Format_RGB888);
resimonizle = new ResimOnizle(1,mw,qim,mw);
cv::cvtColor(tempImColoredAndOlded, tempImColoredAndOlded, CV_RGB2BGR);
resimonizle->show();
return;
}
QMessageBox::information(mw,"Resmi Renklendir NORMAL","Bu işlemi yapabilmeniz seçilen resim renkli olmalıdır.");
return;
}
QMessageBox::information(mw,"Resmi Renklendir NORMAL","Bu işlemi yapabilmeniz için resim seçmiş olmanız gerekmektedir.");
return;
}
void Opencv_::ApplyColorizedImage()
{
if(!tempImColoredAndOlded.empty() && tempImColoredAndOlded.data)
{
tempImColoredAndOlded.copyTo(loadedImage);
QImage *q2image = new QImage(tempImColoredAndOlded.data, tempImColoredAndOlded.cols, tempImColoredAndOlded.rows,tempImColoredAndOlded.step,QImage::Format_RGB888);
poLoaded->PutImageIntoLabel(*q2image, mainImageLabel);
qDebug()<<"ApplyColorizedImage: Success";
return;
}
QMessageBox::information(mw,"NORMAL FUNCAPPLYCOLORIZED","Hay aksi, bilinmeyen bir hata oluştu.");
return;
}
bool Opencv_::findContours(QLCDNumber *countLabel, int mod, int method, int b, int g, int r, int thickness,
bool isNumbered, bool isColored)
{
if(loadedImage.empty())
{
QMessageBox::information(mw,"Resim seçilmemiş !","Hay aksi ! Bu işlemi gerçekleştirilebilmeniz için resim seçmiş olmanız gerekir.");
qDebug()<<"findContours: Loaded image is empty !";
return false;
}
if(loadedImage.channels()>1)
cv::cvtColor(loadedImage, grayImage, CV_BGR2GRAY);
else if(loadedImage.channels()== 1)
loadedImage.copyTo(grayImage);
else
{
QMessageBox::information(mw,"Resim Biçimi Hatası !","Hay aksi ! Yüklenen resmin kanal sayısı uyumsuz.");
return false;
}
originalImage.copyTo(tempdrawcontoursImage);
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hieararchy;
cv::findContours(grayImage, contours, hieararchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cv::RotatedRect rect;
cv::cvtColor(grayImage,grayImage, CV_GRAY2BGR);
for(int i = 0; i < contours.size(); i++)
{
cv::drawContours(grayImage,contours,i,cv::Scalar(b,g,r),thickness,8, hieararchy);
rect = cv::minAreaRect(contours[i]);
if(isColored)
{
cv::drawContours(tempdrawcontoursImage,contours,i,cv::Scalar(b,g,r),thickness,8, hieararchy);
}
if(isNumbered)
{
cv::putText(grayImage, std::to_string(i+1),rect.center,CV_FONT_NORMAL, 1.5, cv::Scalar(b,g,r),2);
if(isColored)
{
cv::putText(tempdrawcontoursImage, std::to_string(i+1),rect.center,CV_FONT_NORMAL, 1.5, cv::Scalar(b,g,r),2);
}
}
}
cv::cvtColor(grayImage,grayImage,CV_BGR2RGB);
QImage *q2image = new QImage(grayImage.data, grayImage.cols, grayImage.rows,grayImage.step,QImage::Format_RGB888);
poProcess->PutImageIntoLabel(*q2image, processImageLabel);
countLabel->display((int)contours.size());
if(isColored)
{
cv::cvtColor(tempdrawcontoursImage,tempdrawcontoursImage,CV_BGR2RGB);
QImage *q22image = new QImage(tempdrawcontoursImage.data, tempdrawcontoursImage.cols, tempdrawcontoursImage.rows,tempdrawcontoursImage.step,QImage::Format_RGB888);
resimonizle = new ResimOnizle(0,mw, q22image, mw);
resimonizle->show();
}
qDebug()<<"findContours: Success";
return true;
}
void Opencv_::TakeBackEverything()
{
if(!originalImage.empty() && originalImage.data)
{
cv::Mat tempLoaded;
originalImage.copyTo(loadedImage);
if(loadedImage.channels() > 1)
{
loadedImage.copyTo(OriginalColoredImage);
cv::cvtColor(loadedImage, tempLoaded,CV_BGR2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
}
else if(loadedImage.channels() == 1)
{
cv::cvtColor(loadedImage, tempLoaded,CV_GRAY2RGB);
QImageLoaded = new QImage(tempLoaded.data,tempLoaded.cols,tempLoaded.rows,tempLoaded.step,QImage::Format_RGB888);
}
poLoaded->PutImageIntoLabel(*QImageLoaded, mainImageLabel);
SetLoadedImageInfo();
qDebug() << "LoadImage: Succes";
return;
}
}
| 25,309 | 8,756 |
#pragma once
#include <ui/widgets/config.hxx>
#include <QLabel>
PRAM_NS_BEGIN
WIDGETS_NAMESPACE_BEGIN
class Label: public QLabel
{
Q_OBJECT
public:
using QLabel::QLabel;
};
PRAM_NS_END
WIDGETS_NAMESPACE_END
| 220 | 96 |
// Copyright 2019, Collabora, Ltd.
// SPDX-License-Identifier: BSL-1.0
/*!
* @file
* @brief Small helper struct that for debugging views.
* @author Jakob Bornecrantz <jakob@collabora.com>
* @ingroup aux_tracking
*/
#pragma once
#ifndef __cplusplus
#error "This header is C++-only."
#endif
#include <opencv2/opencv.hpp>
#include "util/u_frame.h"
struct HelperDebugSink
{
public:
enum Kind
{
AllAvailable,
AlwaysSingle,
};
public:
Kind kind = AllAvailable;
struct xrt_frame_sink *sink = {};
struct xrt_frame *frame = {};
cv::Mat rgb[2] = {};
public:
HelperDebugSink(Kind kind)
{
this->kind = kind;
}
HelperDebugSink() = delete;
~HelperDebugSink()
{
xrt_frame_reference(&frame, NULL);
}
void
refresh(struct xrt_frame *xf)
{
if (sink == NULL) {
return;
}
// But what about second breakfast?
bool second_view = false;
int rows, cols, width, height;
cols = xf->width;
rows = xf->height;
width = xf->width;
height = xf->height;
enum xrt_stereo_format stereo_format = xf->stereo_format;
switch (xf->stereo_format) {
case XRT_STEREO_FORMAT_SBS:
cols /= 2;
if (kind == AllAvailable) {
second_view = true;
} else {
stereo_format = XRT_STEREO_FORMAT_NONE;
width /= 2;
second_view = false;
}
break;
case XRT_STEREO_FORMAT_NONE:
// Noop
break;
default: return;
}
// Create a new frame and also dereferences the old frame.
u_frame_create_one_off(XRT_FORMAT_R8G8B8, width, height, &frame);
// Copy needed info.
frame->source_sequence = xf->source_sequence;
frame->stereo_format = stereo_format;
// Doesn't claim ownership of the frame data,
// points directly at the frame data.
rgb[0] = cv::Mat( //
rows, // rows
cols, // cols
CV_8UC3, // channels
frame->data, // data
frame->stride); // stride
if (second_view) {
// Doesn't claim ownership of the frame data,
// points directly at the frame data.
rgb[1] = cv::Mat( //
rows, // rows
cols, // cols
CV_8UC3, // channels
frame->data + 3 * cols, // data
frame->stride); // stride
}
}
void
submit()
{
if (frame != NULL) {
// Make sure that the cv::Mats doesn't use the data.
rgb[0] = cv::Mat();
rgb[1] = cv::Mat();
sink->push_frame(sink, frame);
}
// We unreference the frame here, downstream is either
// done with it or have referenced it themselves.
xrt_frame_reference(&frame, NULL);
}
};
| 2,567 | 1,062 |
/* mbed Microcontroller Library
* Copyright (c) 20015 ARM Limited
*
* 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 SpwfSAInterface.cpp
* @author STMicroelectronics
* @brief Implementation of the NetworkStack for the SPWF Device
******************************************************************************
* @copy
*
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
* TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
* DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
* FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
* CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* <h2><center>© COPYRIGHT 2016 STMicroelectronics</center></h2>
******************************************************************************
*/
#include "SpwfSAInterface.h"
#include "mbed_debug.h"
#include "BlockExecuter.h"
#if MBED_CONF_RTOS_PRESENT
static Mutex _spwf_mutex; // assuming a recursive mutex
static void _spwf_lock() {
(void)(_spwf_mutex.lock());
}
static Callback<void()> _callback_spwf_lock(&_spwf_lock);
static void _spwf_unlock() {
(void)(_spwf_mutex.unlock());
}
static Callback<void()> _callback_spwf_unlock(&_spwf_unlock);
#define SYNC_HANDLER \
BlockExecuter sync_handler(_callback_spwf_unlock, _callback_spwf_lock)
#else
#define SYNC_HANDLER
#endif
SpwfSAInterface::SpwfSAInterface(PinName tx, PinName rx,
PinName rts, PinName cts, bool debug,
PinName wakeup, PinName reset)
: _spwf(tx, rx, rts, cts, *this, debug, wakeup, reset),
_dbg_on(debug)
{
inner_constructor();
reset_credentials();
}
nsapi_error_t SpwfSAInterface::init(void)
{
_spwf.setTimeout(SPWF_INIT_TIMEOUT);
if(_spwf.startup(0)) {
return NSAPI_ERROR_OK;
}
else return NSAPI_ERROR_DEVICE_ERROR;
}
nsapi_error_t SpwfSAInterface::connect(void)
{
int mode;
char *pass_phrase = ap_pass;
SYNC_HANDLER;
// check for valid SSID
if(ap_ssid[0] == '\0') {
return NSAPI_ERROR_PARAMETER;
}
switch(ap_sec)
{
case NSAPI_SECURITY_NONE:
mode = 0;
pass_phrase = NULL;
break;
case NSAPI_SECURITY_WEP:
mode = 1;
break;
case NSAPI_SECURITY_WPA:
case NSAPI_SECURITY_WPA2:
mode = 2;
break;
default:
mode = 2;
break;
}
// First: disconnect
if(_connected_to_network) {
if(!disconnect()) {
return NSAPI_ERROR_DEVICE_ERROR;
}
}
//initialize the device before connecting
if(!_isInitialized)
{
if(init() != NSAPI_ERROR_OK) return NSAPI_ERROR_DEVICE_ERROR;
_isInitialized=true;
}
// Then: (re-)connect
_spwf.setTimeout(SPWF_CONNECT_TIMEOUT);
if (!_spwf.connect(ap_ssid, pass_phrase, mode)) {
return NSAPI_ERROR_AUTH_FAILURE;
}
if (!_spwf.getIPAddress()) {
return NSAPI_ERROR_DHCP_FAILURE;
}
_connected_to_network = true;
return NSAPI_ERROR_OK;
}
nsapi_error_t SpwfSAInterface::connect(const char *ssid, const char *pass, nsapi_security_t security,
uint8_t channel)
{
nsapi_error_t ret;
SYNC_HANDLER;
if (channel != 0) {
return NSAPI_ERROR_UNSUPPORTED;
}
ret = set_credentials(ssid, pass, security);
if(ret != NSAPI_ERROR_OK) return ret;
return connect();
}
nsapi_error_t SpwfSAInterface::disconnect(void)
{
SYNC_HANDLER;
_spwf.setTimeout(SPWF_DISCONNECT_TIMEOUT);
if (!_spwf.disconnect()) {
return NSAPI_ERROR_DEVICE_ERROR;
}
return NSAPI_ERROR_OK;
}
const char *SpwfSAInterface::get_ip_address(void)
{
SYNC_HANDLER;
_spwf.setTimeout(SPWF_MISC_TIMEOUT);
return _spwf.getIPAddress();
}
const char *SpwfSAInterface::get_mac_address(void)
{
SYNC_HANDLER;
_spwf.setTimeout(SPWF_MISC_TIMEOUT);
return _spwf.getMACAddress();
}
const char *SpwfSAInterface::get_gateway(void)
{
SYNC_HANDLER;
if(!_connected_to_network) return NULL;
_spwf.setTimeout(SPWF_MISC_TIMEOUT);
return _spwf.getGateway();
}
const char *SpwfSAInterface::get_netmask(void)
{
SYNC_HANDLER;
if(!_connected_to_network) return NULL;
_spwf.setTimeout(SPWF_MISC_TIMEOUT);
return _spwf.getNetmask();
}
nsapi_error_t SpwfSAInterface::socket_open(void **handle, nsapi_protocol_t proto)
{
int internal_id;
SYNC_HANDLER;
for (internal_id = 0; internal_id < SPWFSA_SOCKET_COUNT; internal_id++) {
if(_ids[internal_id].internal_id == SPWFSA_SOCKET_COUNT) break;
}
if(internal_id == SPWFSA_SOCKET_COUNT) {
debug_if(_dbg_on, "NO Socket ID Error\r\n");
return NSAPI_ERROR_NO_SOCKET;
}
spwf_socket_t *socket = &_ids[internal_id];
socket->internal_id = internal_id;
socket->spwf_id = SPWFSA_SOCKET_COUNT;
socket->server_gone = false;
socket->no_more_data = false;
socket->proto = proto;
socket->addr = SocketAddress();
*handle = socket;
return NSAPI_ERROR_OK;
}
nsapi_error_t SpwfSAInterface::socket_connect(void *handle, const SocketAddress &addr)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
SYNC_HANDLER;
MBED_ASSERT(((unsigned int)socket->internal_id) < ((unsigned int)SPWFSA_SOCKET_COUNT));
if(_socket_has_connected(socket->internal_id)) {
return NSAPI_ERROR_IS_CONNECTED;
}
_spwf.setTimeout(SPWF_OPEN_TIMEOUT);
const char *proto = (socket->proto == NSAPI_UDP) ? "u" : "t"; //"s" for secure socket?
if(addr.get_ip_version() != NSAPI_IPv4) { // IPv6 not supported (yet)
return NSAPI_ERROR_UNSUPPORTED;
}
{
BlockExecuter netsock_wa_obj(Callback<void()>(&_spwf, &SPWFSAxx::_unblock_event_callback),
Callback<void()>(&_spwf, &SPWFSAxx::_block_event_callback)); /* disable calling (external) callback in IRQ context */
/* block asynchronous indications */
if(!_spwf._winds_off()) {
return NSAPI_ERROR_DEVICE_ERROR;
}
{
BlockExecuter bh_handler(Callback<void()>(&_spwf, &SPWFSAxx::_execute_bottom_halves));
{
BlockExecuter winds_enabler(Callback<void()>(&_spwf, &SPWFSAxx::_winds_on));
if(!_spwf.open(proto, &socket->spwf_id, addr.get_ip_address(), addr.get_port())) {
MBED_ASSERT(_spwf._call_event_callback_blocked == 1);
return NSAPI_ERROR_DEVICE_ERROR;
}
/* check for the module to report a valid id */
MBED_ASSERT(((unsigned int)socket->spwf_id) < ((unsigned int)SPWFSA_SOCKET_COUNT));
_internal_ids[socket->spwf_id] = socket->internal_id;
socket->addr = addr;
MBED_ASSERT(_spwf._call_event_callback_blocked == 1);
return NSAPI_ERROR_OK;
}
}
}
}
nsapi_error_t SpwfSAInterface::socket_bind(void *handle, const SocketAddress &address)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t SpwfSAInterface::socket_listen(void *handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t SpwfSAInterface::socket_accept(nsapi_socket_t server, nsapi_socket_t *handle, SocketAddress *address)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t SpwfSAInterface::socket_close(void *handle)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
int internal_id = socket->internal_id;
SYNC_HANDLER;
if(!_socket_is_open(internal_id)) return NSAPI_ERROR_NO_SOCKET;
if(_socket_has_connected(socket)) {
_spwf.setTimeout(SPWF_CLOSE_TIMEOUT);
if (!_spwf.close(socket->spwf_id)) {
return NSAPI_ERROR_DEVICE_ERROR;
}
_internal_ids[socket->spwf_id] = SPWFSA_SOCKET_COUNT;
}
_ids[internal_id].internal_id = SPWFSA_SOCKET_COUNT;
_ids[internal_id].spwf_id = SPWFSA_SOCKET_COUNT;
return NSAPI_ERROR_OK;
}
nsapi_size_or_error_t SpwfSAInterface::socket_send(void *handle, const void *data, unsigned size)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
SYNC_HANDLER;
CHECK_NOT_CONNECTED_ERR();
_spwf.setTimeout(SPWF_SEND_TIMEOUT);
return _spwf.send(socket->spwf_id, data, size, socket->internal_id);
}
nsapi_size_or_error_t SpwfSAInterface::socket_recv(void *handle, void *data, unsigned size)
{
SYNC_HANDLER;
return _socket_recv(handle, data, size, false);
}
nsapi_size_or_error_t SpwfSAInterface::_socket_recv(void *handle, void *data, unsigned size, bool datagram)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
CHECK_NOT_CONNECTED_ERR();
if(!_socket_has_connected(socket)) {
return NSAPI_ERROR_WOULD_BLOCK;
} else if(socket->no_more_data) {
return 0;
}
_spwf.setTimeout(SPWF_RECV_TIMEOUT);
int32_t recv = _spwf.recv(socket->spwf_id, (char*)data, (uint32_t)size, datagram);
MBED_ASSERT(!_spwf._is_event_callback_blocked());
MBED_ASSERT((recv != 0) || (size == 0));
if (recv < 0) {
if(!_socket_is_still_connected(socket)) {
socket->no_more_data = true;
return 0;
}
return NSAPI_ERROR_WOULD_BLOCK;
}
return recv;
}
nsapi_size_or_error_t SpwfSAInterface::socket_sendto(void *handle, const SocketAddress &addr, const void *data, unsigned size)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
SYNC_HANDLER;
CHECK_NOT_CONNECTED_ERR();
if ((_socket_has_connected(socket)) && (socket->addr != addr)) {
_spwf.setTimeout(SPWF_CLOSE_TIMEOUT);
if (!_spwf.close(socket->spwf_id)) {
return NSAPI_ERROR_DEVICE_ERROR;
}
_internal_ids[socket->spwf_id] = SPWFSA_SOCKET_COUNT;
socket->spwf_id = SPWFSA_SOCKET_COUNT;
}
_spwf.setTimeout(SPWF_CONN_SND_TIMEOUT);
if (!_socket_has_connected(socket)) {
nsapi_error_t err = socket_connect(socket, addr);
if (err < 0) {
return err;
}
}
return socket_send(socket, data, size);
}
nsapi_size_or_error_t SpwfSAInterface::socket_recvfrom(void *handle, SocketAddress *addr, void *data, unsigned size)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
nsapi_error_t ret;
SYNC_HANDLER;
ret = _socket_recv(socket, data, size, true);
if (ret >= 0 && addr) {
*addr = socket->addr;
}
return ret;
}
void SpwfSAInterface::socket_attach(void *handle, void (*callback)(void *), void *data)
{
spwf_socket_t *socket = (spwf_socket_t*)handle;
SYNC_HANDLER;
if(!_socket_is_open(socket)) return; // might happen e.g. after module hard fault or voluntary disconnection
_cbs[socket->internal_id].callback = callback;
_cbs[socket->internal_id].data = data;
}
void SpwfSAInterface::event(void) {
for (int internal_id = 0; internal_id < SPWFSA_SOCKET_COUNT; internal_id++) {
if (_cbs[internal_id].callback && (_ids[internal_id].internal_id != SPWFSA_SOCKET_COUNT)) {
_cbs[internal_id].callback(_cbs[internal_id].data);
}
}
}
nsapi_error_t SpwfSAInterface::set_credentials(const char *ssid, const char *pass, nsapi_security_t security)
{
SYNC_HANDLER;
if((ssid == NULL) || (strlen(ssid) == 0)) {
return NSAPI_ERROR_PARAMETER;
}
if((pass != NULL) && (strlen(pass) > 0)) {
if(strlen(pass) < sizeof(ap_pass)) {
if(security == NSAPI_SECURITY_NONE) {
return NSAPI_ERROR_PARAMETER;
}
} else {
return NSAPI_ERROR_PARAMETER;
}
} else if(security != NSAPI_SECURITY_NONE) {
return NSAPI_ERROR_PARAMETER;
}
reset_credentials();
ap_sec = security;
strncpy(ap_ssid, ssid, sizeof(ap_ssid) - 1);
strncpy(ap_pass, pass, sizeof(ap_pass) - 1);
return NSAPI_ERROR_OK;
}
nsapi_error_t SpwfSAInterface::set_channel(uint8_t channel)
{
return NSAPI_ERROR_UNSUPPORTED;
}
int8_t SpwfSAInterface::get_rssi(void)
{
SYNC_HANDLER;
if(!_connected_to_network) return 0;
_spwf.setTimeout(SPWF_MISC_TIMEOUT);
return _spwf.getRssi();
}
nsapi_size_or_error_t SpwfSAInterface::scan(WiFiAccessPoint *res, unsigned count)
{
SYNC_HANDLER;
nsapi_size_or_error_t ret;
//initialize the device before scanning
if(!_isInitialized)
{
if(init() != NSAPI_ERROR_OK) return NSAPI_ERROR_DEVICE_ERROR;
}
_spwf.setTimeout(SPWF_SCAN_TIMEOUT);
{
BlockExecuter netsock_wa_obj(Callback<void()>(&_spwf, &SPWFSAxx::_unblock_event_callback),
Callback<void()>(&_spwf, &SPWFSAxx::_block_event_callback)); /* disable calling (external) callback in IRQ context */
/* block asynchronous indications */
if(!_spwf._winds_off()) {
MBED_ASSERT(_spwf._call_event_callback_blocked == 1);
return NSAPI_ERROR_DEVICE_ERROR;
}
ret = _spwf.scan(res, count);
/* unblock asynchronous indications */
_spwf._winds_on();
}
MBED_ASSERT(!_spwf._is_event_callback_blocked());
//de-initialize the device after scanning
if(!_isInitialized)
{
nsapi_error_t err = disconnect();
if(err != NSAPI_ERROR_OK) return err;
}
return ret;
}
| 14,141 | 5,243 |
#pragma once
#include "Transformer.hpp"
namespace Classifier::Data::Transformation
{
class TransformerBuilder
{
public:
template<typename ...Ts>
static Transformer<InputFeatures<Ts...>, OutputFeatures<Ts...>> from(FeatureSet<Ts...>& set)
{
return Transformer<InputFeatures<Ts...>, OutputFeatures<Ts...>>(set);
}
};
} | 333 | 123 |
/*
Copyright (c) 2017-2020,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable
Energy, LLC. See the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "Filters.hpp"
#include "CoreApp.hpp"
#include "FilterOperations.hpp"
#include <algorithm>
#include <map>
#include <memory>
#include <utility>
namespace helics {
static const std::map<std::string, filter_types> filterTypes{
{"clone", filter_types::clone},
{"cloning", filter_types::clone},
{"delay", filter_types::delay},
{"timedelay", filter_types::delay},
{"randomdelay", filter_types::random_delay},
{"randomdrop", filter_types::random_drop},
{"time_delay", filter_types::delay},
{"random_delay", filter_types::random_delay},
{"random_drop", filter_types::random_drop},
{"time delay", filter_types::delay},
{"random delay", filter_types::random_delay},
{"random drop", filter_types::random_drop},
{"reroute", filter_types::reroute},
{"redirect", filter_types::reroute},
{"firewall", filter_types::firewall},
{"custom", filter_types::custom}};
filter_types filterTypeFromString(const std::string& filterType) noexcept
{
auto fnd = filterTypes.find(filterType);
if (fnd != filterTypes.end()) {
return fnd->second;
}
auto nfilt = filterType;
std::transform(nfilt.begin(), nfilt.end(), nfilt.begin(), ::tolower);
fnd = filterTypes.find(nfilt);
if (fnd != filterTypes.end()) {
return fnd->second;
}
return filter_types::unrecognized;
}
void addOperations(Filter* filt, filter_types type, Core* /*cptr*/)
{
switch (type) {
case filter_types::custom:
default:
break;
case filter_types::random_delay: {
auto op = std::make_shared<RandomDelayFilterOperation>();
filt->setFilterOperations(std::move(op));
} break;
case filter_types::delay: {
auto op = std::make_shared<DelayFilterOperation>();
filt->setFilterOperations(std::move(op));
} break;
case filter_types::random_drop: {
auto op = std::make_shared<RandomDropFilterOperation>();
filt->setFilterOperations(std::move(op));
} break;
case filter_types::reroute: {
auto op = std::make_shared<RerouteFilterOperation>();
filt->setFilterOperations(std::move(op));
} break;
case filter_types::clone: {
auto op = std::make_shared<CloneFilterOperation>();
filt->setFilterOperations(std::move(op));
} break;
case filter_types::firewall: {
auto op = std::make_shared<FirewallFilterOperation>();
filt->setFilterOperations(std::move(op));
} break;
}
}
Filter::Filter(Federate* ffed, const std::string& filtName): Filter(ffed->registerFilter(filtName))
{
}
Filter::Filter(Federate* ffed, const std::string& filtName, interface_handle ihandle):
fed(ffed), handle(ihandle), name(filtName)
{
if (ffed != nullptr) {
corePtr = ffed->getCorePointer().get();
}
}
Filter::Filter(interface_visibility locality, Federate* ffed, const std::string& filtName)
{
if (ffed != nullptr) {
corePtr = ffed->getCorePointer().get();
if (locality == interface_visibility::global) {
operator=(ffed->registerGlobalFilter(filtName));
} else {
operator=(ffed->registerFilter(filtName));
}
}
}
Filter::Filter(Core* cr, const std::string& filtName): corePtr(cr), name(filtName)
{
if (corePtr != nullptr) {
handle = corePtr->registerFilter(filtName, std::string(), std::string());
fed = nullptr;
}
}
void Filter::setOperator(std::shared_ptr<FilterOperator> mo)
{
if (corePtr != nullptr) {
corePtr->setFilterOperator(handle, std::move(mo));
}
}
void Filter::setFilterOperations(std::shared_ptr<FilterOperations> filterOps)
{
filtOp = std::move(filterOps);
if (corePtr != nullptr) {
corePtr->setFilterOperator(handle, (filtOp) ? filtOp->getOperator() : nullptr);
}
}
static const std::string emptyStr;
const std::string& Filter::getKey() const
{
if (corePtr != nullptr) {
return corePtr->getHandleName(handle);
}
return emptyStr;
}
const std::string& Filter::getInjectionType() const
{
if (corePtr != nullptr) {
return corePtr->getInjectionType(handle);
}
return emptyStr;
}
const std::string& Filter::getExtractionType() const
{
if (corePtr != nullptr) {
return corePtr->getExtractionType(handle);
}
return emptyStr;
}
const std::string& Filter::getInfo() const
{
return corePtr->getInterfaceInfo(handle);
}
void Filter::setInfo(const std::string& info)
{
corePtr->setInterfaceInfo(handle, info);
}
void Filter::set(const std::string& property, double val)
{
if (filtOp) {
filtOp->set(property, val);
}
}
void Filter::setString(const std::string& property, const std::string& val)
{
if (filtOp) {
filtOp->setString(property, val);
}
}
CloningFilter::CloningFilter(Core* cr, const std::string& filtName)
{
corePtr = cr;
if (corePtr != nullptr) {
handle = corePtr->registerCloningFilter(filtName, std::string(), std::string());
name = filtName;
}
setFilterOperations(std::make_shared<CloneFilterOperation>());
}
CloningFilter::CloningFilter(Federate* ffed, const std::string& filtName):
Filter(ffed->registerCloningFilter(filtName))
{
if (corePtr != nullptr) {
setFilterOperations(std::make_shared<CloneFilterOperation>());
}
}
CloningFilter::CloningFilter(Federate* ffed, const std::string& filtName, interface_handle ihandle):
Filter(ffed, filtName, ihandle)
{
}
CloningFilter::CloningFilter(interface_visibility locality,
Federate* ffed,
const std::string& filtName)
{
if (ffed != nullptr) {
corePtr = ffed->getCorePointer().get();
if (locality == interface_visibility::global) {
operator=(ffed->registerGlobalCloningFilter(filtName));
} else {
operator=(ffed->registerCloningFilter(filtName));
}
setFilterOperations(std::make_shared<CloneFilterOperation>());
}
}
void Filter::addSourceTarget(const std::string& sourceName)
{
// sourceEndpoints.push_back (sourceName);
corePtr->addSourceTarget(handle, sourceName);
}
void Filter::addDestinationTarget(const std::string& destinationName)
{
// destEndpoints.push_back (destinationName);
corePtr->addDestinationTarget(handle, destinationName);
}
void CloningFilter::addDeliveryEndpoint(const std::string& endpoint)
{
Filter::setString("add delivery", endpoint);
}
void Filter::removeTarget(const std::string& sourceName)
{
corePtr->removeTarget(handle, sourceName);
}
void Filter::setOption(int32_t option, int32_t value)
{
corePtr->setHandleOption(handle, option, value);
}
/** close a filter during an active simulation
@details it is not necessary to call this function unless you are continuing the simulation after
the close*/
void Filter::close()
{
corePtr->closeHandle(handle);
}
/** get the current value of a flag for the handle*/
int32_t Filter::getOption(int32_t option) const
{
return corePtr->getHandleOption(handle, option);
}
void CloningFilter::removeDeliveryEndpoint(const std::string& endpoint)
{
Filter::setString("remove delivery", endpoint);
}
void CloningFilter::setString(const std::string& property, const std::string& val)
{
if ((property == "source") || (property == "add source")) {
addSourceTarget(val);
} else if ((property == "dest") || (property == "destination") ||
(property == "add destination") || (property == "add dest")) {
addDestinationTarget(val);
} else if ((property == "endpoint") || (property == "add endpoint")) {
addSourceTarget(val);
addDestinationTarget(val);
} else if ((property == "remove destination") || (property == "remove dest")) {
removeTarget(val);
} else if (property == "remove source") {
removeTarget(val);
} else if (property == "remove endpoint") {
removeTarget(val);
} else {
Filter::setString(property, val);
}
}
Filter& make_filter(filter_types type, Federate* mFed, const std::string& name)
{
if (type == filter_types::clone) {
Filter& dfilt = mFed->registerCloningFilter(name);
addOperations(&dfilt, type, mFed->getCorePointer().get());
dfilt.setString("delivery", name);
return dfilt;
}
auto& dfilt = mFed->registerFilter(name);
addOperations(&dfilt, type, nullptr);
return dfilt;
}
Filter& make_filter(interface_visibility locality,
filter_types type,
Federate* mFed,
const std::string& name)
{
if (type == filter_types::clone) {
Filter& dfilt = (locality == interface_visibility::global) ?
mFed->registerGlobalCloningFilter(name) :
mFed->registerCloningFilter(name);
addOperations(&dfilt, type, mFed->getCorePointer().get());
dfilt.setString("delivery", name);
return dfilt;
}
auto& dfilt = (locality == interface_visibility::global) ? mFed->registerGlobalFilter(name) :
mFed->registerFilter(name);
addOperations(&dfilt, type, nullptr);
return dfilt;
}
std::unique_ptr<Filter> make_filter(filter_types type, Core* cr, const std::string& name)
{
if (type == filter_types::clone) {
std::unique_ptr<Filter> dfilt = std::make_unique<CloningFilter>(cr, name);
addOperations(dfilt.get(), type, cr);
dfilt->setString("delivery", name);
return dfilt;
}
auto dfilt = std::make_unique<Filter>(cr, name);
addOperations(dfilt.get(), type, cr);
return dfilt;
}
std::unique_ptr<Filter> make_filter(filter_types type, CoreApp& cr, const std::string& name)
{
return make_filter(type, cr.getCopyofCorePointer().get(), name);
}
CloningFilter& make_cloning_filter(filter_types type,
Federate* mFed,
const std::string& delivery,
const std::string& name)
{
auto& dfilt = mFed->registerCloningFilter(name);
addOperations(&dfilt, type, mFed->getCorePointer().get());
if (!delivery.empty()) {
dfilt.addDeliveryEndpoint(delivery);
}
return dfilt;
}
CloningFilter& make_cloning_filter(interface_visibility locality,
filter_types type,
Federate* mFed,
const std::string& delivery,
const std::string& name)
{
auto& dfilt = (locality == interface_visibility::global) ?
mFed->registerGlobalCloningFilter(name) :
mFed->registerCloningFilter(name);
addOperations(&dfilt, type, mFed->getCorePointer().get());
if (!delivery.empty()) {
dfilt.addDeliveryEndpoint(delivery);
}
return dfilt;
}
std::unique_ptr<CloningFilter> make_cloning_filter(filter_types type,
Core* cr,
const std::string& delivery,
const std::string& name)
{
auto dfilt = std::make_unique<CloningFilter>(cr, name);
addOperations(dfilt.get(), type, cr);
if (!delivery.empty()) {
dfilt->addDeliveryEndpoint(delivery);
}
return dfilt;
}
std::unique_ptr<CloningFilter> make_cloning_filter(filter_types type,
CoreApp& cr,
const std::string& delivery,
const std::string& name)
{
return make_cloning_filter(type, cr.getCopyofCorePointer().get(), delivery, name);
}
} // namespace helics
| 12,177 | 3,681 |
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ecs/model/DescribeDedicatedHostsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ecs;
using namespace AlibabaCloud::Ecs::Model;
DescribeDedicatedHostsResult::DescribeDedicatedHostsResult() :
ServiceResult()
{}
DescribeDedicatedHostsResult::DescribeDedicatedHostsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeDedicatedHostsResult::~DescribeDedicatedHostsResult()
{}
void DescribeDedicatedHostsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allDedicatedHostsNode = value["DedicatedHosts"]["DedicatedHost"];
for (auto valueDedicatedHostsDedicatedHost : allDedicatedHostsNode)
{
DedicatedHost dedicatedHostsObject;
if(!valueDedicatedHostsDedicatedHost["CreationTime"].isNull())
dedicatedHostsObject.creationTime = valueDedicatedHostsDedicatedHost["CreationTime"].asString();
if(!valueDedicatedHostsDedicatedHost["Status"].isNull())
dedicatedHostsObject.status = valueDedicatedHostsDedicatedHost["Status"].asString();
if(!valueDedicatedHostsDedicatedHost["Cores"].isNull())
dedicatedHostsObject.cores = std::stoi(valueDedicatedHostsDedicatedHost["Cores"].asString());
if(!valueDedicatedHostsDedicatedHost["AutoPlacement"].isNull())
dedicatedHostsObject.autoPlacement = valueDedicatedHostsDedicatedHost["AutoPlacement"].asString();
if(!valueDedicatedHostsDedicatedHost["GPUSpec"].isNull())
dedicatedHostsObject.gPUSpec = valueDedicatedHostsDedicatedHost["GPUSpec"].asString();
if(!valueDedicatedHostsDedicatedHost["AutoReleaseTime"].isNull())
dedicatedHostsObject.autoReleaseTime = valueDedicatedHostsDedicatedHost["AutoReleaseTime"].asString();
if(!valueDedicatedHostsDedicatedHost["ChargeType"].isNull())
dedicatedHostsObject.chargeType = valueDedicatedHostsDedicatedHost["ChargeType"].asString();
if(!valueDedicatedHostsDedicatedHost["CpuOverCommitRatio"].isNull())
dedicatedHostsObject.cpuOverCommitRatio = std::stof(valueDedicatedHostsDedicatedHost["CpuOverCommitRatio"].asString());
if(!valueDedicatedHostsDedicatedHost["ActionOnMaintenance"].isNull())
dedicatedHostsObject.actionOnMaintenance = valueDedicatedHostsDedicatedHost["ActionOnMaintenance"].asString();
if(!valueDedicatedHostsDedicatedHost["SaleCycle"].isNull())
dedicatedHostsObject.saleCycle = valueDedicatedHostsDedicatedHost["SaleCycle"].asString();
if(!valueDedicatedHostsDedicatedHost["PhysicalGpus"].isNull())
dedicatedHostsObject.physicalGpus = std::stoi(valueDedicatedHostsDedicatedHost["PhysicalGpus"].asString());
if(!valueDedicatedHostsDedicatedHost["RegionId"].isNull())
dedicatedHostsObject.regionId = valueDedicatedHostsDedicatedHost["RegionId"].asString();
if(!valueDedicatedHostsDedicatedHost["DedicatedHostName"].isNull())
dedicatedHostsObject.dedicatedHostName = valueDedicatedHostsDedicatedHost["DedicatedHostName"].asString();
if(!valueDedicatedHostsDedicatedHost["Description"].isNull())
dedicatedHostsObject.description = valueDedicatedHostsDedicatedHost["Description"].asString();
if(!valueDedicatedHostsDedicatedHost["DedicatedHostClusterId"].isNull())
dedicatedHostsObject.dedicatedHostClusterId = valueDedicatedHostsDedicatedHost["DedicatedHostClusterId"].asString();
if(!valueDedicatedHostsDedicatedHost["ExpiredTime"].isNull())
dedicatedHostsObject.expiredTime = valueDedicatedHostsDedicatedHost["ExpiredTime"].asString();
if(!valueDedicatedHostsDedicatedHost["DedicatedHostType"].isNull())
dedicatedHostsObject.dedicatedHostType = valueDedicatedHostsDedicatedHost["DedicatedHostType"].asString();
if(!valueDedicatedHostsDedicatedHost["ResourceGroupId"].isNull())
dedicatedHostsObject.resourceGroupId = valueDedicatedHostsDedicatedHost["ResourceGroupId"].asString();
if(!valueDedicatedHostsDedicatedHost["ZoneId"].isNull())
dedicatedHostsObject.zoneId = valueDedicatedHostsDedicatedHost["ZoneId"].asString();
if(!valueDedicatedHostsDedicatedHost["DedicatedHostId"].isNull())
dedicatedHostsObject.dedicatedHostId = valueDedicatedHostsDedicatedHost["DedicatedHostId"].asString();
if(!valueDedicatedHostsDedicatedHost["Sockets"].isNull())
dedicatedHostsObject.sockets = std::stoi(valueDedicatedHostsDedicatedHost["Sockets"].asString());
if(!valueDedicatedHostsDedicatedHost["MachineId"].isNull())
dedicatedHostsObject.machineId = valueDedicatedHostsDedicatedHost["MachineId"].asString();
auto allInstancesNode = valueDedicatedHostsDedicatedHost["Instances"]["Instance"];
for (auto valueDedicatedHostsDedicatedHostInstancesInstance : allInstancesNode)
{
DedicatedHost::Instance instancesObject;
if(!valueDedicatedHostsDedicatedHostInstancesInstance["InstanceType"].isNull())
instancesObject.instanceType = valueDedicatedHostsDedicatedHostInstancesInstance["InstanceType"].asString();
if(!valueDedicatedHostsDedicatedHostInstancesInstance["InstanceId"].isNull())
instancesObject.instanceId = valueDedicatedHostsDedicatedHostInstancesInstance["InstanceId"].asString();
dedicatedHostsObject.instances.push_back(instancesObject);
}
auto allOperationLocksNode = valueDedicatedHostsDedicatedHost["OperationLocks"]["OperationLock"];
for (auto valueDedicatedHostsDedicatedHostOperationLocksOperationLock : allOperationLocksNode)
{
DedicatedHost::OperationLock operationLocksObject;
if(!valueDedicatedHostsDedicatedHostOperationLocksOperationLock["LockReason"].isNull())
operationLocksObject.lockReason = valueDedicatedHostsDedicatedHostOperationLocksOperationLock["LockReason"].asString();
dedicatedHostsObject.operationLocks.push_back(operationLocksObject);
}
auto allTagsNode = valueDedicatedHostsDedicatedHost["Tags"]["Tag"];
for (auto valueDedicatedHostsDedicatedHostTagsTag : allTagsNode)
{
DedicatedHost::Tag tagsObject;
if(!valueDedicatedHostsDedicatedHostTagsTag["TagValue"].isNull())
tagsObject.tagValue = valueDedicatedHostsDedicatedHostTagsTag["TagValue"].asString();
if(!valueDedicatedHostsDedicatedHostTagsTag["TagKey"].isNull())
tagsObject.tagKey = valueDedicatedHostsDedicatedHostTagsTag["TagKey"].asString();
dedicatedHostsObject.tags.push_back(tagsObject);
}
auto capacityNode = value["Capacity"];
if(!capacityNode["AvailableMemory"].isNull())
dedicatedHostsObject.capacity.availableMemory = std::stof(capacityNode["AvailableMemory"].asString());
if(!capacityNode["LocalStorageCategory"].isNull())
dedicatedHostsObject.capacity.localStorageCategory = capacityNode["LocalStorageCategory"].asString();
if(!capacityNode["TotalMemory"].isNull())
dedicatedHostsObject.capacity.totalMemory = std::stof(capacityNode["TotalMemory"].asString());
if(!capacityNode["TotalLocalStorage"].isNull())
dedicatedHostsObject.capacity.totalLocalStorage = std::stoi(capacityNode["TotalLocalStorage"].asString());
if(!capacityNode["TotalVcpus"].isNull())
dedicatedHostsObject.capacity.totalVcpus = std::stoi(capacityNode["TotalVcpus"].asString());
if(!capacityNode["TotalVgpus"].isNull())
dedicatedHostsObject.capacity.totalVgpus = std::stoi(capacityNode["TotalVgpus"].asString());
if(!capacityNode["AvailableLocalStorage"].isNull())
dedicatedHostsObject.capacity.availableLocalStorage = std::stoi(capacityNode["AvailableLocalStorage"].asString());
if(!capacityNode["AvailableVcpus"].isNull())
dedicatedHostsObject.capacity.availableVcpus = std::stoi(capacityNode["AvailableVcpus"].asString());
if(!capacityNode["AvailableVgpus"].isNull())
dedicatedHostsObject.capacity.availableVgpus = std::stoi(capacityNode["AvailableVgpus"].asString());
auto networkAttributesNode = value["NetworkAttributes"];
if(!networkAttributesNode["UdpTimeout"].isNull())
dedicatedHostsObject.networkAttributes.udpTimeout = std::stoi(networkAttributesNode["UdpTimeout"].asString());
if(!networkAttributesNode["SlbUdpTimeout"].isNull())
dedicatedHostsObject.networkAttributes.slbUdpTimeout = std::stoi(networkAttributesNode["SlbUdpTimeout"].asString());
auto hostDetailInfoNode = value["HostDetailInfo"];
if(!hostDetailInfoNode["SerialNumber"].isNull())
dedicatedHostsObject.hostDetailInfo.serialNumber = hostDetailInfoNode["SerialNumber"].asString();
auto allSupportedInstanceTypeFamilies = value["SupportedInstanceTypeFamilies"]["SupportedInstanceTypeFamily"];
for (auto value : allSupportedInstanceTypeFamilies)
dedicatedHostsObject.supportedInstanceTypeFamilies.push_back(value.asString());
auto allSupportedCustomInstanceTypeFamilies = value["SupportedCustomInstanceTypeFamilies"]["SupportedCustomInstanceTypeFamily"];
for (auto value : allSupportedCustomInstanceTypeFamilies)
dedicatedHostsObject.supportedCustomInstanceTypeFamilies.push_back(value.asString());
auto allSupportedInstanceTypesList = value["SupportedInstanceTypesList"]["SupportedInstanceTypesList"];
for (auto value : allSupportedInstanceTypesList)
dedicatedHostsObject.supportedInstanceTypesList.push_back(value.asString());
dedicatedHosts_.push_back(dedicatedHostsObject);
}
if(!value["PageSize"].isNull())
pageSize_ = std::stoi(value["PageSize"].asString());
if(!value["PageNumber"].isNull())
pageNumber_ = std::stoi(value["PageNumber"].asString());
if(!value["TotalCount"].isNull())
totalCount_ = std::stoi(value["TotalCount"].asString());
}
std::vector<DescribeDedicatedHostsResult::DedicatedHost> DescribeDedicatedHostsResult::getDedicatedHosts()const
{
return dedicatedHosts_;
}
int DescribeDedicatedHostsResult::getTotalCount()const
{
return totalCount_;
}
int DescribeDedicatedHostsResult::getPageSize()const
{
return pageSize_;
}
int DescribeDedicatedHostsResult::getPageNumber()const
{
return pageNumber_;
}
| 10,369 | 3,430 |
// See LICENSE_CELLO file for license and copyright information
/// @file control_stopping.cpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2013-04-26
/// @brief Charm-related functions associated with initialization
/// @ingroup Control
///
/// STOPPING
///
/// Block::stopping()
/// update_boundary_()
/// compute dt
/// compute stopping
/// contribute( >>>>> Block::r_output() >>>>> )
#include "simulation.hpp"
#include "mesh.hpp"
#include "control.hpp"
#include "charm_simulation.hpp"
#include "charm_mesh.hpp"
// #define DEBUG_STOPPING
#ifdef DEBUG_STOPPING
# define TRACE_STOPPING(A) \
CkPrintf ("%d %s:%d %s TRACE %s\n", \
CkMyPe(),__FILE__,__LINE__,name_.c_str(),A); \
fflush(stdout);
#else
# define TRACE_STOPPING(A) ;
#endif
//----------------------------------------------------------------------
void Block::stopping_enter_()
{
stopping_begin_();
}
//----------------------------------------------------------------------
void Block::stopping_begin_()
{
TRACE_STOPPING("Block::stopping_begin_");
Simulation * simulation = cello::simulation();
simulation->set_phase(phase_stopping);
int stopping_interval = simulation->config()->stopping_interval;
bool stopping_reduce = stopping_interval ?
((cycle_ % stopping_interval) == 0) : false;
if (stopping_reduce || dt_==0.0) {
// Compute local dt
Problem * problem = simulation->problem();
int index = 0;
Method * method;
double dt_block = std::numeric_limits<double>::max();
while ((method = problem->method(index++))) {
dt_block = std::min(dt_block,method->timestep(this));
}
// Reduce timestep to coincide with scheduled output if needed
int index_output=0;
while (Output * output = problem->output(index_output++)) {
Schedule * schedule = output->schedule();
dt_block = schedule->update_timestep(time_,dt_block);
}
// Reduce timestep to not overshoot final time from stopping criteria
Stopping * stopping = problem->stopping();
double time_stop = stopping->stop_time();
double time_curr = time_;
dt_block = MIN (dt_block, (time_stop - time_curr));
// Evaluate local stopping criteria
int stop_block = stopping->complete(cycle_,time_);
// Reduce to find Block array minimum dt and stopping criteria
double min_reduce[2];
min_reduce[0] = dt_block;
min_reduce[1] = stop_block ? 1.0 : 0.0;
CkCallback callback (CkIndex_Block::r_stopping_compute_timestep(NULL),
thisProxy);
#ifdef TRACE_CONTRIBUTE
CkPrintf ("%s %s:%d DEBUG_CONTRIBUTE\n",
name().c_str(),__FILE__,__LINE__); fflush(stdout);
#endif
contribute(2*sizeof(double), min_reduce, CkReduction::min_double, callback);
} else {
stopping_balance_();
}
}
//----------------------------------------------------------------------
void Block::r_stopping_compute_timestep(CkReductionMsg * msg)
{
performance_start_(perf_stopping);
TRACE_STOPPING("Block::r_stopping_compute_timestep");
++age_;
double * min_reduce = (double * )msg->getData();
dt_ = min_reduce[0];
stop_ = min_reduce[1] == 1.0 ? true : false;
delete msg;
Simulation * simulation = cello::simulation();
dt_ *= Method::courant_global;
set_dt (dt_);
set_stop (stop_);
simulation->set_dt(dt_);
simulation->set_stop(stop_);
#ifdef CONFIG_USE_PROJECTIONS
bool was_off = (simulation->projections_tracing() == false);
bool was_on = (simulation->projections_tracing() == true);
Schedule * schedule_on = simulation->projections_schedule_on();
Schedule * schedule_off = simulation->projections_schedule_off();
bool turn_on = schedule_on ? schedule_on->write_this_cycle(cycle_,time_) : false;
bool turn_off = schedule_off ? schedule_off->write_this_cycle(cycle_,time_) : false;
static bool active = false;
if (!active && turn_on) {
active = true;
simulation->monitor()->print
("Performance","turning projections logging ON\n");
simulation->set_projections_tracing(true);
traceBegin();
} else if (active && turn_off) {
active = false;
simulation->monitor()->print
("Performance","turning projections logging OFF\n");
simulation->set_projections_tracing(false);
traceEnd();
}
#endif
stopping_balance_();
performance_stop_(perf_stopping);
}
//----------------------------------------------------------------------
void Block::stopping_balance_()
{
TRACE_STOPPING("Block::stopping_balance_");
Schedule * schedule = cello::simulation()->schedule_balance();
bool do_balance = (schedule &&
schedule->write_this_cycle(cycle_,time_));
if (do_balance) {
if (index_.is_root())
cello::monitor()->print ("Balance","starting load balance step");
control_sync_quiescence (CkIndex_Main::p_stopping_balance());
} else {
stopping_exit_();
}
}
//----------------------------------------------------------------------
void Block::p_stopping_balance()
{
performance_start_(perf_stopping);
TRACE_STOPPING("Block::p_stopping_balance");
cello::simulation()->set_phase (phase_balance);
// Monitor * monitor = simulation()->monitor();
// int mode_saved = monitor->mode();
// monitor->set_mode(monitor_mode_all);
// if (index().is_root()) monitor->print ("Balance","BEGIN");
// monitor->set_mode(mode_saved);
AtSync();
performance_stop_(perf_stopping);
}
//----------------------------------------------------------------------
void Block::ResumeFromSync()
{
// Monitor * monitor = simulation()->monitor();
// int mode_saved = monitor->mode();
// monitor->set_mode(monitor_mode_all);
// if (index().is_root()) monitor->print ("Balance","END");
// monitor->set_mode(mode_saved);
TRACE_STOPPING("Block::balance_exit");
if (index_.is_root()) {
thisProxy.doneInserting();
}
stopping_exit_();
}
//----------------------------------------------------------------------
void Block::exit_()
{
TRACE_STOPPING("Block::exit_");
const int in = cello::index_static();
if (index().is_root()) {
if (DataMsg::counter[in] != 0) {
CkPrintf ("%d Block::exit_() DataMsg::counter = %ld != 0\n",
CkMyPe(),DataMsg::counter[in]);
CkPrintf ("%d Block::exit_() ParticleData::counter = %ld != 0\n",
CkMyPe(),ParticleData::counter[in]);
}
if (FieldFace::counter[in] != 0) {
CkPrintf ("%d Block::exit_() FieldFace::counter = %ld != 0\n",
CkMyPe(),FieldFace::counter[in]);
}
if (MsgCoarsen::counter[in] != 0) {
CkPrintf ("%d Block::exit_() MsgCoarsen::counter = %ld != 0\n",
CkMyPe(),MsgCoarsen::counter[in]);
}
if (MsgInitial::counter[in] != 0) {
CkPrintf ("%d Block::exit_() MsgInitial::counter = %ld != 0\n",
CkMyPe(),MsgInitial::counter[in]);
}
if (MsgOutput::counter[in] != 0) {
CkPrintf ("%d Block::exit_() MsgOutput::counter = %ld != 0\n",
CkMyPe(),MsgOutput::counter[in]);
}
if (MsgRefine::counter[in] != 0) {
CkPrintf ("%d Block::exit_() MsgRefine::counter = %ld != 0\n",
CkMyPe(),MsgRefine::counter[in]);
}
if (MsgRefresh::counter[in] != 0) {
CkPrintf ("%d Block::exit_() MsgRefresh::counter = %ld != 0\n",
CkMyPe(),MsgRefresh::counter[in]);
}
}
if (index_.is_root()) {
proxy_main.p_exit(1);
}
}
| 7,373 | 2,573 |
/*
Chemistry
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Ben Andre
Base class for ion exchange sites (e.g. X- in standard geochemistry notation)
*/
#include "ion_exchange_site.hh"
#include <cmath>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "VerboseObject.hh"
namespace Amanzi {
namespace AmanziChemistry {
IonExchangeSite::IonExchangeSite()
: name_(),
cation_exchange_capacity_(0.0),
mineral_name_("bulk"),
charge_(0.0) {
}
IonExchangeSite::IonExchangeSite(const IonxSiteName in_name)
: name_(in_name),
cation_exchange_capacity_(0.0),
mineral_name_("bulk"),
charge_(0.0) {
}
IonExchangeSite::IonExchangeSite(const IonxSiteName name,
const double charge,
const std::string location)
: name_(name),
cation_exchange_capacity_(0.0),
mineral_name_(location),
charge_(charge) {
}
void IonExchangeSite::Display(const Teuchos::Ptr<VerboseObject> vo) const {
std::stringstream message;
message << std::setw(15) << get_name()
<< std::setw(20) << get_mineral_name()
<< std::setw(10) << std::fixed << get_charge()
<< std::setw(10) << std::scientific << get_cation_exchange_capacity()
<< std::fixed << std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
}
void IonExchangeSite::DisplayResultsHeader(const Teuchos::Ptr<VerboseObject> vo) const {
std::stringstream message;
message << std::setw(15) << "Name"
<< std::setw(15) << "CEC"
<< std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
}
void IonExchangeSite::DisplayResults(const Teuchos::Ptr<VerboseObject> vo) const {
std::stringstream message;
message << std::setw(15) << get_name()
<< std::setw(15) << get_cation_exchange_capacity()
<< std::endl;
vo->Write(Teuchos::VERB_HIGH, message.str());
}
} // namespace AmanziChemistry
} // namespace Amanzi
| 2,178 | 776 |
#ifndef RF_SYSTEM_HARDWARE_PROCESSORFEATURES_HPP
#define RF_SYSTEM_HARDWARE_PROCESSORFEATURES_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include <RadonFramework/Collections/BitSet.hpp>
namespace RadonFramework::System::Hardware::ProcessorFeatures {
enum Type
{
AES, // Advanced Encryption Standard instruction set
AVX, // Advanced Vector Extensions instruction set
CLFLUSH, // Prefetch and flush instructions
CMOV, // conditional move instruction
CX16, // compare and exchange 16 bytes instruction
CX8, // compare and exchange 8 bytes instruction
FMA, // FMA instruction set
FMOV, // floating point conditional move instruction
FPU, // Floating point unit
HTT, // hyper threading
MMX, // MMX instruction set
MOVBE, // move big endian instruction
PCLMUL, // carry-less multiplication instruction
POPCNT, // population count instruction
SSE, // SSE1 instruction set
SSE2, // SSE2 instruction set
SSE3, // SSE3 instruction set
SSSE3, // SSE4 instruction set
SSE4_1, // SSE4.1 instruction set
SSE4_2, // SSE4.2 instruction set
SSE4A, // SSE4a instruction set
TSC, // RDTSC instruction supported
SHA1, // sha128 hash instruction set
SHA2, // sha256 hash instruction set
AVX512, // AVX512 instruction set
FMA4, // FMA4 instruction set
XOP, // XOP instruction set
NEON, // NEON instruction set(ARM only)
CRC32, // CRC32 instructions set(ARM only)
MAX // number of extensions(internal use)
};
}
namespace RadonFramework::System::Hardware {
class ProcessorFeatureMask: public Collections::BitSet<ProcessorFeatures::MAX>
{
};
}
#endif // RF_SYSTEM_HARDWARE_PROCESSORFEATURES_HPP | 1,714 | 567 |
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright (C) 2020, Raspberry Pi (Trading) Ltd.
*
* egl_preview.cpp - X/EGL-based preview window.
*/
#include <map>
#include <string>
// Include libcamera stuff before X11, as X11 #defines both Status and None
// which upsets the libcamera headers.
#include "core/options.hpp"
#include "preview.hpp"
#include <libdrm/drm_fourcc.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
// We don't use Status below, so we could consider #undefining it here.
// We do use None, so if we had to #undefine it we could replace it by zero
// in what follows below.
#include <epoxy/egl.h>
#include <epoxy/gl.h>
class EglPreview : public Preview
{
public:
EglPreview(Options const *options);
~EglPreview();
virtual void SetInfoText(const std::string &text) override;
// Display the buffer. You get given the fd back in the BufferDoneCallback
// once its available for re-use.
virtual void Show(int fd, libcamera::Span<uint8_t> span, StreamInfo const &info) override;
// Reset the preview window, clearing the current buffers and being ready to
// show new ones.
virtual void Reset() override;
// Check if the window manager has closed the preview.
virtual bool Quit() override;
// Return the maximum image size allowed.
virtual void MaxImageSize(unsigned int &w, unsigned int &h) const override
{
w = max_image_width_;
h = max_image_height_;
}
private:
struct Buffer
{
Buffer() : fd(-1) {}
int fd;
size_t size;
StreamInfo info;
GLuint texture;
};
void makeWindow(char const *name);
void makeBuffer(int fd, size_t size, StreamInfo const &info, Buffer &buffer);
::Display *display_;
EGLDisplay egl_display_;
Window window_;
EGLContext egl_context_;
EGLSurface egl_surface_;
std::map<int, Buffer> buffers_; // map the DMABUF's fd to the Buffer
int last_fd_;
bool first_time_;
Atom wm_delete_window_;
// size of preview window
int x_;
int y_;
int width_;
int height_;
unsigned int max_image_width_;
unsigned int max_image_height_;
};
static GLint compile_shader(GLenum target, const char *source)
{
GLuint s = glCreateShader(target);
glShaderSource(s, 1, (const GLchar **)&source, NULL);
glCompileShader(s);
GLint ok;
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok)
{
GLchar *info;
GLint size;
glGetShaderiv(s, GL_INFO_LOG_LENGTH, &size);
info = (GLchar *)malloc(size);
glGetShaderInfoLog(s, size, NULL, info);
throw std::runtime_error("failed to compile shader: " + std::string(info) + "\nsource:\n" +
std::string(source));
}
return s;
}
static GLint link_program(GLint vs, GLint fs)
{
GLint prog = glCreateProgram();
glAttachShader(prog, vs);
glAttachShader(prog, fs);
glLinkProgram(prog);
GLint ok;
glGetProgramiv(prog, GL_LINK_STATUS, &ok);
if (!ok)
{
/* Some drivers return a size of 1 for an empty log. This is the size
* of a log that contains only a terminating NUL character.
*/
GLint size;
GLchar *info = NULL;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &size);
if (size > 1)
{
info = (GLchar *)malloc(size);
glGetProgramInfoLog(prog, size, NULL, info);
}
throw std::runtime_error("failed to link: " + std::string(info ? info : "<empty log>"));
}
return prog;
}
static void gl_setup(int width, int height, int window_width, int window_height)
{
float w_factor = width / (float)window_width;
float h_factor = height / (float)window_height;
float max_dimension = std::max(w_factor, h_factor);
w_factor /= max_dimension;
h_factor /= max_dimension;
char vs[256];
snprintf(vs, sizeof(vs),
"attribute vec4 pos;\n"
"varying vec2 texcoord;\n"
"\n"
"void main() {\n"
" gl_Position = pos;\n"
" texcoord.x = pos.x / %f + 0.5;\n"
" texcoord.y = 0.5 - pos.y / %f;\n"
"}\n",
2.0 * w_factor, 2.0 * h_factor);
vs[sizeof(vs) - 1] = 0;
GLint vs_s = compile_shader(GL_VERTEX_SHADER, vs);
const char *fs = "#extension GL_OES_EGL_image_external : enable\n"
"precision mediump float;\n"
"uniform samplerExternalOES s;\n"
"varying vec2 texcoord;\n"
"void main() {\n"
" gl_FragColor = texture2D(s, texcoord);\n"
"}\n";
GLint fs_s = compile_shader(GL_FRAGMENT_SHADER, fs);
GLint prog = link_program(vs_s, fs_s);
glUseProgram(prog);
static const float verts[] = { -w_factor, -h_factor, w_factor, -h_factor, w_factor, h_factor, -w_factor, h_factor };
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, verts);
glEnableVertexAttribArray(0);
}
EglPreview::EglPreview(Options const *options) : Preview(options), last_fd_(-1), first_time_(true)
{
display_ = XOpenDisplay(NULL);
if (!display_)
throw std::runtime_error("Couldn't open X display");
egl_display_ = eglGetDisplay(display_);
if (!egl_display_)
throw std::runtime_error("eglGetDisplay() failed");
EGLint egl_major, egl_minor;
if (!eglInitialize(egl_display_, &egl_major, &egl_minor))
throw std::runtime_error("eglInitialize() failed");
x_ = options_->preview_x;
y_ = options_->preview_y;
width_ = options_->preview_width;
height_ = options_->preview_height;
makeWindow("libcamera-app");
// gl_setup() has to happen later, once we're sure we're in the display thread.
}
EglPreview::~EglPreview()
{
}
static void no_border(Display *display, Window window)
{
static const unsigned MWM_HINTS_DECORATIONS = (1 << 1);
static const int PROP_MOTIF_WM_HINTS_ELEMENTS = 5;
typedef struct
{
unsigned long flags;
unsigned long functions;
unsigned long decorations;
long inputMode;
unsigned long status;
} PropMotifWmHints;
PropMotifWmHints motif_hints;
Atom prop, proptype;
unsigned long flags = 0;
/* setup the property */
motif_hints.flags = MWM_HINTS_DECORATIONS;
motif_hints.decorations = flags;
/* get the atom for the property */
prop = XInternAtom(display, "_MOTIF_WM_HINTS", True);
if (!prop)
{
/* something went wrong! */
return;
}
/* not sure this is correct, seems to work, XA_WM_HINTS didn't work */
proptype = prop;
XChangeProperty(display, window, /* display, window */
prop, proptype, /* property, type */
32, /* format: 32-bit datums */
PropModeReplace, /* mode */
(unsigned char *)&motif_hints, /* data */
PROP_MOTIF_WM_HINTS_ELEMENTS /* nelements */
);
}
void EglPreview::makeWindow(char const *name)
{
int screen_num = DefaultScreen(display_);
XSetWindowAttributes attr;
unsigned long mask;
Window root = RootWindow(display_, screen_num);
int screen_width = DisplayWidth(display_, screen_num);
int screen_height = DisplayHeight(display_, screen_num);
// Default behaviour here is to use a 1024x768 window.
if (width_ == 0 || height_ == 0)
{
width_ = 1024;
height_ = 768;
}
if (options_->fullscreen || x_ + width_ > screen_width || y_ + height_ > screen_height)
{
x_ = y_ = 0;
width_ = DisplayWidth(display_, screen_num);
height_ = DisplayHeight(display_, screen_num);
}
static const EGLint attribs[] =
{
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_NONE
};
EGLConfig config;
EGLint num_configs;
if (!eglChooseConfig(egl_display_, attribs, &config, 1, &num_configs))
throw std::runtime_error("couldn't get an EGL visual config");
EGLint vid;
if (!eglGetConfigAttrib(egl_display_, config, EGL_NATIVE_VISUAL_ID, &vid))
throw std::runtime_error("eglGetConfigAttrib() failed\n");
XVisualInfo visTemplate = {};
visTemplate.visualid = (VisualID)vid;
int num_visuals;
XVisualInfo *visinfo = XGetVisualInfo(display_, VisualIDMask, &visTemplate, &num_visuals);
/* window attributes */
attr.background_pixel = 0;
attr.border_pixel = 0;
attr.colormap = XCreateColormap(display_, root, visinfo->visual, AllocNone);
attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
/* XXX this is a bad way to get a borderless window! */
mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
window_ = XCreateWindow(display_, root, x_, y_, width_, height_, 0, visinfo->depth, InputOutput, visinfo->visual,
mask, &attr);
if (options_->fullscreen)
no_border(display_, window_);
/* set hints and properties */
{
XSizeHints sizehints;
sizehints.x = x_;
sizehints.y = y_;
sizehints.width = width_;
sizehints.height = height_;
sizehints.flags = USSize | USPosition;
XSetNormalHints(display_, window_, &sizehints);
XSetStandardProperties(display_, window_, name, name, None, (char **)NULL, 0, &sizehints);
}
eglBindAPI(EGL_OPENGL_ES_API);
static const EGLint ctx_attribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
egl_context_ = eglCreateContext(egl_display_, config, EGL_NO_CONTEXT, ctx_attribs);
if (!egl_context_)
throw std::runtime_error("eglCreateContext failed");
XFree(visinfo);
XMapWindow(display_, window_);
// This stops the window manager from closing the window, so we get an event instead.
wm_delete_window_ = XInternAtom(display_, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display_, window_, &wm_delete_window_, 1);
egl_surface_ = eglCreateWindowSurface(egl_display_, config, reinterpret_cast<EGLNativeWindowType>(window_), NULL);
if (!egl_surface_)
throw std::runtime_error("eglCreateWindowSurface failed");
// We have to do eglMakeCurrent in the thread where it will run, but we must do it
// here temporarily so as to get the maximum texture size.
eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context_);
int max_texture_size = 0;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
max_image_width_ = max_image_height_ = max_texture_size;
// This "undoes" the previous eglMakeCurrent.
eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
static void get_colour_space_info(std::optional<libcamera::ColorSpace> const &cs, EGLint &encoding, EGLint &range)
{
encoding = EGL_ITU_REC601_EXT;
range = EGL_YUV_NARROW_RANGE_EXT;
if (cs == libcamera::ColorSpace::Jpeg)
range = EGL_YUV_FULL_RANGE_EXT;
else if (cs == libcamera::ColorSpace::Smpte170m)
/* all good */;
else if (cs == libcamera::ColorSpace::Rec709)
encoding = EGL_ITU_REC709_EXT;
else
std::cerr << "EglPreview: unexpected colour space " << libcamera::ColorSpace::toString(cs) << std::endl;
}
void EglPreview::makeBuffer(int fd, size_t size, StreamInfo const &info, Buffer &buffer)
{
if (first_time_)
{
// This stuff has to be delayed until we know we're in the thread doing the display.
if (!eglMakeCurrent(egl_display_, egl_surface_, egl_surface_, egl_context_))
throw std::runtime_error("eglMakeCurrent failed");
gl_setup(info.width, info.height, width_, height_);
first_time_ = false;
}
buffer.fd = fd;
buffer.size = size;
buffer.info = info;
EGLint encoding, range;
get_colour_space_info(info.colour_space, encoding, range);
EGLint attribs[] = {
EGL_WIDTH, static_cast<EGLint>(info.width),
EGL_HEIGHT, static_cast<EGLint>(info.height),
EGL_LINUX_DRM_FOURCC_EXT, DRM_FORMAT_YUV420,
EGL_DMA_BUF_PLANE0_FD_EXT, fd,
EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0,
EGL_DMA_BUF_PLANE0_PITCH_EXT, static_cast<EGLint>(info.stride),
EGL_DMA_BUF_PLANE1_FD_EXT, fd,
EGL_DMA_BUF_PLANE1_OFFSET_EXT, static_cast<EGLint>(info.stride * info.height),
EGL_DMA_BUF_PLANE1_PITCH_EXT, static_cast<EGLint>(info.stride / 2),
EGL_DMA_BUF_PLANE2_FD_EXT, fd,
EGL_DMA_BUF_PLANE2_OFFSET_EXT, static_cast<EGLint>(info.stride * info.height + (info.stride / 2) * (info.height / 2)),
EGL_DMA_BUF_PLANE2_PITCH_EXT, static_cast<EGLint>(info.stride / 2),
EGL_YUV_COLOR_SPACE_HINT_EXT, encoding,
EGL_SAMPLE_RANGE_HINT_EXT, range,
EGL_NONE
};
EGLImage image = eglCreateImageKHR(egl_display_, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attribs);
if (!image)
throw std::runtime_error("failed to import fd " + std::to_string(fd));
glGenTextures(1, &buffer.texture);
glBindTexture(GL_TEXTURE_EXTERNAL_OES, buffer.texture);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, image);
eglDestroyImageKHR(egl_display_, image);
}
void EglPreview::SetInfoText(const std::string &text)
{
if (!text.empty())
XStoreName(display_, window_, text.c_str());
}
void EglPreview::Show(int fd, libcamera::Span<uint8_t> span, StreamInfo const &info)
{
Buffer &buffer = buffers_[fd];
if (buffer.fd == -1)
makeBuffer(fd, span.size(), info, buffer);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_EXTERNAL_OES, buffer.texture);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
EGLBoolean success [[maybe_unused]] = eglSwapBuffers(egl_display_, egl_surface_);
if (last_fd_ >= 0)
done_callback_(last_fd_);
last_fd_ = fd;
}
void EglPreview::Reset()
{
for (auto &it : buffers_)
glDeleteTextures(1, &it.second.texture);
buffers_.clear();
last_fd_ = -1;
eglMakeCurrent(egl_display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
first_time_ = true;
}
bool EglPreview::Quit()
{
XEvent event;
while (XCheckTypedWindowEvent(display_, window_, ClientMessage, &event))
{
if (static_cast<Atom>(event.xclient.data.l[0]) == wm_delete_window_)
return true;
}
return false;
}
Preview *make_egl_preview(Options const *options)
{
return new EglPreview(options);
}
| 13,295 | 5,458 |
#include "pch.h"
#include "logging.h"
#include "sourceconsole.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "hookutils.h"
#include "dedicated.h"
#include "convar.h"
#include <iomanip>
#include <sstream>
#include <Psapi.h>
#include <minidumpapiset.h>
#include "configurables.h"
// This needs to be called after hooks are loaded so we can access the command line args
void CreateLogFiles()
{
if (strstr(GetCommandLineA(), "-disablelogs"))
{
spdlog::default_logger()->set_level(spdlog::level::off);
}
else
{
// todo: might be good to delete logs that are too old
time_t time = std::time(nullptr);
tm currentTime = *std::localtime(&time);
std::stringstream stream;
stream << std::put_time(¤tTime, (GetNorthstarPrefix() + "/logs/nslog%Y-%m-%d %H-%M-%S.txt").c_str());
spdlog::default_logger()->sinks().push_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>(stream.str(), false));
spdlog::flush_on(spdlog::level::info);
}
}
long __stdcall ExceptionFilter(EXCEPTION_POINTERS* exceptionInfo)
{
static bool logged = false;
if (logged)
return EXCEPTION_CONTINUE_SEARCH;
if (!IsDebuggerPresent())
{
const DWORD exceptionCode = exceptionInfo->ExceptionRecord->ExceptionCode;
if (exceptionCode != EXCEPTION_ACCESS_VIOLATION && exceptionCode != EXCEPTION_ARRAY_BOUNDS_EXCEEDED &&
exceptionCode != EXCEPTION_DATATYPE_MISALIGNMENT && exceptionCode != EXCEPTION_FLT_DENORMAL_OPERAND &&
exceptionCode != EXCEPTION_FLT_DIVIDE_BY_ZERO && exceptionCode != EXCEPTION_FLT_INEXACT_RESULT &&
exceptionCode != EXCEPTION_FLT_INVALID_OPERATION && exceptionCode != EXCEPTION_FLT_OVERFLOW &&
exceptionCode != EXCEPTION_FLT_STACK_CHECK && exceptionCode != EXCEPTION_FLT_UNDERFLOW &&
exceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION && exceptionCode != EXCEPTION_IN_PAGE_ERROR &&
exceptionCode != EXCEPTION_INT_DIVIDE_BY_ZERO && exceptionCode != EXCEPTION_INT_OVERFLOW &&
exceptionCode != EXCEPTION_INVALID_DISPOSITION && exceptionCode != EXCEPTION_NONCONTINUABLE_EXCEPTION &&
exceptionCode != EXCEPTION_PRIV_INSTRUCTION && exceptionCode != EXCEPTION_STACK_OVERFLOW)
return EXCEPTION_CONTINUE_SEARCH;
std::stringstream exceptionCause;
exceptionCause << "Cause: ";
switch (exceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
case EXCEPTION_IN_PAGE_ERROR:
{
exceptionCause << "Access Violation" << std::endl;
auto exceptionInfo0 = exceptionInfo->ExceptionRecord->ExceptionInformation[0];
auto exceptionInfo1 = exceptionInfo->ExceptionRecord->ExceptionInformation[1];
if (!exceptionInfo0)
exceptionCause << "Attempted to read from: 0x" << (void*)exceptionInfo1;
else if (exceptionInfo0 == 1)
exceptionCause << "Attempted to write to: 0x" << (void*)exceptionInfo1;
else if (exceptionInfo0 == 8)
exceptionCause << "Data Execution Prevention (DEP) at: 0x" << (void*)std::hex << exceptionInfo1;
else
exceptionCause << "Unknown access violation at: 0x" << (void*)exceptionInfo1;
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
exceptionCause << "Array bounds exceeded";
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
exceptionCause << "Datatype misalignment";
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
exceptionCause << "Denormal operand";
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
exceptionCause << "Divide by zero (float)";
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
exceptionCause << "Divide by zero (int)";
break;
case EXCEPTION_FLT_INEXACT_RESULT:
exceptionCause << "Inexact result";
break;
case EXCEPTION_FLT_INVALID_OPERATION:
exceptionCause << "Invalid operation";
break;
case EXCEPTION_FLT_OVERFLOW:
case EXCEPTION_INT_OVERFLOW:
exceptionCause << "Numeric overflow";
break;
case EXCEPTION_FLT_UNDERFLOW:
exceptionCause << "Numeric underflow";
break;
case EXCEPTION_FLT_STACK_CHECK:
exceptionCause << "Stack check";
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
exceptionCause << "Illegal instruction";
break;
case EXCEPTION_INVALID_DISPOSITION:
exceptionCause << "Invalid disposition";
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
exceptionCause << "Noncontinuable exception";
break;
case EXCEPTION_PRIV_INSTRUCTION:
exceptionCause << "Priviledged instruction";
break;
case EXCEPTION_STACK_OVERFLOW:
exceptionCause << "Stack overflow";
break;
default:
exceptionCause << "Unknown";
break;
}
void* exceptionAddress = exceptionInfo->ExceptionRecord->ExceptionAddress;
HMODULE crashedModuleHandle;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast<LPCSTR>(exceptionAddress), &crashedModuleHandle);
MODULEINFO crashedModuleInfo;
GetModuleInformation(GetCurrentProcess(), crashedModuleHandle, &crashedModuleInfo, sizeof(crashedModuleInfo));
char crashedModuleFullName[MAX_PATH];
GetModuleFileNameExA(GetCurrentProcess(), crashedModuleHandle, crashedModuleFullName, MAX_PATH);
char* crashedModuleName = strrchr(crashedModuleFullName, '\\') + 1;
DWORD64 crashedModuleOffset = ((DWORD64)exceptionAddress) - ((DWORD64)crashedModuleInfo.lpBaseOfDll);
CONTEXT* exceptionContext = exceptionInfo->ContextRecord;
spdlog::error("Northstar has crashed! a minidump has been written and exception info is available below:");
spdlog::error(exceptionCause.str());
spdlog::error("At: {} + {}", crashedModuleName, (void*)crashedModuleOffset);
PVOID framesToCapture[62];
int frames = RtlCaptureStackBackTrace(0, 62, framesToCapture, NULL);
for (int i = 0; i < frames; i++)
{
HMODULE backtraceModuleHandle;
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast<LPCSTR>(framesToCapture[i]), &backtraceModuleHandle);
char backtraceModuleFullName[MAX_PATH];
GetModuleFileNameExA(GetCurrentProcess(), backtraceModuleHandle, backtraceModuleFullName, MAX_PATH);
char* backtraceModuleName = strrchr(backtraceModuleFullName, '\\') + 1;
void* actualAddress = (void*)framesToCapture[i];
void* relativeAddress = (void*)(uintptr_t(actualAddress) - uintptr_t(backtraceModuleHandle));
spdlog::error(" {} + {} ({})", backtraceModuleName, relativeAddress, actualAddress);
}
spdlog::error("RAX: 0x{0:x}", exceptionContext->Rax);
spdlog::error("RBX: 0x{0:x}", exceptionContext->Rbx);
spdlog::error("RCX: 0x{0:x}", exceptionContext->Rcx);
spdlog::error("RDX: 0x{0:x}", exceptionContext->Rdx);
spdlog::error("RSI: 0x{0:x}", exceptionContext->Rsi);
spdlog::error("RDI: 0x{0:x}", exceptionContext->Rdi);
spdlog::error("RBP: 0x{0:x}", exceptionContext->Rbp);
spdlog::error("RSP: 0x{0:x}", exceptionContext->Rsp);
spdlog::error("R8: 0x{0:x}", exceptionContext->R8);
spdlog::error("R9: 0x{0:x}", exceptionContext->R9);
spdlog::error("R10: 0x{0:x}", exceptionContext->R10);
spdlog::error("R11: 0x{0:x}", exceptionContext->R11);
spdlog::error("R12: 0x{0:x}", exceptionContext->R12);
spdlog::error("R13: 0x{0:x}", exceptionContext->R13);
spdlog::error("R14: 0x{0:x}", exceptionContext->R14);
spdlog::error("R15: 0x{0:x}", exceptionContext->R15);
time_t time = std::time(nullptr);
tm currentTime = *std::localtime(&time);
std::stringstream stream;
stream << std::put_time(¤tTime, (GetNorthstarPrefix() + "/logs/nsdump%Y-%m-%d %H-%M-%S.dmp").c_str());
auto hMinidumpFile = CreateFileA(stream.str().c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hMinidumpFile)
{
MINIDUMP_EXCEPTION_INFORMATION dumpExceptionInfo;
dumpExceptionInfo.ThreadId = GetCurrentThreadId();
dumpExceptionInfo.ExceptionPointers = exceptionInfo;
dumpExceptionInfo.ClientPointers = false;
MiniDumpWriteDump(
GetCurrentProcess(),
GetCurrentProcessId(),
hMinidumpFile,
MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory),
&dumpExceptionInfo,
nullptr,
nullptr);
CloseHandle(hMinidumpFile);
}
else
spdlog::error("Failed to write minidump file {}!", stream.str());
if (!IsDedicated())
MessageBoxA(
0, "Northstar has crashed! Crash info can be found in R2Northstar/logs", "Northstar has crashed!", MB_ICONERROR | MB_OK);
}
logged = true;
return EXCEPTION_EXECUTE_HANDLER;
}
HANDLE hExceptionFilter;
BOOL WINAPI ConsoleHandlerRoutine(DWORD eventCode)
{
switch (eventCode)
{
case CTRL_CLOSE_EVENT:
// User closed console, shut everything down
spdlog::info("Exiting due to console close...");
RemoveVectoredExceptionHandler(hExceptionFilter);
exit(EXIT_SUCCESS);
return FALSE;
}
return TRUE;
}
void InitialiseLogging()
{
hExceptionFilter = AddVectoredExceptionHandler(TRUE, ExceptionFilter);
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
spdlog::default_logger()->set_pattern("[%H:%M:%S] [%l] %v");
SetConsoleCtrlHandler(ConsoleHandlerRoutine, true);
}
ConVar* Cvar_spewlog_enable;
enum SpewType_t
{
SPEW_MESSAGE = 0,
SPEW_WARNING,
SPEW_ASSERT,
SPEW_ERROR,
SPEW_LOG,
SPEW_TYPE_COUNT
};
typedef void (*EngineSpewFuncType)();
EngineSpewFuncType EngineSpewFunc;
void EngineSpewFuncHook(void* engineServer, SpewType_t type, const char* format, va_list args)
{
if (!Cvar_spewlog_enable->GetBool())
return;
const char* typeStr;
switch (type)
{
case SPEW_MESSAGE:
{
typeStr = "SPEW_MESSAGE";
break;
}
case SPEW_WARNING:
{
typeStr = "SPEW_WARNING";
break;
}
case SPEW_ASSERT:
{
typeStr = "SPEW_ASSERT";
break;
}
case SPEW_ERROR:
{
typeStr = "SPEW_ERROR";
break;
}
case SPEW_LOG:
{
typeStr = "SPEW_LOG";
break;
}
default:
{
typeStr = "SPEW_UNKNOWN";
break;
}
}
char formatted[2048] = {0};
bool shouldFormat = true;
// because titanfall 2 is quite possibly the worst thing to yet exist, it sometimes gives invalid specifiers which will crash
// ttf2sdk had a way to prevent them from crashing but it doesnt work in debug builds
// so we use this instead
for (int i = 0; format[i]; i++)
{
if (format[i] == '%')
{
switch (format[i + 1])
{
// this is fucking awful lol
case 'd':
case 'i':
case 'u':
case 'x':
case 'X':
case 'f':
case 'F':
case 'g':
case 'G':
case 'a':
case 'A':
case 'c':
case 's':
case 'p':
case 'n':
case '%':
case '-':
case '+':
case ' ':
case '#':
case '*':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
default:
{
shouldFormat = false;
break;
}
}
}
}
if (shouldFormat)
vsnprintf(formatted, sizeof(formatted), format, args);
else
{
spdlog::warn("Failed to format {} \"{}\"", typeStr, format);
}
auto endpos = strlen(formatted);
if (formatted[endpos - 1] == '\n')
formatted[endpos - 1] = '\0'; // cut off repeated newline
spdlog::info("[SERVER {}] {}", typeStr, formatted);
}
typedef void (*Status_ConMsg_Type)(const char* text, ...);
Status_ConMsg_Type Status_ConMsg_Original;
void Status_ConMsg_Hook(const char* text, ...)
{
char formatted[2048];
va_list list;
va_start(list, text);
vsprintf_s(formatted, text, list);
va_end(list);
auto endpos = strlen(formatted);
if (formatted[endpos - 1] == '\n')
formatted[endpos - 1] = '\0'; // cut off repeated newline
spdlog::info(formatted);
}
typedef bool (*CClientState_ProcessPrint_Type)(__int64 thisptr, __int64 msg);
CClientState_ProcessPrint_Type CClientState_ProcessPrint_Original;
bool CClientState_ProcessPrint_Hook(__int64 thisptr, __int64 msg)
{
char* text = *(char**)(msg + 0x20);
auto endpos = strlen(text);
if (text[endpos - 1] == '\n')
text[endpos - 1] = '\0'; // cut off repeated newline
spdlog::info(text);
return true;
}
void InitialiseEngineSpewFuncHooks(HMODULE baseAddress)
{
HookEnabler hook;
ENABLER_CREATEHOOK(hook, (char*)baseAddress + 0x11CA80, EngineSpewFuncHook, reinterpret_cast<LPVOID*>(&EngineSpewFunc));
// Hook print function that status concmd uses to actually print data
ENABLER_CREATEHOOK(hook, (char*)baseAddress + 0x15ABD0, Status_ConMsg_Hook, reinterpret_cast<LPVOID*>(&Status_ConMsg_Original));
// Hook CClientState::ProcessPrint
ENABLER_CREATEHOOK(
hook,
(char*)baseAddress + 0x1A1530,
CClientState_ProcessPrint_Hook,
reinterpret_cast<LPVOID*>(&CClientState_ProcessPrint_Original));
Cvar_spewlog_enable = new ConVar("spewlog_enable", "1", FCVAR_NONE, "Enables/disables whether the engine spewfunc should be logged");
}
#include "bitbuf.h"
ConVar* Cvar_cl_showtextmsg;
typedef void (*TextMsg_Type)(__int64);
TextMsg_Type TextMsg_Original;
class ICenterPrint
{
public:
virtual void ctor() = 0;
virtual void Clear(void) = 0;
virtual void ColorPrint(int r, int g, int b, int a, wchar_t* text) = 0;
virtual void ColorPrint(int r, int g, int b, int a, char* text) = 0;
virtual void Print(wchar_t* text) = 0;
virtual void Print(char* text) = 0;
virtual void SetTextColor(int r, int g, int b, int a) = 0;
};
ICenterPrint* internalCenterPrint = NULL;
void TextMsgHook(BFRead* msg)
{
int msg_dest = msg->ReadByte();
char text[256];
msg->ReadString(text, sizeof(text));
if (!Cvar_cl_showtextmsg->GetBool())
return;
switch (msg_dest)
{
case 4: // HUD_PRINTCENTER
internalCenterPrint->Print(text);
break;
default:
spdlog::warn("Unimplemented TextMsg type {}! printing to console", msg_dest);
[[fallthrough]];
case 2: // HUD_PRINTCONSOLE
auto endpos = strlen(text);
if (text[endpos - 1] == '\n')
text[endpos - 1] = '\0'; // cut off repeated newline
spdlog::info(text);
break;
}
}
void InitialiseClientPrintHooks(HMODULE baseAddress)
{
HookEnabler hook;
internalCenterPrint = (ICenterPrint*)((char*)baseAddress + 0x216E940);
// "TextMsg" usermessage
ENABLER_CREATEHOOK(hook, (char*)baseAddress + 0x198710, TextMsgHook, reinterpret_cast<LPVOID*>(&TextMsg_Original));
Cvar_cl_showtextmsg = new ConVar("cl_showtextmsg", "1", FCVAR_NONE, "Enable/disable text messages printing on the screen.");
} | 13,966 | 5,706 |
/* *************************************************************************
* Copyright (c) 2005 VMware, Inc.
*
* 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.
* *************************************************************************/
/*
* reparenter.cc --
*
* Implements the Reparenter class.
*
* The problem
* -----------
* Unlike gtk_container_remove() + gtk_container_add(),
* gtk_widget_reparent() tries to avoid unrealizing the widget. It is
* important when the widget is a VmMks, because unrealizing it breaks the
* connection to the MKS thread.
*
* Unfortunately, gtk_widget_reparent(widget, new parent) is poorly
* implemented (see gtk_widget_reparent_subwindows()):
* o If the widget has its own GDK window, then it is reparented to the GDK
* window of the new parent.
* o If the widget does not have its own GDK window, then its children GDK
* windows are reparented to the GDK window of the new parent.
* The catch is: the GDK windows _are also positionned at (0, 0)_ inside the
* GDK window of the new parent.
*
* This implies that the user can visually see the GDK windows jump to the
* wrong place.
*
* Normally this visual effect is just temporary (i.e. to the user it looks
* like flicker) because the new parent imposes a different size to the
* widget, so quickly after that, the size allocation code asynchronously
* kicks in and properly repositions the GDK windows.
*
* Unfortunately, there is no guarantee the size allocation code will kick
* in: the new parent could very well allocate the same size to the
* widget as the old parent.
*
* In fact, this is precisely what happens when you rename a team in the
* Favorites list, while watching the team's MultiMks: the widget is
* synchronously reparented to a new parent, then back to its old parent.
* Consequently, the final parent allocates exactly the same size as the
* original parent, so the size allocation code does not kick in, and the GDK
* windows stay at the wrong place!
*
* The workaround
* --------------
* 1) Instead of having to deal with the many children GDK window of the
* widget, we simplify the problem by restricting the client code to only
* pass us widgets that have their own GDK window.
*
* 2) Let's try to avoid the jump. Ideally, we want to hide the GDK window
* while it is at the wrong place, then let the allocation code give it its
* proper size and position, then show it again.
*
* The problem is that for the size of the widget to be allocated, it needs
* to be visible, and to make it visible we have to use show(), but show()
* will show the window at the wrong position, even if only for a very short
* time.
*
* So the trick is to lie to GTK: we let it think that the window is
* visible, but in secret we ask GDK to hide it.
*
* 3) Forcefully mark all the widget's GTK children as needing a size
* re-allocation.
*
* --hpreg
*/
#include <libview/reparenter.hh>
namespace view {
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::Reparenter --
*
* Constructor of a Reparenter.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
Reparenter::Reparenter(Gtk::Widget &widget) // IN
: mWidget(widget),
mTrackable(NULL)
{
}
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::~Reparenter --
*
* Destructor of a Reparenter.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
Reparenter::~Reparenter()
{
delete mTrackable;
}
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::OnEvent --
*
* Called when a event we are waiting on occurs.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
void
Reparenter::OnEvent(void)
{
if (mCnx || mTrackable) {
/* Continue to wait until both events have occured. */
return;
}
/* Time to complete workaround 2. */
if (mWasMapped && !mWidget.has_no_window() && mWidget.is_mapped()) {
g_assert(mWidget.is_realized());
/*
* Now that the widget has been allocated, its GDK window has been
* properly repositionned, and we do not need to hide it anymore. Show
* it without modifying its stacking order.
*/
mWidget.get_window()->show_unraised();
}
}
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::OnWidgetSizeAllocate --
*
* "size_allocate" signal handler for a Reparenter's widget.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
void
Reparenter::OnWidgetSizeAllocate(void)
{
mCnx.disconnect();
OnEvent();
}
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::OnSlotCalled --
*
* Called when the slot returned by the last Reparent() call is invoked.
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
void
Reparenter::OnSlotCalled(sigc::trackable &trackable) // IN
{
g_assert(&trackable == mTrackable);
delete mTrackable;
mTrackable = NULL;
OnEvent();
}
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::RecurseQueueResize --
*
* Recursively call queue_resize() on 'widget' and its children (if any).
*
* Results:
* None
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
void
Reparenter::RecurseQueueResize(Gtk::Widget &widget) // IN
{
widget.queue_resize();
Gtk::Container *container = dynamic_cast<Gtk::Container *>(&widget);
if (container) {
container->foreach(sigc::ptr_fun(RecurseQueueResize));
}
}
/*
*-----------------------------------------------------------------------------
*
* view::Reparenter::Reparent --
*
* Reparent a Reparenter's widget in 'newParent'.
*
* Results:
* A slot that client code must invoke when it is ready for the GDK window
* to be shown again.
*
* Side effects:
* None
*
*-----------------------------------------------------------------------------
*/
sigc::slot<void>
Reparenter::Reparent(Gtk::Container &newParent) // IN
{
/*
* Workaround 1: We check that property every time this method is
* called instead of once in the constructor, because that property can
* change over time (see gtk_event_box_set_visible_window() for example).
*/
g_assert(!mWidget.has_no_window());
mCnx.disconnect();
delete mTrackable;
mTrackable = NULL;
if (mWidget.is_mapped()) {
g_assert(mWidget.is_realized());
/*
* Workaround 2: It is OK not to tell GTK (i.e. not to change the
* result of is_mapped()), because unmapping a GDK window is an
* idempotent operation.
*/
mWidget.get_window()->hide();
mWidget.get_display()->sync();
}
mCnx = mWidget.signal_size_allocate().connect(
sigc::hide(sigc::mem_fun(this, &Reparenter::OnWidgetSizeAllocate)));
mTrackable = new sigc::trackable();
mWidget.reparent(newParent);
/*
* Must come after reparent(), because reparent() can modify the result of
* is_mapped().
*/
mWasMapped = mWidget.is_mapped();
/* Workaround 3 */
RecurseQueueResize(mWidget);
/*
* We purposedly bind a reference to the sigc::trackable object to the slot,
* so we can invalidate the slot (i.e. make sure we won't be called back) at
* any time by destroying the object.
*/
return sigc::bind(sigc::mem_fun(this, &Reparenter::OnSlotCalled),
sigc::ref(*mTrackable));
}
} /* namespace view */
| 9,210 | 2,654 |
/********************************************************************************
* Copyright 2018 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 RW_GEOMETRY_ANALYTIC_FACE_HPP_
#define RW_GEOMETRY_ANALYTIC_FACE_HPP_
/**
* @file Face.hpp
*
* \copydoc rw::geometry::Face
*/
#if !defined(SWIG)
#include <rw/core/Ptr.hpp>
#include <rw/geometry/OBB.hpp>
#include <rw/math/Transform3D.hpp>
#include <rw/math/Vector3D.hpp>
#endif
namespace rw { namespace geometry {
class Curve;
class Surface;
class TriMesh;
//! @addtogroup geometry
#if !defined(SWIG)
//! @{
#endif
/**
* @brief Abstract interface for geometric faces.
*
* A face consist of a surface and curves that form the boundary of the face.
*
* For all faces there must be the same number of vertices and curves.
* The order of vertices and curves are ordered such that a curve at a certain index will have a
* corresponding start vertex at the same vertex index.
*/
class Face
{
public:
//! @brief Smart pointer type to Face
typedef rw::core::Ptr< rw::geometry::Face > Ptr;
//! @brief Smart pointer type to const Face
typedef rw::core::Ptr< const rw::geometry::Face > CPtr;
//! @brief Constructor.
Face ();
//! @brief Destructor.
virtual ~Face ();
/**
* @brief Get the surface of the face.
* @return a reference to the surface data.
*/
virtual const rw::geometry::Surface& surface () const = 0;
/**
* @brief Get the number of curves in the face.
* @return the number of curves.
*/
virtual std::size_t curveCount () const = 0;
/**
* @brief Get a curve of the face.
* @param i [in] the curve index, which should be less than the number returned by
* curveCount().
* @return a reference to the curve data.
*/
virtual const rw::geometry::Curve& getCurve (std::size_t i) const = 0;
/**
* @brief Get the vertices of the face.
* @return a reference to the vertex vector.
*/
virtual const std::vector< rw::math::Vector3D<double> >& vertices () const = 0;
/**
* @brief Transform the face.
* @param T [in] transform.
*/
virtual void transform (const rw::math::Transform3D<>& T) = 0;
/**
* @brief Translation of face.
* @param P [in] translation vector.
*/
virtual void transform (const rw::math::Vector3D<double>& P) = 0;
/**
* @brief Create a TriMesh representation of the face.
*
* This function relies on the resolution set with setMeshResolution.
* The resolution is passed on to Curve::discretizeAdaptive and
* Surface::setDiscretizationResolution.
*
* @param forceCopy [in] (not currently used in default implementation)
* @return a new TriMesh.
*/
virtual rw::core::Ptr< rw::geometry::TriMesh > getTriMesh (bool forceCopy = true) const;
/**
* @brief Find the extent of the surface along a specific direction.
* @param dir [in] a normalized direction vector.
* @return the minimum and maximum values along the given direction.
*/
virtual std::pair< double, double > extremums (const rw::math::Vector3D<double>& dir) const;
/**
* @brief Create Oriented Bounding Box.
*
* The default implementation forms a TriMesh in order to estimate the directions for the
* OBB.
*
* @return an OBB around the Face.
*/
virtual rw::geometry::OBB<double> obb ();
/**
* @brief Set the resolution used for discretization in the getTriMesh and faceTriMesh
* functions.
*
* The meaning of this parameter depends on the type of surface.
*
* @param resolution [in] the resolution parameter.
*/
void setMeshResolution (double resolution) { _resolution = resolution; }
protected:
//! @brief Resolution used for discretization into triangle meshes.
double _resolution;
};
#if !defined(SWIG)
//! @}
#endif
}} // namespace rw::geometry
#endif /* RW_GEOMETRY_ANALYTIC_FACE_HPP_ */
| 5,096 | 1,454 |
#pragma once
#include "indexer/ftypes_matcher.hpp"
#include "std/string.hpp"
#include "std/vector.hpp"
#include "base/macros.hpp"
class FeatureType;
namespace search
{
/// Describes 2-level POI-exception types that don't belong to any POI-common classes
/// (amenity, shop, tourism, ...). Used in search algo and search categories index generation.
class TwoLevelPOIChecker : public ftypes::BaseChecker
{
public:
TwoLevelPOIChecker();
};
// This class is used to map feature types to a restricted set of
// different search classes (do not confuse these classes with search
// categories - they are completely different things).
class Model
{
public:
// WARNING: after modifications to the enum below, re-check all methods in the class.
enum Type
{
// Low-level features such as amenities, offices, shops, buildings
// without house number, etc.
TYPE_POI,
// All features with set house number.
TYPE_BUILDING,
TYPE_STREET,
// All low-level features except POI, BUILDING and STREET.
TYPE_UNCLASSIFIED,
TYPE_VILLAGE,
TYPE_CITY,
TYPE_STATE, // US or Canadian states
TYPE_COUNTRY,
TYPE_COUNT
};
static bool IsLocalityType(Type const type)
{
return type >= TYPE_VILLAGE && type <= TYPE_COUNTRY;
}
Type GetType(FeatureType & feature) const;
};
string DebugPrint(Model::Type type);
} // namespace search
| 1,387 | 449 |
// clear && make main && ./main < in > out && subl ./out
#include <bits/stdc++.h>
template<typename T> struct
Node {
T data;
std::shared_ptr<Node> parent;
std::shared_ptr<Node> left;
std::shared_ptr<Node> right;
Node( T data = -1 ) :
data ( data ),
parent ( nullptr ),
left ( nullptr ),
right ( nullptr ) {}
};
template<typename T> class
BST {
private:
std::shared_ptr<Node<T>> root;
public:
BST () : root( nullptr ) {}
~BST () noexcept = default;
std::shared_ptr<Node<T>>
getRoot () { return root; }
int
getHeight ( std::shared_ptr<Node<T>> node ) {
if ( not node ) return 0;
else return ( std::max( getHeight( node->left ), getHeight( node->right ) ) ) + 1;
}
std::shared_ptr<Node<T>>
insert ( std::shared_ptr<Node<T>> node, const T& data ) {
auto newNode( std::make_shared<Node<T>>( data ) );
if ( not newNode ) return nullptr;
if ( not node ) return newNode;
if ( data > node->data )
node->right = insert( node->right, data );
else
node->left = insert( node->left, data );
return node;
}
void
inOrderTraverseSuccessor ( std::shared_ptr<Node<T>> node, std::vector<std::shared_ptr<Node<T>>>& parent, const T& key, std::vector<std::shared_ptr<Node<T>>>& inOrderList ) {
if ( not node ) return ;
inOrderTraverseSuccessor( node->left, parent, key, inOrderList );
inOrderList.push_back( node );
if ( node->left )
if ( key == node->data )
parent.push_back( node );
if ( node->right )
if ( key == node->data )
parent.push_back( node );
inOrderTraverseSuccessor( node->right, parent, key, inOrderList );
}
std::shared_ptr<Node<T>>
getInorderSuccessorNode ( std::shared_ptr<Node<T>> root, std::shared_ptr<Node<T>>& inOrderSuccessorParentNode, const T& key ) {
std::vector<std::shared_ptr<Node<T>>> inOrderList;
std::vector<std::shared_ptr<Node<T>>> parent;
inOrderTraverseSuccessor( root, parent, key, inOrderList );
int successorIndex;
for ( int i = 0; i < inOrderList.size(); ++i )
if ( inOrderList[i]->data == key ) {
successorIndex = i + 1;
break;
}
inOrderSuccessorParentNode = parent.front();
return inOrderList[ successorIndex ];
}
std::shared_ptr<Node<T>>
remove ( std::shared_ptr<Node<T>> root, std::shared_ptr<Node<T>> node, const T& key ) {
// Key is on the Leaf Node
if ( key == node->data and not node->left and not node->right ) {
return nullptr;
}
// Key is on parent node with two children
else if ( key == node->data and node->left and node->right ) {
std::shared_ptr<Node<T>> successorParentNode;
auto successorNode = ( key > root->data )
? getInorderSuccessorNode( root->right, successorParentNode, key )
: getInorderSuccessorNode( root->left, successorParentNode, key );
if ( successorParentNode->right->data == successorNode->data )
successorParentNode->right = nullptr;
else if ( successorParentNode->left->data == successorNode->data )
successorParentNode->left = nullptr;
node->data = successorNode->data;
}
// Key is on parent node with one children on left
else if ( key == node->data and node->left and not node->right ) {
return nullptr;
}
// Key is on parent node with one children on right
else if ( key == node->data and not node->left and node->right ) {
return nullptr;
}
else if ( key > node->data ) {
node->right = remove( root, node->right, key );
} else {
node->left = remove( root, node->left, key );
}
return node;
}
// Traversal //
// void eulerTour () {
// }
// void spiralOrder () {
// }
void
inOrder ( std::shared_ptr<Node<T>> node ) {
if ( not node ) return ;
inOrder( node->left );
std::cout << node->data << " ";
inOrder( node->right );
}
void
preOrder ( std::shared_ptr<Node<T>> node ) {
if ( not node ) return ;
std::cout << node->data << " ";
preOrder( node->left );
preOrder( node->right );
}
void
postOrder ( std::shared_ptr<Node<T>> node ) {
if ( not node ) return ;
postOrder( node->left );
postOrder( node->right );
std::cout << node->data << " ";
}
void
printLevel ( std::shared_ptr<Node<T>> node, unsigned int level = 1 ) {
if ( not node ) return ;
if ( level == 1 ) std::cout << node->data << " ";
printLevel( node->left, level - 1 );
printLevel( node->right, level - 1 );
}
void
levelOrder ( std::shared_ptr<Node<T>> root ) {
int height = getHeight( root );
for ( int i = 1; i <= height; ++i ) {
printLevel( root, i );
}
}
};
typedef int TYPE;
int
main ( void ) {
BST<int> t;
TYPE input;
int n; std::cin >> n;
int data; std::cin >> data;
auto root( std::make_shared<Node<TYPE>>( data ) );
while ( --n ) std::cin >> input, t.insert( root, input );
TYPE query; std::cin >> query;
t.remove( root, root, query );
t.inOrder( root ); std::cout << std::endl;
t.preOrder( root ); std::cout << std::endl;
t.postOrder( root ); std::cout << std::endl;
t.levelOrder( root ); std::cout << std::endl;
return 0;
} | 5,007 | 1,964 |
/*******************************
Copyright (c) 2016-2022 Grégoire Angerand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************/
#include "assets.h"
#include <y/utils/format.h>
#include <external/imgui/yave_imgui.h>
namespace editor {
namespace detail {
std::array<std::string_view, 2> asset_type_names(AssetType type) {
switch(type) {
case AssetType::Mesh:
return {"Mesh", "mesh"};
case AssetType::Image:
return {"Image", "image"};
case AssetType::Animation:
return {"Animation", "animation"};
case AssetType::Font:
return {"Font", "font"};
case AssetType::Scene:
return {"Scene", "scene"};
case AssetType::Material:
return {"Material", "material"};
case AssetType::Prefab:
return {"Prefab", "prefab"};
default:
break;
}
return {"Asset", "asset"};
}
}
std::string_view asset_type_name(AssetType type, bool plural, bool lowercase) {
std::string_view name = detail::asset_type_names(type)[lowercase];
if(plural) {
return fmt("%%", name, name[name.size() - 1] == 'h' ? "es" : "s");
}
return name;
}
std::string_view asset_type_icon(AssetType type) {
switch(type) {
case AssetType::Image:
return ICON_FA_IMAGE;
case AssetType::Mesh:
return ICON_FA_CUBE;
case AssetType::Material:
return ICON_FA_BRUSH;
case AssetType::Scene:
case AssetType::Prefab:
return ICON_FA_DATABASE;
default:
return ICON_FA_QUESTION;
}
return ICON_FA_QUESTION;
}
}
| 2,770 | 921 |
#include "Mouse.h"
namespace Dev::Mouse{
} | 52 | 21 |
// word-grid
// Copyright (c) 2019-2021 Borislav Stanimirov
//
// Distributed under the MIT Software License
// See accompanying file LICENSE.txt or copy at
// https://opensource.org/licenses/MIT
//
#pragma once
#include <core/PRNG.hpp>
#include <iostream>
namespace test
{
core::PRNG makePrng()
{
auto seed = core::PRNG::randomDevice();
std::cout << "Creating PRNG with seed: " << seed << '\n';
return core::PRNG(seed);
}
}
| 441 | 162 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "courgette/disassembler_elf_32_arm.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/logging.h"
#include "courgette/assembly_program.h"
#include "courgette/courgette.h"
#include "courgette/encoded_program.h"
namespace courgette {
CheckBool DisassemblerElf32ARM::Compress(ARM_RVA type, uint32 arm_op, RVA rva,
uint16* c_op, uint32* addr) {
// This method takes an ARM or thumb opcode, extracts the relative
// target address from it (addr), and creates a corresponding
// Courgette opcode (c_op).
//
// Details on ARM the opcodes, and how the relative targets are
// computed were taken from the "ARM Architecture Reference Manual",
// section A4.1.5 and the "Thumb-2 supplement", section 4.6.12.
// ARM_OFF24 is for the ARM opcode. The rest are for thumb opcodes.
switch (type) {
case ARM_OFF8: {
// The offset is given by lower 8 bits of the op. It is a 9-bit
// offset, shifted right one bit and signed extended.
uint32 temp = (arm_op & 0x00FF) << 1;
if (temp & 0x0100)
temp |= 0xFFFFFE00;
temp += 4; // Offset from _next_ PC.
fflush(stdout);
(*addr) = temp;
(*c_op) = (arm_op >> 8) | 0x1000;
break;
}
case ARM_OFF11: {
// The offset is given by lower 11 bits of the op, and is a
// 12-bit offset, shifted right one bit and sign extended.
uint32 temp = (arm_op & 0x07FF) << 1;
if (temp & 0x00000800)
temp |= 0xFFFFF000;
temp += 4; // Offset from _next_ PC.
(*addr) = temp;
(*c_op) = (arm_op >> 11) | 0x2000;
break;
}
case ARM_OFF24: {
// The offset is given by the lower 24-bits of the op, shifted
// left 2 bits, and sign extended.
uint32 temp = (arm_op & 0x00FFFFFF) << 2;
if (temp & 0x02000000)
temp |= 0xFC000000;
temp += 8;
(*addr) = temp;
(*c_op) = (arm_op >> 24) | 0x3000;
break;
}
case ARM_OFF25: {
uint32 temp = 0;
temp |= (arm_op & 0x000007FF) << 1; // imm11
temp |= (arm_op & 0x03FF0000) >> 4; // imm10
uint32 S = (arm_op & (1 << 26)) >> 26;
uint32 j2 = (arm_op & (1 << 11)) >> 11;
uint32 j1 = (arm_op & (1 << 13)) >> 13;
bool bit12 = ((arm_op & (1 << 12)) >> 12) != 0;
bool bit14 = ((arm_op & (1 << 14)) >> 14) != 0;
uint32 i2 = ~(j2 ^ S) & 1;
uint32 i1 = ~(j1 ^ S) & 1;
bool toARM = bit14 && !bit12;
temp |= (S << 24) | (i1 << 23) | (i2 << 22);
if (temp & 0x01000000) // sign extension
temp |= 0xFE000000;
uint32 prefetch;
if (toARM) {
// Align PC on 4-byte boundary
uint32 align4byte = (rva % 4) ? 2 : 4;
prefetch = align4byte;
} else {
prefetch = 4;
}
temp += prefetch;
(*addr) = temp;
uint32 temp2 = 0x4000;
temp2 |= (arm_op & (1 << 12)) >> 12;
temp2 |= (arm_op & (1 << 14)) >> 13;
temp2 |= (arm_op & (1 << 15)) >> 13;
temp2 |= (arm_op & 0xF8000000) >> 24;
temp2 |= (prefetch & 0x0000000F) << 8;
(*c_op) = temp2;
break;
}
case ARM_OFF21: {
uint32 temp = 0;
temp |= (arm_op & 0x000007FF) << 1; // imm11
temp |= (arm_op & 0x003F0000) >> 4; // imm6
uint32 S = (arm_op & (1 << 26)) >> 26;
uint32 j2 = (arm_op & (1 << 11)) >> 11;
uint32 j1 = (arm_op & (1 << 13)) >> 13;
temp |= (S << 20) | (j1 << 19) | (j2 << 18);
if (temp & 0x00100000) // sign extension
temp |= 0xFFE00000;
temp += 4;
(*addr) = temp;
uint32 temp2 = 0x5000;
temp2 |= (arm_op & 0x03C00000) >> 22; // just save the cond
(*c_op) = temp2;
break;
}
default:
return false;
}
return true;
}
CheckBool DisassemblerElf32ARM::Decompress(ARM_RVA type, uint16 c_op,
uint32 addr, uint32* arm_op) {
// Reverses the process in the compress() method. Takes the
// Courgette op and relative address and reconstructs the original
// ARM or thumb op.
switch (type) {
case ARM_OFF8:
(*arm_op) = ((c_op & 0x0FFF) << 8) | (((addr - 4) >> 1) & 0x000000FF);
break;
case ARM_OFF11:
(*arm_op) = ((c_op & 0x0FFF) << 11) | (((addr - 4) >> 1) & 0x000007FF);
break;
case ARM_OFF24:
(*arm_op) = ((c_op & 0x0FFF) << 24) | (((addr - 8) >> 2) & 0x00FFFFFF);
break;
case ARM_OFF25: {
uint32 temp = 0;
temp |= (c_op & (1 << 0)) << 12;
temp |= (c_op & (1 << 1)) << 13;
temp |= (c_op & (1 << 2)) << 13;
temp |= (c_op & (0xF8000000 >> 24)) << 24;
uint32 prefetch = (c_op & 0x0F00) >> 8;
addr -= prefetch;
addr &= 0x01FFFFFF;
uint32 S = (addr & (1 << 24)) >> 24;
uint32 i1 = (addr & (1 << 23)) >> 23;
uint32 i2 = (addr & (1 << 22)) >> 22;
uint32 j1 = ((~i1) ^ S) & 1;
uint32 j2 = ((~i2) ^ S) & 1;
temp |= S << 26;
temp |= j2 << 11;
temp |= j1 << 13;
temp |= (addr & (0x000007FF << 1)) >> 1;
temp |= (addr & (0x03FF0000 >> 4)) << 4;
(*arm_op) = temp;
break;
}
case ARM_OFF21: {
uint32 temp = 0xF0008000;
temp |= (c_op & (0x03C00000 >> 22)) << 22;
addr -= 4;
addr &= 0x001FFFFF;
uint32 S = (addr & (1 << 20)) >> 20;
uint32 j1 = (addr & (1 << 19)) >> 19;
uint32 j2 = (addr & (1 << 18)) >> 18;
temp |= S << 26;
temp |= j2 << 11;
temp |= j1 << 13;
temp |= (addr & (0x000007FF << 1)) >> 1;
temp |= (addr & (0x003F0000 >> 4)) << 4;
(*arm_op) = temp;
break;
}
default:
return false;
}
return true;
}
uint16 DisassemblerElf32ARM::TypedRVAARM::op_size() const {
switch (type_) {
case ARM_OFF8:
return 2;
case ARM_OFF11:
return 2;
case ARM_OFF24:
return 4;
case ARM_OFF25:
return 4;
case ARM_OFF21:
return 4;
default:
return -1;
}
}
CheckBool DisassemblerElf32ARM::TypedRVAARM::ComputeRelativeTarget(
const uint8* op_pointer) {
arm_op_ = op_pointer;
switch (type_) {
case ARM_OFF8:
// Fall through
case ARM_OFF11: {
RVA relative_target;
CheckBool ret = Compress(type_, Read16LittleEndian(op_pointer), rva(),
&c_op_, &relative_target);
set_relative_target(relative_target);
return ret;
}
case ARM_OFF24: {
RVA relative_target;
CheckBool ret = Compress(type_, Read32LittleEndian(op_pointer), rva(),
&c_op_, &relative_target);
set_relative_target(relative_target);
return ret;
}
case ARM_OFF25:
// Fall through
case ARM_OFF21: {
// A thumb-2 op is 32 bits stored as two 16-bit words
uint32 pval = (Read16LittleEndian(op_pointer) << 16)
| Read16LittleEndian(op_pointer + 2);
RVA relative_target;
CheckBool ret = Compress(type_, pval, rva(), &c_op_, &relative_target);
set_relative_target(relative_target);
return ret;
}
default:
return false;
}
}
CheckBool DisassemblerElf32ARM::TypedRVAARM::EmitInstruction(
AssemblyProgram* program,
RVA target_rva) {
return program->EmitRel32ARM(c_op(),
program->FindOrMakeRel32Label(target_rva),
arm_op_,
op_size());
}
DisassemblerElf32ARM::DisassemblerElf32ARM(const void* start, size_t length)
: DisassemblerElf32(start, length) {
}
// Convert an ELF relocation struction into an RVA
CheckBool DisassemblerElf32ARM::RelToRVA(Elf32_Rel rel, RVA* result) const {
// The rightmost byte of r_info is the type...
elf32_rel_arm_type_values type =
(elf32_rel_arm_type_values)(unsigned char)rel.r_info;
// The other 3 bytes of r_info are the symbol
uint32 symbol = rel.r_info >> 8;
switch(type)
{
case R_ARM_RELATIVE:
if (symbol != 0)
return false;
// This is a basic ABS32 relocation address
*result = rel.r_offset;
return true;
default:
return false;
}
}
CheckBool DisassemblerElf32ARM::ParseRelocationSection(
const Elf32_Shdr *section_header,
AssemblyProgram* program) {
// This method compresses a contiguous stretch of R_ARM_RELATIVE
// entries in the relocation table with a Courgette relocation table
// instruction. It skips any entries at the beginning that appear
// in a section that Courgette doesn't support, e.g. INIT.
// Specifically, the entries should be
// (1) In the same relocation table
// (2) Are consecutive
// (3) Are sorted in memory address order
//
// Happily, this is normally the case, but it's not required by spec
// so we check, and just don't do it if we don't match up.
//
// The expectation is that one relocation section will contain
// all of our R_ARM_RELATIVE entries in the expected order followed
// by assorted other entries we can't use special handling for.
bool match = true;
// Walk all the bytes in the section, matching relocation table or not
size_t file_offset = section_header->sh_offset;
size_t section_end = section_header->sh_offset + section_header->sh_size;
Elf32_Rel *section_relocs_iter =
(Elf32_Rel *)OffsetToPointer(section_header->sh_offset);
uint32 section_relocs_count = section_header->sh_size /
section_header->sh_entsize;
if (abs32_locations_.size() > section_relocs_count)
match = false;
if (!abs32_locations_.empty()) {
std::vector<RVA>::iterator reloc_iter = abs32_locations_.begin();
for (uint32 i = 0; i < section_relocs_count; i++) {
if (section_relocs_iter->r_offset == *reloc_iter)
break;
if (!ParseSimpleRegion(file_offset, file_offset + sizeof(Elf32_Rel),
program))
return false;
file_offset += sizeof(Elf32_Rel);
++section_relocs_iter;
}
while (match && (reloc_iter != abs32_locations_.end())) {
if (section_relocs_iter->r_info != R_ARM_RELATIVE ||
section_relocs_iter->r_offset != *reloc_iter)
match = false;
section_relocs_iter++;
reloc_iter++;
file_offset += sizeof(Elf32_Rel);
}
if (match) {
// Skip over relocation tables
if (!program->EmitElfARMRelocationInstruction())
return false;
}
}
return ParseSimpleRegion(file_offset, section_end, program);
}
CheckBool DisassemblerElf32ARM::ParseRel32RelocsFromSection(
const Elf32_Shdr* section_header) {
uint32 start_file_offset = section_header->sh_offset;
uint32 end_file_offset = start_file_offset + section_header->sh_size;
const uint8* start_pointer = OffsetToPointer(start_file_offset);
const uint8* end_pointer = OffsetToPointer(end_file_offset);
// Quick way to convert from Pointer to RVA within a single Section is to
// subtract 'pointer_to_rva'.
const uint8* const adjust_pointer_to_rva = start_pointer -
section_header->sh_addr;
// Find the rel32 relocations.
const uint8* p = start_pointer;
bool on_32bit = 1; // 32-bit ARM ops appear on 32-bit boundaries, so track it
while (p < end_pointer) {
// Heuristic discovery of rel32 locations in instruction stream: are the
// next few bytes the start of an instruction containing a rel32
// addressing mode?
TypedRVAARM* rel32_rva = NULL;
RVA target_rva;
bool found = false;
// 16-bit thumb ops
if (!found && (p + 3) <= end_pointer) {
uint16 pval = Read16LittleEndian(p);
if ((pval & 0xF000) == 0xD000) {
RVA rva = static_cast<RVA>(p - adjust_pointer_to_rva);
rel32_rva = new TypedRVAARM(ARM_OFF8, rva);
if (!rel32_rva->ComputeRelativeTarget((uint8*) p)) {
return false;
}
target_rva = rel32_rva->rva() + rel32_rva->relative_target();
found = true;
} else if ((pval & 0xF800) == 0xE000) {
RVA rva = static_cast<RVA>(p - adjust_pointer_to_rva);
rel32_rva = new TypedRVAARM(ARM_OFF11, rva);
if (!rel32_rva->ComputeRelativeTarget((uint8*) p)) {
return false;
}
target_rva = rel32_rva->rva() + rel32_rva->relative_target();
found = true;
}
}
// thumb-2 ops comprised of two 16-bit words
if (!found && (p + 5) <= end_pointer) {
// This is really two 16-bit words, not one 32-bit word.
uint32 pval = (Read16LittleEndian(p) << 16) | Read16LittleEndian(p + 2);
if ((pval & 0xF8008000) == 0xF0008000) {
// Covers thumb-2's 32-bit conditional/unconditional branches
if ( (pval & (1 << 14)) || (pval & (1 << 12)) ) {
// A branch, with link, or with link and exchange.
RVA rva = static_cast<RVA>(p - adjust_pointer_to_rva);
rel32_rva = new TypedRVAARM(ARM_OFF25, rva);
if (!rel32_rva->ComputeRelativeTarget((uint8*) p)) {
return false;
}
target_rva = rel32_rva->rva() + rel32_rva->relative_target();
found = true;
} else {
// TODO(paulgazz) make sure cond is not 111
// A conditional branch instruction
RVA rva = static_cast<RVA>(p - adjust_pointer_to_rva);
rel32_rva = new TypedRVAARM(ARM_OFF21, rva);
if (!rel32_rva->ComputeRelativeTarget((uint8*) p)) {
return false;
}
target_rva = rel32_rva->rva() + rel32_rva->relative_target();
found = true;
}
}
}
// 32-bit ARM ops
if (!found && on_32bit && (p + 5) <= end_pointer) {
uint32 pval = Read32LittleEndian(p);
if ((pval & 0x0E000000) == 0x0A000000) {
// Covers both 0x0A 0x0B ARM relative branches
RVA rva = static_cast<RVA>(p - adjust_pointer_to_rva);
rel32_rva = new TypedRVAARM(ARM_OFF24, rva);
if (!rel32_rva->ComputeRelativeTarget((uint8*) p)) {
return false;
}
target_rva = rel32_rva->rva() + rel32_rva->relative_target();
found = true;
}
}
if (found && IsValidRVA(target_rva)) {
rel32_locations_.push_back(rel32_rva);
#if COURGETTE_HISTOGRAM_TARGETS
++rel32_target_rvas_[target_rva];
#endif
p += rel32_rva->op_size();
// A tricky way to update the on_32bit flag. Here is the truth table:
// on_32bit | on_32bit size is 4
// ---------+---------------------
// 1 | 0 0
// 0 | 0 1
// 0 | 1 0
// 1 | 1 1
on_32bit = (~(on_32bit ^ (rel32_rva->op_size() == 4))) != 0;
} else {
// Move 2 bytes at a time, but track 32-bit boundaries
p += 2;
on_32bit = ((on_32bit + 1) % 2) != 0;
}
}
return true;
}
} // namespace courgette
| 15,118 | 6,059 |
// Copyright 2021 Butescu Vladimir
#include <mpi.h>
#include <vector>
#include <random>
#include <algorithm>
#include"./butescu_v_vector_average.h"
std::vector<int> getRandomPositiveVector(int size) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(1, 100);
if (size < 0) { size = 0; }
std::vector<int> vec(size);
for (int i = 0; i < size; i++) { vec[i] = dist(gen); }
return vec;
}
int getParallelAverage(std::vector<int> parall_vec, int size) {
int ProcRank, ProcNum, sum_all;
double Paverage;
if (size <= 0) {
return 0;
}
MPI_Comm_size(MPI_COMM_WORLD, &ProcNum);
MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank);
int real_size = size;
int add = ProcNum - size % ProcNum;
for (int i = 0; i < add; i++) {
parall_vec.push_back(0);
size++;
}
int partSize = size / ProcNum;
if (ProcRank == 0) {
for (int i = 1; i < ProcNum; i++) {
MPI_Send(parall_vec.data() + i * partSize, partSize, MPI_INT, i, 0, MPI_COMM_WORLD);
}
}
std::vector<int> local_vec(partSize);
if (ProcRank == 0) {
local_vec = std::vector<int>(parall_vec.begin(), parall_vec.begin() + partSize);
} else {
MPI_Status status;
MPI_Recv(local_vec.data(), partSize, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
}
int sum = sum_all = 0;
for (int i = 0; i < partSize; i++) {
sum += local_vec[i];
}
MPI_Reduce(&sum, &sum_all, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
Paverage = static_cast<double>(sum_all) / real_size;
return Paverage;
}
int getSequentialAverage(std::vector<int> sequent_vec) {
int size = sequent_vec.size(), sum_all = 0;
double Saverage = 0;
if (size <= 0) {
return 0;
}
for (int i = 0; i < size; i++) {
sum_all += sequent_vec[i];
}
Saverage = static_cast<double>(sum_all) / size;
return Saverage;
}
| 1,967 | 810 |
/*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* 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 <sstream>
#include <string>
#include <vector>
#include <ignition/common/Filesystem.hh>
#include "ignition/fuel_tools/ClientConfig.hh"
#include "ignition/fuel_tools/CollectionIdentifier.hh"
using namespace ignition;
using namespace fuel_tools;
class ignition::fuel_tools::CollectionIdentifierPrivate
{
/// \brief a name given to this collection by a user
public: std::string name;
/// \brief owner who this collection is attributed to
public: std::string owner;
/// \brief Server of this collection
public: ServerConfig server;
};
//////////////////////////////////////////////////
CollectionIdentifier::CollectionIdentifier()
: dataPtr(std::make_unique<CollectionIdentifierPrivate>())
{
}
//////////////////////////////////////////////////
CollectionIdentifier::CollectionIdentifier(const CollectionIdentifier &_orig)
: dataPtr(std::make_unique<CollectionIdentifierPrivate>(*_orig.dataPtr))
{
}
//////////////////////////////////////////////////
CollectionIdentifier &CollectionIdentifier::operator=(
const CollectionIdentifier &_orig)
{
this->dataPtr = std::make_unique<CollectionIdentifierPrivate>(*_orig.dataPtr);
return *this;
}
//////////////////////////////////////////////////
bool CollectionIdentifier::operator==(const CollectionIdentifier &_rhs) const
{
return this->UniqueName() == _rhs.UniqueName();
}
//////////////////////////////////////////////////
CollectionIdentifier::~CollectionIdentifier() = default;
//////////////////////////////////////////////////
std::string CollectionIdentifier::UniqueName() const
{
return common::joinPaths(this->dataPtr->server.Url().Str(),
this->dataPtr->owner, "collections",
this->dataPtr->name);
}
//////////////////////////////////////////////////
std::string CollectionIdentifier::Name() const
{
return this->dataPtr->name;
}
//////////////////////////////////////////////////
bool CollectionIdentifier::SetName(const std::string &_name)
{
this->dataPtr->name = _name;
return true;
}
//////////////////////////////////////////////////
std::string CollectionIdentifier::Owner() const
{
return this->dataPtr->owner;
}
//////////////////////////////////////////////////
bool CollectionIdentifier::SetOwner(const std::string &_name)
{
this->dataPtr->owner = _name;
return true;
}
//////////////////////////////////////////////////
bool CollectionIdentifier::SetServer(const ServerConfig &_server)
{
bool success = _server.Url().Valid();
if (success)
this->dataPtr->server = _server;
return success;
}
//////////////////////////////////////////////////
ServerConfig &CollectionIdentifier::Server() const
{
return this->dataPtr->server;
}
//////////////////////////////////////////////////
std::string CollectionIdentifier::AsString(const std::string &_prefix) const
{
std::stringstream out;
out << _prefix << "Name: " << this->Name() << std::endl
<< _prefix << "Owner: " << this->Owner() << std::endl
<< _prefix << "Unique name: " << this->UniqueName() << std::endl
<< _prefix << "Server:" << std::endl
<< this->Server().AsString(_prefix + " ");
return out.str();
}
//////////////////////////////////////////////////
std::string CollectionIdentifier::AsPrettyString(
const std::string &_prefix) const
{
std::string prop = "\033[96m\033[1m";
std::string value = "\033[37m";
std::string reset = "\033[0m";
std::stringstream out;
if (!this->Name().empty())
{
out << _prefix << prop << "Name: " << reset
<< value << this->Name() << reset << std::endl;
}
if (!this->Owner().empty())
{
out << _prefix << prop << "Owner: " << reset
<< value << this->Owner() << reset << std::endl;
}
out << _prefix << prop << "Server:" << reset << std::endl
<< this->Server().AsPrettyString(_prefix + " ");
return out.str();
}
| 4,507 | 1,221 |
/*=========================================================================
Program: Visualization Toolkit
Module: TestMultiblockDisplayProperties.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// This test tests setting up of display properties of individual blocks in
// composite datasets.
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataDisplayAttributes.h"
#include "vtkCompositePolyDataMapper2.h"
#include "vtkDataObject.h"
#include "vtkNew.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTestUtilities.h"
#include "vtkXMLMultiBlockDataReader.h"
int TestMultiblockDisplayProperties(int argc, char* argv[])
{
vtkNew<vtkXMLMultiBlockDataReader> reader;
char * fname = vtkTestUtilities::ExpandDataFileName(
argc, argv, "Data/many_blocks/many_blocks.vtm");
reader->SetFileName(fname);
delete[] fname;
vtkNew<vtkRenderWindow> renWin;
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
vtkNew<vtkRenderer> renderer;
renWin->AddRenderer(renderer.GetPointer());
vtkNew<vtkActor> actor;
renderer->AddActor(actor.GetPointer());
vtkNew<vtkCompositePolyDataMapper2> mapper;
mapper->SetInputConnection(reader->GetOutputPort());
actor->SetMapper(mapper.GetPointer());
renWin->SetSize(400,400);
renderer->GetActiveCamera()->SetViewUp(0, 0, 1);
renderer->GetActiveCamera()->SetPosition(-1.3, 0, 1.7);
renderer->GetActiveCamera()->SetFocalPoint(0, 0, 1.6);
renderer->SetBackground(0.1,0.2,0.4);
renderer->ResetCamera();
renWin->Render();
vtkNew<vtkCompositeDataDisplayAttributes> attributes;
mapper->SetCompositeDataDisplayAttributes(attributes.GetPointer());
mapper->SetBlockVisibility(1, 0);
mapper->SetBlockVisibility(23, 1);
mapper->SetBlockVisibility(27, 0);
mapper->SetBlockVisibility(29, 0);
renWin->Render();
mapper->RemoveBlockVisibility(29);
renWin->Render();
// Color "Group B" green.
mapper->SetBlockColor(67, 0, 0.33, 0.0);
renWin->Render();
// Show "Group ACAA" and color it yellow.
mapper->SetBlockVisibility(46, true);
mapper->SetBlockColor(46, 1, 1, 0.5);
renWin->Render();
// Set opacity on "Group AC" to 0.5
mapper->SetBlockOpacity(34, 0.5);
renWin->Render();
// Change solid color.
actor->GetProperty()->SetColor(0.5, 0.1, 0.1);
renWin->Render();
// Remove all opacity overrides.
mapper->RemoveBlockOpacities();
renWin->Render();
int retVal = vtkRegressionTestImage(renWin.GetPointer());
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
| 3,104 | 1,100 |
#include <iostream>
using namespace std;
int binarysearch(int arr[], int l,int r, int x);
int main()
{
int array[] = {1,2,3,4,5,6,7,9};
int n = sizeof(array)/sizeof(array[0]);
int x = 2;
int result = binarysearch(array,0,n-1,x);
if (result==-1) cout<<x<<" is not present in the array"<<endl;
else
cout<<x<<" is pressent at "<<result<<" index";
}
int binarysearch(int arr[], int l,int r, int x)
{
if(r>=l)
{
int mid = l +(r-1)/2;
if(arr[mid]==x)return mid;
if(arr[mid]>x)return binarysearch(arr,l,mid-1,x);
return binarysearch(arr,mid+1,r,x); //else return;
}
else
return -1;
}
| 641 | 266 |
#include <Functions/JSONPath/ASTs/ASTJSONPathRoot.h>
#include <Functions/JSONPath/Parsers/ParserJSONPathRoot.h>
#include <Parsers/Lexer.h>
namespace DB
{
/**
*
* @param pos token iterator
* @param node node of ASTJSONPathRoot
* @param expected stuff for logging
* @return was parse successful
*/
bool ParserJSONPathRoot::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
{
if (pos->type != TokenType::DollarSign)
{
expected.add(pos, "dollar sign (start of jsonpath)");
return false;
}
node = std::make_shared<ASTJSONPathRoot>();
++pos;
return true;
}
}
| 609 | 206 |
/*
* Clusterer on undirected graphs that produces an agglomeration tree.
*
* Graph vertices are initialized to each be a single element tree. Each
* step of the agglomeration merges the vertices at the ends of the highest
* priority edge and updates the costs of the edges connected to the merged
* vertex. The merged vertex is a tree containing the original vertices as
* subtrees.
*/
#ifndef MLEARNING__CLUSTERING__CLUSTERERS__GRAPH__TREE_CLUSTERER_HH
#define MLEARNING__CLUSTERING__CLUSTERERS__GRAPH__TREE_CLUSTERER_HH
#include "collections/abstract/collection.hh"
#include "collections/array_list.hh"
#include "collections/list.hh"
#include "collections/pointers/auto_collection.hh"
#include "functors/comparable_functors.hh"
#include "lang/array.hh"
#include "lang/iterators/iterator.hh"
#include "lang/pointers/auto_ptr.hh"
#include "mlearning/clustering/clusterers/abstract/clusterer.hh"
#include "mlearning/clustering/clusterers/graph/basic_clusterer.hh"
namespace mlearning {
namespace clustering {
namespace clusterers {
namespace graph {
/*
* Imports.
*/
using collections::abstract::collection;
using collections::array_list;
using collections::list;
using collections::pointers::auto_collection;
using functors::comparable_functor;
using functors::compare_functors;
using lang::array;
using lang::iterators::iterator;
using lang::pointers::auto_ptr;
using mlearning::clustering::clusterers::abstract::clusterer;
/*
* Clusterer on undirected graphs that produces an agglomeration tree.
*
* T is the type of data contained in each node of the tree.
* E is the edge type for the graph.
*
* Note that T must be copy-constructible.
*
* Vertices in the graph are binary trees whos nodes are elements of type T.
*/
template <typename T, typename E>
class tree_clusterer : public clusterer<T> {
public:
/*
* Agglomeration tree.
*/
class tree {
public:
/*
* Constructors.
*/
explicit tree(auto_ptr<T> t)
: data(t), left(), right() { }
explicit tree(auto_ptr<T> t, auto_ptr<tree> l, auto_ptr<tree> r)
: data(t), left(l), right(r) { }
/*
* Copy constructor.
* Transfer ownership of tree's elements to the copy.
*/
explicit tree(const tree& t)
: data(t.data), left(t.left), right(t.right) { }
/*
* Destructor.
*/
~tree() { /* do nothing */ }
/*
* Tree data.
*/
mutable auto_ptr<T> data; /* data */
mutable auto_ptr<tree> left; /* left subtree */
mutable auto_ptr<tree> right; /* right subtree */
};
/*
* Abstract base class for agglomeration functionality on trees.
*/
class agglomerator {
public:
/*
* Destructor.
*/
virtual ~agglomerator() { }
/*
* Return whether the vertices at the end of the edge can be merged.
* Agglomeration stops when the highest priority edge is unmergeable.
*
* Default to always allowing merges. In this case, the tree clusterer
* returns a single tree rather than a forest of trees.
*/
virtual bool is_mergeable(const E&) const {
return true;
}
/*
* Merge two vertices and return the data for the merged vertex.
*/
virtual auto_ptr<T> merge(const tree&, const tree&) const = 0;
/*
* Compute the edge between the two vertices in the graph.
*/
virtual auto_ptr<E> update(const tree&, const tree&) const = 0;
};
/*
* Constructor.
* Specify the agglomerator to use for merge and update operations.
* Optionally specify the comparison functor for prioritizing edges.
*/
explicit tree_clusterer(
const agglomerator&,
const comparable_functor<E>& = compare_functors<E>::f_compare()
);
/*
* Copy constructor.
* Create a clusterer that uses the same agglomerator and priority functor.
*/
tree_clusterer(const tree_clusterer<T,E>&);
/*
* Destructor.
*/
virtual ~tree_clusterer();
/*
* Clustering.
* Assume a fully connected undirected graph.
* Return the cluster assignments.
*/
virtual array<unsigned long> cluster(
const collection<T>& /* items to cluster */
) const;
/*
* Clustering.
* Assume a fully connected undirected graph.
* Return both the cluster assignments and the clustering result.
*/
virtual array<unsigned long> cluster(
const collection<T>&, /* items to cluster */
auto_collection< tree, array_list<tree> >& /* clustering result */
) const;
/*
* Clustering.
* Specify the edges in the undirected graph.
* Return the cluster assignments.
*/
virtual array<unsigned long> cluster(
const collection<T>&, /* items to cluster */
const collection< array<unsigned long> >& /* edges in graph */
) const;
/*
* Clustering.
* Specify the edges in the undirected graph.
* Return both the cluster assignments and the clustering result.
*/
virtual array<unsigned long> cluster(
const collection<T>&, /* items to cluster */
const collection< array<unsigned long> >&, /* edges in graph */
auto_collection< tree, array_list<tree> >& /* clustering result */
) const;
protected:
/*
* Agglomerator which translates a tree agglomerator into one
* that can be used with the basic graph clustering algorithm.
*/
class basic_agglomerator
: public basic_clusterer<tree,E>::agglomerator {
public:
/*
* Constructor.
*/
explicit basic_agglomerator(const agglomerator& agglm)
: _agglm(agglm) { }
/*
* Copy constructor.
*/
basic_agglomerator(const basic_agglomerator& agglm)
: _agglm(agglm._agglm) { }
/*
* Return whether the vertices at the end of the edge can be merged.
* Agglomeration stops when the highest priority edge is unmergeable.
*/
bool is_mergeable(const E& e) const {
return _agglm.is_mergeable(e);
}
/*
* Merge two vertices and return the merged vertex.
*/
auto_ptr<tree> merge(const tree& t0, const tree& t1) const {
/* compute data for merged node */
auto_ptr<T> data = _agglm.merge(t0, t1);
/* construct tree that owns t0, t1 subtrees */
auto_ptr<tree> t0_copy(new tree(t0));
auto_ptr<tree> t1_copy(new tree(t1));
auto_ptr<tree> t(new tree(data, t0_copy, t1_copy));
return t;
}
/*
* Compute the edge between the two vertices in the graph.
*/
auto_ptr<E> update(const tree& t0, const tree& t1) const {
return _agglm.update(t0, t1);
}
protected:
const agglomerator& _agglm; /* agglomerator on trees */
};
/*
* Helper function.
* Return a collection of single element trees given a collection of
* elements.
*/
static auto_collection<tree> make_trees(const collection<T>&);
/*
* Tree clusterer data.
*/
const basic_agglomerator _agglm; /* agglomerator for basic clusterer */
const comparable_functor<E>& _f; /* edge priority functor */
const basic_clusterer<tree,E> _c; /* basic graph clusterer */
};
/***************************************************************************
* Tree clusterer implementation.
***************************************************************************/
/*
* Constructor.
* Specify the agglomerator to use for merge and update operations.
* Specify the comparison functor for prioritizing edges.
*/
template <typename T, typename E>
tree_clusterer<T,E>::tree_clusterer(
const agglomerator& agglm,
const comparable_functor<E>& f)
: _agglm(agglm),
_f(f),
_c(_agglm, _f)
{ }
/*
* Copy constructor.
* Create a clusterer that uses the same agglomerator and priority functor.
*/
template <typename T, typename E>
tree_clusterer<T,E>::tree_clusterer(const tree_clusterer<T,E>& c)
: _agglm(c._agglm),
_f(c._f),
_c(_agglm, _f)
{ }
/*
* Destructor.
*/
template <typename T, typename E>
tree_clusterer<T,E>::~tree_clusterer() {
/* do nothing */
}
/*
* Clustering.
* Assume a fully connected undirected graph.
* Return the cluster assignments.
*/
template <typename T, typename E>
array<unsigned long> tree_clusterer<T,E>::cluster(
const collection<T>& items) const
{
auto_collection<tree> trees = tree_clusterer<T,E>::make_trees(items);
return _c.cluster(*trees);
}
/*
* Clustering.
* Assume a fully connected undirected graph.
* Return both the cluster assignments and the clustering result.
*/
template <typename T, typename E>
array<unsigned long> tree_clusterer<T,E>::cluster(
const collection<T>& items,
auto_collection< tree, array_list<tree> >& vertices) const
{
auto_collection<tree> trees = tree_clusterer<T,E>::make_trees(items);
return _c.cluster(*trees, vertices);
}
/*
* Clustering.
* Specify the edges in the undirected graph.
* Return the cluster assignments.
*/
template <typename T, typename E>
array<unsigned long> tree_clusterer<T,E>::cluster(
const collection<T>& items,
const collection< array<unsigned long> >& edges) const
{
auto_collection<tree> trees = tree_clusterer<T,E>::make_trees(items);
return _c.cluster(*trees, edges);
}
/*
* Clustering.
* Specify the edges in the undirected graph.
* Return both the cluster assignments and the clustering result.
*/
template <typename T, typename E>
array<unsigned long> tree_clusterer<T,E>::cluster(
const collection<T>& items,
const collection< array<unsigned long> >& edges,
auto_collection< tree, array_list<tree> >& vertices) const
{
auto_collection<tree> trees = tree_clusterer<T,E>::make_trees(items);
return _c.cluster(*trees, edges, vertices);
}
/*
* Helper function.
* Return a collection of single element trees given a collection of
* elements.
*/
template <typename T, typename E>
auto_collection<typename tree_clusterer<T,E>::tree>
tree_clusterer<T,E>::make_trees(const collection<T>& items)
{
auto_collection<tree> trees(new list<tree>);
for (auto_ptr< iterator<T> > i = items.iter_create(); i->has_next(); ) {
T& item = i->next();
auto_ptr<T> item_copy(new T(item));
auto_ptr<tree> t(new tree(item_copy));
trees->add(*t);
t.release();
}
return trees;
}
} /* namespace graph */
} /* namesapce clusterers */
} /* namespace clustering */
} /* namespace mlearning */
#endif
| 10,748 | 3,297 |
/****************************************************************************************
* @author: kzvd4729 created: 2017-08-07 23:11:59
* solution_verdict: Wrong answer language: C++
* run_time: memory_used:
* problem: https://vjudge.net/problem/UVA-116
****************************************************************************************/
#include<bits/stdc++.h>
using namespace std;
long long int r,c,i,j,grid[15][115],dp[15][115];
vector<long long int>ans;
long long int fx(long long int row,long long int col)
{
if(col==c+1)return 0;
if(dp[row][col]!=-1)return dp[row][col];
long long int p1,p2,p3;
if(row==1)p1=grid[row][col]+fx(r,col+1);
else p1=grid[row][col]+fx(row-1,col+1);
p2=grid[row][col]+fx(row,col+1);
if(row==r)p3=grid[row][col]+fx(1,col+1);
else p3=grid[row][col]+fx(row+1,col+1);
return dp[row][col]=min(p1,min(p2,p3));
}
int main()
{
ofstream cout("out.txt");
while(cin>>r>>c)
{
for(i=1; i<=r; i++)
{
for(j=1; j<=c; j++)
{
cin>>grid[i][j];
}
}
long long int ck=99999999;
long long int x,z;
if(c==1)
{
for(i=1; i<=r; i++)
{
if(grid[i][1]<ck)
{
ck=grid[i][1];
x=i;
}
}
cout<<x<<endl;
cout<<ck<<endl;
continue;
}
memset(dp,-1,sizeof(dp));
long long int mn=99999999999999;
for(i=1; i<=r; i++)
{
mn=min(mn,fx(i,1));
}
long long int mmn=mn;
long long int mark;
mark=2;
for(i=1; i<=r; i++)
{
if(dp[i][1]==mn)
{
mark=i;
mn-=grid[i][1];
ans.push_back(mark);
break;
}
}
long long int cnt=1;
while(true)
{
cnt++;
if(mark==1)
{
if(dp[mark][cnt]==mn)
{
ans.push_back(mark);
mn-=grid[mark][cnt];
}
else if(dp[mark+1][cnt]==mn)
{
mark++;
ans.push_back(mark);
mn-=grid[mark][cnt];
}
else if(dp[r][cnt]==mn)
{
mark=r;
ans.push_back(mark);
mn-=grid[mark][cnt];
}
}
else if(mark==r)
{
if(dp[1][cnt]==mn)
{
mark=1;
ans.push_back(mark);
mn-=grid[mark][cnt];
}
else if(dp[mark-1][cnt]==mn)
{
mark--;
ans.push_back(mark);
mn-=grid[mark][cnt];
}
else if(dp[mark][cnt]==mn)
{
ans.push_back(mark);
mn-=grid[mark][cnt];
}
}
else
{
if(dp[mark-1][cnt]==mn)
{
mark--;
ans.push_back(mark);
mn-=grid[mark][cnt];
}
else if(dp[mark][cnt]==mn)
{
ans.push_back(mark);
mn-=grid[mark][cnt];
}
else if(dp[mark+1][cnt]==mn)
{
mark++;
ans.push_back(mark);
mn-=grid[mark][cnt];
}
}
if(cnt==c)break;
}
for(i=0; i<ans.size(); i++)
{
cout<<ans[i];
if(i!=ans.size()-1)cout<<" ";
}
cout<<endl;
cout<<mmn<<endl;
ans.clear();
}
return 0;
} | 4,217 | 1,323 |
// Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_openfl__Vector_IVector
#include <openfl/_Vector/IVector.h>
#endif
#ifndef INCLUDED_openfl__Vector_ObjectVector
#include <openfl/_Vector/ObjectVector.h>
#endif
#ifndef INCLUDED_openfl_ui_Multitouch
#include <openfl/ui/Multitouch.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_d04537844d94f90f_112___init__,"::openfl::ui::Multitouch_obj","__init__",0xd9e1825c,"::openfl::ui::Multitouch_obj.__init__","openfl/ui/Multitouch.hx",112,0xce42901c)
HX_LOCAL_STACK_FRAME(_hx_pos_0f8b8e224a678ffc_141_get_supportsTouchEvents,"openfl.ui.Multitouch","get_supportsTouchEvents",0x2ba8207f,"openfl.ui.Multitouch.get_supportsTouchEvents","openfl/ui/Multitouch.hx",141,0xce42901c)
namespace openfl{
namespace ui{
void Multitouch_obj::__construct() { }
Dynamic Multitouch_obj::__CreateEmpty() { return new Multitouch_obj; }
void *Multitouch_obj::_hx_vtable = 0;
Dynamic Multitouch_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< Multitouch_obj > _hx_result = new Multitouch_obj();
_hx_result->__construct();
return _hx_result;
}
bool Multitouch_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x647efaea;
}
void Multitouch_obj::__init__(){
HX_STACKFRAME(&_hx_pos_d04537844d94f90f_112___init__)
HXLINE( 113) ::openfl::ui::Multitouch_obj::maxTouchPoints = 2;
HXLINE( 114) ::openfl::ui::Multitouch_obj::supportedGestures = null();
HXLINE( 115) ::openfl::ui::Multitouch_obj::supportsGestureEvents = false;
HXLINE( 116) ::openfl::ui::Multitouch_obj::inputMode = 2;
}
::Dynamic Multitouch_obj::inputMode;
int Multitouch_obj::maxTouchPoints;
::openfl::_Vector::ObjectVector Multitouch_obj::supportedGestures;
bool Multitouch_obj::supportsGestureEvents;
bool Multitouch_obj::get_supportsTouchEvents(){
HX_STACKFRAME(&_hx_pos_0f8b8e224a678ffc_141_get_supportsTouchEvents)
HXDLIN( 141) return true;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC0(Multitouch_obj,get_supportsTouchEvents,return )
Multitouch_obj::Multitouch_obj()
{
}
bool Multitouch_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 9:
if (HX_FIELD_EQ(inName,"inputMode") ) { outValue = ( inputMode ); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"maxTouchPoints") ) { outValue = ( maxTouchPoints ); return true; }
break;
case 17:
if (HX_FIELD_EQ(inName,"supportedGestures") ) { outValue = ( supportedGestures ); return true; }
break;
case 19:
if (HX_FIELD_EQ(inName,"supportsTouchEvents") ) { if (inCallProp == ::hx::paccAlways) { outValue = ( get_supportsTouchEvents() ); return true; } }
break;
case 21:
if (HX_FIELD_EQ(inName,"supportsGestureEvents") ) { outValue = ( supportsGestureEvents ); return true; }
break;
case 23:
if (HX_FIELD_EQ(inName,"get_supportsTouchEvents") ) { outValue = get_supportsTouchEvents_dyn(); return true; }
}
return false;
}
bool Multitouch_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 9:
if (HX_FIELD_EQ(inName,"inputMode") ) { inputMode=ioValue.Cast< ::Dynamic >(); return true; }
break;
case 14:
if (HX_FIELD_EQ(inName,"maxTouchPoints") ) { maxTouchPoints=ioValue.Cast< int >(); return true; }
break;
case 17:
if (HX_FIELD_EQ(inName,"supportedGestures") ) { supportedGestures=ioValue.Cast< ::openfl::_Vector::ObjectVector >(); return true; }
break;
case 21:
if (HX_FIELD_EQ(inName,"supportsGestureEvents") ) { supportsGestureEvents=ioValue.Cast< bool >(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *Multitouch_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo Multitouch_obj_sStaticStorageInfo[] = {
{::hx::fsObject /* ::Dynamic */ ,(void *) &Multitouch_obj::inputMode,HX_("inputMode",8d,90,8b,0f)},
{::hx::fsInt,(void *) &Multitouch_obj::maxTouchPoints,HX_("maxTouchPoints",fe,7e,0e,64)},
{::hx::fsObject /* ::openfl::_Vector::ObjectVector */ ,(void *) &Multitouch_obj::supportedGestures,HX_("supportedGestures",18,be,c8,bc)},
{::hx::fsBool,(void *) &Multitouch_obj::supportsGestureEvents,HX_("supportsGestureEvents",5e,d6,ce,30)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static void Multitouch_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(Multitouch_obj::inputMode,"inputMode");
HX_MARK_MEMBER_NAME(Multitouch_obj::maxTouchPoints,"maxTouchPoints");
HX_MARK_MEMBER_NAME(Multitouch_obj::supportedGestures,"supportedGestures");
HX_MARK_MEMBER_NAME(Multitouch_obj::supportsGestureEvents,"supportsGestureEvents");
};
#ifdef HXCPP_VISIT_ALLOCS
static void Multitouch_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(Multitouch_obj::inputMode,"inputMode");
HX_VISIT_MEMBER_NAME(Multitouch_obj::maxTouchPoints,"maxTouchPoints");
HX_VISIT_MEMBER_NAME(Multitouch_obj::supportedGestures,"supportedGestures");
HX_VISIT_MEMBER_NAME(Multitouch_obj::supportsGestureEvents,"supportsGestureEvents");
};
#endif
::hx::Class Multitouch_obj::__mClass;
static ::String Multitouch_obj_sStaticFields[] = {
HX_("inputMode",8d,90,8b,0f),
HX_("maxTouchPoints",fe,7e,0e,64),
HX_("supportedGestures",18,be,c8,bc),
HX_("supportsGestureEvents",5e,d6,ce,30),
HX_("get_supportsTouchEvents",ab,97,f3,72),
::String(null())
};
void Multitouch_obj::__register()
{
Multitouch_obj _hx_dummy;
Multitouch_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.ui.Multitouch",42,0d,e8,9b);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Multitouch_obj::__GetStatic;
__mClass->mSetStaticField = &Multitouch_obj::__SetStatic;
__mClass->mMarkFunc = Multitouch_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(Multitouch_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< Multitouch_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = Multitouch_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Multitouch_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Multitouch_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void Multitouch_obj::__boot()
{
}
} // end namespace openfl
} // end namespace ui
| 6,503 | 2,757 |
#include "renderer.h"
#include "config.hpp"
extern Config conf;
void Renderer::setCamera(Camera *cam) { this->camera = cam; };
void Renderer::addLight(Light *light) { this->lights.push_back(light); };
void Renderer::setVolume(Volume *vol) { this->volume = vol; };
void Renderer::setClassifier(Classifier *classifier) { this->classifier = classifier; };
void Renderer::setInterpolator(Interpolator *interpolator) { this->interpolator = interpolator; };
opticsData Renderer::getOpticsData(const Ray &ray, float t, float dt)
{
/* Get position of the sampled point */
Eigen::Vector3f vo_p = ray.getPoint(t);
/* Retrieve located voxel */
voxel vo = this->volume->getVoxel(vo_p);
/* Interpolate voxel data by its located voxel */
volumeData vol_d = this->interpolator->interpolate(vo_p, vo);
/* Get optical data by transfer function */
opticsData opt_d = this->classifier->transfer(vol_d, dt, this->camera, this->lights, this->volume->grad_maxnorm);
return opt_d;
};
void Renderer::renderFrontToBack(std::string imgPath)
{
float dt = conf.sample_step;
#pragma omp parallel for
for (int i = 0; i < camera->m_Film.m_Res.x() * camera->m_Film.m_Res.y(); i++)
{
int dy = i / camera->m_Film.m_Res.x();
int dx = i - dy * camera->m_Film.m_Res.x();
Eigen::Vector3f color(0, 0, 0);
Eigen::Vector3f alpha(0, 0, 0);
Ray ray = camera->generateRay((float)dx, (float)dy);
float t_start, t_end;
/* Integration calculation */
if (this->volume->getRayStartEnd(ray, t_start, t_end))
{
float t = t_start;
while (t <= t_end)
{
/* Get optical data at position t */
opticsData opt_d = getOpticsData(ray, t, dt);
/* Composition */
Compositor::compositeFrontToBack(color, alpha, opt_d.getColor(), opt_d.getOpacity());
t += dt;
}
}
camera->setPixel(dx, dy, color);
}
camera->m_Film.write(imgPath);
};
void Renderer::renderBackToFront(std::string imgPath)
{
float dt = conf.sample_step;
#pragma omp parallel for
for (int i = 0; i < camera->m_Film.m_Res.x() * camera->m_Film.m_Res.y(); i++)
{
int dy = i / camera->m_Film.m_Res.x();
int dx = i - dy * camera->m_Film.m_Res.x();
Eigen::Vector3f color(0, 0, 0);
Ray ray = camera->generateRay((float)dx, (float)dy);
float t_start, t_end;
/* Integration calculation */
if (this->volume->getRayStartEnd(ray, t_start, t_end))
{
float t = t_end;
while (t >= t_start)
{
/* Get optical data at position t */
opticsData opt_d = getOpticsData(ray, t, dt);
/* Composition */
Compositor::compositeBackToFront(color, opt_d.getColor(), opt_d.getOpacity());
t -= dt;
}
}
camera->setPixel(dx, dy, color);
}
camera->m_Film.write(imgPath);
}; | 3,049 | 1,031 |
/*
* Copyright 2017 Facebook, Inc.
* Copyright 2017 Yeolar
*
* 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 "accelerator/thread/Futex.h"
#include <cerrno>
#include <linux/futex.h>
#include <sys/syscall.h>
namespace acc {
namespace {
////////////////////////////////////////////////////
// native implementation using the futex() syscall
int nativeFutexWake(void* addr, int count, uint32_t wakeMask) {
int rv = syscall(__NR_futex,
addr, /* addr1 */
FUTEX_WAKE_BITSET | FUTEX_PRIVATE_FLAG, /* op */
count, /* val */
nullptr, /* timeout */
nullptr, /* addr2 */
wakeMask); /* val3 */
/* NOTE: we ignore errors on wake for the case of a futex
guarding its own destruction, similar to this
glibc bug with sem_post/sem_wait:
https://sourceware.org/bugzilla/show_bug.cgi?id=12674 */
if (rv < 0) {
return 0;
}
return rv;
}
FutexResult nativeFutexWaitImpl(void* addr,
uint32_t expected,
struct timespec* timeout,
uint32_t waitMask) {
// Unlike FUTEX_WAIT, FUTEX_WAIT_BITSET requires an absolute timeout
// value - http://locklessinc.com/articles/futex_cheat_sheet/
int rv = syscall(__NR_futex,
addr, /* addr1 */
FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG
| FUTEX_CLOCK_REALTIME, /* op */
expected, /* val */
timeout, /* timeout */
nullptr, /* addr2 */
waitMask); /* val3 */
if (rv == 0) {
return FutexResult::AWOKEN;
} else {
switch(errno) {
case ETIMEDOUT:
assert(timeout != nullptr);
return FutexResult::TIMEDOUT;
case EINTR:
return FutexResult::INTERRUPTED;
case EWOULDBLOCK:
return FutexResult::VALUE_CHANGED;
default:
assert(false);
// EINVAL, EACCESS, or EFAULT. EINVAL means there was an invalid
// op (should be impossible) or an invalid timeout (should have
// been sanitized by timeSpecFromTimePoint). EACCESS or EFAULT
// means *addr points to invalid memory, which is unlikely because
// the caller should have segfaulted already. We can either
// crash, or return a value that lets the process continue for
// a bit. We choose the latter. VALUE_CHANGED probably turns the
// caller into a spin lock.
return FutexResult::VALUE_CHANGED;
}
}
}
} // namespace
int Futex::futexWake(int count, uint32_t wakeMask) {
return nativeFutexWake(this, count, wakeMask);
}
FutexResult Futex::futexWaitImpl(uint32_t expected,
struct timespec* timeout,
uint32_t waitMask) {
return nativeFutexWaitImpl(this, expected, timeout, waitMask);
}
} // namespace acc
| 3,482 | 1,065 |
#include <sstream>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#define PIXELS_WIDE 25
#define PIXELS_TALL 6
#define ASCII_ZERO 48
template <class T>
std::vector<T> extract_subvector(std::vector<T> v, int begin_index, int end_index) {
auto begin = v.begin() + begin_index;
auto end = v.begin() + end_index;
std::vector<T> subvector(begin, end);
return subvector;
}
int** alloc_array(int tall, int wide) {
// dynamically allocates memory for pixels_wide
// number continuously of integer pointers and
// returns pointer to the 1st element of the
// sequence
int** p = new int*[tall];
// p[0] is first element, p[2] is second etc.
// p is a pointer to first element
for(int i = 0; i < tall; i++) {
p[i] = new int[wide];
}
return p;
}
int** ini_to_negative_value(int tall, int wide) {
// dynamically allocates memory for pixels_wide
// number continuously of integer pointers and
// returns pointer to the 1st element of the
// sequence
int** p = new int*[tall];
// p[0] is first element, p[2] is second etc.
// p is a pointer to first element
for(int i = 0; i < tall; i++) {
p[i] = new int[wide];
for(int j = 0; j < wide; j++) {
p[i][j] = -1;
}
}
return p;
}
/**
* image cosists of layers, each layer has matrix
* matrix has defined number of pixels wide and tall
* */
class Layer
{
private:
int wide;
int tall;
int calculate_occurence(int element) {
int count = 0;
for(int i = 0; i < tall; i++) {
for(int j = 0; j < wide; j++) {
if(matrix[i][j] == element) {
count++;
}
}
}
return count;
}
int** build_matrix(std::vector<int> elements) {
int **p = alloc_array(tall, wide);
for(int i = 0; i <tall ; i++) {
for(int j = 0; j <wide ; j++) {
p[i][j] = elements[i*wide+j];
}
}
return p;
}
public:
int **matrix;
Layer(int pixels_wide, int pixels_tall,
std::vector<int> elements)
{
wide = pixels_wide;
tall = pixels_tall;
matrix = build_matrix(elements);
}
int get_zero() {
return calculate_occurence(0);
}
int get_one() {
return calculate_occurence(1);
}
int get_two() {
return calculate_occurence(2);
}
};
int main() {
std::ifstream file("day8.txt");
std::string str;
std::getline(file, str);
std::stringstream ss(str);
std::vector<int> elements;
std::for_each(str.begin(), str.end(), [&](char c)
{elements.push_back((int)c-ASCII_ZERO);});
int elements_in_layer = PIXELS_WIDE*PIXELS_TALL;
int number_of_layers = elements.size()/elements_in_layer;
std::vector<Layer> image;
int min = PIXELS_WIDE*PIXELS_TALL;
int mul = 0;
int** visible_pixels = ini_to_negative_value(PIXELS_TALL, PIXELS_WIDE);
for(int i = 0; i < number_of_layers; i++) {
int begin = i*elements_in_layer;
int end = i == 0 ? i*elements_in_layer + elements_in_layer : i*elements_in_layer + 1 + elements_in_layer;
Layer l(PIXELS_WIDE, PIXELS_TALL,
extract_subvector(elements, begin, end));
image.push_back(l);
if(l.get_zero() < min) {
min = l.get_zero();
mul = l.get_one() * l.get_two();
}
for(int j = 0; j < PIXELS_TALL; j++) {
for(int k = 0; k < PIXELS_WIDE; k++) {
if(visible_pixels[j][k] < 0 && l.matrix[j][k] != 2) {
visible_pixels[j][k] = l.matrix[j][k];
}
}
}
}
std::cout << "part1 = " << mul << std::endl;
std::cout << "part2: " << std::endl;
for(int j = 0; j < PIXELS_TALL; j++) {
for(int k = 0; k < PIXELS_WIDE; k++) {
if(visible_pixels[j][k] == 0)
std::cout << " ";
else
std::cout << visible_pixels[j][k];
}
std::cout << std::endl;
}
} | 4,354 | 1,511 |
/*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include <fcntl.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <string>
#include "eckit/config/Resource.h"
#include "eckit/exception/Exceptions.h"
#include "eckit/runtime/Application.h"
using namespace eckit;
class Test : public Application {
virtual void run();
public:
Test(int argc, char** argv) :
Application(argc, argv, "HOME") {}
};
const size_t SIZE = 1024;
const char* PATH = "/eckit-shmem-ipc";
const char* FULL = "/eckit-shmem-ipc-full";
const char* EMPTY = "/eckit-shmem-ipc-empty";
class NamedSemaphore {
public:
NamedSemaphore(const std::string& name, int value, bool create = true, bool unlink = false, int mode = 0664);
~NamedSemaphore();
void wait();
void post();
private:
std::string name_;
bool unlink_;
sem_t* semaphore_ = SEM_FAILED;
};
NamedSemaphore::NamedSemaphore(const std::string& name, int value, bool create, bool unlink, int mode) :
name_(name), unlink_(unlink) {
semaphore_ = sem_open(name_.c_str(), create ? O_CREAT : 0, mode, value);
if (semaphore_ == SEM_FAILED) {
throw FailedSystemCall("sem_open(" + name_ + ")");
}
}
NamedSemaphore::~NamedSemaphore() {
if (semaphore_ != SEM_FAILED) {
SYSCALL(::sem_close(semaphore_));
}
if (unlink_) {
SYSCALL(::sem_unlink(name_.c_str()));
}
}
void NamedSemaphore::wait() {
SYSCALL(::sem_wait(semaphore_));
}
void NamedSemaphore::post() {
SYSCALL(::sem_post(semaphore_));
}
void writer() {
// shm_unlink(PATH);
int fd = SYSCALL(shm_open(PATH, O_RDWR | O_CREAT, 0644));
struct stat s;
SYSCALL(fstat(fd, &s));
std::cout << "SIZE " << s.st_size << std::endl;
if (s.st_size == 0) {
SYSCALL(ftruncate(fd, SIZE));
}
void* memptr = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
ASSERT(memptr != MAP_FAILED);
NamedSemaphore full(FULL, 0);
NamedSemaphore empty(EMPTY, 1);
for (size_t i = 0; i < 10; i++) {
empty.wait();
::memcpy(memptr, "hello\0", 6);
full.post();
}
SYSCALL(munmap(memptr, SIZE));
SYSCALL(close(fd));
// SYSCALL(shm_unlink(PATH));
// SYSCALL(sem_unlink(FULL));
// SYSCALL(sem_unlink(EMPTY));
}
void reader() {
int fd = SYSCALL2(shm_open(PATH, O_RDWR, 0644), PATH);
// SYSCALL(ftruncate(fd, SIZE));
void* memptr = mmap(NULL, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
ASSERT(memptr != MAP_FAILED);
NamedSemaphore full(FULL, 0);
NamedSemaphore empty(EMPTY, 1);
for (;;) {
full.wait();
std::cout << (char*)memptr << std::endl;
empty.post();
}
SYSCALL(munmap(memptr, SIZE));
SYSCALL(close(fd));
}
void Test::run() {
if (Resource<bool>("--reader", false)) {
reader();
}
else {
writer();
}
}
//----------------------------------------------------------------------------------------------------------------------
int main(int argc, char** argv) {
Test app(argc, argv);
app.start();
return 0;
}
| 3,534 | 1,391 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/protobuf/meta_graph.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "tensorflow/core/protobuf/meta_graph.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.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)
namespace tensorflow {
namespace {
const ::google::protobuf::Descriptor* MetaGraphDef_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
MetaGraphDef_reflection_ = NULL;
const ::google::protobuf::Descriptor* MetaGraphDef_MetaInfoDef_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
MetaGraphDef_MetaInfoDef_reflection_ = NULL;
const ::google::protobuf::Descriptor* MetaGraphDef_CollectionDefEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* MetaGraphDef_SignatureDefEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* CollectionDef_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CollectionDef_reflection_ = NULL;
struct CollectionDefOneofInstance {
const ::tensorflow::CollectionDef_NodeList* node_list_;
const ::tensorflow::CollectionDef_BytesList* bytes_list_;
const ::tensorflow::CollectionDef_Int64List* int64_list_;
const ::tensorflow::CollectionDef_FloatList* float_list_;
const ::tensorflow::CollectionDef_AnyList* any_list_;
}* CollectionDef_default_oneof_instance_ = NULL;
const ::google::protobuf::Descriptor* CollectionDef_NodeList_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CollectionDef_NodeList_reflection_ = NULL;
const ::google::protobuf::Descriptor* CollectionDef_BytesList_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CollectionDef_BytesList_reflection_ = NULL;
const ::google::protobuf::Descriptor* CollectionDef_Int64List_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CollectionDef_Int64List_reflection_ = NULL;
const ::google::protobuf::Descriptor* CollectionDef_FloatList_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CollectionDef_FloatList_reflection_ = NULL;
const ::google::protobuf::Descriptor* CollectionDef_AnyList_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
CollectionDef_AnyList_reflection_ = NULL;
const ::google::protobuf::Descriptor* TensorInfo_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TensorInfo_reflection_ = NULL;
struct TensorInfoOneofInstance {
::google::protobuf::internal::ArenaStringPtr name_;
const ::tensorflow::TensorInfo_CooSparse* coo_sparse_;
}* TensorInfo_default_oneof_instance_ = NULL;
const ::google::protobuf::Descriptor* TensorInfo_CooSparse_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
TensorInfo_CooSparse_reflection_ = NULL;
const ::google::protobuf::Descriptor* SignatureDef_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
SignatureDef_reflection_ = NULL;
const ::google::protobuf::Descriptor* SignatureDef_InputsEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* SignatureDef_OutputsEntry_descriptor_ = NULL;
const ::google::protobuf::Descriptor* AssetFileDef_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
AssetFileDef_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto() {
protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"tensorflow/core/protobuf/meta_graph.proto");
GOOGLE_CHECK(file != NULL);
MetaGraphDef_descriptor_ = file->message_type(0);
static const int MetaGraphDef_offsets_[6] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, meta_info_def_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, graph_def_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, saver_def_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, collection_def_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, signature_def_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, asset_file_def_),
};
MetaGraphDef_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MetaGraphDef_descriptor_,
MetaGraphDef::internal_default_instance(),
MetaGraphDef_offsets_,
-1,
-1,
-1,
sizeof(MetaGraphDef),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef, _internal_metadata_));
MetaGraphDef_MetaInfoDef_descriptor_ = MetaGraphDef_descriptor_->nested_type(0);
static const int MetaGraphDef_MetaInfoDef_offsets_[6] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, meta_graph_version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, stripped_op_list_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, any_info_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, tags_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, tensorflow_version_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, tensorflow_git_version_),
};
MetaGraphDef_MetaInfoDef_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MetaGraphDef_MetaInfoDef_descriptor_,
MetaGraphDef_MetaInfoDef::internal_default_instance(),
MetaGraphDef_MetaInfoDef_offsets_,
-1,
-1,
-1,
sizeof(MetaGraphDef_MetaInfoDef),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetaGraphDef_MetaInfoDef, _internal_metadata_));
MetaGraphDef_CollectionDefEntry_descriptor_ = MetaGraphDef_descriptor_->nested_type(1);
MetaGraphDef_SignatureDefEntry_descriptor_ = MetaGraphDef_descriptor_->nested_type(2);
CollectionDef_descriptor_ = file->message_type(1);
static const int CollectionDef_offsets_[6] = {
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(CollectionDef_default_oneof_instance_, node_list_),
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(CollectionDef_default_oneof_instance_, bytes_list_),
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(CollectionDef_default_oneof_instance_, int64_list_),
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(CollectionDef_default_oneof_instance_, float_list_),
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(CollectionDef_default_oneof_instance_, any_list_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef, kind_),
};
CollectionDef_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CollectionDef_descriptor_,
CollectionDef::internal_default_instance(),
CollectionDef_offsets_,
-1,
-1,
-1,
CollectionDef_default_oneof_instance_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef, _oneof_case_[0]),
sizeof(CollectionDef),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef, _internal_metadata_));
CollectionDef_NodeList_descriptor_ = CollectionDef_descriptor_->nested_type(0);
static const int CollectionDef_NodeList_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_NodeList, value_),
};
CollectionDef_NodeList_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CollectionDef_NodeList_descriptor_,
CollectionDef_NodeList::internal_default_instance(),
CollectionDef_NodeList_offsets_,
-1,
-1,
-1,
sizeof(CollectionDef_NodeList),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_NodeList, _internal_metadata_));
CollectionDef_BytesList_descriptor_ = CollectionDef_descriptor_->nested_type(1);
static const int CollectionDef_BytesList_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_BytesList, value_),
};
CollectionDef_BytesList_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CollectionDef_BytesList_descriptor_,
CollectionDef_BytesList::internal_default_instance(),
CollectionDef_BytesList_offsets_,
-1,
-1,
-1,
sizeof(CollectionDef_BytesList),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_BytesList, _internal_metadata_));
CollectionDef_Int64List_descriptor_ = CollectionDef_descriptor_->nested_type(2);
static const int CollectionDef_Int64List_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_Int64List, value_),
};
CollectionDef_Int64List_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CollectionDef_Int64List_descriptor_,
CollectionDef_Int64List::internal_default_instance(),
CollectionDef_Int64List_offsets_,
-1,
-1,
-1,
sizeof(CollectionDef_Int64List),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_Int64List, _internal_metadata_));
CollectionDef_FloatList_descriptor_ = CollectionDef_descriptor_->nested_type(3);
static const int CollectionDef_FloatList_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_FloatList, value_),
};
CollectionDef_FloatList_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CollectionDef_FloatList_descriptor_,
CollectionDef_FloatList::internal_default_instance(),
CollectionDef_FloatList_offsets_,
-1,
-1,
-1,
sizeof(CollectionDef_FloatList),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_FloatList, _internal_metadata_));
CollectionDef_AnyList_descriptor_ = CollectionDef_descriptor_->nested_type(4);
static const int CollectionDef_AnyList_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_AnyList, value_),
};
CollectionDef_AnyList_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
CollectionDef_AnyList_descriptor_,
CollectionDef_AnyList::internal_default_instance(),
CollectionDef_AnyList_offsets_,
-1,
-1,
-1,
sizeof(CollectionDef_AnyList),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CollectionDef_AnyList, _internal_metadata_));
TensorInfo_descriptor_ = file->message_type(2);
static const int TensorInfo_offsets_[5] = {
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(TensorInfo_default_oneof_instance_, name_),
PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET(TensorInfo_default_oneof_instance_, coo_sparse_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo, dtype_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo, tensor_shape_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo, encoding_),
};
TensorInfo_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TensorInfo_descriptor_,
TensorInfo::internal_default_instance(),
TensorInfo_offsets_,
-1,
-1,
-1,
TensorInfo_default_oneof_instance_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo, _oneof_case_[0]),
sizeof(TensorInfo),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo, _internal_metadata_));
TensorInfo_CooSparse_descriptor_ = TensorInfo_descriptor_->nested_type(0);
static const int TensorInfo_CooSparse_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo_CooSparse, values_tensor_name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo_CooSparse, indices_tensor_name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo_CooSparse, dense_shape_tensor_name_),
};
TensorInfo_CooSparse_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
TensorInfo_CooSparse_descriptor_,
TensorInfo_CooSparse::internal_default_instance(),
TensorInfo_CooSparse_offsets_,
-1,
-1,
-1,
sizeof(TensorInfo_CooSparse),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorInfo_CooSparse, _internal_metadata_));
SignatureDef_descriptor_ = file->message_type(3);
static const int SignatureDef_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SignatureDef, inputs_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SignatureDef, outputs_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SignatureDef, method_name_),
};
SignatureDef_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
SignatureDef_descriptor_,
SignatureDef::internal_default_instance(),
SignatureDef_offsets_,
-1,
-1,
-1,
sizeof(SignatureDef),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SignatureDef, _internal_metadata_));
SignatureDef_InputsEntry_descriptor_ = SignatureDef_descriptor_->nested_type(0);
SignatureDef_OutputsEntry_descriptor_ = SignatureDef_descriptor_->nested_type(1);
AssetFileDef_descriptor_ = file->message_type(4);
static const int AssetFileDef_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(AssetFileDef, tensor_info_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(AssetFileDef, filename_),
};
AssetFileDef_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
AssetFileDef_descriptor_,
AssetFileDef::internal_default_instance(),
AssetFileDef_offsets_,
-1,
-1,
-1,
sizeof(AssetFileDef),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(AssetFileDef, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MetaGraphDef_descriptor_, MetaGraphDef::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MetaGraphDef_MetaInfoDef_descriptor_, MetaGraphDef_MetaInfoDef::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MetaGraphDef_CollectionDefEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::tensorflow::CollectionDef,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
MetaGraphDef_CollectionDefEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MetaGraphDef_SignatureDefEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::tensorflow::SignatureDef,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
MetaGraphDef_SignatureDefEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CollectionDef_descriptor_, CollectionDef::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CollectionDef_NodeList_descriptor_, CollectionDef_NodeList::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CollectionDef_BytesList_descriptor_, CollectionDef_BytesList::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CollectionDef_Int64List_descriptor_, CollectionDef_Int64List::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CollectionDef_FloatList_descriptor_, CollectionDef_FloatList::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
CollectionDef_AnyList_descriptor_, CollectionDef_AnyList::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TensorInfo_descriptor_, TensorInfo::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
TensorInfo_CooSparse_descriptor_, TensorInfo_CooSparse::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
SignatureDef_descriptor_, SignatureDef::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
SignatureDef_InputsEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::tensorflow::TensorInfo,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
SignatureDef_InputsEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
SignatureDef_OutputsEntry_descriptor_,
::google::protobuf::internal::MapEntry<
::std::string,
::tensorflow::TensorInfo,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0>::CreateDefaultInstance(
SignatureDef_OutputsEntry_descriptor_));
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
AssetFileDef_descriptor_, AssetFileDef::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto() {
MetaGraphDef_default_instance_.Shutdown();
delete MetaGraphDef_reflection_;
MetaGraphDef_MetaInfoDef_default_instance_.Shutdown();
delete MetaGraphDef_MetaInfoDef_reflection_;
CollectionDef_default_instance_.Shutdown();
delete CollectionDef_default_oneof_instance_;
delete CollectionDef_reflection_;
CollectionDef_NodeList_default_instance_.Shutdown();
delete CollectionDef_NodeList_reflection_;
CollectionDef_BytesList_default_instance_.Shutdown();
delete CollectionDef_BytesList_reflection_;
CollectionDef_Int64List_default_instance_.Shutdown();
delete CollectionDef_Int64List_reflection_;
CollectionDef_FloatList_default_instance_.Shutdown();
delete CollectionDef_FloatList_reflection_;
CollectionDef_AnyList_default_instance_.Shutdown();
delete CollectionDef_AnyList_reflection_;
TensorInfo_default_instance_.Shutdown();
delete TensorInfo_default_oneof_instance_;
delete TensorInfo_reflection_;
TensorInfo_CooSparse_default_instance_.Shutdown();
delete TensorInfo_CooSparse_reflection_;
SignatureDef_default_instance_.Shutdown();
delete SignatureDef_reflection_;
AssetFileDef_default_instance_.Shutdown();
delete AssetFileDef_reflection_;
}
void protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::protobuf_InitDefaults_google_2fprotobuf_2fany_2eproto();
::tensorflow::protobuf_InitDefaults_tensorflow_2fcore_2fframework_2fgraph_2eproto();
::tensorflow::protobuf_InitDefaults_tensorflow_2fcore_2fframework_2fop_5fdef_2eproto();
::tensorflow::protobuf_InitDefaults_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto();
::tensorflow::protobuf_InitDefaults_tensorflow_2fcore_2fframework_2ftypes_2eproto();
::tensorflow::protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fsaver_2eproto();
::google::protobuf::internal::GetEmptyString();
MetaGraphDef_default_instance_.DefaultConstruct();
::google::protobuf::internal::GetEmptyString();
MetaGraphDef_MetaInfoDef_default_instance_.DefaultConstruct();
::google::protobuf::internal::GetEmptyString();
::google::protobuf::internal::GetEmptyString();
CollectionDef_default_instance_.DefaultConstruct();
CollectionDef_default_oneof_instance_ = new CollectionDefOneofInstance();
::google::protobuf::internal::GetEmptyString();
CollectionDef_NodeList_default_instance_.DefaultConstruct();
::google::protobuf::internal::GetEmptyString();
CollectionDef_BytesList_default_instance_.DefaultConstruct();
CollectionDef_Int64List_default_instance_.DefaultConstruct();
CollectionDef_FloatList_default_instance_.DefaultConstruct();
CollectionDef_AnyList_default_instance_.DefaultConstruct();
::google::protobuf::internal::GetEmptyString();
TensorInfo_default_instance_.DefaultConstruct();
TensorInfo_default_oneof_instance_ = new TensorInfoOneofInstance();
::google::protobuf::internal::GetEmptyString();
TensorInfo_CooSparse_default_instance_.DefaultConstruct();
::google::protobuf::internal::GetEmptyString();
SignatureDef_default_instance_.DefaultConstruct();
::google::protobuf::internal::GetEmptyString();
AssetFileDef_default_instance_.DefaultConstruct();
MetaGraphDef_default_instance_.get_mutable()->InitAsDefaultInstance();
MetaGraphDef_MetaInfoDef_default_instance_.get_mutable()->InitAsDefaultInstance();
CollectionDef_default_instance_.get_mutable()->InitAsDefaultInstance();
CollectionDef_NodeList_default_instance_.get_mutable()->InitAsDefaultInstance();
CollectionDef_BytesList_default_instance_.get_mutable()->InitAsDefaultInstance();
CollectionDef_Int64List_default_instance_.get_mutable()->InitAsDefaultInstance();
CollectionDef_FloatList_default_instance_.get_mutable()->InitAsDefaultInstance();
CollectionDef_AnyList_default_instance_.get_mutable()->InitAsDefaultInstance();
TensorInfo_default_instance_.get_mutable()->InitAsDefaultInstance();
TensorInfo_CooSparse_default_instance_.get_mutable()->InitAsDefaultInstance();
SignatureDef_default_instance_.get_mutable()->InitAsDefaultInstance();
AssetFileDef_default_instance_.get_mutable()->InitAsDefaultInstance();
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_once_);
void protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_once_,
&protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_impl);
}
void protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n)tensorflow/core/protobuf/meta_graph.pr"
"oto\022\ntensorflow\032\031google/protobuf/any.pro"
"to\032%tensorflow/core/framework/graph.prot"
"o\032&tensorflow/core/framework/op_def.prot"
"o\032,tensorflow/core/framework/tensor_shap"
"e.proto\032%tensorflow/core/framework/types"
".proto\032$tensorflow/core/protobuf/saver.p"
"roto\"\303\005\n\014MetaGraphDef\022;\n\rmeta_info_def\030\001"
" \001(\0132$.tensorflow.MetaGraphDef.MetaInfoD"
"ef\022\'\n\tgraph_def\030\002 \001(\0132\024.tensorflow.Graph"
"Def\022\'\n\tsaver_def\030\003 \001(\0132\024.tensorflow.Save"
"rDef\022C\n\016collection_def\030\004 \003(\0132+.tensorflo"
"w.MetaGraphDef.CollectionDefEntry\022A\n\rsig"
"nature_def\030\005 \003(\0132*.tensorflow.MetaGraphD"
"ef.SignatureDefEntry\0220\n\016asset_file_def\030\006"
" \003(\0132\030.tensorflow.AssetFileDef\032\311\001\n\013MetaI"
"nfoDef\022\032\n\022meta_graph_version\030\001 \001(\t\022,\n\020st"
"ripped_op_list\030\002 \001(\0132\022.tensorflow.OpList"
"\022&\n\010any_info\030\003 \001(\0132\024.google.protobuf.Any"
"\022\014\n\004tags\030\004 \003(\t\022\032\n\022tensorflow_version\030\005 \001"
"(\t\022\036\n\026tensorflow_git_version\030\006 \001(\t\032O\n\022Co"
"llectionDefEntry\022\013\n\003key\030\001 \001(\t\022(\n\005value\030\002"
" \001(\0132\031.tensorflow.CollectionDef:\0028\001\032M\n\021S"
"ignatureDefEntry\022\013\n\003key\030\001 \001(\t\022\'\n\005value\030\002"
" \001(\0132\030.tensorflow.SignatureDef:\0028\001\"\337\003\n\rC"
"ollectionDef\0227\n\tnode_list\030\001 \001(\0132\".tensor"
"flow.CollectionDef.NodeListH\000\0229\n\nbytes_l"
"ist\030\002 \001(\0132#.tensorflow.CollectionDef.Byt"
"esListH\000\0229\n\nint64_list\030\003 \001(\0132#.tensorflo"
"w.CollectionDef.Int64ListH\000\0229\n\nfloat_lis"
"t\030\004 \001(\0132#.tensorflow.CollectionDef.Float"
"ListH\000\0225\n\010any_list\030\005 \001(\0132!.tensorflow.Co"
"llectionDef.AnyListH\000\032\031\n\010NodeList\022\r\n\005val"
"ue\030\001 \003(\t\032\032\n\tBytesList\022\r\n\005value\030\001 \003(\014\032\036\n\t"
"Int64List\022\021\n\005value\030\001 \003(\003B\002\020\001\032\036\n\tFloatLis"
"t\022\021\n\005value\030\001 \003(\002B\002\020\001\032.\n\007AnyList\022#\n\005value"
"\030\001 \003(\0132\024.google.protobuf.AnyB\006\n\004kind\"\240\002\n"
"\nTensorInfo\022\016\n\004name\030\001 \001(\tH\000\0226\n\ncoo_spars"
"e\030\004 \001(\0132 .tensorflow.TensorInfo.CooSpars"
"eH\000\022#\n\005dtype\030\002 \001(\0162\024.tensorflow.DataType"
"\0222\n\014tensor_shape\030\003 \001(\0132\034.tensorflow.Tens"
"orShapeProto\032e\n\tCooSparse\022\032\n\022values_tens"
"or_name\030\001 \001(\t\022\033\n\023indices_tensor_name\030\002 \001"
"(\t\022\037\n\027dense_shape_tensor_name\030\003 \001(\tB\n\n\010e"
"ncoding\"\240\002\n\014SignatureDef\0224\n\006inputs\030\001 \003(\013"
"2$.tensorflow.SignatureDef.InputsEntry\0226"
"\n\007outputs\030\002 \003(\0132%.tensorflow.SignatureDe"
"f.OutputsEntry\022\023\n\013method_name\030\003 \001(\t\032E\n\013I"
"nputsEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026"
".tensorflow.TensorInfo:\0028\001\032F\n\014OutputsEnt"
"ry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.tensorf"
"low.TensorInfo:\0028\001\"M\n\014AssetFileDef\022+\n\013te"
"nsor_info\030\001 \001(\0132\026.tensorflow.TensorInfo\022"
"\020\n\010filename\030\002 \001(\tB0\n\030org.tensorflow.fram"
"eworkB\017MetaGraphProtosP\001\370\001\001b\006proto3", 2195);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"tensorflow/core/protobuf/meta_graph.proto", &protobuf_RegisterTypes);
::google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fany_2eproto();
::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2fgraph_2eproto();
::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2fop_5fdef_2eproto();
::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto();
::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftypes_2eproto();
::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fsaver_2eproto();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto);
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_once_);
void protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_once_,
&protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_impl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto {
StaticDescriptorInitializer_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto() {
protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
}
} static_descriptor_initializer_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto_;
namespace {
static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
static void MergeFromFail(int line) {
::google::protobuf::internal::MergeFromFail(__FILE__, line);
}
} // namespace
// ===================================================================
void MetaGraphDef_MetaInfoDef::_slow_mutable_stripped_op_list() {
stripped_op_list_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::OpList >(
GetArenaNoVirtual());
}
::tensorflow::OpList* MetaGraphDef_MetaInfoDef::_slow_release_stripped_op_list() {
if (stripped_op_list_ == NULL) {
return NULL;
} else {
::tensorflow::OpList* temp = new ::tensorflow::OpList(*stripped_op_list_);
stripped_op_list_ = NULL;
return temp;
}
}
::tensorflow::OpList* MetaGraphDef_MetaInfoDef::unsafe_arena_release_stripped_op_list() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.MetaInfoDef.stripped_op_list)
::tensorflow::OpList* temp = stripped_op_list_;
stripped_op_list_ = NULL;
return temp;
}
void MetaGraphDef_MetaInfoDef::_slow_set_allocated_stripped_op_list(
::google::protobuf::Arena* message_arena, ::tensorflow::OpList** stripped_op_list) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*stripped_op_list) == NULL) {
message_arena->Own(*stripped_op_list);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*stripped_op_list)) {
::tensorflow::OpList* new_stripped_op_list =
::google::protobuf::Arena::CreateMessage< ::tensorflow::OpList >(
message_arena);
new_stripped_op_list->CopyFrom(**stripped_op_list);
*stripped_op_list = new_stripped_op_list;
}
}
void MetaGraphDef_MetaInfoDef::unsafe_arena_set_allocated_stripped_op_list(
::tensorflow::OpList* stripped_op_list) {
if (GetArenaNoVirtual() == NULL) {
delete stripped_op_list_;
}
stripped_op_list_ = stripped_op_list;
if (stripped_op_list) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.stripped_op_list)
}
void MetaGraphDef_MetaInfoDef::_slow_mutable_any_info() {
any_info_ = ::google::protobuf::Arena::Create< ::google::protobuf::Any >(
GetArenaNoVirtual());
}
::google::protobuf::Any* MetaGraphDef_MetaInfoDef::_slow_release_any_info() {
if (any_info_ == NULL) {
return NULL;
} else {
::google::protobuf::Any* temp = new ::google::protobuf::Any(*any_info_);
any_info_ = NULL;
return temp;
}
}
::google::protobuf::Any* MetaGraphDef_MetaInfoDef::unsafe_arena_release_any_info() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.MetaInfoDef.any_info)
::google::protobuf::Any* temp = any_info_;
any_info_ = NULL;
return temp;
}
void MetaGraphDef_MetaInfoDef::unsafe_arena_set_allocated_any_info(
::google::protobuf::Any* any_info) {
if (GetArenaNoVirtual() == NULL) {
delete any_info_;
}
any_info_ = any_info;
if (any_info) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.any_info)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MetaGraphDef_MetaInfoDef::kMetaGraphVersionFieldNumber;
const int MetaGraphDef_MetaInfoDef::kStrippedOpListFieldNumber;
const int MetaGraphDef_MetaInfoDef::kAnyInfoFieldNumber;
const int MetaGraphDef_MetaInfoDef::kTagsFieldNumber;
const int MetaGraphDef_MetaInfoDef::kTensorflowVersionFieldNumber;
const int MetaGraphDef_MetaInfoDef::kTensorflowGitVersionFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MetaGraphDef_MetaInfoDef::MetaGraphDef_MetaInfoDef()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.MetaGraphDef.MetaInfoDef)
}
MetaGraphDef_MetaInfoDef::MetaGraphDef_MetaInfoDef(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
tags_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.MetaGraphDef.MetaInfoDef)
}
void MetaGraphDef_MetaInfoDef::InitAsDefaultInstance() {
stripped_op_list_ = const_cast< ::tensorflow::OpList*>(
::tensorflow::OpList::internal_default_instance());
any_info_ = const_cast< ::google::protobuf::Any*>(
::google::protobuf::Any::internal_default_instance());
}
MetaGraphDef_MetaInfoDef::MetaGraphDef_MetaInfoDef(const MetaGraphDef_MetaInfoDef& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.MetaGraphDef.MetaInfoDef)
}
void MetaGraphDef_MetaInfoDef::SharedCtor() {
meta_graph_version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
tensorflow_version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
tensorflow_git_version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
stripped_op_list_ = NULL;
any_info_ = NULL;
_cached_size_ = 0;
}
MetaGraphDef_MetaInfoDef::~MetaGraphDef_MetaInfoDef() {
// @@protoc_insertion_point(destructor:tensorflow.MetaGraphDef.MetaInfoDef)
SharedDtor();
}
void MetaGraphDef_MetaInfoDef::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
meta_graph_version_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
tensorflow_version_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
tensorflow_git_version_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
if (this != &MetaGraphDef_MetaInfoDef_default_instance_.get()) {
delete stripped_op_list_;
delete any_info_;
}
}
void MetaGraphDef_MetaInfoDef::ArenaDtor(void* object) {
MetaGraphDef_MetaInfoDef* _this = reinterpret_cast< MetaGraphDef_MetaInfoDef* >(object);
(void)_this;
}
void MetaGraphDef_MetaInfoDef::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MetaGraphDef_MetaInfoDef::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MetaGraphDef_MetaInfoDef::descriptor() {
protobuf_AssignDescriptorsOnce();
return MetaGraphDef_MetaInfoDef_descriptor_;
}
const MetaGraphDef_MetaInfoDef& MetaGraphDef_MetaInfoDef::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<MetaGraphDef_MetaInfoDef> MetaGraphDef_MetaInfoDef_default_instance_;
MetaGraphDef_MetaInfoDef* MetaGraphDef_MetaInfoDef::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<MetaGraphDef_MetaInfoDef>(arena);
}
void MetaGraphDef_MetaInfoDef::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.MetaGraphDef.MetaInfoDef)
meta_graph_version_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == NULL && stripped_op_list_ != NULL) delete stripped_op_list_;
stripped_op_list_ = NULL;
if (GetArenaNoVirtual() == NULL && any_info_ != NULL) delete any_info_;
any_info_ = NULL;
tensorflow_version_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
tensorflow_git_version_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
tags_.Clear();
}
bool MetaGraphDef_MetaInfoDef::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.MetaGraphDef.MetaInfoDef)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string meta_graph_version = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_meta_graph_version()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->meta_graph_version().data(), this->meta_graph_version().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_stripped_op_list;
break;
}
// optional .tensorflow.OpList stripped_op_list = 2;
case 2: {
if (tag == 18) {
parse_stripped_op_list:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_stripped_op_list()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_any_info;
break;
}
// optional .google.protobuf.Any any_info = 3;
case 3: {
if (tag == 26) {
parse_any_info:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_any_info()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_tags;
break;
}
// repeated string tags = 4;
case 4: {
if (tag == 34) {
parse_tags:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_tags()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tags(this->tags_size() - 1).data(),
this->tags(this->tags_size() - 1).length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.MetaGraphDef.MetaInfoDef.tags"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_tags;
if (input->ExpectTag(42)) goto parse_tensorflow_version;
break;
}
// optional string tensorflow_version = 5;
case 5: {
if (tag == 42) {
parse_tensorflow_version:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_tensorflow_version()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tensorflow_version().data(), this->tensorflow_version().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(50)) goto parse_tensorflow_git_version;
break;
}
// optional string tensorflow_git_version = 6;
case 6: {
if (tag == 50) {
parse_tensorflow_git_version:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_tensorflow_git_version()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tensorflow_git_version().data(), this->tensorflow_git_version().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version"));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.MetaGraphDef.MetaInfoDef)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.MetaGraphDef.MetaInfoDef)
return false;
#undef DO_
}
void MetaGraphDef_MetaInfoDef::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.MetaGraphDef.MetaInfoDef)
// optional string meta_graph_version = 1;
if (this->meta_graph_version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->meta_graph_version().data(), this->meta_graph_version().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->meta_graph_version(), output);
}
// optional .tensorflow.OpList stripped_op_list = 2;
if (this->has_stripped_op_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *this->stripped_op_list_, output);
}
// optional .google.protobuf.Any any_info = 3;
if (this->has_any_info()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->any_info_, output);
}
// repeated string tags = 4;
for (int i = 0; i < this->tags_size(); i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tags(i).data(), this->tags(i).length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.tags");
::google::protobuf::internal::WireFormatLite::WriteString(
4, this->tags(i), output);
}
// optional string tensorflow_version = 5;
if (this->tensorflow_version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tensorflow_version().data(), this->tensorflow_version().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
5, this->tensorflow_version(), output);
}
// optional string tensorflow_git_version = 6;
if (this->tensorflow_git_version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tensorflow_git_version().data(), this->tensorflow_git_version().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
6, this->tensorflow_git_version(), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.MetaGraphDef.MetaInfoDef)
}
::google::protobuf::uint8* MetaGraphDef_MetaInfoDef::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.MetaGraphDef.MetaInfoDef)
// optional string meta_graph_version = 1;
if (this->meta_graph_version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->meta_graph_version().data(), this->meta_graph_version().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->meta_graph_version(), target);
}
// optional .tensorflow.OpList stripped_op_list = 2;
if (this->has_stripped_op_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *this->stripped_op_list_, false, target);
}
// optional .google.protobuf.Any any_info = 3;
if (this->has_any_info()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->any_info_, false, target);
}
// repeated string tags = 4;
for (int i = 0; i < this->tags_size(); i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tags(i).data(), this->tags(i).length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.tags");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(4, this->tags(i), target);
}
// optional string tensorflow_version = 5;
if (this->tensorflow_version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tensorflow_version().data(), this->tensorflow_version().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
5, this->tensorflow_version(), target);
}
// optional string tensorflow_git_version = 6;
if (this->tensorflow_git_version().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->tensorflow_git_version().data(), this->tensorflow_git_version().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
6, this->tensorflow_git_version(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.MetaGraphDef.MetaInfoDef)
return target;
}
size_t MetaGraphDef_MetaInfoDef::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.MetaGraphDef.MetaInfoDef)
size_t total_size = 0;
// optional string meta_graph_version = 1;
if (this->meta_graph_version().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->meta_graph_version());
}
// optional .tensorflow.OpList stripped_op_list = 2;
if (this->has_stripped_op_list()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->stripped_op_list_);
}
// optional .google.protobuf.Any any_info = 3;
if (this->has_any_info()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->any_info_);
}
// optional string tensorflow_version = 5;
if (this->tensorflow_version().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->tensorflow_version());
}
// optional string tensorflow_git_version = 6;
if (this->tensorflow_git_version().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->tensorflow_git_version());
}
// repeated string tags = 4;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->tags_size());
for (int i = 0; i < this->tags_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->tags(i));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MetaGraphDef_MetaInfoDef::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.MetaGraphDef.MetaInfoDef)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const MetaGraphDef_MetaInfoDef* source =
::google::protobuf::internal::DynamicCastToGenerated<const MetaGraphDef_MetaInfoDef>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.MetaGraphDef.MetaInfoDef)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.MetaGraphDef.MetaInfoDef)
UnsafeMergeFrom(*source);
}
}
void MetaGraphDef_MetaInfoDef::MergeFrom(const MetaGraphDef_MetaInfoDef& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.MetaGraphDef.MetaInfoDef)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void MetaGraphDef_MetaInfoDef::UnsafeMergeFrom(const MetaGraphDef_MetaInfoDef& from) {
GOOGLE_DCHECK(&from != this);
tags_.UnsafeMergeFrom(from.tags_);
if (from.meta_graph_version().size() > 0) {
set_meta_graph_version(from.meta_graph_version());
}
if (from.has_stripped_op_list()) {
mutable_stripped_op_list()->::tensorflow::OpList::MergeFrom(from.stripped_op_list());
}
if (from.has_any_info()) {
mutable_any_info()->::google::protobuf::Any::MergeFrom(from.any_info());
}
if (from.tensorflow_version().size() > 0) {
set_tensorflow_version(from.tensorflow_version());
}
if (from.tensorflow_git_version().size() > 0) {
set_tensorflow_git_version(from.tensorflow_git_version());
}
}
void MetaGraphDef_MetaInfoDef::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.MetaGraphDef.MetaInfoDef)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MetaGraphDef_MetaInfoDef::CopyFrom(const MetaGraphDef_MetaInfoDef& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.MetaGraphDef.MetaInfoDef)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool MetaGraphDef_MetaInfoDef::IsInitialized() const {
return true;
}
void MetaGraphDef_MetaInfoDef::Swap(MetaGraphDef_MetaInfoDef* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
MetaGraphDef_MetaInfoDef temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void MetaGraphDef_MetaInfoDef::UnsafeArenaSwap(MetaGraphDef_MetaInfoDef* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MetaGraphDef_MetaInfoDef::InternalSwap(MetaGraphDef_MetaInfoDef* other) {
meta_graph_version_.Swap(&other->meta_graph_version_);
std::swap(stripped_op_list_, other->stripped_op_list_);
std::swap(any_info_, other->any_info_);
tags_.UnsafeArenaSwap(&other->tags_);
tensorflow_version_.Swap(&other->tensorflow_version_);
tensorflow_git_version_.Swap(&other->tensorflow_git_version_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MetaGraphDef_MetaInfoDef::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = MetaGraphDef_MetaInfoDef_descriptor_;
metadata.reflection = MetaGraphDef_MetaInfoDef_reflection_;
return metadata;
}
// -------------------------------------------------------------------
void MetaGraphDef::_slow_mutable_meta_info_def() {
meta_info_def_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::MetaGraphDef_MetaInfoDef >(
GetArenaNoVirtual());
}
::tensorflow::MetaGraphDef_MetaInfoDef* MetaGraphDef::_slow_release_meta_info_def() {
if (meta_info_def_ == NULL) {
return NULL;
} else {
::tensorflow::MetaGraphDef_MetaInfoDef* temp = new ::tensorflow::MetaGraphDef_MetaInfoDef(*meta_info_def_);
meta_info_def_ = NULL;
return temp;
}
}
::tensorflow::MetaGraphDef_MetaInfoDef* MetaGraphDef::unsafe_arena_release_meta_info_def() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.meta_info_def)
::tensorflow::MetaGraphDef_MetaInfoDef* temp = meta_info_def_;
meta_info_def_ = NULL;
return temp;
}
void MetaGraphDef::_slow_set_allocated_meta_info_def(
::google::protobuf::Arena* message_arena, ::tensorflow::MetaGraphDef_MetaInfoDef** meta_info_def) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*meta_info_def) == NULL) {
message_arena->Own(*meta_info_def);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*meta_info_def)) {
::tensorflow::MetaGraphDef_MetaInfoDef* new_meta_info_def =
::google::protobuf::Arena::CreateMessage< ::tensorflow::MetaGraphDef_MetaInfoDef >(
message_arena);
new_meta_info_def->CopyFrom(**meta_info_def);
*meta_info_def = new_meta_info_def;
}
}
void MetaGraphDef::unsafe_arena_set_allocated_meta_info_def(
::tensorflow::MetaGraphDef_MetaInfoDef* meta_info_def) {
if (GetArenaNoVirtual() == NULL) {
delete meta_info_def_;
}
meta_info_def_ = meta_info_def;
if (meta_info_def) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.meta_info_def)
}
void MetaGraphDef::_slow_mutable_graph_def() {
graph_def_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::GraphDef >(
GetArenaNoVirtual());
}
::tensorflow::GraphDef* MetaGraphDef::_slow_release_graph_def() {
if (graph_def_ == NULL) {
return NULL;
} else {
::tensorflow::GraphDef* temp = new ::tensorflow::GraphDef(*graph_def_);
graph_def_ = NULL;
return temp;
}
}
::tensorflow::GraphDef* MetaGraphDef::unsafe_arena_release_graph_def() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.graph_def)
::tensorflow::GraphDef* temp = graph_def_;
graph_def_ = NULL;
return temp;
}
void MetaGraphDef::_slow_set_allocated_graph_def(
::google::protobuf::Arena* message_arena, ::tensorflow::GraphDef** graph_def) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*graph_def) == NULL) {
message_arena->Own(*graph_def);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*graph_def)) {
::tensorflow::GraphDef* new_graph_def =
::google::protobuf::Arena::CreateMessage< ::tensorflow::GraphDef >(
message_arena);
new_graph_def->CopyFrom(**graph_def);
*graph_def = new_graph_def;
}
}
void MetaGraphDef::unsafe_arena_set_allocated_graph_def(
::tensorflow::GraphDef* graph_def) {
if (GetArenaNoVirtual() == NULL) {
delete graph_def_;
}
graph_def_ = graph_def;
if (graph_def) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.graph_def)
}
void MetaGraphDef::_slow_mutable_saver_def() {
saver_def_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::SaverDef >(
GetArenaNoVirtual());
}
::tensorflow::SaverDef* MetaGraphDef::_slow_release_saver_def() {
if (saver_def_ == NULL) {
return NULL;
} else {
::tensorflow::SaverDef* temp = new ::tensorflow::SaverDef(*saver_def_);
saver_def_ = NULL;
return temp;
}
}
::tensorflow::SaverDef* MetaGraphDef::unsafe_arena_release_saver_def() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.saver_def)
::tensorflow::SaverDef* temp = saver_def_;
saver_def_ = NULL;
return temp;
}
void MetaGraphDef::_slow_set_allocated_saver_def(
::google::protobuf::Arena* message_arena, ::tensorflow::SaverDef** saver_def) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*saver_def) == NULL) {
message_arena->Own(*saver_def);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*saver_def)) {
::tensorflow::SaverDef* new_saver_def =
::google::protobuf::Arena::CreateMessage< ::tensorflow::SaverDef >(
message_arena);
new_saver_def->CopyFrom(**saver_def);
*saver_def = new_saver_def;
}
}
void MetaGraphDef::unsafe_arena_set_allocated_saver_def(
::tensorflow::SaverDef* saver_def) {
if (GetArenaNoVirtual() == NULL) {
delete saver_def_;
}
saver_def_ = saver_def;
if (saver_def) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.saver_def)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MetaGraphDef::kMetaInfoDefFieldNumber;
const int MetaGraphDef::kGraphDefFieldNumber;
const int MetaGraphDef::kSaverDefFieldNumber;
const int MetaGraphDef::kCollectionDefFieldNumber;
const int MetaGraphDef::kSignatureDefFieldNumber;
const int MetaGraphDef::kAssetFileDefFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MetaGraphDef::MetaGraphDef()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.MetaGraphDef)
}
MetaGraphDef::MetaGraphDef(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
collection_def_(arena),
signature_def_(arena),
asset_file_def_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.MetaGraphDef)
}
void MetaGraphDef::InitAsDefaultInstance() {
meta_info_def_ = const_cast< ::tensorflow::MetaGraphDef_MetaInfoDef*>(
::tensorflow::MetaGraphDef_MetaInfoDef::internal_default_instance());
graph_def_ = const_cast< ::tensorflow::GraphDef*>(
::tensorflow::GraphDef::internal_default_instance());
saver_def_ = const_cast< ::tensorflow::SaverDef*>(
::tensorflow::SaverDef::internal_default_instance());
}
MetaGraphDef::MetaGraphDef(const MetaGraphDef& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.MetaGraphDef)
}
void MetaGraphDef::SharedCtor() {
collection_def_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
collection_def_.SetEntryDescriptor(
&::tensorflow::MetaGraphDef_CollectionDefEntry_descriptor_);
signature_def_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
signature_def_.SetEntryDescriptor(
&::tensorflow::MetaGraphDef_SignatureDefEntry_descriptor_);
meta_info_def_ = NULL;
graph_def_ = NULL;
saver_def_ = NULL;
_cached_size_ = 0;
}
MetaGraphDef::~MetaGraphDef() {
// @@protoc_insertion_point(destructor:tensorflow.MetaGraphDef)
SharedDtor();
}
void MetaGraphDef::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
if (this != &MetaGraphDef_default_instance_.get()) {
delete meta_info_def_;
delete graph_def_;
delete saver_def_;
}
}
void MetaGraphDef::ArenaDtor(void* object) {
MetaGraphDef* _this = reinterpret_cast< MetaGraphDef* >(object);
(void)_this;
}
void MetaGraphDef::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void MetaGraphDef::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MetaGraphDef::descriptor() {
protobuf_AssignDescriptorsOnce();
return MetaGraphDef_descriptor_;
}
const MetaGraphDef& MetaGraphDef::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<MetaGraphDef> MetaGraphDef_default_instance_;
MetaGraphDef* MetaGraphDef::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<MetaGraphDef>(arena);
}
void MetaGraphDef::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.MetaGraphDef)
if (GetArenaNoVirtual() == NULL && meta_info_def_ != NULL) delete meta_info_def_;
meta_info_def_ = NULL;
if (GetArenaNoVirtual() == NULL && graph_def_ != NULL) delete graph_def_;
graph_def_ = NULL;
if (GetArenaNoVirtual() == NULL && saver_def_ != NULL) delete saver_def_;
saver_def_ = NULL;
collection_def_.Clear();
signature_def_.Clear();
asset_file_def_.Clear();
}
bool MetaGraphDef::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.MetaGraphDef)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .tensorflow.MetaGraphDef.MetaInfoDef meta_info_def = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_meta_info_def()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_graph_def;
break;
}
// optional .tensorflow.GraphDef graph_def = 2;
case 2: {
if (tag == 18) {
parse_graph_def:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_graph_def()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_saver_def;
break;
}
// optional .tensorflow.SaverDef saver_def = 3;
case 3: {
if (tag == 26) {
parse_saver_def:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_saver_def()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_collection_def;
break;
}
// map<string, .tensorflow.CollectionDef> collection_def = 4;
case 4: {
if (tag == 34) {
parse_collection_def:
DO_(input->IncrementRecursionDepth());
parse_loop_collection_def:
MetaGraphDef_CollectionDefEntry::Parser< ::google::protobuf::internal::MapField<
::std::string, ::tensorflow::CollectionDef,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef > > parser(&collection_def_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), parser.key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.MetaGraphDef.CollectionDefEntry.key"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_loop_collection_def;
if (input->ExpectTag(42)) goto parse_loop_signature_def;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<string, .tensorflow.SignatureDef> signature_def = 5;
case 5: {
if (tag == 42) {
DO_(input->IncrementRecursionDepth());
parse_loop_signature_def:
MetaGraphDef_SignatureDefEntry::Parser< ::google::protobuf::internal::MapField<
::std::string, ::tensorflow::SignatureDef,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef > > parser(&signature_def_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), parser.key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.MetaGraphDef.SignatureDefEntry.key"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(42)) goto parse_loop_signature_def;
if (input->ExpectTag(50)) goto parse_loop_asset_file_def;
input->UnsafeDecrementRecursionDepth();
break;
}
// repeated .tensorflow.AssetFileDef asset_file_def = 6;
case 6: {
if (tag == 50) {
DO_(input->IncrementRecursionDepth());
parse_loop_asset_file_def:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_asset_file_def()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(50)) goto parse_loop_asset_file_def;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.MetaGraphDef)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.MetaGraphDef)
return false;
#undef DO_
}
void MetaGraphDef::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.MetaGraphDef)
// optional .tensorflow.MetaGraphDef.MetaInfoDef meta_info_def = 1;
if (this->has_meta_info_def()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->meta_info_def_, output);
}
// optional .tensorflow.GraphDef graph_def = 2;
if (this->has_graph_def()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *this->graph_def_, output);
}
// optional .tensorflow.SaverDef saver_def = 3;
if (this->has_saver_def()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->saver_def_, output);
}
// map<string, .tensorflow.CollectionDef> collection_def = 4;
if (!this->collection_def().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.CollectionDefEntry.key");
}
};
if (output->IsSerializationDeterminstic() &&
this->collection_def().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->collection_def().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_iterator
it = this->collection_def().begin();
it != this->collection_def().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<MetaGraphDef_CollectionDefEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(collection_def_.NewEntryWrapper(
items[i]->first, items[i]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<MetaGraphDef_CollectionDefEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_iterator
it = this->collection_def().begin();
it != this->collection_def().end(); ++it) {
entry.reset(collection_def_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// map<string, .tensorflow.SignatureDef> signature_def = 5;
if (!this->signature_def().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.SignatureDefEntry.key");
}
};
if (output->IsSerializationDeterminstic() &&
this->signature_def().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->signature_def().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_iterator
it = this->signature_def().begin();
it != this->signature_def().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<MetaGraphDef_SignatureDefEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(signature_def_.NewEntryWrapper(
items[i]->first, items[i]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<MetaGraphDef_SignatureDefEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_iterator
it = this->signature_def().begin();
it != this->signature_def().end(); ++it) {
entry.reset(signature_def_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// repeated .tensorflow.AssetFileDef asset_file_def = 6;
for (unsigned int i = 0, n = this->asset_file_def_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, this->asset_file_def(i), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.MetaGraphDef)
}
::google::protobuf::uint8* MetaGraphDef::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.MetaGraphDef)
// optional .tensorflow.MetaGraphDef.MetaInfoDef meta_info_def = 1;
if (this->has_meta_info_def()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->meta_info_def_, false, target);
}
// optional .tensorflow.GraphDef graph_def = 2;
if (this->has_graph_def()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *this->graph_def_, false, target);
}
// optional .tensorflow.SaverDef saver_def = 3;
if (this->has_saver_def()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->saver_def_, false, target);
}
// map<string, .tensorflow.CollectionDef> collection_def = 4;
if (!this->collection_def().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.CollectionDefEntry.key");
}
};
if (deterministic &&
this->collection_def().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->collection_def().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_iterator
it = this->collection_def().begin();
it != this->collection_def().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<MetaGraphDef_CollectionDefEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(collection_def_.NewEntryWrapper(
items[i]->first, items[i]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<MetaGraphDef_CollectionDefEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_iterator
it = this->collection_def().begin();
it != this->collection_def().end(); ++it) {
entry.reset(collection_def_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// map<string, .tensorflow.SignatureDef> signature_def = 5;
if (!this->signature_def().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.MetaGraphDef.SignatureDefEntry.key");
}
};
if (deterministic &&
this->signature_def().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->signature_def().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_iterator
it = this->signature_def().begin();
it != this->signature_def().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<MetaGraphDef_SignatureDefEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(signature_def_.NewEntryWrapper(
items[i]->first, items[i]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
5, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<MetaGraphDef_SignatureDefEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_iterator
it = this->signature_def().begin();
it != this->signature_def().end(); ++it) {
entry.reset(signature_def_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
5, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// repeated .tensorflow.AssetFileDef asset_file_def = 6;
for (unsigned int i = 0, n = this->asset_file_def_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
6, this->asset_file_def(i), false, target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.MetaGraphDef)
return target;
}
size_t MetaGraphDef::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.MetaGraphDef)
size_t total_size = 0;
// optional .tensorflow.MetaGraphDef.MetaInfoDef meta_info_def = 1;
if (this->has_meta_info_def()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->meta_info_def_);
}
// optional .tensorflow.GraphDef graph_def = 2;
if (this->has_graph_def()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->graph_def_);
}
// optional .tensorflow.SaverDef saver_def = 3;
if (this->has_saver_def()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->saver_def_);
}
// map<string, .tensorflow.CollectionDef> collection_def = 4;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->collection_def_size());
{
::google::protobuf::scoped_ptr<MetaGraphDef_CollectionDefEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >::const_iterator
it = this->collection_def().begin();
it != this->collection_def().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(collection_def_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, .tensorflow.SignatureDef> signature_def = 5;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->signature_def_size());
{
::google::protobuf::scoped_ptr<MetaGraphDef_SignatureDefEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >::const_iterator
it = this->signature_def().begin();
it != this->signature_def().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(signature_def_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// repeated .tensorflow.AssetFileDef asset_file_def = 6;
{
unsigned int count = this->asset_file_def_size();
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->asset_file_def(i));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MetaGraphDef::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.MetaGraphDef)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const MetaGraphDef* source =
::google::protobuf::internal::DynamicCastToGenerated<const MetaGraphDef>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.MetaGraphDef)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.MetaGraphDef)
UnsafeMergeFrom(*source);
}
}
void MetaGraphDef::MergeFrom(const MetaGraphDef& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.MetaGraphDef)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void MetaGraphDef::UnsafeMergeFrom(const MetaGraphDef& from) {
GOOGLE_DCHECK(&from != this);
collection_def_.MergeFrom(from.collection_def_);
signature_def_.MergeFrom(from.signature_def_);
asset_file_def_.MergeFrom(from.asset_file_def_);
if (from.has_meta_info_def()) {
mutable_meta_info_def()->::tensorflow::MetaGraphDef_MetaInfoDef::MergeFrom(from.meta_info_def());
}
if (from.has_graph_def()) {
mutable_graph_def()->::tensorflow::GraphDef::MergeFrom(from.graph_def());
}
if (from.has_saver_def()) {
mutable_saver_def()->::tensorflow::SaverDef::MergeFrom(from.saver_def());
}
}
void MetaGraphDef::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.MetaGraphDef)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MetaGraphDef::CopyFrom(const MetaGraphDef& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.MetaGraphDef)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool MetaGraphDef::IsInitialized() const {
return true;
}
void MetaGraphDef::Swap(MetaGraphDef* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
MetaGraphDef temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void MetaGraphDef::UnsafeArenaSwap(MetaGraphDef* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void MetaGraphDef::InternalSwap(MetaGraphDef* other) {
std::swap(meta_info_def_, other->meta_info_def_);
std::swap(graph_def_, other->graph_def_);
std::swap(saver_def_, other->saver_def_);
collection_def_.Swap(&other->collection_def_);
signature_def_.Swap(&other->signature_def_);
asset_file_def_.UnsafeArenaSwap(&other->asset_file_def_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MetaGraphDef::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = MetaGraphDef_descriptor_;
metadata.reflection = MetaGraphDef_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// MetaGraphDef_MetaInfoDef
// optional string meta_graph_version = 1;
void MetaGraphDef_MetaInfoDef::clear_meta_graph_version() {
meta_graph_version_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& MetaGraphDef_MetaInfoDef::meta_graph_version() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
return meta_graph_version_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void MetaGraphDef_MetaInfoDef::set_meta_graph_version(const ::std::string& value) {
meta_graph_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
}
void MetaGraphDef_MetaInfoDef::set_meta_graph_version(const char* value) {
meta_graph_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
}
void MetaGraphDef_MetaInfoDef::set_meta_graph_version(const char* value,
size_t size) {
meta_graph_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
}
::std::string* MetaGraphDef_MetaInfoDef::mutable_meta_graph_version() {
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
return meta_graph_version_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* MetaGraphDef_MetaInfoDef::release_meta_graph_version() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
return meta_graph_version_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* MetaGraphDef_MetaInfoDef::unsafe_arena_release_meta_graph_version() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return meta_graph_version_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void MetaGraphDef_MetaInfoDef::set_allocated_meta_graph_version(::std::string* meta_graph_version) {
if (meta_graph_version != NULL) {
} else {
}
meta_graph_version_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), meta_graph_version,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
}
void MetaGraphDef_MetaInfoDef::unsafe_arena_set_allocated_meta_graph_version(
::std::string* meta_graph_version) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (meta_graph_version != NULL) {
} else {
}
meta_graph_version_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
meta_graph_version, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.meta_graph_version)
}
// optional .tensorflow.OpList stripped_op_list = 2;
bool MetaGraphDef_MetaInfoDef::has_stripped_op_list() const {
return this != internal_default_instance() && stripped_op_list_ != NULL;
}
void MetaGraphDef_MetaInfoDef::clear_stripped_op_list() {
if (GetArenaNoVirtual() == NULL && stripped_op_list_ != NULL) delete stripped_op_list_;
stripped_op_list_ = NULL;
}
const ::tensorflow::OpList& MetaGraphDef_MetaInfoDef::stripped_op_list() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.MetaInfoDef.stripped_op_list)
return stripped_op_list_ != NULL ? *stripped_op_list_
: *::tensorflow::OpList::internal_default_instance();
}
::tensorflow::OpList* MetaGraphDef_MetaInfoDef::mutable_stripped_op_list() {
if (stripped_op_list_ == NULL) {
_slow_mutable_stripped_op_list();
}
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.MetaInfoDef.stripped_op_list)
return stripped_op_list_;
}
::tensorflow::OpList* MetaGraphDef_MetaInfoDef::release_stripped_op_list() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.MetaInfoDef.stripped_op_list)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_stripped_op_list();
} else {
::tensorflow::OpList* temp = stripped_op_list_;
stripped_op_list_ = NULL;
return temp;
}
}
void MetaGraphDef_MetaInfoDef::set_allocated_stripped_op_list(::tensorflow::OpList* stripped_op_list) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete stripped_op_list_;
}
if (stripped_op_list != NULL) {
_slow_set_allocated_stripped_op_list(message_arena, &stripped_op_list);
}
stripped_op_list_ = stripped_op_list;
if (stripped_op_list) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.stripped_op_list)
}
// optional .google.protobuf.Any any_info = 3;
bool MetaGraphDef_MetaInfoDef::has_any_info() const {
return this != internal_default_instance() && any_info_ != NULL;
}
void MetaGraphDef_MetaInfoDef::clear_any_info() {
if (GetArenaNoVirtual() == NULL && any_info_ != NULL) delete any_info_;
any_info_ = NULL;
}
const ::google::protobuf::Any& MetaGraphDef_MetaInfoDef::any_info() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.MetaInfoDef.any_info)
return any_info_ != NULL ? *any_info_
: *::google::protobuf::Any::internal_default_instance();
}
::google::protobuf::Any* MetaGraphDef_MetaInfoDef::mutable_any_info() {
if (any_info_ == NULL) {
_slow_mutable_any_info();
}
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.MetaInfoDef.any_info)
return any_info_;
}
::google::protobuf::Any* MetaGraphDef_MetaInfoDef::release_any_info() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.MetaInfoDef.any_info)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_any_info();
} else {
::google::protobuf::Any* temp = any_info_;
any_info_ = NULL;
return temp;
}
}
void MetaGraphDef_MetaInfoDef::set_allocated_any_info(::google::protobuf::Any* any_info) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete any_info_;
}
if (any_info != NULL) {
if (message_arena != NULL) {
message_arena->Own(any_info);
}
}
any_info_ = any_info;
if (any_info) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.any_info)
}
// repeated string tags = 4;
int MetaGraphDef_MetaInfoDef::tags_size() const {
return tags_.size();
}
void MetaGraphDef_MetaInfoDef::clear_tags() {
tags_.Clear();
}
const ::std::string& MetaGraphDef_MetaInfoDef::tags(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.MetaInfoDef.tags)
return tags_.Get(index);
}
::std::string* MetaGraphDef_MetaInfoDef::mutable_tags(int index) {
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.MetaInfoDef.tags)
return tags_.Mutable(index);
}
void MetaGraphDef_MetaInfoDef::set_tags(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:tensorflow.MetaGraphDef.MetaInfoDef.tags)
tags_.Mutable(index)->assign(value);
}
void MetaGraphDef_MetaInfoDef::set_tags(int index, const char* value) {
tags_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:tensorflow.MetaGraphDef.MetaInfoDef.tags)
}
void MetaGraphDef_MetaInfoDef::set_tags(int index, const char* value, size_t size) {
tags_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:tensorflow.MetaGraphDef.MetaInfoDef.tags)
}
::std::string* MetaGraphDef_MetaInfoDef::add_tags() {
// @@protoc_insertion_point(field_add_mutable:tensorflow.MetaGraphDef.MetaInfoDef.tags)
return tags_.Add();
}
void MetaGraphDef_MetaInfoDef::add_tags(const ::std::string& value) {
tags_.Add()->assign(value);
// @@protoc_insertion_point(field_add:tensorflow.MetaGraphDef.MetaInfoDef.tags)
}
void MetaGraphDef_MetaInfoDef::add_tags(const char* value) {
tags_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:tensorflow.MetaGraphDef.MetaInfoDef.tags)
}
void MetaGraphDef_MetaInfoDef::add_tags(const char* value, size_t size) {
tags_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:tensorflow.MetaGraphDef.MetaInfoDef.tags)
}
const ::google::protobuf::RepeatedPtrField< ::std::string>&
MetaGraphDef_MetaInfoDef::tags() const {
// @@protoc_insertion_point(field_list:tensorflow.MetaGraphDef.MetaInfoDef.tags)
return tags_;
}
::google::protobuf::RepeatedPtrField< ::std::string>*
MetaGraphDef_MetaInfoDef::mutable_tags() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.MetaGraphDef.MetaInfoDef.tags)
return &tags_;
}
// optional string tensorflow_version = 5;
void MetaGraphDef_MetaInfoDef::clear_tensorflow_version() {
tensorflow_version_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& MetaGraphDef_MetaInfoDef::tensorflow_version() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
return tensorflow_version_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void MetaGraphDef_MetaInfoDef::set_tensorflow_version(const ::std::string& value) {
tensorflow_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
}
void MetaGraphDef_MetaInfoDef::set_tensorflow_version(const char* value) {
tensorflow_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
}
void MetaGraphDef_MetaInfoDef::set_tensorflow_version(const char* value,
size_t size) {
tensorflow_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
}
::std::string* MetaGraphDef_MetaInfoDef::mutable_tensorflow_version() {
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
return tensorflow_version_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* MetaGraphDef_MetaInfoDef::release_tensorflow_version() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
return tensorflow_version_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* MetaGraphDef_MetaInfoDef::unsafe_arena_release_tensorflow_version() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return tensorflow_version_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void MetaGraphDef_MetaInfoDef::set_allocated_tensorflow_version(::std::string* tensorflow_version) {
if (tensorflow_version != NULL) {
} else {
}
tensorflow_version_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), tensorflow_version,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
}
void MetaGraphDef_MetaInfoDef::unsafe_arena_set_allocated_tensorflow_version(
::std::string* tensorflow_version) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (tensorflow_version != NULL) {
} else {
}
tensorflow_version_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
tensorflow_version, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_version)
}
// optional string tensorflow_git_version = 6;
void MetaGraphDef_MetaInfoDef::clear_tensorflow_git_version() {
tensorflow_git_version_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& MetaGraphDef_MetaInfoDef::tensorflow_git_version() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
return tensorflow_git_version_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void MetaGraphDef_MetaInfoDef::set_tensorflow_git_version(const ::std::string& value) {
tensorflow_git_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
}
void MetaGraphDef_MetaInfoDef::set_tensorflow_git_version(const char* value) {
tensorflow_git_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
}
void MetaGraphDef_MetaInfoDef::set_tensorflow_git_version(const char* value,
size_t size) {
tensorflow_git_version_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
}
::std::string* MetaGraphDef_MetaInfoDef::mutable_tensorflow_git_version() {
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
return tensorflow_git_version_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* MetaGraphDef_MetaInfoDef::release_tensorflow_git_version() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
return tensorflow_git_version_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* MetaGraphDef_MetaInfoDef::unsafe_arena_release_tensorflow_git_version() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return tensorflow_git_version_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void MetaGraphDef_MetaInfoDef::set_allocated_tensorflow_git_version(::std::string* tensorflow_git_version) {
if (tensorflow_git_version != NULL) {
} else {
}
tensorflow_git_version_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), tensorflow_git_version,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
}
void MetaGraphDef_MetaInfoDef::unsafe_arena_set_allocated_tensorflow_git_version(
::std::string* tensorflow_git_version) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (tensorflow_git_version != NULL) {
} else {
}
tensorflow_git_version_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
tensorflow_git_version, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.MetaGraphDef.MetaInfoDef.tensorflow_git_version)
}
inline const MetaGraphDef_MetaInfoDef* MetaGraphDef_MetaInfoDef::internal_default_instance() {
return &MetaGraphDef_MetaInfoDef_default_instance_.get();
}
// -------------------------------------------------------------------
// MetaGraphDef
// optional .tensorflow.MetaGraphDef.MetaInfoDef meta_info_def = 1;
bool MetaGraphDef::has_meta_info_def() const {
return this != internal_default_instance() && meta_info_def_ != NULL;
}
void MetaGraphDef::clear_meta_info_def() {
if (GetArenaNoVirtual() == NULL && meta_info_def_ != NULL) delete meta_info_def_;
meta_info_def_ = NULL;
}
const ::tensorflow::MetaGraphDef_MetaInfoDef& MetaGraphDef::meta_info_def() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.meta_info_def)
return meta_info_def_ != NULL ? *meta_info_def_
: *::tensorflow::MetaGraphDef_MetaInfoDef::internal_default_instance();
}
::tensorflow::MetaGraphDef_MetaInfoDef* MetaGraphDef::mutable_meta_info_def() {
if (meta_info_def_ == NULL) {
_slow_mutable_meta_info_def();
}
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.meta_info_def)
return meta_info_def_;
}
::tensorflow::MetaGraphDef_MetaInfoDef* MetaGraphDef::release_meta_info_def() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.meta_info_def)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_meta_info_def();
} else {
::tensorflow::MetaGraphDef_MetaInfoDef* temp = meta_info_def_;
meta_info_def_ = NULL;
return temp;
}
}
void MetaGraphDef::set_allocated_meta_info_def(::tensorflow::MetaGraphDef_MetaInfoDef* meta_info_def) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete meta_info_def_;
}
if (meta_info_def != NULL) {
_slow_set_allocated_meta_info_def(message_arena, &meta_info_def);
}
meta_info_def_ = meta_info_def;
if (meta_info_def) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.meta_info_def)
}
// optional .tensorflow.GraphDef graph_def = 2;
bool MetaGraphDef::has_graph_def() const {
return this != internal_default_instance() && graph_def_ != NULL;
}
void MetaGraphDef::clear_graph_def() {
if (GetArenaNoVirtual() == NULL && graph_def_ != NULL) delete graph_def_;
graph_def_ = NULL;
}
const ::tensorflow::GraphDef& MetaGraphDef::graph_def() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.graph_def)
return graph_def_ != NULL ? *graph_def_
: *::tensorflow::GraphDef::internal_default_instance();
}
::tensorflow::GraphDef* MetaGraphDef::mutable_graph_def() {
if (graph_def_ == NULL) {
_slow_mutable_graph_def();
}
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.graph_def)
return graph_def_;
}
::tensorflow::GraphDef* MetaGraphDef::release_graph_def() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.graph_def)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_graph_def();
} else {
::tensorflow::GraphDef* temp = graph_def_;
graph_def_ = NULL;
return temp;
}
}
void MetaGraphDef::set_allocated_graph_def(::tensorflow::GraphDef* graph_def) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete graph_def_;
}
if (graph_def != NULL) {
_slow_set_allocated_graph_def(message_arena, &graph_def);
}
graph_def_ = graph_def;
if (graph_def) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.graph_def)
}
// optional .tensorflow.SaverDef saver_def = 3;
bool MetaGraphDef::has_saver_def() const {
return this != internal_default_instance() && saver_def_ != NULL;
}
void MetaGraphDef::clear_saver_def() {
if (GetArenaNoVirtual() == NULL && saver_def_ != NULL) delete saver_def_;
saver_def_ = NULL;
}
const ::tensorflow::SaverDef& MetaGraphDef::saver_def() const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.saver_def)
return saver_def_ != NULL ? *saver_def_
: *::tensorflow::SaverDef::internal_default_instance();
}
::tensorflow::SaverDef* MetaGraphDef::mutable_saver_def() {
if (saver_def_ == NULL) {
_slow_mutable_saver_def();
}
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.saver_def)
return saver_def_;
}
::tensorflow::SaverDef* MetaGraphDef::release_saver_def() {
// @@protoc_insertion_point(field_release:tensorflow.MetaGraphDef.saver_def)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_saver_def();
} else {
::tensorflow::SaverDef* temp = saver_def_;
saver_def_ = NULL;
return temp;
}
}
void MetaGraphDef::set_allocated_saver_def(::tensorflow::SaverDef* saver_def) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete saver_def_;
}
if (saver_def != NULL) {
_slow_set_allocated_saver_def(message_arena, &saver_def);
}
saver_def_ = saver_def;
if (saver_def) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.MetaGraphDef.saver_def)
}
// map<string, .tensorflow.CollectionDef> collection_def = 4;
int MetaGraphDef::collection_def_size() const {
return collection_def_.size();
}
void MetaGraphDef::clear_collection_def() {
collection_def_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >&
MetaGraphDef::collection_def() const {
// @@protoc_insertion_point(field_map:tensorflow.MetaGraphDef.collection_def)
return collection_def_.GetMap();
}
::google::protobuf::Map< ::std::string, ::tensorflow::CollectionDef >*
MetaGraphDef::mutable_collection_def() {
// @@protoc_insertion_point(field_mutable_map:tensorflow.MetaGraphDef.collection_def)
return collection_def_.MutableMap();
}
// map<string, .tensorflow.SignatureDef> signature_def = 5;
int MetaGraphDef::signature_def_size() const {
return signature_def_.size();
}
void MetaGraphDef::clear_signature_def() {
signature_def_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >&
MetaGraphDef::signature_def() const {
// @@protoc_insertion_point(field_map:tensorflow.MetaGraphDef.signature_def)
return signature_def_.GetMap();
}
::google::protobuf::Map< ::std::string, ::tensorflow::SignatureDef >*
MetaGraphDef::mutable_signature_def() {
// @@protoc_insertion_point(field_mutable_map:tensorflow.MetaGraphDef.signature_def)
return signature_def_.MutableMap();
}
// repeated .tensorflow.AssetFileDef asset_file_def = 6;
int MetaGraphDef::asset_file_def_size() const {
return asset_file_def_.size();
}
void MetaGraphDef::clear_asset_file_def() {
asset_file_def_.Clear();
}
const ::tensorflow::AssetFileDef& MetaGraphDef::asset_file_def(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.MetaGraphDef.asset_file_def)
return asset_file_def_.Get(index);
}
::tensorflow::AssetFileDef* MetaGraphDef::mutable_asset_file_def(int index) {
// @@protoc_insertion_point(field_mutable:tensorflow.MetaGraphDef.asset_file_def)
return asset_file_def_.Mutable(index);
}
::tensorflow::AssetFileDef* MetaGraphDef::add_asset_file_def() {
// @@protoc_insertion_point(field_add:tensorflow.MetaGraphDef.asset_file_def)
return asset_file_def_.Add();
}
::google::protobuf::RepeatedPtrField< ::tensorflow::AssetFileDef >*
MetaGraphDef::mutable_asset_file_def() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.MetaGraphDef.asset_file_def)
return &asset_file_def_;
}
const ::google::protobuf::RepeatedPtrField< ::tensorflow::AssetFileDef >&
MetaGraphDef::asset_file_def() const {
// @@protoc_insertion_point(field_list:tensorflow.MetaGraphDef.asset_file_def)
return asset_file_def_;
}
inline const MetaGraphDef* MetaGraphDef::internal_default_instance() {
return &MetaGraphDef_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CollectionDef_NodeList::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CollectionDef_NodeList::CollectionDef_NodeList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.CollectionDef.NodeList)
}
CollectionDef_NodeList::CollectionDef_NodeList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.CollectionDef.NodeList)
}
void CollectionDef_NodeList::InitAsDefaultInstance() {
}
CollectionDef_NodeList::CollectionDef_NodeList(const CollectionDef_NodeList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.CollectionDef.NodeList)
}
void CollectionDef_NodeList::SharedCtor() {
_cached_size_ = 0;
}
CollectionDef_NodeList::~CollectionDef_NodeList() {
// @@protoc_insertion_point(destructor:tensorflow.CollectionDef.NodeList)
SharedDtor();
}
void CollectionDef_NodeList::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void CollectionDef_NodeList::ArenaDtor(void* object) {
CollectionDef_NodeList* _this = reinterpret_cast< CollectionDef_NodeList* >(object);
(void)_this;
}
void CollectionDef_NodeList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void CollectionDef_NodeList::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CollectionDef_NodeList::descriptor() {
protobuf_AssignDescriptorsOnce();
return CollectionDef_NodeList_descriptor_;
}
const CollectionDef_NodeList& CollectionDef_NodeList::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<CollectionDef_NodeList> CollectionDef_NodeList_default_instance_;
CollectionDef_NodeList* CollectionDef_NodeList::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<CollectionDef_NodeList>(arena);
}
void CollectionDef_NodeList::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.CollectionDef.NodeList)
value_.Clear();
}
bool CollectionDef_NodeList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.CollectionDef.NodeList)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated string value = 1;
case 1: {
if (tag == 10) {
parse_value:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->add_value()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->value(this->value_size() - 1).data(),
this->value(this->value_size() - 1).length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.CollectionDef.NodeList.value"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_value;
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.CollectionDef.NodeList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.CollectionDef.NodeList)
return false;
#undef DO_
}
void CollectionDef_NodeList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.CollectionDef.NodeList)
// repeated string value = 1;
for (int i = 0; i < this->value_size(); i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->value(i).data(), this->value(i).length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.CollectionDef.NodeList.value");
::google::protobuf::internal::WireFormatLite::WriteString(
1, this->value(i), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.CollectionDef.NodeList)
}
::google::protobuf::uint8* CollectionDef_NodeList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.CollectionDef.NodeList)
// repeated string value = 1;
for (int i = 0; i < this->value_size(); i++) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->value(i).data(), this->value(i).length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.CollectionDef.NodeList.value");
target = ::google::protobuf::internal::WireFormatLite::
WriteStringToArray(1, this->value(i), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.CollectionDef.NodeList)
return target;
}
size_t CollectionDef_NodeList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.CollectionDef.NodeList)
size_t total_size = 0;
// repeated string value = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->value_size());
for (int i = 0; i < this->value_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::StringSize(
this->value(i));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CollectionDef_NodeList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.CollectionDef.NodeList)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const CollectionDef_NodeList* source =
::google::protobuf::internal::DynamicCastToGenerated<const CollectionDef_NodeList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.CollectionDef.NodeList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.CollectionDef.NodeList)
UnsafeMergeFrom(*source);
}
}
void CollectionDef_NodeList::MergeFrom(const CollectionDef_NodeList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.CollectionDef.NodeList)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void CollectionDef_NodeList::UnsafeMergeFrom(const CollectionDef_NodeList& from) {
GOOGLE_DCHECK(&from != this);
value_.UnsafeMergeFrom(from.value_);
}
void CollectionDef_NodeList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.CollectionDef.NodeList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CollectionDef_NodeList::CopyFrom(const CollectionDef_NodeList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.CollectionDef.NodeList)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool CollectionDef_NodeList::IsInitialized() const {
return true;
}
void CollectionDef_NodeList::Swap(CollectionDef_NodeList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
CollectionDef_NodeList temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void CollectionDef_NodeList::UnsafeArenaSwap(CollectionDef_NodeList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void CollectionDef_NodeList::InternalSwap(CollectionDef_NodeList* other) {
value_.UnsafeArenaSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CollectionDef_NodeList::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CollectionDef_NodeList_descriptor_;
metadata.reflection = CollectionDef_NodeList_reflection_;
return metadata;
}
// -------------------------------------------------------------------
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CollectionDef_BytesList::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CollectionDef_BytesList::CollectionDef_BytesList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.CollectionDef.BytesList)
}
CollectionDef_BytesList::CollectionDef_BytesList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.CollectionDef.BytesList)
}
void CollectionDef_BytesList::InitAsDefaultInstance() {
}
CollectionDef_BytesList::CollectionDef_BytesList(const CollectionDef_BytesList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.CollectionDef.BytesList)
}
void CollectionDef_BytesList::SharedCtor() {
_cached_size_ = 0;
}
CollectionDef_BytesList::~CollectionDef_BytesList() {
// @@protoc_insertion_point(destructor:tensorflow.CollectionDef.BytesList)
SharedDtor();
}
void CollectionDef_BytesList::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void CollectionDef_BytesList::ArenaDtor(void* object) {
CollectionDef_BytesList* _this = reinterpret_cast< CollectionDef_BytesList* >(object);
(void)_this;
}
void CollectionDef_BytesList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void CollectionDef_BytesList::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CollectionDef_BytesList::descriptor() {
protobuf_AssignDescriptorsOnce();
return CollectionDef_BytesList_descriptor_;
}
const CollectionDef_BytesList& CollectionDef_BytesList::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<CollectionDef_BytesList> CollectionDef_BytesList_default_instance_;
CollectionDef_BytesList* CollectionDef_BytesList::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<CollectionDef_BytesList>(arena);
}
void CollectionDef_BytesList::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.CollectionDef.BytesList)
value_.Clear();
}
bool CollectionDef_BytesList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.CollectionDef.BytesList)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated bytes value = 1;
case 1: {
if (tag == 10) {
parse_value:
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->add_value()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_value;
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.CollectionDef.BytesList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.CollectionDef.BytesList)
return false;
#undef DO_
}
void CollectionDef_BytesList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.CollectionDef.BytesList)
// repeated bytes value = 1;
for (int i = 0; i < this->value_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteBytes(
1, this->value(i), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.CollectionDef.BytesList)
}
::google::protobuf::uint8* CollectionDef_BytesList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.CollectionDef.BytesList)
// repeated bytes value = 1;
for (int i = 0; i < this->value_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteBytesToArray(1, this->value(i), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.CollectionDef.BytesList)
return target;
}
size_t CollectionDef_BytesList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.CollectionDef.BytesList)
size_t total_size = 0;
// repeated bytes value = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->value_size());
for (int i = 0; i < this->value_size(); i++) {
total_size += ::google::protobuf::internal::WireFormatLite::BytesSize(
this->value(i));
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CollectionDef_BytesList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.CollectionDef.BytesList)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const CollectionDef_BytesList* source =
::google::protobuf::internal::DynamicCastToGenerated<const CollectionDef_BytesList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.CollectionDef.BytesList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.CollectionDef.BytesList)
UnsafeMergeFrom(*source);
}
}
void CollectionDef_BytesList::MergeFrom(const CollectionDef_BytesList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.CollectionDef.BytesList)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void CollectionDef_BytesList::UnsafeMergeFrom(const CollectionDef_BytesList& from) {
GOOGLE_DCHECK(&from != this);
value_.UnsafeMergeFrom(from.value_);
}
void CollectionDef_BytesList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.CollectionDef.BytesList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CollectionDef_BytesList::CopyFrom(const CollectionDef_BytesList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.CollectionDef.BytesList)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool CollectionDef_BytesList::IsInitialized() const {
return true;
}
void CollectionDef_BytesList::Swap(CollectionDef_BytesList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
CollectionDef_BytesList temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void CollectionDef_BytesList::UnsafeArenaSwap(CollectionDef_BytesList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void CollectionDef_BytesList::InternalSwap(CollectionDef_BytesList* other) {
value_.UnsafeArenaSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CollectionDef_BytesList::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CollectionDef_BytesList_descriptor_;
metadata.reflection = CollectionDef_BytesList_reflection_;
return metadata;
}
// -------------------------------------------------------------------
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CollectionDef_Int64List::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CollectionDef_Int64List::CollectionDef_Int64List()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.CollectionDef.Int64List)
}
CollectionDef_Int64List::CollectionDef_Int64List(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.CollectionDef.Int64List)
}
void CollectionDef_Int64List::InitAsDefaultInstance() {
}
CollectionDef_Int64List::CollectionDef_Int64List(const CollectionDef_Int64List& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.CollectionDef.Int64List)
}
void CollectionDef_Int64List::SharedCtor() {
_cached_size_ = 0;
}
CollectionDef_Int64List::~CollectionDef_Int64List() {
// @@protoc_insertion_point(destructor:tensorflow.CollectionDef.Int64List)
SharedDtor();
}
void CollectionDef_Int64List::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void CollectionDef_Int64List::ArenaDtor(void* object) {
CollectionDef_Int64List* _this = reinterpret_cast< CollectionDef_Int64List* >(object);
(void)_this;
}
void CollectionDef_Int64List::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void CollectionDef_Int64List::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CollectionDef_Int64List::descriptor() {
protobuf_AssignDescriptorsOnce();
return CollectionDef_Int64List_descriptor_;
}
const CollectionDef_Int64List& CollectionDef_Int64List::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<CollectionDef_Int64List> CollectionDef_Int64List_default_instance_;
CollectionDef_Int64List* CollectionDef_Int64List::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<CollectionDef_Int64List>(arena);
}
void CollectionDef_Int64List::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.CollectionDef.Int64List)
value_.Clear();
}
bool CollectionDef_Int64List::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.CollectionDef.Int64List)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated int64 value = 1 [packed = true];
case 1: {
if (tag == 10) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, this->mutable_value())));
} else if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
1, 10, input, this->mutable_value())));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.CollectionDef.Int64List)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.CollectionDef.Int64List)
return false;
#undef DO_
}
void CollectionDef_Int64List::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.CollectionDef.Int64List)
// repeated int64 value = 1 [packed = true];
if (this->value_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_value_cached_byte_size_);
}
for (int i = 0; i < this->value_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteInt64NoTag(
this->value(i), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.CollectionDef.Int64List)
}
::google::protobuf::uint8* CollectionDef_Int64List::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.CollectionDef.Int64List)
// repeated int64 value = 1 [packed = true];
if (this->value_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_value_cached_byte_size_, target);
}
for (int i = 0; i < this->value_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteInt64NoTagToArray(this->value(i), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.CollectionDef.Int64List)
return target;
}
size_t CollectionDef_Int64List::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.CollectionDef.Int64List)
size_t total_size = 0;
// repeated int64 value = 1 [packed = true];
{
size_t data_size = 0;
unsigned int count = this->value_size();
for (unsigned int i = 0; i < count; i++) {
data_size += ::google::protobuf::internal::WireFormatLite::
Int64Size(this->value(i));
}
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_value_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CollectionDef_Int64List::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.CollectionDef.Int64List)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const CollectionDef_Int64List* source =
::google::protobuf::internal::DynamicCastToGenerated<const CollectionDef_Int64List>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.CollectionDef.Int64List)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.CollectionDef.Int64List)
UnsafeMergeFrom(*source);
}
}
void CollectionDef_Int64List::MergeFrom(const CollectionDef_Int64List& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.CollectionDef.Int64List)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void CollectionDef_Int64List::UnsafeMergeFrom(const CollectionDef_Int64List& from) {
GOOGLE_DCHECK(&from != this);
value_.UnsafeMergeFrom(from.value_);
}
void CollectionDef_Int64List::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.CollectionDef.Int64List)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CollectionDef_Int64List::CopyFrom(const CollectionDef_Int64List& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.CollectionDef.Int64List)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool CollectionDef_Int64List::IsInitialized() const {
return true;
}
void CollectionDef_Int64List::Swap(CollectionDef_Int64List* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
CollectionDef_Int64List temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void CollectionDef_Int64List::UnsafeArenaSwap(CollectionDef_Int64List* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void CollectionDef_Int64List::InternalSwap(CollectionDef_Int64List* other) {
value_.UnsafeArenaSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CollectionDef_Int64List::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CollectionDef_Int64List_descriptor_;
metadata.reflection = CollectionDef_Int64List_reflection_;
return metadata;
}
// -------------------------------------------------------------------
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CollectionDef_FloatList::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CollectionDef_FloatList::CollectionDef_FloatList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.CollectionDef.FloatList)
}
CollectionDef_FloatList::CollectionDef_FloatList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.CollectionDef.FloatList)
}
void CollectionDef_FloatList::InitAsDefaultInstance() {
}
CollectionDef_FloatList::CollectionDef_FloatList(const CollectionDef_FloatList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.CollectionDef.FloatList)
}
void CollectionDef_FloatList::SharedCtor() {
_cached_size_ = 0;
}
CollectionDef_FloatList::~CollectionDef_FloatList() {
// @@protoc_insertion_point(destructor:tensorflow.CollectionDef.FloatList)
SharedDtor();
}
void CollectionDef_FloatList::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void CollectionDef_FloatList::ArenaDtor(void* object) {
CollectionDef_FloatList* _this = reinterpret_cast< CollectionDef_FloatList* >(object);
(void)_this;
}
void CollectionDef_FloatList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void CollectionDef_FloatList::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CollectionDef_FloatList::descriptor() {
protobuf_AssignDescriptorsOnce();
return CollectionDef_FloatList_descriptor_;
}
const CollectionDef_FloatList& CollectionDef_FloatList::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<CollectionDef_FloatList> CollectionDef_FloatList_default_instance_;
CollectionDef_FloatList* CollectionDef_FloatList::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<CollectionDef_FloatList>(arena);
}
void CollectionDef_FloatList::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.CollectionDef.FloatList)
value_.Clear();
}
bool CollectionDef_FloatList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.CollectionDef.FloatList)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated float value = 1 [packed = true];
case 1: {
if (tag == 10) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, this->mutable_value())));
} else if (tag == 13) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
1, 10, input, this->mutable_value())));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.CollectionDef.FloatList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.CollectionDef.FloatList)
return false;
#undef DO_
}
void CollectionDef_FloatList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.CollectionDef.FloatList)
// repeated float value = 1 [packed = true];
if (this->value_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_value_cached_byte_size_);
}
for (int i = 0; i < this->value_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteFloatNoTag(
this->value(i), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.CollectionDef.FloatList)
}
::google::protobuf::uint8* CollectionDef_FloatList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.CollectionDef.FloatList)
// repeated float value = 1 [packed = true];
if (this->value_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
1,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_value_cached_byte_size_, target);
}
for (int i = 0; i < this->value_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteFloatNoTagToArray(this->value(i), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.CollectionDef.FloatList)
return target;
}
size_t CollectionDef_FloatList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.CollectionDef.FloatList)
size_t total_size = 0;
// repeated float value = 1 [packed = true];
{
size_t data_size = 0;
unsigned int count = this->value_size();
data_size = 4UL * count;
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_value_cached_byte_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CollectionDef_FloatList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.CollectionDef.FloatList)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const CollectionDef_FloatList* source =
::google::protobuf::internal::DynamicCastToGenerated<const CollectionDef_FloatList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.CollectionDef.FloatList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.CollectionDef.FloatList)
UnsafeMergeFrom(*source);
}
}
void CollectionDef_FloatList::MergeFrom(const CollectionDef_FloatList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.CollectionDef.FloatList)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void CollectionDef_FloatList::UnsafeMergeFrom(const CollectionDef_FloatList& from) {
GOOGLE_DCHECK(&from != this);
value_.UnsafeMergeFrom(from.value_);
}
void CollectionDef_FloatList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.CollectionDef.FloatList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CollectionDef_FloatList::CopyFrom(const CollectionDef_FloatList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.CollectionDef.FloatList)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool CollectionDef_FloatList::IsInitialized() const {
return true;
}
void CollectionDef_FloatList::Swap(CollectionDef_FloatList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
CollectionDef_FloatList temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void CollectionDef_FloatList::UnsafeArenaSwap(CollectionDef_FloatList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void CollectionDef_FloatList::InternalSwap(CollectionDef_FloatList* other) {
value_.UnsafeArenaSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CollectionDef_FloatList::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CollectionDef_FloatList_descriptor_;
metadata.reflection = CollectionDef_FloatList_reflection_;
return metadata;
}
// -------------------------------------------------------------------
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CollectionDef_AnyList::kValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CollectionDef_AnyList::CollectionDef_AnyList()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.CollectionDef.AnyList)
}
CollectionDef_AnyList::CollectionDef_AnyList(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
value_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.CollectionDef.AnyList)
}
void CollectionDef_AnyList::InitAsDefaultInstance() {
}
CollectionDef_AnyList::CollectionDef_AnyList(const CollectionDef_AnyList& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.CollectionDef.AnyList)
}
void CollectionDef_AnyList::SharedCtor() {
_cached_size_ = 0;
}
CollectionDef_AnyList::~CollectionDef_AnyList() {
// @@protoc_insertion_point(destructor:tensorflow.CollectionDef.AnyList)
SharedDtor();
}
void CollectionDef_AnyList::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void CollectionDef_AnyList::ArenaDtor(void* object) {
CollectionDef_AnyList* _this = reinterpret_cast< CollectionDef_AnyList* >(object);
(void)_this;
}
void CollectionDef_AnyList::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void CollectionDef_AnyList::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CollectionDef_AnyList::descriptor() {
protobuf_AssignDescriptorsOnce();
return CollectionDef_AnyList_descriptor_;
}
const CollectionDef_AnyList& CollectionDef_AnyList::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<CollectionDef_AnyList> CollectionDef_AnyList_default_instance_;
CollectionDef_AnyList* CollectionDef_AnyList::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<CollectionDef_AnyList>(arena);
}
void CollectionDef_AnyList::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.CollectionDef.AnyList)
value_.Clear();
}
bool CollectionDef_AnyList::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.CollectionDef.AnyList)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.protobuf.Any value = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_value:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_value()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_value;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.CollectionDef.AnyList)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.CollectionDef.AnyList)
return false;
#undef DO_
}
void CollectionDef_AnyList::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.CollectionDef.AnyList)
// repeated .google.protobuf.Any value = 1;
for (unsigned int i = 0, n = this->value_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->value(i), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.CollectionDef.AnyList)
}
::google::protobuf::uint8* CollectionDef_AnyList::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.CollectionDef.AnyList)
// repeated .google.protobuf.Any value = 1;
for (unsigned int i = 0, n = this->value_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, this->value(i), false, target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.CollectionDef.AnyList)
return target;
}
size_t CollectionDef_AnyList::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.CollectionDef.AnyList)
size_t total_size = 0;
// repeated .google.protobuf.Any value = 1;
{
unsigned int count = this->value_size();
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->value(i));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CollectionDef_AnyList::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.CollectionDef.AnyList)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const CollectionDef_AnyList* source =
::google::protobuf::internal::DynamicCastToGenerated<const CollectionDef_AnyList>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.CollectionDef.AnyList)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.CollectionDef.AnyList)
UnsafeMergeFrom(*source);
}
}
void CollectionDef_AnyList::MergeFrom(const CollectionDef_AnyList& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.CollectionDef.AnyList)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void CollectionDef_AnyList::UnsafeMergeFrom(const CollectionDef_AnyList& from) {
GOOGLE_DCHECK(&from != this);
value_.MergeFrom(from.value_);
}
void CollectionDef_AnyList::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.CollectionDef.AnyList)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CollectionDef_AnyList::CopyFrom(const CollectionDef_AnyList& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.CollectionDef.AnyList)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool CollectionDef_AnyList::IsInitialized() const {
return true;
}
void CollectionDef_AnyList::Swap(CollectionDef_AnyList* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
CollectionDef_AnyList temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void CollectionDef_AnyList::UnsafeArenaSwap(CollectionDef_AnyList* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void CollectionDef_AnyList::InternalSwap(CollectionDef_AnyList* other) {
value_.UnsafeArenaSwap(&other->value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CollectionDef_AnyList::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CollectionDef_AnyList_descriptor_;
metadata.reflection = CollectionDef_AnyList_reflection_;
return metadata;
}
// -------------------------------------------------------------------
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int CollectionDef::kNodeListFieldNumber;
const int CollectionDef::kBytesListFieldNumber;
const int CollectionDef::kInt64ListFieldNumber;
const int CollectionDef::kFloatListFieldNumber;
const int CollectionDef::kAnyListFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
CollectionDef::CollectionDef()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.CollectionDef)
}
CollectionDef::CollectionDef(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.CollectionDef)
}
void CollectionDef::InitAsDefaultInstance() {
CollectionDef_default_oneof_instance_->node_list_ = const_cast< ::tensorflow::CollectionDef_NodeList*>(
::tensorflow::CollectionDef_NodeList::internal_default_instance());
CollectionDef_default_oneof_instance_->bytes_list_ = const_cast< ::tensorflow::CollectionDef_BytesList*>(
::tensorflow::CollectionDef_BytesList::internal_default_instance());
CollectionDef_default_oneof_instance_->int64_list_ = const_cast< ::tensorflow::CollectionDef_Int64List*>(
::tensorflow::CollectionDef_Int64List::internal_default_instance());
CollectionDef_default_oneof_instance_->float_list_ = const_cast< ::tensorflow::CollectionDef_FloatList*>(
::tensorflow::CollectionDef_FloatList::internal_default_instance());
CollectionDef_default_oneof_instance_->any_list_ = const_cast< ::tensorflow::CollectionDef_AnyList*>(
::tensorflow::CollectionDef_AnyList::internal_default_instance());
}
CollectionDef::CollectionDef(const CollectionDef& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.CollectionDef)
}
void CollectionDef::SharedCtor() {
clear_has_kind();
_cached_size_ = 0;
}
CollectionDef::~CollectionDef() {
// @@protoc_insertion_point(destructor:tensorflow.CollectionDef)
SharedDtor();
}
void CollectionDef::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
if (has_kind()) {
clear_kind();
}
}
void CollectionDef::ArenaDtor(void* object) {
CollectionDef* _this = reinterpret_cast< CollectionDef* >(object);
(void)_this;
}
void CollectionDef::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void CollectionDef::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CollectionDef::descriptor() {
protobuf_AssignDescriptorsOnce();
return CollectionDef_descriptor_;
}
const CollectionDef& CollectionDef::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<CollectionDef> CollectionDef_default_instance_;
CollectionDef* CollectionDef::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<CollectionDef>(arena);
}
void CollectionDef::clear_kind() {
// @@protoc_insertion_point(one_of_clear_start:tensorflow.CollectionDef)
switch (kind_case()) {
case kNodeList: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.node_list_;
}
break;
}
case kBytesList: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.bytes_list_;
}
break;
}
case kInt64List: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.int64_list_;
}
break;
}
case kFloatList: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.float_list_;
}
break;
}
case kAnyList: {
if (GetArenaNoVirtual() == NULL) {
delete kind_.any_list_;
}
break;
}
case KIND_NOT_SET: {
break;
}
}
_oneof_case_[0] = KIND_NOT_SET;
}
void CollectionDef::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.CollectionDef)
clear_kind();
}
bool CollectionDef::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.CollectionDef)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .tensorflow.CollectionDef.NodeList node_list = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_node_list()));
} else {
goto handle_unusual;
}
goto after_any_list;
break;
}
// optional .tensorflow.CollectionDef.BytesList bytes_list = 2;
case 2: {
if (tag == 18) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_bytes_list()));
} else {
goto handle_unusual;
}
goto after_any_list;
break;
}
// optional .tensorflow.CollectionDef.Int64List int64_list = 3;
case 3: {
if (tag == 26) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_int64_list()));
} else {
goto handle_unusual;
}
goto after_any_list;
break;
}
// optional .tensorflow.CollectionDef.FloatList float_list = 4;
case 4: {
if (tag == 34) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_float_list()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(42)) goto parse_any_list;
break;
}
// optional .tensorflow.CollectionDef.AnyList any_list = 5;
case 5: {
if (tag == 42) {
parse_any_list:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_any_list()));
} else {
goto handle_unusual;
}
after_any_list:
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.CollectionDef)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.CollectionDef)
return false;
#undef DO_
}
void CollectionDef::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.CollectionDef)
// optional .tensorflow.CollectionDef.NodeList node_list = 1;
if (has_node_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *kind_.node_list_, output);
}
// optional .tensorflow.CollectionDef.BytesList bytes_list = 2;
if (has_bytes_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *kind_.bytes_list_, output);
}
// optional .tensorflow.CollectionDef.Int64List int64_list = 3;
if (has_int64_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *kind_.int64_list_, output);
}
// optional .tensorflow.CollectionDef.FloatList float_list = 4;
if (has_float_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *kind_.float_list_, output);
}
// optional .tensorflow.CollectionDef.AnyList any_list = 5;
if (has_any_list()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *kind_.any_list_, output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.CollectionDef)
}
::google::protobuf::uint8* CollectionDef::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.CollectionDef)
// optional .tensorflow.CollectionDef.NodeList node_list = 1;
if (has_node_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *kind_.node_list_, false, target);
}
// optional .tensorflow.CollectionDef.BytesList bytes_list = 2;
if (has_bytes_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *kind_.bytes_list_, false, target);
}
// optional .tensorflow.CollectionDef.Int64List int64_list = 3;
if (has_int64_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *kind_.int64_list_, false, target);
}
// optional .tensorflow.CollectionDef.FloatList float_list = 4;
if (has_float_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, *kind_.float_list_, false, target);
}
// optional .tensorflow.CollectionDef.AnyList any_list = 5;
if (has_any_list()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
5, *kind_.any_list_, false, target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.CollectionDef)
return target;
}
size_t CollectionDef::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.CollectionDef)
size_t total_size = 0;
switch (kind_case()) {
// optional .tensorflow.CollectionDef.NodeList node_list = 1;
case kNodeList: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*kind_.node_list_);
break;
}
// optional .tensorflow.CollectionDef.BytesList bytes_list = 2;
case kBytesList: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*kind_.bytes_list_);
break;
}
// optional .tensorflow.CollectionDef.Int64List int64_list = 3;
case kInt64List: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*kind_.int64_list_);
break;
}
// optional .tensorflow.CollectionDef.FloatList float_list = 4;
case kFloatList: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*kind_.float_list_);
break;
}
// optional .tensorflow.CollectionDef.AnyList any_list = 5;
case kAnyList: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*kind_.any_list_);
break;
}
case KIND_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void CollectionDef::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.CollectionDef)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const CollectionDef* source =
::google::protobuf::internal::DynamicCastToGenerated<const CollectionDef>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.CollectionDef)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.CollectionDef)
UnsafeMergeFrom(*source);
}
}
void CollectionDef::MergeFrom(const CollectionDef& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.CollectionDef)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void CollectionDef::UnsafeMergeFrom(const CollectionDef& from) {
GOOGLE_DCHECK(&from != this);
switch (from.kind_case()) {
case kNodeList: {
mutable_node_list()->::tensorflow::CollectionDef_NodeList::MergeFrom(from.node_list());
break;
}
case kBytesList: {
mutable_bytes_list()->::tensorflow::CollectionDef_BytesList::MergeFrom(from.bytes_list());
break;
}
case kInt64List: {
mutable_int64_list()->::tensorflow::CollectionDef_Int64List::MergeFrom(from.int64_list());
break;
}
case kFloatList: {
mutable_float_list()->::tensorflow::CollectionDef_FloatList::MergeFrom(from.float_list());
break;
}
case kAnyList: {
mutable_any_list()->::tensorflow::CollectionDef_AnyList::MergeFrom(from.any_list());
break;
}
case KIND_NOT_SET: {
break;
}
}
}
void CollectionDef::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.CollectionDef)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void CollectionDef::CopyFrom(const CollectionDef& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.CollectionDef)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool CollectionDef::IsInitialized() const {
return true;
}
void CollectionDef::Swap(CollectionDef* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
CollectionDef temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void CollectionDef::UnsafeArenaSwap(CollectionDef* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void CollectionDef::InternalSwap(CollectionDef* other) {
std::swap(kind_, other->kind_);
std::swap(_oneof_case_[0], other->_oneof_case_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata CollectionDef::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = CollectionDef_descriptor_;
metadata.reflection = CollectionDef_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// CollectionDef_NodeList
// repeated string value = 1;
int CollectionDef_NodeList::value_size() const {
return value_.size();
}
void CollectionDef_NodeList::clear_value() {
value_.Clear();
}
const ::std::string& CollectionDef_NodeList::value(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.NodeList.value)
return value_.Get(index);
}
::std::string* CollectionDef_NodeList::mutable_value(int index) {
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.NodeList.value)
return value_.Mutable(index);
}
void CollectionDef_NodeList::set_value(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:tensorflow.CollectionDef.NodeList.value)
value_.Mutable(index)->assign(value);
}
void CollectionDef_NodeList::set_value(int index, const char* value) {
value_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:tensorflow.CollectionDef.NodeList.value)
}
void CollectionDef_NodeList::set_value(int index, const char* value, size_t size) {
value_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:tensorflow.CollectionDef.NodeList.value)
}
::std::string* CollectionDef_NodeList::add_value() {
// @@protoc_insertion_point(field_add_mutable:tensorflow.CollectionDef.NodeList.value)
return value_.Add();
}
void CollectionDef_NodeList::add_value(const ::std::string& value) {
value_.Add()->assign(value);
// @@protoc_insertion_point(field_add:tensorflow.CollectionDef.NodeList.value)
}
void CollectionDef_NodeList::add_value(const char* value) {
value_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:tensorflow.CollectionDef.NodeList.value)
}
void CollectionDef_NodeList::add_value(const char* value, size_t size) {
value_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:tensorflow.CollectionDef.NodeList.value)
}
const ::google::protobuf::RepeatedPtrField< ::std::string>&
CollectionDef_NodeList::value() const {
// @@protoc_insertion_point(field_list:tensorflow.CollectionDef.NodeList.value)
return value_;
}
::google::protobuf::RepeatedPtrField< ::std::string>*
CollectionDef_NodeList::mutable_value() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.CollectionDef.NodeList.value)
return &value_;
}
inline const CollectionDef_NodeList* CollectionDef_NodeList::internal_default_instance() {
return &CollectionDef_NodeList_default_instance_.get();
}
// -------------------------------------------------------------------
// CollectionDef_BytesList
// repeated bytes value = 1;
int CollectionDef_BytesList::value_size() const {
return value_.size();
}
void CollectionDef_BytesList::clear_value() {
value_.Clear();
}
const ::std::string& CollectionDef_BytesList::value(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.BytesList.value)
return value_.Get(index);
}
::std::string* CollectionDef_BytesList::mutable_value(int index) {
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.BytesList.value)
return value_.Mutable(index);
}
void CollectionDef_BytesList::set_value(int index, const ::std::string& value) {
// @@protoc_insertion_point(field_set:tensorflow.CollectionDef.BytesList.value)
value_.Mutable(index)->assign(value);
}
void CollectionDef_BytesList::set_value(int index, const char* value) {
value_.Mutable(index)->assign(value);
// @@protoc_insertion_point(field_set_char:tensorflow.CollectionDef.BytesList.value)
}
void CollectionDef_BytesList::set_value(int index, const void* value, size_t size) {
value_.Mutable(index)->assign(
reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_set_pointer:tensorflow.CollectionDef.BytesList.value)
}
::std::string* CollectionDef_BytesList::add_value() {
// @@protoc_insertion_point(field_add_mutable:tensorflow.CollectionDef.BytesList.value)
return value_.Add();
}
void CollectionDef_BytesList::add_value(const ::std::string& value) {
value_.Add()->assign(value);
// @@protoc_insertion_point(field_add:tensorflow.CollectionDef.BytesList.value)
}
void CollectionDef_BytesList::add_value(const char* value) {
value_.Add()->assign(value);
// @@protoc_insertion_point(field_add_char:tensorflow.CollectionDef.BytesList.value)
}
void CollectionDef_BytesList::add_value(const void* value, size_t size) {
value_.Add()->assign(reinterpret_cast<const char*>(value), size);
// @@protoc_insertion_point(field_add_pointer:tensorflow.CollectionDef.BytesList.value)
}
const ::google::protobuf::RepeatedPtrField< ::std::string>&
CollectionDef_BytesList::value() const {
// @@protoc_insertion_point(field_list:tensorflow.CollectionDef.BytesList.value)
return value_;
}
::google::protobuf::RepeatedPtrField< ::std::string>*
CollectionDef_BytesList::mutable_value() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.CollectionDef.BytesList.value)
return &value_;
}
inline const CollectionDef_BytesList* CollectionDef_BytesList::internal_default_instance() {
return &CollectionDef_BytesList_default_instance_.get();
}
// -------------------------------------------------------------------
// CollectionDef_Int64List
// repeated int64 value = 1 [packed = true];
int CollectionDef_Int64List::value_size() const {
return value_.size();
}
void CollectionDef_Int64List::clear_value() {
value_.Clear();
}
::google::protobuf::int64 CollectionDef_Int64List::value(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.Int64List.value)
return value_.Get(index);
}
void CollectionDef_Int64List::set_value(int index, ::google::protobuf::int64 value) {
value_.Set(index, value);
// @@protoc_insertion_point(field_set:tensorflow.CollectionDef.Int64List.value)
}
void CollectionDef_Int64List::add_value(::google::protobuf::int64 value) {
value_.Add(value);
// @@protoc_insertion_point(field_add:tensorflow.CollectionDef.Int64List.value)
}
const ::google::protobuf::RepeatedField< ::google::protobuf::int64 >&
CollectionDef_Int64List::value() const {
// @@protoc_insertion_point(field_list:tensorflow.CollectionDef.Int64List.value)
return value_;
}
::google::protobuf::RepeatedField< ::google::protobuf::int64 >*
CollectionDef_Int64List::mutable_value() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.CollectionDef.Int64List.value)
return &value_;
}
inline const CollectionDef_Int64List* CollectionDef_Int64List::internal_default_instance() {
return &CollectionDef_Int64List_default_instance_.get();
}
// -------------------------------------------------------------------
// CollectionDef_FloatList
// repeated float value = 1 [packed = true];
int CollectionDef_FloatList::value_size() const {
return value_.size();
}
void CollectionDef_FloatList::clear_value() {
value_.Clear();
}
float CollectionDef_FloatList::value(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.FloatList.value)
return value_.Get(index);
}
void CollectionDef_FloatList::set_value(int index, float value) {
value_.Set(index, value);
// @@protoc_insertion_point(field_set:tensorflow.CollectionDef.FloatList.value)
}
void CollectionDef_FloatList::add_value(float value) {
value_.Add(value);
// @@protoc_insertion_point(field_add:tensorflow.CollectionDef.FloatList.value)
}
const ::google::protobuf::RepeatedField< float >&
CollectionDef_FloatList::value() const {
// @@protoc_insertion_point(field_list:tensorflow.CollectionDef.FloatList.value)
return value_;
}
::google::protobuf::RepeatedField< float >*
CollectionDef_FloatList::mutable_value() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.CollectionDef.FloatList.value)
return &value_;
}
inline const CollectionDef_FloatList* CollectionDef_FloatList::internal_default_instance() {
return &CollectionDef_FloatList_default_instance_.get();
}
// -------------------------------------------------------------------
// CollectionDef_AnyList
// repeated .google.protobuf.Any value = 1;
int CollectionDef_AnyList::value_size() const {
return value_.size();
}
void CollectionDef_AnyList::clear_value() {
value_.Clear();
}
const ::google::protobuf::Any& CollectionDef_AnyList::value(int index) const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.AnyList.value)
return value_.Get(index);
}
::google::protobuf::Any* CollectionDef_AnyList::mutable_value(int index) {
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.AnyList.value)
return value_.Mutable(index);
}
::google::protobuf::Any* CollectionDef_AnyList::add_value() {
// @@protoc_insertion_point(field_add:tensorflow.CollectionDef.AnyList.value)
return value_.Add();
}
::google::protobuf::RepeatedPtrField< ::google::protobuf::Any >*
CollectionDef_AnyList::mutable_value() {
// @@protoc_insertion_point(field_mutable_list:tensorflow.CollectionDef.AnyList.value)
return &value_;
}
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Any >&
CollectionDef_AnyList::value() const {
// @@protoc_insertion_point(field_list:tensorflow.CollectionDef.AnyList.value)
return value_;
}
inline const CollectionDef_AnyList* CollectionDef_AnyList::internal_default_instance() {
return &CollectionDef_AnyList_default_instance_.get();
}
// -------------------------------------------------------------------
// CollectionDef
// optional .tensorflow.CollectionDef.NodeList node_list = 1;
bool CollectionDef::has_node_list() const {
return kind_case() == kNodeList;
}
void CollectionDef::set_has_node_list() {
_oneof_case_[0] = kNodeList;
}
void CollectionDef::clear_node_list() {
if (has_node_list()) {
if (GetArenaNoVirtual() == NULL) {
delete kind_.node_list_;
}
clear_has_kind();
}
}
const ::tensorflow::CollectionDef_NodeList& CollectionDef::node_list() const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.node_list)
return has_node_list()
? *kind_.node_list_
: ::tensorflow::CollectionDef_NodeList::default_instance();
}
::tensorflow::CollectionDef_NodeList* CollectionDef::mutable_node_list() {
if (!has_node_list()) {
clear_kind();
set_has_node_list();
kind_.node_list_ =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_NodeList >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.node_list)
return kind_.node_list_;
}
::tensorflow::CollectionDef_NodeList* CollectionDef::release_node_list() {
// @@protoc_insertion_point(field_release:tensorflow.CollectionDef.node_list)
if (has_node_list()) {
clear_has_kind();
if (GetArenaNoVirtual() != NULL) {
::tensorflow::CollectionDef_NodeList* temp = new ::tensorflow::CollectionDef_NodeList(*kind_.node_list_);
kind_.node_list_ = NULL;
return temp;
} else {
::tensorflow::CollectionDef_NodeList* temp = kind_.node_list_;
kind_.node_list_ = NULL;
return temp;
}
} else {
return NULL;
}
}
void CollectionDef::set_allocated_node_list(::tensorflow::CollectionDef_NodeList* node_list) {
clear_kind();
if (node_list) {
if (GetArenaNoVirtual() != NULL &&
::google::protobuf::Arena::GetArena(node_list) == NULL) {
GetArenaNoVirtual()->Own(node_list);
} else if (GetArenaNoVirtual() !=
::google::protobuf::Arena::GetArena(node_list)) {
::tensorflow::CollectionDef_NodeList* new_node_list =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_NodeList >(
GetArenaNoVirtual());
new_node_list->CopyFrom(*node_list);
node_list = new_node_list;
}
set_has_node_list();
kind_.node_list_ = node_list;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.CollectionDef.node_list)
}
::tensorflow::CollectionDef_NodeList* CollectionDef::unsafe_arena_release_node_list() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.CollectionDef.node_list)
if (has_node_list()) {
clear_has_kind();
::tensorflow::CollectionDef_NodeList* temp = kind_.node_list_;
kind_.node_list_ = NULL;
return temp;
} else {
return NULL;
}
}
void CollectionDef::unsafe_arena_set_allocated_node_list(::tensorflow::CollectionDef_NodeList* node_list) {
clear_kind();
if (node_list) {
set_has_node_list();
kind_.node_list_ = node_list;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CollectionDef.node_list)
}
// optional .tensorflow.CollectionDef.BytesList bytes_list = 2;
bool CollectionDef::has_bytes_list() const {
return kind_case() == kBytesList;
}
void CollectionDef::set_has_bytes_list() {
_oneof_case_[0] = kBytesList;
}
void CollectionDef::clear_bytes_list() {
if (has_bytes_list()) {
if (GetArenaNoVirtual() == NULL) {
delete kind_.bytes_list_;
}
clear_has_kind();
}
}
const ::tensorflow::CollectionDef_BytesList& CollectionDef::bytes_list() const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.bytes_list)
return has_bytes_list()
? *kind_.bytes_list_
: ::tensorflow::CollectionDef_BytesList::default_instance();
}
::tensorflow::CollectionDef_BytesList* CollectionDef::mutable_bytes_list() {
if (!has_bytes_list()) {
clear_kind();
set_has_bytes_list();
kind_.bytes_list_ =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_BytesList >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.bytes_list)
return kind_.bytes_list_;
}
::tensorflow::CollectionDef_BytesList* CollectionDef::release_bytes_list() {
// @@protoc_insertion_point(field_release:tensorflow.CollectionDef.bytes_list)
if (has_bytes_list()) {
clear_has_kind();
if (GetArenaNoVirtual() != NULL) {
::tensorflow::CollectionDef_BytesList* temp = new ::tensorflow::CollectionDef_BytesList(*kind_.bytes_list_);
kind_.bytes_list_ = NULL;
return temp;
} else {
::tensorflow::CollectionDef_BytesList* temp = kind_.bytes_list_;
kind_.bytes_list_ = NULL;
return temp;
}
} else {
return NULL;
}
}
void CollectionDef::set_allocated_bytes_list(::tensorflow::CollectionDef_BytesList* bytes_list) {
clear_kind();
if (bytes_list) {
if (GetArenaNoVirtual() != NULL &&
::google::protobuf::Arena::GetArena(bytes_list) == NULL) {
GetArenaNoVirtual()->Own(bytes_list);
} else if (GetArenaNoVirtual() !=
::google::protobuf::Arena::GetArena(bytes_list)) {
::tensorflow::CollectionDef_BytesList* new_bytes_list =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_BytesList >(
GetArenaNoVirtual());
new_bytes_list->CopyFrom(*bytes_list);
bytes_list = new_bytes_list;
}
set_has_bytes_list();
kind_.bytes_list_ = bytes_list;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.CollectionDef.bytes_list)
}
::tensorflow::CollectionDef_BytesList* CollectionDef::unsafe_arena_release_bytes_list() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.CollectionDef.bytes_list)
if (has_bytes_list()) {
clear_has_kind();
::tensorflow::CollectionDef_BytesList* temp = kind_.bytes_list_;
kind_.bytes_list_ = NULL;
return temp;
} else {
return NULL;
}
}
void CollectionDef::unsafe_arena_set_allocated_bytes_list(::tensorflow::CollectionDef_BytesList* bytes_list) {
clear_kind();
if (bytes_list) {
set_has_bytes_list();
kind_.bytes_list_ = bytes_list;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CollectionDef.bytes_list)
}
// optional .tensorflow.CollectionDef.Int64List int64_list = 3;
bool CollectionDef::has_int64_list() const {
return kind_case() == kInt64List;
}
void CollectionDef::set_has_int64_list() {
_oneof_case_[0] = kInt64List;
}
void CollectionDef::clear_int64_list() {
if (has_int64_list()) {
if (GetArenaNoVirtual() == NULL) {
delete kind_.int64_list_;
}
clear_has_kind();
}
}
const ::tensorflow::CollectionDef_Int64List& CollectionDef::int64_list() const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.int64_list)
return has_int64_list()
? *kind_.int64_list_
: ::tensorflow::CollectionDef_Int64List::default_instance();
}
::tensorflow::CollectionDef_Int64List* CollectionDef::mutable_int64_list() {
if (!has_int64_list()) {
clear_kind();
set_has_int64_list();
kind_.int64_list_ =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_Int64List >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.int64_list)
return kind_.int64_list_;
}
::tensorflow::CollectionDef_Int64List* CollectionDef::release_int64_list() {
// @@protoc_insertion_point(field_release:tensorflow.CollectionDef.int64_list)
if (has_int64_list()) {
clear_has_kind();
if (GetArenaNoVirtual() != NULL) {
::tensorflow::CollectionDef_Int64List* temp = new ::tensorflow::CollectionDef_Int64List(*kind_.int64_list_);
kind_.int64_list_ = NULL;
return temp;
} else {
::tensorflow::CollectionDef_Int64List* temp = kind_.int64_list_;
kind_.int64_list_ = NULL;
return temp;
}
} else {
return NULL;
}
}
void CollectionDef::set_allocated_int64_list(::tensorflow::CollectionDef_Int64List* int64_list) {
clear_kind();
if (int64_list) {
if (GetArenaNoVirtual() != NULL &&
::google::protobuf::Arena::GetArena(int64_list) == NULL) {
GetArenaNoVirtual()->Own(int64_list);
} else if (GetArenaNoVirtual() !=
::google::protobuf::Arena::GetArena(int64_list)) {
::tensorflow::CollectionDef_Int64List* new_int64_list =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_Int64List >(
GetArenaNoVirtual());
new_int64_list->CopyFrom(*int64_list);
int64_list = new_int64_list;
}
set_has_int64_list();
kind_.int64_list_ = int64_list;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.CollectionDef.int64_list)
}
::tensorflow::CollectionDef_Int64List* CollectionDef::unsafe_arena_release_int64_list() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.CollectionDef.int64_list)
if (has_int64_list()) {
clear_has_kind();
::tensorflow::CollectionDef_Int64List* temp = kind_.int64_list_;
kind_.int64_list_ = NULL;
return temp;
} else {
return NULL;
}
}
void CollectionDef::unsafe_arena_set_allocated_int64_list(::tensorflow::CollectionDef_Int64List* int64_list) {
clear_kind();
if (int64_list) {
set_has_int64_list();
kind_.int64_list_ = int64_list;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CollectionDef.int64_list)
}
// optional .tensorflow.CollectionDef.FloatList float_list = 4;
bool CollectionDef::has_float_list() const {
return kind_case() == kFloatList;
}
void CollectionDef::set_has_float_list() {
_oneof_case_[0] = kFloatList;
}
void CollectionDef::clear_float_list() {
if (has_float_list()) {
if (GetArenaNoVirtual() == NULL) {
delete kind_.float_list_;
}
clear_has_kind();
}
}
const ::tensorflow::CollectionDef_FloatList& CollectionDef::float_list() const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.float_list)
return has_float_list()
? *kind_.float_list_
: ::tensorflow::CollectionDef_FloatList::default_instance();
}
::tensorflow::CollectionDef_FloatList* CollectionDef::mutable_float_list() {
if (!has_float_list()) {
clear_kind();
set_has_float_list();
kind_.float_list_ =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_FloatList >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.float_list)
return kind_.float_list_;
}
::tensorflow::CollectionDef_FloatList* CollectionDef::release_float_list() {
// @@protoc_insertion_point(field_release:tensorflow.CollectionDef.float_list)
if (has_float_list()) {
clear_has_kind();
if (GetArenaNoVirtual() != NULL) {
::tensorflow::CollectionDef_FloatList* temp = new ::tensorflow::CollectionDef_FloatList(*kind_.float_list_);
kind_.float_list_ = NULL;
return temp;
} else {
::tensorflow::CollectionDef_FloatList* temp = kind_.float_list_;
kind_.float_list_ = NULL;
return temp;
}
} else {
return NULL;
}
}
void CollectionDef::set_allocated_float_list(::tensorflow::CollectionDef_FloatList* float_list) {
clear_kind();
if (float_list) {
if (GetArenaNoVirtual() != NULL &&
::google::protobuf::Arena::GetArena(float_list) == NULL) {
GetArenaNoVirtual()->Own(float_list);
} else if (GetArenaNoVirtual() !=
::google::protobuf::Arena::GetArena(float_list)) {
::tensorflow::CollectionDef_FloatList* new_float_list =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_FloatList >(
GetArenaNoVirtual());
new_float_list->CopyFrom(*float_list);
float_list = new_float_list;
}
set_has_float_list();
kind_.float_list_ = float_list;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.CollectionDef.float_list)
}
::tensorflow::CollectionDef_FloatList* CollectionDef::unsafe_arena_release_float_list() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.CollectionDef.float_list)
if (has_float_list()) {
clear_has_kind();
::tensorflow::CollectionDef_FloatList* temp = kind_.float_list_;
kind_.float_list_ = NULL;
return temp;
} else {
return NULL;
}
}
void CollectionDef::unsafe_arena_set_allocated_float_list(::tensorflow::CollectionDef_FloatList* float_list) {
clear_kind();
if (float_list) {
set_has_float_list();
kind_.float_list_ = float_list;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CollectionDef.float_list)
}
// optional .tensorflow.CollectionDef.AnyList any_list = 5;
bool CollectionDef::has_any_list() const {
return kind_case() == kAnyList;
}
void CollectionDef::set_has_any_list() {
_oneof_case_[0] = kAnyList;
}
void CollectionDef::clear_any_list() {
if (has_any_list()) {
if (GetArenaNoVirtual() == NULL) {
delete kind_.any_list_;
}
clear_has_kind();
}
}
const ::tensorflow::CollectionDef_AnyList& CollectionDef::any_list() const {
// @@protoc_insertion_point(field_get:tensorflow.CollectionDef.any_list)
return has_any_list()
? *kind_.any_list_
: ::tensorflow::CollectionDef_AnyList::default_instance();
}
::tensorflow::CollectionDef_AnyList* CollectionDef::mutable_any_list() {
if (!has_any_list()) {
clear_kind();
set_has_any_list();
kind_.any_list_ =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_AnyList >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:tensorflow.CollectionDef.any_list)
return kind_.any_list_;
}
::tensorflow::CollectionDef_AnyList* CollectionDef::release_any_list() {
// @@protoc_insertion_point(field_release:tensorflow.CollectionDef.any_list)
if (has_any_list()) {
clear_has_kind();
if (GetArenaNoVirtual() != NULL) {
::tensorflow::CollectionDef_AnyList* temp = new ::tensorflow::CollectionDef_AnyList(*kind_.any_list_);
kind_.any_list_ = NULL;
return temp;
} else {
::tensorflow::CollectionDef_AnyList* temp = kind_.any_list_;
kind_.any_list_ = NULL;
return temp;
}
} else {
return NULL;
}
}
void CollectionDef::set_allocated_any_list(::tensorflow::CollectionDef_AnyList* any_list) {
clear_kind();
if (any_list) {
if (GetArenaNoVirtual() != NULL &&
::google::protobuf::Arena::GetArena(any_list) == NULL) {
GetArenaNoVirtual()->Own(any_list);
} else if (GetArenaNoVirtual() !=
::google::protobuf::Arena::GetArena(any_list)) {
::tensorflow::CollectionDef_AnyList* new_any_list =
::google::protobuf::Arena::CreateMessage< ::tensorflow::CollectionDef_AnyList >(
GetArenaNoVirtual());
new_any_list->CopyFrom(*any_list);
any_list = new_any_list;
}
set_has_any_list();
kind_.any_list_ = any_list;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.CollectionDef.any_list)
}
::tensorflow::CollectionDef_AnyList* CollectionDef::unsafe_arena_release_any_list() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.CollectionDef.any_list)
if (has_any_list()) {
clear_has_kind();
::tensorflow::CollectionDef_AnyList* temp = kind_.any_list_;
kind_.any_list_ = NULL;
return temp;
} else {
return NULL;
}
}
void CollectionDef::unsafe_arena_set_allocated_any_list(::tensorflow::CollectionDef_AnyList* any_list) {
clear_kind();
if (any_list) {
set_has_any_list();
kind_.any_list_ = any_list;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.CollectionDef.any_list)
}
bool CollectionDef::has_kind() const {
return kind_case() != KIND_NOT_SET;
}
void CollectionDef::clear_has_kind() {
_oneof_case_[0] = KIND_NOT_SET;
}
CollectionDef::KindCase CollectionDef::kind_case() const {
return CollectionDef::KindCase(_oneof_case_[0]);
}
inline const CollectionDef* CollectionDef::internal_default_instance() {
return &CollectionDef_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TensorInfo_CooSparse::kValuesTensorNameFieldNumber;
const int TensorInfo_CooSparse::kIndicesTensorNameFieldNumber;
const int TensorInfo_CooSparse::kDenseShapeTensorNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TensorInfo_CooSparse::TensorInfo_CooSparse()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.TensorInfo.CooSparse)
}
TensorInfo_CooSparse::TensorInfo_CooSparse(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.TensorInfo.CooSparse)
}
void TensorInfo_CooSparse::InitAsDefaultInstance() {
}
TensorInfo_CooSparse::TensorInfo_CooSparse(const TensorInfo_CooSparse& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.TensorInfo.CooSparse)
}
void TensorInfo_CooSparse::SharedCtor() {
values_tensor_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
indices_tensor_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
dense_shape_tensor_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_cached_size_ = 0;
}
TensorInfo_CooSparse::~TensorInfo_CooSparse() {
// @@protoc_insertion_point(destructor:tensorflow.TensorInfo.CooSparse)
SharedDtor();
}
void TensorInfo_CooSparse::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
values_tensor_name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
indices_tensor_name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
dense_shape_tensor_name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
}
void TensorInfo_CooSparse::ArenaDtor(void* object) {
TensorInfo_CooSparse* _this = reinterpret_cast< TensorInfo_CooSparse* >(object);
(void)_this;
}
void TensorInfo_CooSparse::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TensorInfo_CooSparse::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TensorInfo_CooSparse::descriptor() {
protobuf_AssignDescriptorsOnce();
return TensorInfo_CooSparse_descriptor_;
}
const TensorInfo_CooSparse& TensorInfo_CooSparse::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<TensorInfo_CooSparse> TensorInfo_CooSparse_default_instance_;
TensorInfo_CooSparse* TensorInfo_CooSparse::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TensorInfo_CooSparse>(arena);
}
void TensorInfo_CooSparse::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.TensorInfo.CooSparse)
values_tensor_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
indices_tensor_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
dense_shape_tensor_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
bool TensorInfo_CooSparse::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.TensorInfo.CooSparse)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string values_tensor_name = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_values_tensor_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->values_tensor_name().data(), this->values_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.TensorInfo.CooSparse.values_tensor_name"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_indices_tensor_name;
break;
}
// optional string indices_tensor_name = 2;
case 2: {
if (tag == 18) {
parse_indices_tensor_name:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_indices_tensor_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->indices_tensor_name().data(), this->indices_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.TensorInfo.CooSparse.indices_tensor_name"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_dense_shape_tensor_name;
break;
}
// optional string dense_shape_tensor_name = 3;
case 3: {
if (tag == 26) {
parse_dense_shape_tensor_name:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_dense_shape_tensor_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->dense_shape_tensor_name().data(), this->dense_shape_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name"));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.TensorInfo.CooSparse)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.TensorInfo.CooSparse)
return false;
#undef DO_
}
void TensorInfo_CooSparse::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.TensorInfo.CooSparse)
// optional string values_tensor_name = 1;
if (this->values_tensor_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->values_tensor_name().data(), this->values_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.CooSparse.values_tensor_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->values_tensor_name(), output);
}
// optional string indices_tensor_name = 2;
if (this->indices_tensor_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->indices_tensor_name().data(), this->indices_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.CooSparse.indices_tensor_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->indices_tensor_name(), output);
}
// optional string dense_shape_tensor_name = 3;
if (this->dense_shape_tensor_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->dense_shape_tensor_name().data(), this->dense_shape_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
3, this->dense_shape_tensor_name(), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.TensorInfo.CooSparse)
}
::google::protobuf::uint8* TensorInfo_CooSparse::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.TensorInfo.CooSparse)
// optional string values_tensor_name = 1;
if (this->values_tensor_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->values_tensor_name().data(), this->values_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.CooSparse.values_tensor_name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->values_tensor_name(), target);
}
// optional string indices_tensor_name = 2;
if (this->indices_tensor_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->indices_tensor_name().data(), this->indices_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.CooSparse.indices_tensor_name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->indices_tensor_name(), target);
}
// optional string dense_shape_tensor_name = 3;
if (this->dense_shape_tensor_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->dense_shape_tensor_name().data(), this->dense_shape_tensor_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
3, this->dense_shape_tensor_name(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.TensorInfo.CooSparse)
return target;
}
size_t TensorInfo_CooSparse::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.TensorInfo.CooSparse)
size_t total_size = 0;
// optional string values_tensor_name = 1;
if (this->values_tensor_name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->values_tensor_name());
}
// optional string indices_tensor_name = 2;
if (this->indices_tensor_name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->indices_tensor_name());
}
// optional string dense_shape_tensor_name = 3;
if (this->dense_shape_tensor_name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->dense_shape_tensor_name());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TensorInfo_CooSparse::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.TensorInfo.CooSparse)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TensorInfo_CooSparse* source =
::google::protobuf::internal::DynamicCastToGenerated<const TensorInfo_CooSparse>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.TensorInfo.CooSparse)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.TensorInfo.CooSparse)
UnsafeMergeFrom(*source);
}
}
void TensorInfo_CooSparse::MergeFrom(const TensorInfo_CooSparse& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.TensorInfo.CooSparse)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void TensorInfo_CooSparse::UnsafeMergeFrom(const TensorInfo_CooSparse& from) {
GOOGLE_DCHECK(&from != this);
if (from.values_tensor_name().size() > 0) {
set_values_tensor_name(from.values_tensor_name());
}
if (from.indices_tensor_name().size() > 0) {
set_indices_tensor_name(from.indices_tensor_name());
}
if (from.dense_shape_tensor_name().size() > 0) {
set_dense_shape_tensor_name(from.dense_shape_tensor_name());
}
}
void TensorInfo_CooSparse::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.TensorInfo.CooSparse)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TensorInfo_CooSparse::CopyFrom(const TensorInfo_CooSparse& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.TensorInfo.CooSparse)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool TensorInfo_CooSparse::IsInitialized() const {
return true;
}
void TensorInfo_CooSparse::Swap(TensorInfo_CooSparse* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TensorInfo_CooSparse temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TensorInfo_CooSparse::UnsafeArenaSwap(TensorInfo_CooSparse* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TensorInfo_CooSparse::InternalSwap(TensorInfo_CooSparse* other) {
values_tensor_name_.Swap(&other->values_tensor_name_);
indices_tensor_name_.Swap(&other->indices_tensor_name_);
dense_shape_tensor_name_.Swap(&other->dense_shape_tensor_name_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TensorInfo_CooSparse::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TensorInfo_CooSparse_descriptor_;
metadata.reflection = TensorInfo_CooSparse_reflection_;
return metadata;
}
// -------------------------------------------------------------------
void TensorInfo::_slow_mutable_tensor_shape() {
tensor_shape_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorShapeProto >(
GetArenaNoVirtual());
}
::tensorflow::TensorShapeProto* TensorInfo::_slow_release_tensor_shape() {
if (tensor_shape_ == NULL) {
return NULL;
} else {
::tensorflow::TensorShapeProto* temp = new ::tensorflow::TensorShapeProto(*tensor_shape_);
tensor_shape_ = NULL;
return temp;
}
}
::tensorflow::TensorShapeProto* TensorInfo::unsafe_arena_release_tensor_shape() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorInfo.tensor_shape)
::tensorflow::TensorShapeProto* temp = tensor_shape_;
tensor_shape_ = NULL;
return temp;
}
void TensorInfo::_slow_set_allocated_tensor_shape(
::google::protobuf::Arena* message_arena, ::tensorflow::TensorShapeProto** tensor_shape) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*tensor_shape) == NULL) {
message_arena->Own(*tensor_shape);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*tensor_shape)) {
::tensorflow::TensorShapeProto* new_tensor_shape =
::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorShapeProto >(
message_arena);
new_tensor_shape->CopyFrom(**tensor_shape);
*tensor_shape = new_tensor_shape;
}
}
void TensorInfo::unsafe_arena_set_allocated_tensor_shape(
::tensorflow::TensorShapeProto* tensor_shape) {
if (GetArenaNoVirtual() == NULL) {
delete tensor_shape_;
}
tensor_shape_ = tensor_shape;
if (tensor_shape) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorInfo.tensor_shape)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TensorInfo::kNameFieldNumber;
const int TensorInfo::kCooSparseFieldNumber;
const int TensorInfo::kDtypeFieldNumber;
const int TensorInfo::kTensorShapeFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
TensorInfo::TensorInfo()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.TensorInfo)
}
TensorInfo::TensorInfo(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.TensorInfo)
}
void TensorInfo::InitAsDefaultInstance() {
TensorInfo_default_oneof_instance_->name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
TensorInfo_default_oneof_instance_->coo_sparse_ = const_cast< ::tensorflow::TensorInfo_CooSparse*>(
::tensorflow::TensorInfo_CooSparse::internal_default_instance());
tensor_shape_ = const_cast< ::tensorflow::TensorShapeProto*>(
::tensorflow::TensorShapeProto::internal_default_instance());
}
TensorInfo::TensorInfo(const TensorInfo& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.TensorInfo)
}
void TensorInfo::SharedCtor() {
tensor_shape_ = NULL;
dtype_ = 0;
clear_has_encoding();
_cached_size_ = 0;
}
TensorInfo::~TensorInfo() {
// @@protoc_insertion_point(destructor:tensorflow.TensorInfo)
SharedDtor();
}
void TensorInfo::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
if (has_encoding()) {
clear_encoding();
}
if (this != &TensorInfo_default_instance_.get()) {
delete tensor_shape_;
}
}
void TensorInfo::ArenaDtor(void* object) {
TensorInfo* _this = reinterpret_cast< TensorInfo* >(object);
(void)_this;
}
void TensorInfo::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TensorInfo::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TensorInfo::descriptor() {
protobuf_AssignDescriptorsOnce();
return TensorInfo_descriptor_;
}
const TensorInfo& TensorInfo::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<TensorInfo> TensorInfo_default_instance_;
TensorInfo* TensorInfo::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<TensorInfo>(arena);
}
void TensorInfo::clear_encoding() {
// @@protoc_insertion_point(one_of_clear_start:tensorflow.TensorInfo)
switch (encoding_case()) {
case kName: {
encoding_.name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
break;
}
case kCooSparse: {
if (GetArenaNoVirtual() == NULL) {
delete encoding_.coo_sparse_;
}
break;
}
case ENCODING_NOT_SET: {
break;
}
}
_oneof_case_[0] = ENCODING_NOT_SET;
}
void TensorInfo::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.TensorInfo)
dtype_ = 0;
if (GetArenaNoVirtual() == NULL && tensor_shape_ != NULL) delete tensor_shape_;
tensor_shape_ = NULL;
clear_encoding();
}
bool TensorInfo::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.TensorInfo)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional string name = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.TensorInfo.name"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(16)) goto parse_dtype;
break;
}
// optional .tensorflow.DataType dtype = 2;
case 2: {
if (tag == 16) {
parse_dtype:
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_dtype(static_cast< ::tensorflow::DataType >(value));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_tensor_shape;
break;
}
// optional .tensorflow.TensorShapeProto tensor_shape = 3;
case 3: {
if (tag == 26) {
parse_tensor_shape:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_tensor_shape()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(34)) goto parse_coo_sparse;
break;
}
// optional .tensorflow.TensorInfo.CooSparse coo_sparse = 4;
case 4: {
if (tag == 34) {
parse_coo_sparse:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_coo_sparse()));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.TensorInfo)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.TensorInfo)
return false;
#undef DO_
}
void TensorInfo::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.TensorInfo)
// optional string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// optional .tensorflow.DataType dtype = 2;
if (this->dtype() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
2, this->dtype(), output);
}
// optional .tensorflow.TensorShapeProto tensor_shape = 3;
if (this->has_tensor_shape()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, *this->tensor_shape_, output);
}
// optional .tensorflow.TensorInfo.CooSparse coo_sparse = 4;
if (has_coo_sparse()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
4, *encoding_.coo_sparse_, output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.TensorInfo)
}
::google::protobuf::uint8* TensorInfo::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.TensorInfo)
// optional string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.TensorInfo.name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// optional .tensorflow.DataType dtype = 2;
if (this->dtype() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
2, this->dtype(), target);
}
// optional .tensorflow.TensorShapeProto tensor_shape = 3;
if (this->has_tensor_shape()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
3, *this->tensor_shape_, false, target);
}
// optional .tensorflow.TensorInfo.CooSparse coo_sparse = 4;
if (has_coo_sparse()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
4, *encoding_.coo_sparse_, false, target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.TensorInfo)
return target;
}
size_t TensorInfo::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.TensorInfo)
size_t total_size = 0;
// optional .tensorflow.DataType dtype = 2;
if (this->dtype() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->dtype());
}
// optional .tensorflow.TensorShapeProto tensor_shape = 3;
if (this->has_tensor_shape()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->tensor_shape_);
}
switch (encoding_case()) {
// optional string name = 1;
case kName: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
break;
}
// optional .tensorflow.TensorInfo.CooSparse coo_sparse = 4;
case kCooSparse: {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*encoding_.coo_sparse_);
break;
}
case ENCODING_NOT_SET: {
break;
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void TensorInfo::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.TensorInfo)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const TensorInfo* source =
::google::protobuf::internal::DynamicCastToGenerated<const TensorInfo>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.TensorInfo)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.TensorInfo)
UnsafeMergeFrom(*source);
}
}
void TensorInfo::MergeFrom(const TensorInfo& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.TensorInfo)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void TensorInfo::UnsafeMergeFrom(const TensorInfo& from) {
GOOGLE_DCHECK(&from != this);
switch (from.encoding_case()) {
case kName: {
set_name(from.name());
break;
}
case kCooSparse: {
mutable_coo_sparse()->::tensorflow::TensorInfo_CooSparse::MergeFrom(from.coo_sparse());
break;
}
case ENCODING_NOT_SET: {
break;
}
}
if (from.dtype() != 0) {
set_dtype(from.dtype());
}
if (from.has_tensor_shape()) {
mutable_tensor_shape()->::tensorflow::TensorShapeProto::MergeFrom(from.tensor_shape());
}
}
void TensorInfo::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.TensorInfo)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void TensorInfo::CopyFrom(const TensorInfo& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.TensorInfo)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool TensorInfo::IsInitialized() const {
return true;
}
void TensorInfo::Swap(TensorInfo* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
TensorInfo temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void TensorInfo::UnsafeArenaSwap(TensorInfo* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void TensorInfo::InternalSwap(TensorInfo* other) {
std::swap(dtype_, other->dtype_);
std::swap(tensor_shape_, other->tensor_shape_);
std::swap(encoding_, other->encoding_);
std::swap(_oneof_case_[0], other->_oneof_case_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata TensorInfo::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = TensorInfo_descriptor_;
metadata.reflection = TensorInfo_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TensorInfo_CooSparse
// optional string values_tensor_name = 1;
void TensorInfo_CooSparse::clear_values_tensor_name() {
values_tensor_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& TensorInfo_CooSparse::values_tensor_name() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.CooSparse.values_tensor_name)
return values_tensor_name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void TensorInfo_CooSparse::set_values_tensor_name(const ::std::string& value) {
values_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.TensorInfo.CooSparse.values_tensor_name)
}
void TensorInfo_CooSparse::set_values_tensor_name(const char* value) {
values_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.TensorInfo.CooSparse.values_tensor_name)
}
void TensorInfo_CooSparse::set_values_tensor_name(const char* value,
size_t size) {
values_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.TensorInfo.CooSparse.values_tensor_name)
}
::std::string* TensorInfo_CooSparse::mutable_values_tensor_name() {
// @@protoc_insertion_point(field_mutable:tensorflow.TensorInfo.CooSparse.values_tensor_name)
return values_tensor_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* TensorInfo_CooSparse::release_values_tensor_name() {
// @@protoc_insertion_point(field_release:tensorflow.TensorInfo.CooSparse.values_tensor_name)
return values_tensor_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* TensorInfo_CooSparse::unsafe_arena_release_values_tensor_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorInfo.CooSparse.values_tensor_name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return values_tensor_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void TensorInfo_CooSparse::set_allocated_values_tensor_name(::std::string* values_tensor_name) {
if (values_tensor_name != NULL) {
} else {
}
values_tensor_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), values_tensor_name,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.TensorInfo.CooSparse.values_tensor_name)
}
void TensorInfo_CooSparse::unsafe_arena_set_allocated_values_tensor_name(
::std::string* values_tensor_name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (values_tensor_name != NULL) {
} else {
}
values_tensor_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
values_tensor_name, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorInfo.CooSparse.values_tensor_name)
}
// optional string indices_tensor_name = 2;
void TensorInfo_CooSparse::clear_indices_tensor_name() {
indices_tensor_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& TensorInfo_CooSparse::indices_tensor_name() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
return indices_tensor_name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void TensorInfo_CooSparse::set_indices_tensor_name(const ::std::string& value) {
indices_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
}
void TensorInfo_CooSparse::set_indices_tensor_name(const char* value) {
indices_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
}
void TensorInfo_CooSparse::set_indices_tensor_name(const char* value,
size_t size) {
indices_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
}
::std::string* TensorInfo_CooSparse::mutable_indices_tensor_name() {
// @@protoc_insertion_point(field_mutable:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
return indices_tensor_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* TensorInfo_CooSparse::release_indices_tensor_name() {
// @@protoc_insertion_point(field_release:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
return indices_tensor_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* TensorInfo_CooSparse::unsafe_arena_release_indices_tensor_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return indices_tensor_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void TensorInfo_CooSparse::set_allocated_indices_tensor_name(::std::string* indices_tensor_name) {
if (indices_tensor_name != NULL) {
} else {
}
indices_tensor_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), indices_tensor_name,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
}
void TensorInfo_CooSparse::unsafe_arena_set_allocated_indices_tensor_name(
::std::string* indices_tensor_name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (indices_tensor_name != NULL) {
} else {
}
indices_tensor_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
indices_tensor_name, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorInfo.CooSparse.indices_tensor_name)
}
// optional string dense_shape_tensor_name = 3;
void TensorInfo_CooSparse::clear_dense_shape_tensor_name() {
dense_shape_tensor_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& TensorInfo_CooSparse::dense_shape_tensor_name() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
return dense_shape_tensor_name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void TensorInfo_CooSparse::set_dense_shape_tensor_name(const ::std::string& value) {
dense_shape_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
}
void TensorInfo_CooSparse::set_dense_shape_tensor_name(const char* value) {
dense_shape_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
}
void TensorInfo_CooSparse::set_dense_shape_tensor_name(const char* value,
size_t size) {
dense_shape_tensor_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
}
::std::string* TensorInfo_CooSparse::mutable_dense_shape_tensor_name() {
// @@protoc_insertion_point(field_mutable:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
return dense_shape_tensor_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* TensorInfo_CooSparse::release_dense_shape_tensor_name() {
// @@protoc_insertion_point(field_release:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
return dense_shape_tensor_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* TensorInfo_CooSparse::unsafe_arena_release_dense_shape_tensor_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return dense_shape_tensor_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void TensorInfo_CooSparse::set_allocated_dense_shape_tensor_name(::std::string* dense_shape_tensor_name) {
if (dense_shape_tensor_name != NULL) {
} else {
}
dense_shape_tensor_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), dense_shape_tensor_name,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
}
void TensorInfo_CooSparse::unsafe_arena_set_allocated_dense_shape_tensor_name(
::std::string* dense_shape_tensor_name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (dense_shape_tensor_name != NULL) {
} else {
}
dense_shape_tensor_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
dense_shape_tensor_name, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorInfo.CooSparse.dense_shape_tensor_name)
}
inline const TensorInfo_CooSparse* TensorInfo_CooSparse::internal_default_instance() {
return &TensorInfo_CooSparse_default_instance_.get();
}
// -------------------------------------------------------------------
// TensorInfo
// optional string name = 1;
bool TensorInfo::has_name() const {
return encoding_case() == kName;
}
void TensorInfo::set_has_name() {
_oneof_case_[0] = kName;
}
void TensorInfo::clear_name() {
if (has_name()) {
encoding_.name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
clear_has_encoding();
}
}
const ::std::string& TensorInfo::name() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.name)
if (has_name()) {
return encoding_.name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
return *&::google::protobuf::internal::GetEmptyStringAlreadyInited();
}
void TensorInfo::set_name(const ::std::string& value) {
if (!has_name()) {
clear_encoding();
set_has_name();
encoding_.name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
encoding_.name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.TensorInfo.name)
}
void TensorInfo::set_name(const char* value) {
if (!has_name()) {
clear_encoding();
set_has_name();
encoding_.name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
encoding_.name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(value), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.TensorInfo.name)
}
void TensorInfo::set_name(const char* value,
size_t size) {
if (!has_name()) {
clear_encoding();
set_has_name();
encoding_.name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
encoding_.name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.TensorInfo.name)
}
::std::string* TensorInfo::mutable_name() {
if (!has_name()) {
clear_encoding();
set_has_name();
encoding_.name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
return encoding_.name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_mutable:tensorflow.TensorInfo.name)
}
::std::string* TensorInfo::release_name() {
// @@protoc_insertion_point(field_release:tensorflow.TensorInfo.name)
if (has_name()) {
clear_has_encoding();
return encoding_.name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
} else {
return NULL;
}
}
::std::string* TensorInfo::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorInfo.name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (has_name()) {
clear_has_encoding();
return encoding_.name_.UnsafeArenaRelease(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
} else {
return NULL;
}
}
void TensorInfo::set_allocated_name(::std::string* name) {
if (!has_name()) {
encoding_.name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
clear_encoding();
if (name != NULL) {
set_has_name();
encoding_.name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.TensorInfo.name)
}
void TensorInfo::unsafe_arena_set_allocated_name(::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (!has_name()) {
encoding_.name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
clear_encoding();
if (name) {
set_has_name();
encoding_.name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name, GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorInfo.name)
}
// optional .tensorflow.TensorInfo.CooSparse coo_sparse = 4;
bool TensorInfo::has_coo_sparse() const {
return encoding_case() == kCooSparse;
}
void TensorInfo::set_has_coo_sparse() {
_oneof_case_[0] = kCooSparse;
}
void TensorInfo::clear_coo_sparse() {
if (has_coo_sparse()) {
if (GetArenaNoVirtual() == NULL) {
delete encoding_.coo_sparse_;
}
clear_has_encoding();
}
}
const ::tensorflow::TensorInfo_CooSparse& TensorInfo::coo_sparse() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.coo_sparse)
return has_coo_sparse()
? *encoding_.coo_sparse_
: ::tensorflow::TensorInfo_CooSparse::default_instance();
}
::tensorflow::TensorInfo_CooSparse* TensorInfo::mutable_coo_sparse() {
if (!has_coo_sparse()) {
clear_encoding();
set_has_coo_sparse();
encoding_.coo_sparse_ =
::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorInfo_CooSparse >(
GetArenaNoVirtual());
}
// @@protoc_insertion_point(field_mutable:tensorflow.TensorInfo.coo_sparse)
return encoding_.coo_sparse_;
}
::tensorflow::TensorInfo_CooSparse* TensorInfo::release_coo_sparse() {
// @@protoc_insertion_point(field_release:tensorflow.TensorInfo.coo_sparse)
if (has_coo_sparse()) {
clear_has_encoding();
if (GetArenaNoVirtual() != NULL) {
::tensorflow::TensorInfo_CooSparse* temp = new ::tensorflow::TensorInfo_CooSparse(*encoding_.coo_sparse_);
encoding_.coo_sparse_ = NULL;
return temp;
} else {
::tensorflow::TensorInfo_CooSparse* temp = encoding_.coo_sparse_;
encoding_.coo_sparse_ = NULL;
return temp;
}
} else {
return NULL;
}
}
void TensorInfo::set_allocated_coo_sparse(::tensorflow::TensorInfo_CooSparse* coo_sparse) {
clear_encoding();
if (coo_sparse) {
if (GetArenaNoVirtual() != NULL &&
::google::protobuf::Arena::GetArena(coo_sparse) == NULL) {
GetArenaNoVirtual()->Own(coo_sparse);
} else if (GetArenaNoVirtual() !=
::google::protobuf::Arena::GetArena(coo_sparse)) {
::tensorflow::TensorInfo_CooSparse* new_coo_sparse =
::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorInfo_CooSparse >(
GetArenaNoVirtual());
new_coo_sparse->CopyFrom(*coo_sparse);
coo_sparse = new_coo_sparse;
}
set_has_coo_sparse();
encoding_.coo_sparse_ = coo_sparse;
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.TensorInfo.coo_sparse)
}
::tensorflow::TensorInfo_CooSparse* TensorInfo::unsafe_arena_release_coo_sparse() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorInfo.coo_sparse)
if (has_coo_sparse()) {
clear_has_encoding();
::tensorflow::TensorInfo_CooSparse* temp = encoding_.coo_sparse_;
encoding_.coo_sparse_ = NULL;
return temp;
} else {
return NULL;
}
}
void TensorInfo::unsafe_arena_set_allocated_coo_sparse(::tensorflow::TensorInfo_CooSparse* coo_sparse) {
clear_encoding();
if (coo_sparse) {
set_has_coo_sparse();
encoding_.coo_sparse_ = coo_sparse;
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorInfo.coo_sparse)
}
// optional .tensorflow.DataType dtype = 2;
void TensorInfo::clear_dtype() {
dtype_ = 0;
}
::tensorflow::DataType TensorInfo::dtype() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.dtype)
return static_cast< ::tensorflow::DataType >(dtype_);
}
void TensorInfo::set_dtype(::tensorflow::DataType value) {
dtype_ = value;
// @@protoc_insertion_point(field_set:tensorflow.TensorInfo.dtype)
}
// optional .tensorflow.TensorShapeProto tensor_shape = 3;
bool TensorInfo::has_tensor_shape() const {
return this != internal_default_instance() && tensor_shape_ != NULL;
}
void TensorInfo::clear_tensor_shape() {
if (GetArenaNoVirtual() == NULL && tensor_shape_ != NULL) delete tensor_shape_;
tensor_shape_ = NULL;
}
const ::tensorflow::TensorShapeProto& TensorInfo::tensor_shape() const {
// @@protoc_insertion_point(field_get:tensorflow.TensorInfo.tensor_shape)
return tensor_shape_ != NULL ? *tensor_shape_
: *::tensorflow::TensorShapeProto::internal_default_instance();
}
::tensorflow::TensorShapeProto* TensorInfo::mutable_tensor_shape() {
if (tensor_shape_ == NULL) {
_slow_mutable_tensor_shape();
}
// @@protoc_insertion_point(field_mutable:tensorflow.TensorInfo.tensor_shape)
return tensor_shape_;
}
::tensorflow::TensorShapeProto* TensorInfo::release_tensor_shape() {
// @@protoc_insertion_point(field_release:tensorflow.TensorInfo.tensor_shape)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_tensor_shape();
} else {
::tensorflow::TensorShapeProto* temp = tensor_shape_;
tensor_shape_ = NULL;
return temp;
}
}
void TensorInfo::set_allocated_tensor_shape(::tensorflow::TensorShapeProto* tensor_shape) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete tensor_shape_;
}
if (tensor_shape != NULL) {
_slow_set_allocated_tensor_shape(message_arena, &tensor_shape);
}
tensor_shape_ = tensor_shape;
if (tensor_shape) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.TensorInfo.tensor_shape)
}
bool TensorInfo::has_encoding() const {
return encoding_case() != ENCODING_NOT_SET;
}
void TensorInfo::clear_has_encoding() {
_oneof_case_[0] = ENCODING_NOT_SET;
}
TensorInfo::EncodingCase TensorInfo::encoding_case() const {
return TensorInfo::EncodingCase(_oneof_case_[0]);
}
inline const TensorInfo* TensorInfo::internal_default_instance() {
return &TensorInfo_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SignatureDef::kInputsFieldNumber;
const int SignatureDef::kOutputsFieldNumber;
const int SignatureDef::kMethodNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SignatureDef::SignatureDef()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.SignatureDef)
}
SignatureDef::SignatureDef(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
inputs_(arena),
outputs_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.SignatureDef)
}
void SignatureDef::InitAsDefaultInstance() {
}
SignatureDef::SignatureDef(const SignatureDef& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.SignatureDef)
}
void SignatureDef::SharedCtor() {
inputs_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
inputs_.SetEntryDescriptor(
&::tensorflow::SignatureDef_InputsEntry_descriptor_);
outputs_.SetAssignDescriptorCallback(
protobuf_AssignDescriptorsOnce);
outputs_.SetEntryDescriptor(
&::tensorflow::SignatureDef_OutputsEntry_descriptor_);
method_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_cached_size_ = 0;
}
SignatureDef::~SignatureDef() {
// @@protoc_insertion_point(destructor:tensorflow.SignatureDef)
SharedDtor();
}
void SignatureDef::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
method_name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
}
void SignatureDef::ArenaDtor(void* object) {
SignatureDef* _this = reinterpret_cast< SignatureDef* >(object);
(void)_this;
}
void SignatureDef::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void SignatureDef::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SignatureDef::descriptor() {
protobuf_AssignDescriptorsOnce();
return SignatureDef_descriptor_;
}
const SignatureDef& SignatureDef::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<SignatureDef> SignatureDef_default_instance_;
SignatureDef* SignatureDef::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<SignatureDef>(arena);
}
void SignatureDef::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.SignatureDef)
method_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
inputs_.Clear();
outputs_.Clear();
}
bool SignatureDef::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.SignatureDef)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// map<string, .tensorflow.TensorInfo> inputs = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_inputs:
SignatureDef_InputsEntry::Parser< ::google::protobuf::internal::MapField<
::std::string, ::tensorflow::TensorInfo,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo > > parser(&inputs_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), parser.key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.SignatureDef.InputsEntry.key"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_inputs;
if (input->ExpectTag(18)) goto parse_loop_outputs;
input->UnsafeDecrementRecursionDepth();
break;
}
// map<string, .tensorflow.TensorInfo> outputs = 2;
case 2: {
if (tag == 18) {
DO_(input->IncrementRecursionDepth());
parse_loop_outputs:
SignatureDef_OutputsEntry::Parser< ::google::protobuf::internal::MapField<
::std::string, ::tensorflow::TensorInfo,
::google::protobuf::internal::WireFormatLite::TYPE_STRING,
::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE,
0 >,
::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo > > parser(&outputs_);
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, &parser));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
parser.key().data(), parser.key().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.SignatureDef.OutputsEntry.key"));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_loop_outputs;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectTag(26)) goto parse_method_name;
break;
}
// optional string method_name = 3;
case 3: {
if (tag == 26) {
parse_method_name:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_method_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->method_name().data(), this->method_name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.SignatureDef.method_name"));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.SignatureDef)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.SignatureDef)
return false;
#undef DO_
}
void SignatureDef::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.SignatureDef)
// map<string, .tensorflow.TensorInfo> inputs = 1;
if (!this->inputs().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.SignatureDef.InputsEntry.key");
}
};
if (output->IsSerializationDeterminstic() &&
this->inputs().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->inputs().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->inputs().begin();
it != this->inputs().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<SignatureDef_InputsEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(inputs_.NewEntryWrapper(
items[i]->first, items[i]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<SignatureDef_InputsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->inputs().begin();
it != this->inputs().end(); ++it) {
entry.reset(inputs_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// map<string, .tensorflow.TensorInfo> outputs = 2;
if (!this->outputs().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.SignatureDef.OutputsEntry.key");
}
};
if (output->IsSerializationDeterminstic() &&
this->outputs().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->outputs().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->outputs().begin();
it != this->outputs().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<SignatureDef_OutputsEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(outputs_.NewEntryWrapper(
items[i]->first, items[i]->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<SignatureDef_OutputsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->outputs().begin();
it != this->outputs().end(); ++it) {
entry.reset(outputs_.NewEntryWrapper(
it->first, it->second));
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *entry, output);
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// optional string method_name = 3;
if (this->method_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->method_name().data(), this->method_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.SignatureDef.method_name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
3, this->method_name(), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.SignatureDef)
}
::google::protobuf::uint8* SignatureDef::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.SignatureDef)
// map<string, .tensorflow.TensorInfo> inputs = 1;
if (!this->inputs().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.SignatureDef.InputsEntry.key");
}
};
if (deterministic &&
this->inputs().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->inputs().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->inputs().begin();
it != this->inputs().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<SignatureDef_InputsEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(inputs_.NewEntryWrapper(
items[i]->first, items[i]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<SignatureDef_InputsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->inputs().begin();
it != this->inputs().end(); ++it) {
entry.reset(inputs_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// map<string, .tensorflow.TensorInfo> outputs = 2;
if (!this->outputs().empty()) {
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_pointer
ConstPtr;
typedef ConstPtr SortItem;
typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less;
struct Utf8Check {
static void Check(ConstPtr p) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
p->first.data(), p->first.length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.SignatureDef.OutputsEntry.key");
}
};
if (deterministic &&
this->outputs().size() > 1) {
::google::protobuf::scoped_array<SortItem> items(
new SortItem[this->outputs().size()]);
typedef ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::size_type size_type;
size_type n = 0;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->outputs().begin();
it != this->outputs().end(); ++it, ++n) {
items[n] = SortItem(&*it);
}
::std::sort(&items[0], &items[n], Less());
::google::protobuf::scoped_ptr<SignatureDef_OutputsEntry> entry;
for (size_type i = 0; i < n; i++) {
entry.reset(outputs_.NewEntryWrapper(
items[i]->first, items[i]->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(items[i]);
}
} else {
::google::protobuf::scoped_ptr<SignatureDef_OutputsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->outputs().begin();
it != this->outputs().end(); ++it) {
entry.reset(outputs_.NewEntryWrapper(
it->first, it->second));
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *entry, deterministic, target);
;
if (entry->GetArena() != NULL) {
entry.release();
}
Utf8Check::Check(&*it);
}
}
}
// optional string method_name = 3;
if (this->method_name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->method_name().data(), this->method_name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.SignatureDef.method_name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
3, this->method_name(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.SignatureDef)
return target;
}
size_t SignatureDef::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.SignatureDef)
size_t total_size = 0;
// optional string method_name = 3;
if (this->method_name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->method_name());
}
// map<string, .tensorflow.TensorInfo> inputs = 1;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->inputs_size());
{
::google::protobuf::scoped_ptr<SignatureDef_InputsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->inputs().begin();
it != this->inputs().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(inputs_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
// map<string, .tensorflow.TensorInfo> outputs = 2;
total_size += 1 *
::google::protobuf::internal::FromIntSize(this->outputs_size());
{
::google::protobuf::scoped_ptr<SignatureDef_OutputsEntry> entry;
for (::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >::const_iterator
it = this->outputs().begin();
it != this->outputs().end(); ++it) {
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
entry.reset(outputs_.NewEntryWrapper(it->first, it->second));
total_size += ::google::protobuf::internal::WireFormatLite::
MessageSizeNoVirtual(*entry);
}
if (entry.get() != NULL && entry->GetArena() != NULL) {
entry.release();
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SignatureDef::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.SignatureDef)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const SignatureDef* source =
::google::protobuf::internal::DynamicCastToGenerated<const SignatureDef>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.SignatureDef)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.SignatureDef)
UnsafeMergeFrom(*source);
}
}
void SignatureDef::MergeFrom(const SignatureDef& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.SignatureDef)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void SignatureDef::UnsafeMergeFrom(const SignatureDef& from) {
GOOGLE_DCHECK(&from != this);
inputs_.MergeFrom(from.inputs_);
outputs_.MergeFrom(from.outputs_);
if (from.method_name().size() > 0) {
set_method_name(from.method_name());
}
}
void SignatureDef::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.SignatureDef)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SignatureDef::CopyFrom(const SignatureDef& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.SignatureDef)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool SignatureDef::IsInitialized() const {
return true;
}
void SignatureDef::Swap(SignatureDef* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
SignatureDef temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void SignatureDef::UnsafeArenaSwap(SignatureDef* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void SignatureDef::InternalSwap(SignatureDef* other) {
inputs_.Swap(&other->inputs_);
outputs_.Swap(&other->outputs_);
method_name_.Swap(&other->method_name_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SignatureDef::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = SignatureDef_descriptor_;
metadata.reflection = SignatureDef_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// SignatureDef
// map<string, .tensorflow.TensorInfo> inputs = 1;
int SignatureDef::inputs_size() const {
return inputs_.size();
}
void SignatureDef::clear_inputs() {
inputs_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >&
SignatureDef::inputs() const {
// @@protoc_insertion_point(field_map:tensorflow.SignatureDef.inputs)
return inputs_.GetMap();
}
::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >*
SignatureDef::mutable_inputs() {
// @@protoc_insertion_point(field_mutable_map:tensorflow.SignatureDef.inputs)
return inputs_.MutableMap();
}
// map<string, .tensorflow.TensorInfo> outputs = 2;
int SignatureDef::outputs_size() const {
return outputs_.size();
}
void SignatureDef::clear_outputs() {
outputs_.Clear();
}
const ::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >&
SignatureDef::outputs() const {
// @@protoc_insertion_point(field_map:tensorflow.SignatureDef.outputs)
return outputs_.GetMap();
}
::google::protobuf::Map< ::std::string, ::tensorflow::TensorInfo >*
SignatureDef::mutable_outputs() {
// @@protoc_insertion_point(field_mutable_map:tensorflow.SignatureDef.outputs)
return outputs_.MutableMap();
}
// optional string method_name = 3;
void SignatureDef::clear_method_name() {
method_name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& SignatureDef::method_name() const {
// @@protoc_insertion_point(field_get:tensorflow.SignatureDef.method_name)
return method_name_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void SignatureDef::set_method_name(const ::std::string& value) {
method_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.SignatureDef.method_name)
}
void SignatureDef::set_method_name(const char* value) {
method_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.SignatureDef.method_name)
}
void SignatureDef::set_method_name(const char* value,
size_t size) {
method_name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.SignatureDef.method_name)
}
::std::string* SignatureDef::mutable_method_name() {
// @@protoc_insertion_point(field_mutable:tensorflow.SignatureDef.method_name)
return method_name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* SignatureDef::release_method_name() {
// @@protoc_insertion_point(field_release:tensorflow.SignatureDef.method_name)
return method_name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* SignatureDef::unsafe_arena_release_method_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.SignatureDef.method_name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return method_name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void SignatureDef::set_allocated_method_name(::std::string* method_name) {
if (method_name != NULL) {
} else {
}
method_name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), method_name,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.SignatureDef.method_name)
}
void SignatureDef::unsafe_arena_set_allocated_method_name(
::std::string* method_name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (method_name != NULL) {
} else {
}
method_name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
method_name, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.SignatureDef.method_name)
}
inline const SignatureDef* SignatureDef::internal_default_instance() {
return &SignatureDef_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
void AssetFileDef::_slow_mutable_tensor_info() {
tensor_info_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorInfo >(
GetArenaNoVirtual());
}
::tensorflow::TensorInfo* AssetFileDef::_slow_release_tensor_info() {
if (tensor_info_ == NULL) {
return NULL;
} else {
::tensorflow::TensorInfo* temp = new ::tensorflow::TensorInfo(*tensor_info_);
tensor_info_ = NULL;
return temp;
}
}
::tensorflow::TensorInfo* AssetFileDef::unsafe_arena_release_tensor_info() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.AssetFileDef.tensor_info)
::tensorflow::TensorInfo* temp = tensor_info_;
tensor_info_ = NULL;
return temp;
}
void AssetFileDef::_slow_set_allocated_tensor_info(
::google::protobuf::Arena* message_arena, ::tensorflow::TensorInfo** tensor_info) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*tensor_info) == NULL) {
message_arena->Own(*tensor_info);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*tensor_info)) {
::tensorflow::TensorInfo* new_tensor_info =
::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorInfo >(
message_arena);
new_tensor_info->CopyFrom(**tensor_info);
*tensor_info = new_tensor_info;
}
}
void AssetFileDef::unsafe_arena_set_allocated_tensor_info(
::tensorflow::TensorInfo* tensor_info) {
if (GetArenaNoVirtual() == NULL) {
delete tensor_info_;
}
tensor_info_ = tensor_info;
if (tensor_info) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.AssetFileDef.tensor_info)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int AssetFileDef::kTensorInfoFieldNumber;
const int AssetFileDef::kFilenameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
AssetFileDef::AssetFileDef()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.AssetFileDef)
}
AssetFileDef::AssetFileDef(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.AssetFileDef)
}
void AssetFileDef::InitAsDefaultInstance() {
tensor_info_ = const_cast< ::tensorflow::TensorInfo*>(
::tensorflow::TensorInfo::internal_default_instance());
}
AssetFileDef::AssetFileDef(const AssetFileDef& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:tensorflow.AssetFileDef)
}
void AssetFileDef::SharedCtor() {
filename_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
tensor_info_ = NULL;
_cached_size_ = 0;
}
AssetFileDef::~AssetFileDef() {
// @@protoc_insertion_point(destructor:tensorflow.AssetFileDef)
SharedDtor();
}
void AssetFileDef::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
filename_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
if (this != &AssetFileDef_default_instance_.get()) {
delete tensor_info_;
}
}
void AssetFileDef::ArenaDtor(void* object) {
AssetFileDef* _this = reinterpret_cast< AssetFileDef* >(object);
(void)_this;
}
void AssetFileDef::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void AssetFileDef::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* AssetFileDef::descriptor() {
protobuf_AssignDescriptorsOnce();
return AssetFileDef_descriptor_;
}
const AssetFileDef& AssetFileDef::default_instance() {
protobuf_InitDefaults_tensorflow_2fcore_2fprotobuf_2fmeta_5fgraph_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<AssetFileDef> AssetFileDef_default_instance_;
AssetFileDef* AssetFileDef::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<AssetFileDef>(arena);
}
void AssetFileDef::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.AssetFileDef)
if (GetArenaNoVirtual() == NULL && tensor_info_ != NULL) delete tensor_info_;
tensor_info_ = NULL;
filename_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
bool AssetFileDef::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.AssetFileDef)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .tensorflow.TensorInfo tensor_info = 1;
case 1: {
if (tag == 10) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_tensor_info()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_filename;
break;
}
// optional string filename = 2;
case 2: {
if (tag == 18) {
parse_filename:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_filename()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->filename().data(), this->filename().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.AssetFileDef.filename"));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.AssetFileDef)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.AssetFileDef)
return false;
#undef DO_
}
void AssetFileDef::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.AssetFileDef)
// optional .tensorflow.TensorInfo tensor_info = 1;
if (this->has_tensor_info()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, *this->tensor_info_, output);
}
// optional string filename = 2;
if (this->filename().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->filename().data(), this->filename().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.AssetFileDef.filename");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->filename(), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.AssetFileDef)
}
::google::protobuf::uint8* AssetFileDef::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.AssetFileDef)
// optional .tensorflow.TensorInfo tensor_info = 1;
if (this->has_tensor_info()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, *this->tensor_info_, false, target);
}
// optional string filename = 2;
if (this->filename().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->filename().data(), this->filename().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.AssetFileDef.filename");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->filename(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.AssetFileDef)
return target;
}
size_t AssetFileDef::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.AssetFileDef)
size_t total_size = 0;
// optional .tensorflow.TensorInfo tensor_info = 1;
if (this->has_tensor_info()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->tensor_info_);
}
// optional string filename = 2;
if (this->filename().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->filename());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void AssetFileDef::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.AssetFileDef)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const AssetFileDef* source =
::google::protobuf::internal::DynamicCastToGenerated<const AssetFileDef>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.AssetFileDef)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.AssetFileDef)
UnsafeMergeFrom(*source);
}
}
void AssetFileDef::MergeFrom(const AssetFileDef& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.AssetFileDef)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void AssetFileDef::UnsafeMergeFrom(const AssetFileDef& from) {
GOOGLE_DCHECK(&from != this);
if (from.has_tensor_info()) {
mutable_tensor_info()->::tensorflow::TensorInfo::MergeFrom(from.tensor_info());
}
if (from.filename().size() > 0) {
set_filename(from.filename());
}
}
void AssetFileDef::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.AssetFileDef)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void AssetFileDef::CopyFrom(const AssetFileDef& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.AssetFileDef)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool AssetFileDef::IsInitialized() const {
return true;
}
void AssetFileDef::Swap(AssetFileDef* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
AssetFileDef temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void AssetFileDef::UnsafeArenaSwap(AssetFileDef* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void AssetFileDef::InternalSwap(AssetFileDef* other) {
std::swap(tensor_info_, other->tensor_info_);
filename_.Swap(&other->filename_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata AssetFileDef::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = AssetFileDef_descriptor_;
metadata.reflection = AssetFileDef_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// AssetFileDef
// optional .tensorflow.TensorInfo tensor_info = 1;
bool AssetFileDef::has_tensor_info() const {
return this != internal_default_instance() && tensor_info_ != NULL;
}
void AssetFileDef::clear_tensor_info() {
if (GetArenaNoVirtual() == NULL && tensor_info_ != NULL) delete tensor_info_;
tensor_info_ = NULL;
}
const ::tensorflow::TensorInfo& AssetFileDef::tensor_info() const {
// @@protoc_insertion_point(field_get:tensorflow.AssetFileDef.tensor_info)
return tensor_info_ != NULL ? *tensor_info_
: *::tensorflow::TensorInfo::internal_default_instance();
}
::tensorflow::TensorInfo* AssetFileDef::mutable_tensor_info() {
if (tensor_info_ == NULL) {
_slow_mutable_tensor_info();
}
// @@protoc_insertion_point(field_mutable:tensorflow.AssetFileDef.tensor_info)
return tensor_info_;
}
::tensorflow::TensorInfo* AssetFileDef::release_tensor_info() {
// @@protoc_insertion_point(field_release:tensorflow.AssetFileDef.tensor_info)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_tensor_info();
} else {
::tensorflow::TensorInfo* temp = tensor_info_;
tensor_info_ = NULL;
return temp;
}
}
void AssetFileDef::set_allocated_tensor_info(::tensorflow::TensorInfo* tensor_info) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete tensor_info_;
}
if (tensor_info != NULL) {
_slow_set_allocated_tensor_info(message_arena, &tensor_info);
}
tensor_info_ = tensor_info;
if (tensor_info) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.AssetFileDef.tensor_info)
}
// optional string filename = 2;
void AssetFileDef::clear_filename() {
filename_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& AssetFileDef::filename() const {
// @@protoc_insertion_point(field_get:tensorflow.AssetFileDef.filename)
return filename_.Get(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void AssetFileDef::set_filename(const ::std::string& value) {
filename_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.AssetFileDef.filename)
}
void AssetFileDef::set_filename(const char* value) {
filename_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.AssetFileDef.filename)
}
void AssetFileDef::set_filename(const char* value,
size_t size) {
filename_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.AssetFileDef.filename)
}
::std::string* AssetFileDef::mutable_filename() {
// @@protoc_insertion_point(field_mutable:tensorflow.AssetFileDef.filename)
return filename_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* AssetFileDef::release_filename() {
// @@protoc_insertion_point(field_release:tensorflow.AssetFileDef.filename)
return filename_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* AssetFileDef::unsafe_arena_release_filename() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.AssetFileDef.filename)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return filename_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void AssetFileDef::set_allocated_filename(::std::string* filename) {
if (filename != NULL) {
} else {
}
filename_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), filename,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.AssetFileDef.filename)
}
void AssetFileDef::unsafe_arena_set_allocated_filename(
::std::string* filename) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (filename != NULL) {
} else {
}
filename_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
filename, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.AssetFileDef.filename)
}
inline const AssetFileDef* AssetFileDef::internal_default_instance() {
return &AssetFileDef_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace tensorflow
// @@protoc_insertion_point(global_scope)
| 294,519 | 100,270 |
//
// FILE NAME: CIDLib_SharedMemory.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/28/1997
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This method provides a derivative of TMemBuf that manages named, shared
// memory buffers. They are much like TSysBuf objects, but are named and
// can be shared between processes.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDLib_.hpp"
// ---------------------------------------------------------------------------
// Do our RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TSharedMemBuf,TMemBuf)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace CIDLib_SharedMemory
{
const tCIDLib::TCard2 c2FmtVersion = 1;
}
// ---------------------------------------------------------------------------
// CLASS: TSharedMemBuf
// PREFIX: mbuf
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TSharedMemBuf: Constructors and Destructor
// ---------------------------------------------------------------------------
TSharedMemBuf::TSharedMemBuf(const tCIDLib::TCard4 c4InitSize
, const tCIDLib::TCard4 c4MaxSize
, const TResourceName& rsnToUse
, tCIDLib::TBoolean& bCreated
, const tCIDLib::EMemAccFlags eAccessFlags
, const tCIDLib::ECreateActs eCreate) :
m_c4Size(c4InitSize)
, m_rsnThis(rsnToUse)
{
//
// Validate the size, but not the expand increment which is set
// implicitly by us and can never be wrong.
//
ValidateSizes(c4InitSize, c4MaxSize);
//
// Determine if we should just pre-commit. If the number of pages needed
// to hold the init and max size are the same, we can.
//
const tCIDLib::TCard4 c4InitPages = TRawMem::c4PagesCovered(c4InitSize);
const tCIDLib::TCard4 c4MaxPages = TRawMem::c4PagesCovered(c4MaxSize);
const tCIDLib::EAllocTypes eAlloc = (c4InitPages == c4MaxPages)
? tCIDLib::EAllocTypes::Commit
: tCIDLib::EAllocTypes::Lazy;
if (!m_ksmbThis.bAlloc
(
m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory).pszBuffer()
, c4MaxSize
, eAlloc
, eAccessFlags
, bCreated
, eCreate))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_AllocShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TCardinal(c4MaxSize)
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
//
// If we created it and its not a fully commited one, then commit the
// pages that are required for the initial size. If we didn't create
// it, then see if the init size is larger than the allocated size
// that we found on the existing buffer, and expand if so.
//
if (bCreated && (eAlloc == tCIDLib::EAllocTypes::Lazy))
{
if (!m_ksmbThis.bCommitToSize(c4InitSize))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_Commit
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TInteger(0)
, TCardinal(c4InitSize)
);
}
}
else if (c4InitSize > (m_ksmbThis.c4AllocatedPages() * kCIDLib::c4MemPageSize))
{
if (!m_ksmbThis.bCommitToSize(c4InitSize))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_Commit
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TInteger(0)
, TCardinal(c4InitSize)
);
}
}
}
TSharedMemBuf::TSharedMemBuf(const TSharedMemBuf& mbufToCopy) :
TMemBuf(mbufToCopy)
, m_c4Size(mbufToCopy.m_c4Size)
, m_rsnThis(mbufToCopy.m_rsnThis)
{
if (!m_ksmbThis.bDuplicate(mbufToCopy.m_ksmbThis))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_AllocShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
}
TSharedMemBuf::~TSharedMemBuf()
{
//
// If we have a buffer, then free it. We cannot just let it destruct
// because we have to catch any errors and translate them to CIDLib
// level errors.
//
if (m_ksmbThis.pData())
{
if (!m_ksmbThis.bFree())
{
// Log as a warning, so it does not propogate out of destructor
facCIDLib().LogKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_FreeShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Warn
, tCIDLib::EErrClasses::CantDo
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
}
}
// ---------------------------------------------------------------------------
// TSharedMemBuf: Public operators
// ---------------------------------------------------------------------------
TSharedMemBuf& TSharedMemBuf::operator=(const TSharedMemBuf& mbufToAssign)
{
if (this == &mbufToAssign)
return *this;
// Do our parent first
TParent::operator=(mbufToAssign);
// If there is an existing buffer, then free it
if (m_ksmbThis.pData())
{
if (!m_ksmbThis.bFree())
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_FreeShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Warn
, tCIDLib::EErrClasses::CantDo
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
}
// Copy all our members over now
m_c4Size = mbufToAssign.m_c4Size;
m_rsnThis = mbufToAssign.m_rsnThis;
// And duplicate the buffer
if (!m_ksmbThis.bDuplicate(mbufToAssign.m_ksmbThis))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_DupShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
return *this;
}
tCIDLib::TBoolean
TSharedMemBuf::operator!=(const TSharedMemBuf& mbufToTest) const
{
return !operator==(mbufToTest);
}
tCIDLib::TBoolean
TSharedMemBuf::operator==(const TSharedMemBuf& mbufToTest) const
{
if (this == &mbufToTest)
return kCIDLib::True;
if ((m_c4Size == mbufToTest.m_c4Size)
&& (m_ksmbThis == mbufToTest.m_ksmbThis)
&& (m_rsnThis == mbufToTest.m_rsnThis)
&& TParent::operator==(mbufToTest))
{
return kCIDLib::True;
}
return kCIDLib::False;
}
// ---------------------------------------------------------------------------
// TSharedMemBuf: Public, inherited methods
// ---------------------------------------------------------------------------
//
// This is the same as the StreamTo() method we inherit from the streamable
// interface, but sometimes we want to only stream part of the current size
// of the buffer, though it cannot be done generically via the streamable
// interface. In order to avoid redundant code, StreamTo() just calls us with
// the current allocation size.
//
tCIDLib::TVoid TSharedMemBuf::StreamCount( TBinOutStream& strmToWriteTo
, const tCIDLib::TCard4 c4Count) const
{
// Do our parent first
TParent::StreamTo(strmToWriteTo);
//
// Stream out our members. Start our part with a frame marker and do
// a format version so we can auto-upgrade this data later.
//
strmToWriteTo << tCIDLib::EStreamMarkers::Frame
<< CIDLib_SharedMemory::c2FmtVersion
<< c4Count
<< m_ksmbThis.eAccess()
<< m_ksmbThis.eAllocType()
<< m_ksmbThis.c4MaxSize()
<< m_rsnThis;
// Now stream out the actual data
strmToWriteTo.c4WriteRawBuffer(m_ksmbThis.pData(), c4Count);
// And end up with and end object marker
strmToWriteTo << tCIDLib::EStreamMarkers::EndObject;
}
// ---------------------------------------------------------------------------
// TSharedMemBuf: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::EMemAccFlags TSharedMemBuf::eAccess() const
{
return m_ksmbThis.eAccess();
}
tCIDLib::TCard4 TSharedMemBuf::c4AllocatedPages() const
{
return m_ksmbThis.c4AllocatedPages();
}
const TResourceName& TSharedMemBuf::rsnName() const
{
return m_rsnThis;
}
//
// This is a shared buffer, so it's possible for others to change it and
// force it to commit more pages. We cache the current size for efficiency,
// but we have to provide a way for apps to force us to resync with the
// actual system buffer status.
//
tCIDLib::TVoid TSharedMemBuf::SyncView()
{
if (!m_ksmbThis.bSyncView())
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_SyncView
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
);
}
// Set our size to the allocated pages times the page size
m_c4Size = m_ksmbThis.c4AllocatedPages() * kCIDLib::c4MemPageSize;
}
// ---------------------------------------------------------------------------
// TSharedMemBuf Hidden Constructors
//
// Needed for polymorphic streaming. Note that it will leave the object in
// a bad condition.
// ---------------------------------------------------------------------------
TSharedMemBuf::TSharedMemBuf() :
TMemBuf()
{
}
// ---------------------------------------------------------------------------
// TSharedMemBuf: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TCard1* TSharedMemBuf::pc1QueryBuf()
{
return reinterpret_cast<tCIDLib::TCard1*>(m_ksmbThis.pData());
}
const tCIDLib::TCard1* TSharedMemBuf::pc1QueryBuf() const
{
return reinterpret_cast<const tCIDLib::TCard1*>(m_ksmbThis.pData());
}
tCIDLib::TCard1*
TSharedMemBuf::pc1QueryBufInfo( tCIDLib::TCard4& c4CurSize
, tCIDLib::TCard4& c4MaxSize)
{
c4CurSize = m_c4Size;
c4MaxSize = m_ksmbThis.c4MaxSize();
return reinterpret_cast<tCIDLib::TCard1*>(m_ksmbThis.pData());
}
const tCIDLib::TCard1*
TSharedMemBuf::pc1QueryBufInfo( tCIDLib::TCard4& c4CurSize
, tCIDLib::TCard4& c4MaxSize) const
{
c4CurSize = m_c4Size;
c4MaxSize = m_ksmbThis.c4MaxSize();
return reinterpret_cast<tCIDLib::TCard1*>(m_ksmbThis.pData());
}
tCIDLib::TVoid
TSharedMemBuf::Realloc( const tCIDLib::TCard4 c4NewSize
, const tCIDLib::TBoolean bPreserve) const
{
//
// Since we commit in pages, but we maintain a byte oriented size
// for semantic reasons, its possible that our parent can call us to
// reallocate, but we really don't need to. If the new size fits
// within our existing pages, we can just increase our size value
// and leave it at that.
//
const tCIDLib::TCard4 c4NewPages = TRawMem::c4PagesCovered(c4NewSize);
tCIDLib::TCard4 c4CurPages = m_ksmbThis.c4AllocatedPages();
if (c4CurPages < c4NewPages)
{
//
// First, see if someone else has already expanded the buffer, in
// which case we can just pick up that existing data.
//
if (!m_ksmbThis.bSyncView())
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_SyncView
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
);
}
//
// If it filled the whole need, then just bump our size to the
// requested size. If we are to preserve, then we can then just
// return, since we just picked up existing content that is
// already in use.
//
c4CurPages = m_ksmbThis.c4AllocatedPages();
if (c4CurPages >= c4NewPages)
{
m_c4Size = c4NewSize;
if (bPreserve)
return;
}
// Still need to expand a bit more
if (!m_ksmbThis.bCommitToSize(c4NewSize))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_Commit
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TCardinal(m_c4Size)
, TCardinal(c4NewSize)
);
}
}
// Store the new actual size now
m_c4Size = c4NewSize;
}
tCIDLib::TVoid TSharedMemBuf::StreamFrom(TBinInStream& strmToReadFrom)
{
// Delete the current buffer
if (m_ksmbThis.pData())
{
if (!m_ksmbThis.bFree())
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_FreeShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
}
// Do our parent first
TParent::StreamFrom(strmToReadFrom);
// We should get a frame marker
strmToReadFrom.CheckForFrameMarker(CID_FILE, CID_LINE);
// Check the format version
tCIDLib::TCard2 c2FmtVersion;
strmToReadFrom >> c2FmtVersion;
if (c2FmtVersion != CIDLib_SharedMemory::c2FmtVersion)
{
facCIDLib().ThrowErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcGen_UnknownFmtVersion
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
, TCardinal(c2FmtVersion)
, clsThis()
);
}
// Get the new info out
tCIDLib::TCard4 c4MaxSize;
tCIDLib::EMemAccFlags eAccess;
tCIDLib::EAllocTypes eAllocType;
strmToReadFrom >> m_c4Size
>> eAccess
>> eAllocType
>> c4MaxSize
>> m_rsnThis;
// Create the buffer
tCIDLib::TBoolean bCreated;
if (!m_ksmbThis.bAlloc
(
m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory).pszBuffer()
, c4MaxSize
, eAllocType
, eAccess
, bCreated
, tCIDLib::ECreateActs::OpenOrCreate))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_AllocShared
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, m_rsnThis.strFullName(tCIDLib::ENamedRscTypes::Memory)
);
}
// Commit up to where it was before
if (!m_ksmbThis.bCommitToSize(m_c4Size))
{
facCIDLib().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMBuf_Commit
, TKrnlError::kerrLast()
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TInteger(0)
, TCardinal(m_c4Size)
);
}
// Now read in the actual data
strmToReadFrom.c4ReadRawBuffer(m_ksmbThis.pData(), m_c4Size);
// We should get an end object marker
strmToReadFrom.CheckForEndMarker(CID_FILE, CID_LINE);
}
tCIDLib::TVoid TSharedMemBuf::StreamTo(TBinOutStream& strmToWriteTo) const
{
// Just call the StreamCount() method with our alloc size
StreamCount(strmToWriteTo, m_c4Size);
}
| 17,404 | 5,589 |
#include <TexturePCH.h>
#include <Texture/Image/ImageUtils.h>
#include <Foundation/SimdMath/SimdVec4f.h>
#include <Texture/Image/ImageConversion.h>
#include <Texture/Image/ImageEnums.h>
#include <Texture/Image/ImageFilter.h>
template <typename TYPE>
static void SetDiff(
const ezImageView& ImageA, const ezImageView& ImageB, ezImage& out_Difference, ezUInt32 w, ezUInt32 h, ezUInt32 d, ezUInt32 comp)
{
const TYPE* pA = ImageA.GetPixelPointer<TYPE>(0, 0, 0, w, h, d);
const TYPE* pB = ImageB.GetPixelPointer<TYPE>(0, 0, 0, w, h, d);
TYPE* pR = out_Difference.GetPixelPointer<TYPE>(0, 0, 0, w, h, d);
for (ezUInt32 i = 0; i < comp; ++i)
pR[i] = pB[i] > pA[i] ? (pB[i] - pA[i]) : (pA[i] - pB[i]);
}
template <typename TYPE>
static ezUInt32 GetError(const ezImageView& Difference, ezUInt32 w, ezUInt32 h, ezUInt32 d, ezUInt32 comp, ezUInt32 pixel)
{
const TYPE* pR = Difference.GetPixelPointer<TYPE>(0, 0, 0, w, h, d);
ezUInt32 uiErrorSum = 0;
for (ezUInt32 p = 0; p < pixel; ++p)
{
ezUInt32 error = 0;
for (ezUInt32 c = 0; c < comp; ++c)
{
error += *pR;
++pR;
}
error /= comp;
uiErrorSum += error * error;
}
return uiErrorSum;
}
void ezImageUtils::ComputeImageDifferenceABS(const ezImageView& ImageA, const ezImageView& ImageB, ezImage& out_Difference)
{
EZ_ASSERT_DEV(ImageA.GetWidth() == ImageB.GetWidth(), "Dimensions do not match");
EZ_ASSERT_DEV(ImageA.GetHeight() == ImageB.GetHeight(), "Dimensions do not match");
EZ_ASSERT_DEV(ImageA.GetDepth() == ImageB.GetDepth(), "Dimensions do not match");
EZ_ASSERT_DEV(ImageA.GetImageFormat() == ImageB.GetImageFormat(), "Format does not match");
ezImageHeader differenceHeader;
differenceHeader.SetWidth(ImageA.GetWidth());
differenceHeader.SetHeight(ImageA.GetHeight());
differenceHeader.SetDepth(ImageA.GetDepth());
differenceHeader.SetImageFormat(ImageA.GetImageFormat());
out_Difference.ResetAndAlloc(differenceHeader);
const ezUInt32 uiSize2D = ImageA.GetHeight() * ImageA.GetWidth();
for (ezUInt32 d = 0; d < ImageA.GetDepth(); ++d)
{
// for (ezUInt32 h = 0; h < ImageA.GetHeight(); ++h)
{
// for (ezUInt32 w = 0; w < ImageA.GetWidth(); ++w)
{
switch (ImageA.GetImageFormat())
{
case ezImageFormat::R8G8B8A8_UNORM:
case ezImageFormat::R8G8B8A8_UNORM_SRGB:
case ezImageFormat::R8G8B8A8_UINT:
case ezImageFormat::R8G8B8A8_SNORM:
case ezImageFormat::R8G8B8A8_SINT:
case ezImageFormat::B8G8R8A8_UNORM:
case ezImageFormat::B8G8R8X8_UNORM:
case ezImageFormat::B8G8R8A8_UNORM_SRGB:
case ezImageFormat::B8G8R8X8_UNORM_SRGB:
{
SetDiff<ezUInt8>(ImageA, ImageB, out_Difference, 0, 0, d, 4 * uiSize2D);
}
break;
case ezImageFormat::B8G8R8_UNORM:
{
SetDiff<ezUInt8>(ImageA, ImageB, out_Difference, 0, 0, d, 3 * uiSize2D);
}
break;
default:
EZ_REPORT_FAILURE("The ezImageFormat {0} is not implemented", (ezUInt32)ImageA.GetImageFormat());
return;
}
}
}
}
}
ezUInt32 ezImageUtils::ComputeMeanSquareError(const ezImageView& DifferenceImage, ezUInt8 uiBlockSize, ezUInt32 offsetx, ezUInt32 offsety)
{
EZ_ASSERT_DEV(uiBlockSize > 1, "Blocksize must be at least 2");
ezUInt32 uiWidth = ezMath::Min(DifferenceImage.GetWidth(), offsetx + uiBlockSize) - offsetx;
ezUInt32 uiHeight = ezMath::Min(DifferenceImage.GetHeight(), offsety + uiBlockSize) - offsety;
if (uiWidth == 0 || uiHeight == 0)
return 0;
switch (DifferenceImage.GetImageFormat())
{
// Supported formats
case ezImageFormat::R8G8B8A8_UNORM:
case ezImageFormat::R8G8B8A8_UNORM_SRGB:
case ezImageFormat::R8G8B8A8_UINT:
case ezImageFormat::R8G8B8A8_SNORM:
case ezImageFormat::R8G8B8A8_SINT:
case ezImageFormat::B8G8R8A8_UNORM:
case ezImageFormat::B8G8R8A8_UNORM_SRGB:
case ezImageFormat::B8G8R8_UNORM:
break;
default:
EZ_REPORT_FAILURE("The ezImageFormat {0} is not implemented", (ezUInt32)DifferenceImage.GetImageFormat());
return 0;
}
ezUInt32 error = 0;
ezUInt64 uiRowPitch = DifferenceImage.GetRowPitch();
ezUInt64 uiDepthPitch = DifferenceImage.GetDepthPitch();
ezUInt32 uiNumComponents = ezImageFormat::GetNumChannels(DifferenceImage.GetImageFormat());
// Treat image as single-component format and scale the width instead
uiWidth *= uiNumComponents;
const ezUInt32 uiSize2D = uiWidth * uiHeight;
const ezUInt8* pSlicePointer = DifferenceImage.GetPixelPointer<ezUInt8>(0, 0, 0, offsetx, offsety);
for (ezUInt32 d = 0; d < DifferenceImage.GetDepth(); ++d)
{
const ezUInt8* pRowPointer = pSlicePointer;
for (ezUInt32 y = 0; y < uiHeight; ++y)
{
const ezUInt8* pPixelPointer = pRowPointer;
for (ezUInt32 x = 0; x < uiWidth; ++x)
{
ezUInt32 uiDiff = *pPixelPointer;
error += uiDiff * uiDiff;
pPixelPointer++;
}
pRowPointer += uiRowPitch;
}
pSlicePointer += uiDepthPitch;
}
error /= uiSize2D;
return error;
}
ezUInt32 ezImageUtils::ComputeMeanSquareError(const ezImageView& DifferenceImage, ezUInt8 uiBlockSize)
{
EZ_ASSERT_DEV(uiBlockSize > 1, "Blocksize must be at least 2");
const ezUInt32 uiHalfBlockSize = uiBlockSize / 2;
const ezUInt32 uiBlocksX = (DifferenceImage.GetWidth() / uiHalfBlockSize) + 1;
const ezUInt32 uiBlocksY = (DifferenceImage.GetHeight() / uiHalfBlockSize) + 1;
ezUInt32 uiMaxError = 0;
for (ezUInt32 by = 0; by < uiBlocksY; ++by)
{
for (ezUInt32 bx = 0; bx < uiBlocksX; ++bx)
{
const ezUInt32 uiBlockError = ComputeMeanSquareError(DifferenceImage, uiBlockSize, bx * uiHalfBlockSize, by * uiHalfBlockSize);
uiMaxError = ezMath::Max(uiMaxError, uiBlockError);
}
}
return uiMaxError;
}
template <typename Func, typename ImageType>
static void ApplyFunc(ImageType& image, Func func)
{
ezUInt32 uiWidth = image.GetWidth();
ezUInt32 uiHeight = image.GetHeight();
ezUInt32 uiDepth = image.GetDepth();
EZ_ASSERT_DEV(uiWidth > 0 && uiHeight > 0 && uiDepth > 0, "The image passed to FindMinMax has illegal dimension {}x{}x{}.", uiWidth,
uiHeight, uiDepth);
ezUInt64 uiRowPitch = image.GetRowPitch();
ezUInt64 uiDepthPitch = image.GetDepthPitch();
ezUInt32 uiNumChannels = ezImageFormat::GetNumChannels(image.GetImageFormat());
auto pSlicePointer = image.template GetPixelPointer<ezUInt8>();
for (ezUInt32 z = 0; z < image.GetDepth(); ++z)
{
auto pRowPointer = pSlicePointer;
for (ezUInt32 y = 0; y < uiHeight; ++y)
{
auto pPixelPointer = pRowPointer;
for (ezUInt32 x = 0; x < uiWidth; ++x)
{
for (ezUInt32 c = 0; c < uiNumChannels; ++c)
{
func(pPixelPointer++, x, y, z, c);
}
}
pRowPointer += uiRowPitch;
}
pSlicePointer += uiDepthPitch;
}
}
static void FindMinMax(const ezImageView& image, ezUInt8& uiMinRgb, ezUInt8& uiMaxRgb, ezUInt8& uiMinAlpha, ezUInt8& uiMaxAlpha)
{
ezImageFormat::Enum imageFormat = image.GetImageFormat();
EZ_ASSERT_DEV(ezImageFormat::GetBitsPerChannel(imageFormat, ezImageFormatChannel::R) == 8 &&
ezImageFormat::GetDataType(imageFormat) == ezImageFormatDataType::UNORM,
"Only 8bpp unorm formats are supported in FindMinMax");
uiMinRgb = 255u;
uiMinAlpha = 255u;
uiMaxRgb = 0u;
uiMaxAlpha = 0u;
auto minMax = [&](const ezUInt8* pixel, ezUInt32 /*x*/, ezUInt32 /*y*/, ezUInt32 /*z*/, ezUInt32 c) {
ezUInt8 val = *pixel;
if (c < 3)
{
uiMinRgb = ezMath::Min(uiMinRgb, val);
uiMaxRgb = ezMath::Max(uiMaxRgb, val);
}
else
{
uiMinAlpha = ezMath::Min(uiMinAlpha, val);
uiMaxAlpha = ezMath::Max(uiMaxAlpha, val);
}
};
ApplyFunc(image, minMax);
}
void ezImageUtils::Normalize(ezImage& image)
{
ezUInt8 uiMinRgb, uiMaxRgb, uiMinAlpha, uiMaxAlpha;
Normalize(image, uiMinRgb, uiMaxRgb, uiMinAlpha, uiMaxAlpha);
}
void ezImageUtils::Normalize(ezImage& image, ezUInt8& uiMinRgb, ezUInt8& uiMaxRgb, ezUInt8& uiMinAlpha, ezUInt8& uiMaxAlpha)
{
ezImageFormat::Enum imageFormat = image.GetImageFormat();
EZ_ASSERT_DEV(ezImageFormat::GetBitsPerChannel(imageFormat, ezImageFormatChannel::R) == 8 &&
ezImageFormat::GetDataType(imageFormat) == ezImageFormatDataType::UNORM,
"Only 8bpp unorm formats are supported in NormalizeImage");
bool ignoreAlpha = false;
if (imageFormat == ezImageFormat::B8G8R8X8_UNORM || imageFormat == ezImageFormat::B8G8R8X8_UNORM_SRGB)
{
ignoreAlpha = true;
}
FindMinMax(image, uiMinRgb, uiMaxRgb, uiMinAlpha, uiMaxAlpha);
ezUInt8 uiRangeRgb = uiMaxRgb - uiMinRgb;
ezUInt8 uiRangeAlpha = uiMaxAlpha - uiMinAlpha;
auto normalize = [&](ezUInt8* pixel, ezUInt32 /*x*/, ezUInt32 /*y*/, ezUInt32 /*z*/, ezUInt32 c) {
ezUInt8 val = *pixel;
if (c < 3)
{
// color channels are uniform when min == max, in that case keep original value as scaling is not meaningful
if (uiRangeRgb != 0)
{
*pixel = static_cast<ezUInt8>(255u * (static_cast<float>(val - uiMinRgb) / (uiRangeRgb)));
}
}
else
{
// alpha is uniform when minAlpha == maxAlpha, in that case keep original alpha as scaling is not meaningful
if (!ignoreAlpha && uiRangeAlpha != 0)
{
*pixel = static_cast<ezUInt8>(255u * (static_cast<float>(val - uiMinAlpha) / (uiRangeAlpha)));
}
}
};
ApplyFunc(image, normalize);
}
void ezImageUtils::ExtractAlphaChannel(const ezImageView& inputImage, ezImage& outputImage)
{
switch (ezImageFormat::Enum imageFormat = inputImage.GetImageFormat())
{
case ezImageFormat::R8G8B8A8_UNORM:
case ezImageFormat::R8G8B8A8_UNORM_SRGB:
case ezImageFormat::R8G8B8A8_UINT:
case ezImageFormat::R8G8B8A8_SNORM:
case ezImageFormat::R8G8B8A8_SINT:
case ezImageFormat::B8G8R8A8_UNORM:
case ezImageFormat::B8G8R8A8_UNORM_SRGB:
break;
default:
EZ_REPORT_FAILURE(
"ExtractAlpha needs an image with 8bpp and 4 channel. The ezImageFormat {} is not supported.", (ezUInt32)imageFormat);
return;
}
ezImageHeader outputHeader = inputImage.GetHeader();
outputHeader.SetImageFormat(ezImageFormat::R8_UNORM);
outputImage.ResetAndAlloc(outputHeader);
const ezUInt8* pInputSlice = inputImage.GetPixelPointer<ezUInt8>();
ezUInt8* pOutputSlice = outputImage.GetPixelPointer<ezUInt8>();
ezUInt64 uiInputRowPitch = inputImage.GetRowPitch();
ezUInt64 uiInputDepthPitch = inputImage.GetDepthPitch();
ezUInt64 uiOutputRowPitch = outputImage.GetRowPitch();
ezUInt64 uiOutputDepthPitch = outputImage.GetDepthPitch();
for (ezUInt32 d = 0; d < inputImage.GetDepth(); ++d)
{
const ezUInt8* pInputRow = pInputSlice;
ezUInt8* pOutputRow = pOutputSlice;
for (ezUInt32 y = 0; y < inputImage.GetHeight(); ++y)
{
const ezUInt8* pInputPixel = pInputRow;
ezUInt8* pOutputPixel = pOutputRow;
for (ezUInt32 x = 0; x < inputImage.GetWidth(); ++x)
{
*pOutputPixel = pInputPixel[3];
pInputPixel += 4;
++pOutputPixel;
}
pInputRow += uiInputRowPitch;
pOutputRow += uiOutputRowPitch;
}
pInputSlice += uiInputDepthPitch;
pOutputSlice += uiOutputDepthPitch;
}
}
void ezImageUtils::CropImage(const ezImageView& input, const ezVec2I32& offset, const ezSizeU32& newsize, ezImage& output)
{
EZ_ASSERT_DEV(offset.x >= 0, "Offset is invalid");
EZ_ASSERT_DEV(offset.y >= 0, "Offset is invalid");
EZ_ASSERT_DEV(offset.x < (ezInt32)input.GetWidth(), "Offset is invalid");
EZ_ASSERT_DEV(offset.y < (ezInt32)input.GetHeight(), "Offset is invalid");
const ezUInt32 uiNewWidth = ezMath::Min(offset.x + newsize.width, input.GetWidth()) - offset.x;
const ezUInt32 uiNewHeight = ezMath::Min(offset.y + newsize.height, input.GetHeight()) - offset.y;
ezImageHeader outputHeader;
outputHeader.SetWidth(uiNewWidth);
outputHeader.SetHeight(uiNewHeight);
outputHeader.SetImageFormat(input.GetImageFormat());
output.ResetAndAlloc(outputHeader);
for (ezUInt32 y = 0; y < uiNewHeight; ++y)
{
for (ezUInt32 x = 0; x < uiNewWidth; ++x)
{
switch (input.GetImageFormat())
{
case ezImageFormat::R8G8B8A8_UNORM:
case ezImageFormat::R8G8B8A8_UNORM_SRGB:
case ezImageFormat::R8G8B8A8_UINT:
case ezImageFormat::R8G8B8A8_SNORM:
case ezImageFormat::R8G8B8A8_SINT:
case ezImageFormat::B8G8R8A8_UNORM:
case ezImageFormat::B8G8R8X8_UNORM:
case ezImageFormat::B8G8R8A8_UNORM_SRGB:
case ezImageFormat::B8G8R8X8_UNORM_SRGB:
output.GetPixelPointer<ezUInt32>(0, 0, 0, x, y)[0] = input.GetPixelPointer<ezUInt32>(0, 0, 0, offset.x + x, offset.y + y)[0];
break;
case ezImageFormat::B8G8R8_UNORM:
output.GetPixelPointer<ezUInt8>(0, 0, 0, x, y)[0] = input.GetPixelPointer<ezUInt8>(0, 0, 0, offset.x + x, offset.y + y)[0];
output.GetPixelPointer<ezUInt8>(0, 0, 0, x, y)[1] = input.GetPixelPointer<ezUInt8>(0, 0, 0, offset.x + x, offset.y + y)[1];
output.GetPixelPointer<ezUInt8>(0, 0, 0, x, y)[2] = input.GetPixelPointer<ezUInt8>(0, 0, 0, offset.x + x, offset.y + y)[2];
break;
default:
EZ_REPORT_FAILURE("The ezImageFormat {0} is not implemented", (ezUInt32)input.GetImageFormat());
return;
}
}
}
}
namespace
{
template <typename T>
void rotate180(T* start, T* end)
{
end = end - 1;
while (start < end)
{
ezMath::Swap(*start, *end);
start++;
end--;
}
}
} // namespace
void ezImageUtils::RotateSubImage180(ezImage& image, ezUInt32 uiMipLevel /*= 0*/, ezUInt32 uiFace /*= 0*/, ezUInt32 uiArrayIndex /*= 0*/)
{
ezUInt8* start = image.GetPixelPointer<ezUInt8>(uiMipLevel, uiFace, uiArrayIndex);
ezUInt8* end = start + image.GetDepthPitch(uiMipLevel);
ezUInt32 bytesPerPixel = ezImageFormat::GetBitsPerPixel(image.GetImageFormat()) / 8;
switch (bytesPerPixel)
{
case 4:
rotate180<ezUInt32>(reinterpret_cast<ezUInt32*>(start), reinterpret_cast<ezUInt32*>(end));
break;
case 12:
rotate180<ezVec3>(reinterpret_cast<ezVec3*>(start), reinterpret_cast<ezVec3*>(end));
break;
case 16:
rotate180<ezVec4>(reinterpret_cast<ezVec4*>(start), reinterpret_cast<ezVec4*>(end));
break;
default:
// fallback version
{
end -= bytesPerPixel;
while (start < end)
{
for (ezUInt32 i = 0; i < bytesPerPixel; i++)
{
ezMath::Swap(start[i], end[i]);
}
start += bytesPerPixel;
end -= bytesPerPixel;
}
}
}
}
ezResult ezImageUtils::Copy(const ezImageView& srcImg, const ezRectU32& srcRect, ezImage& dstImg, const ezVec3U32& dstOffset,
ezUInt32 uiDstMipLevel /*= 0*/, ezUInt32 uiDstFace /*= 0*/, ezUInt32 uiDstArrayIndex /*= 0*/)
{
if (dstImg.GetImageFormat() != srcImg.GetImageFormat()) // Can only copy when the image formats are identical
return EZ_FAILURE;
if (ezImageFormat::IsCompressed(dstImg.GetImageFormat())) // Compressed formats are not supported
return EZ_FAILURE;
const ezUInt64 uiDstRowPitch = dstImg.GetRowPitch(uiDstMipLevel);
const ezUInt64 uiSrcRowPitch = srcImg.GetRowPitch(uiDstMipLevel);
const ezUInt32 uiCopyBytesPerRow = ezImageFormat::GetBitsPerPixel(srcImg.GetImageFormat()) * srcRect.width / 8;
ezUInt8* dstPtr = dstImg.GetPixelPointer<ezUInt8>(uiDstMipLevel, uiDstFace, uiDstArrayIndex, dstOffset.x, dstOffset.y, dstOffset.z);
const ezUInt8* srcPtr = srcImg.GetPixelPointer<ezUInt8>(0, 0, 0, srcRect.x, srcRect.y);
for (ezUInt32 y = 0; y < srcRect.height; y++)
{
ezMemoryUtils::Copy(dstPtr, srcPtr, uiCopyBytesPerRow);
dstPtr += uiDstRowPitch;
srcPtr += uiSrcRowPitch;
}
return EZ_SUCCESS;
}
ezResult ezImageUtils::ExtractLowerMipChain(const ezImageView& srcImg, ezImage& dstImg, ezUInt32 uiNumMips)
{
const ezImageHeader& srcImgHeader = srcImg.GetHeader();
if (srcImgHeader.GetNumFaces() != 1 || srcImgHeader.GetNumArrayIndices() != 1)
{
// Lower mips aren't stored contiguously for array/cube textures and would require copying. This isn't implemented yet.
return EZ_FAILURE;
}
uiNumMips = ezMath::Min(uiNumMips, srcImgHeader.GetNumMipLevels());
ezUInt32 startMipLevel = srcImgHeader.GetNumMipLevels() - uiNumMips;
ezImageFormat::Enum format = srcImgHeader.GetImageFormat();
if (ezImageFormat::RequiresFirstLevelBlockAlignment(format))
{
// Some block compressed image formats require resolutions that are divisible by block size,
// therefore adjust startMipLevel accordingly
while (
srcImgHeader.GetWidth(startMipLevel) % ezImageFormat::GetBlockWidth(format) != 0 ||
srcImgHeader.GetHeight(startMipLevel) % ezImageFormat::GetBlockHeight(format) != 0)
{
if (uiNumMips >= srcImgHeader.GetNumMipLevels())
return EZ_FAILURE;
if (startMipLevel == 0)
return EZ_FAILURE;
++uiNumMips;
--startMipLevel;
}
}
ezImageHeader dstImgHeader = srcImgHeader;
dstImgHeader.SetWidth(srcImgHeader.GetWidth(startMipLevel));
dstImgHeader.SetHeight(srcImgHeader.GetHeight(startMipLevel));
dstImgHeader.SetDepth(srcImgHeader.GetDepth(startMipLevel));
dstImgHeader.SetNumFaces(srcImgHeader.GetNumFaces());
dstImgHeader.SetNumArrayIndices(srcImgHeader.GetNumArrayIndices());
dstImgHeader.SetNumMipLevels(uiNumMips);
const ezUInt8* pDataBegin = srcImg.GetPixelPointer<ezUInt8>(startMipLevel);
const ezUInt8* pDataEnd = srcImg.GetByteBlobPtr().GetEndPtr();
const ptrdiff_t dataSize = reinterpret_cast<ptrdiff_t>(pDataEnd) - reinterpret_cast<ptrdiff_t>(pDataBegin);
const ezConstByteBlobPtr lowResData(pDataBegin, static_cast<ezUInt64>(dataSize));
ezImageView dataview;
dataview.ResetAndViewExternalStorage(dstImgHeader, lowResData);
dstImg.ResetAndCopy(dataview);
return EZ_SUCCESS;
}
ezUInt32 ezImageUtils::GetSampleIndex(ezUInt32 numTexels, ezInt32 index, ezImageAddressMode::Enum addressMode, bool& outUseBorderColor)
{
outUseBorderColor = false;
if (ezUInt32(index) >= numTexels)
{
switch (addressMode)
{
case ezImageAddressMode::Repeat:
index %= numTexels;
if (index < 0)
{
index += numTexels;
}
return index;
case ezImageAddressMode::Mirror:
{
if (index < 0)
{
index = -index - 1;
}
bool flip = (index / numTexels) & 1;
index %= numTexels;
if (flip)
{
index = numTexels - index - 1;
}
return index;
}
case ezImageAddressMode::Clamp:
return ezMath::Clamp<ezInt32>(index, 0, numTexels - 1);
case ezImageAddressMode::ClampBorder:
outUseBorderColor = true;
return 0;
default:
EZ_ASSERT_NOT_IMPLEMENTED
return 0;
}
}
return index;
}
static ezSimdVec4f LoadSample(const ezSimdVec4f* source, ezUInt32 numSourceElements, ezUInt32 stride, ezInt32 index,
ezImageAddressMode::Enum addressMode, const ezSimdVec4f& borderColor)
{
bool useBorderColor = false;
// result is in the range [-(w-1), (w-1)], bring it to [0, w - 1]
index = ezImageUtils::GetSampleIndex(numSourceElements, index, addressMode, useBorderColor);
if (useBorderColor)
{
return borderColor;
}
return source[index * stride];
}
inline static void FilterLine(ezUInt32 numSourceElements, const ezSimdVec4f* __restrict sourceBegin, ezSimdVec4f* __restrict targetBegin,
ezUInt32 stride, const ezImageFilterWeights& weights, ezArrayPtr<const ezInt32> firstSampleIndices, ezImageAddressMode::Enum addressMode,
const ezSimdVec4f& borderColor)
{
// Convolve the image using the precomputed weights
const ezUInt32 numWeights = weights.GetNumWeights();
// When the first source index for the output is between 0 and this value,
// we can fetch all numWeights inputs without taking addressMode into consideration,
// which makes the inner loop a lot faster.
const ezInt32 trivialSourceIndicesEnd = static_cast<ezInt32>(numSourceElements) - static_cast<ezInt32>(numWeights);
const auto weightsView = weights.ViewWeights();
const float* __restrict nextWeightPtr = weightsView.GetPtr();
EZ_ASSERT_DEBUG((static_cast<ezUInt32>(weightsView.GetCount()) % numWeights) == 0, "");
for (ezInt32 firstSourceIdx : firstSampleIndices)
{
ezSimdVec4f total(0.0f, 0.0f, 0.0f, 0.0f);
if (firstSourceIdx >= 0 && firstSourceIdx < trivialSourceIndicesEnd)
{
const auto* __restrict sourcePtr = sourceBegin + firstSourceIdx * stride;
for (ezUInt32 weightIdx = 0; weightIdx < numWeights; ++weightIdx)
{
total = ezSimdVec4f::MulAdd(*sourcePtr, ezSimdVec4f(*nextWeightPtr++), total);
sourcePtr += stride;
}
}
else
{
// Very slow fallback case that respects the addressMode
// (not a lot of pixels are taking this path, so it's probably fine)
ezInt32 sourceIdx = firstSourceIdx;
for (ezUInt32 weightIdx = 0; weightIdx < numWeights; ++weightIdx)
{
total = ezSimdVec4f::MulAdd(
LoadSample(sourceBegin, numSourceElements, stride, sourceIdx, addressMode, borderColor), ezSimdVec4f(*nextWeightPtr++), total);
sourceIdx++;
}
}
// It's ok to check this once per source index, see the assert above
// (number of weights in weightsView is divisible by numWeights)
if (nextWeightPtr == weightsView.GetEndPtr())
{
nextWeightPtr = weightsView.GetPtr();
}
*targetBegin = total;
targetBegin += stride;
}
}
static void DownScaleFastLine(
ezUInt32 pixelStride, const ezUInt8* src, ezUInt8* dest, ezUInt32 lengthIn, ezUInt32 strideIn, ezUInt32 lengthOut, ezUInt32 strideOut)
{
const ezUInt32 downScaleFactor = lengthIn / lengthOut;
const ezUInt32 downScaleFactorLog2 = ezMath::Log2i(static_cast<ezUInt32>(downScaleFactor));
const ezUInt32 roundOffset = downScaleFactor / 2;
for (ezUInt32 offset = 0; offset < lengthOut; ++offset)
{
for (ezUInt32 channel = 0; channel < pixelStride; ++channel)
{
const ezUInt32 destOffset = offset * strideOut + channel;
ezUInt32 curChannel = roundOffset;
for (ezUInt32 index = 0; index < downScaleFactor; ++index)
{
curChannel += static_cast<ezUInt32>(src[channel + index * strideIn]);
}
curChannel = curChannel >> downScaleFactorLog2;
dest[destOffset] = static_cast<ezUInt8>(curChannel);
}
src += downScaleFactor * strideIn;
}
}
static void DownScaleFast(const ezImageView& image, ezImage& out_Result, ezUInt32 width, ezUInt32 height)
{
ezImageFormat::Enum format = image.GetImageFormat();
ezUInt32 originalWidth = image.GetWidth();
ezUInt32 originalHeight = image.GetHeight();
ezUInt32 numArrayElements = image.GetNumArrayIndices();
ezUInt32 numFaces = image.GetNumFaces();
ezUInt32 pixelStride = ezImageFormat::GetBitsPerPixel(format) / 8;
ezImageHeader intermediateHeader;
intermediateHeader.SetWidth(width);
intermediateHeader.SetHeight(originalHeight);
intermediateHeader.SetNumArrayIndices(numArrayElements);
intermediateHeader.SetNumFaces(numFaces);
intermediateHeader.SetImageFormat(format);
ezImage intermediate;
intermediate.ResetAndAlloc(intermediateHeader);
for (ezUInt32 arrayIndex = 0; arrayIndex < numArrayElements; arrayIndex++)
{
for (ezUInt32 face = 0; face < numFaces; face++)
{
for (ezUInt32 row = 0; row < originalHeight; row++)
{
DownScaleFastLine(pixelStride, image.GetPixelPointer<ezUInt8>(0, face, arrayIndex, 0, row),
intermediate.GetPixelPointer<ezUInt8>(0, face, arrayIndex, 0, row), originalWidth, pixelStride, width, pixelStride);
}
}
}
// input and output images may be the same, so we can't access the original image below this point
ezImageHeader outHeader;
outHeader.SetWidth(width);
outHeader.SetHeight(height);
outHeader.SetNumArrayIndices(numArrayElements);
outHeader.SetNumArrayIndices(numFaces);
outHeader.SetImageFormat(format);
out_Result.ResetAndAlloc(outHeader);
EZ_ASSERT_DEBUG(intermediate.GetRowPitch() < ezMath::MaxValue<ezUInt32>(), "Row pitch exceeds ezUInt32 max value.");
EZ_ASSERT_DEBUG(out_Result.GetRowPitch() < ezMath::MaxValue<ezUInt32>(), "Row pitch exceeds ezUInt32 max value.");
for (ezUInt32 arrayIndex = 0; arrayIndex < numArrayElements; arrayIndex++)
{
for (ezUInt32 face = 0; face < numFaces; face++)
{
for (ezUInt32 col = 0; col < width; col++)
{
DownScaleFastLine(pixelStride, intermediate.GetPixelPointer<ezUInt8>(0, face, arrayIndex, col),
out_Result.GetPixelPointer<ezUInt8>(0, face, arrayIndex, col), originalHeight, static_cast<ezUInt32>(intermediate.GetRowPitch()), height,
static_cast<ezUInt32>(out_Result.GetRowPitch()));
}
}
}
}
static float EvaluateAverageCoverage(ezBlobPtr<const ezColor> colors, float alphaThreshold)
{
ezUInt64 totalPixels = colors.GetCount();
ezUInt64 count = 0;
for (ezUInt32 idx = 0; idx < totalPixels; ++idx)
{
count += colors[idx].a >= alphaThreshold;
}
return float(count) / float(totalPixels);
}
static void NormalizeCoverage(ezBlobPtr<ezColor> colors, float alphaThreshold, float targetCoverage)
{
// Based on the idea in http://the-witness.net/news/2010/09/computing-alpha-mipmaps/. Note we're using a histogram
// to find the new alpha threshold here rather than bisecting.
// Generate histogram of alpha values
ezUInt64 totalPixels = colors.GetCount();
ezUInt32 alphaHistogram[256] = {};
for (ezUInt64 idx = 0; idx < totalPixels; ++idx)
{
alphaHistogram[ezMath::ColorFloatToByte(colors[idx].a)]++;
}
// Find range of alpha thresholds so the number of covered pixels matches by summing up the histogram
ezInt32 targetCount = ezInt32(targetCoverage * totalPixels);
ezInt32 coverageCount = 0;
ezInt32 maxThreshold = 255;
for (; maxThreshold >= 0; maxThreshold--)
{
coverageCount += alphaHistogram[maxThreshold];
if (coverageCount >= targetCount)
{
break;
}
}
coverageCount = targetCount;
ezInt32 minThreshold = 0;
for (; minThreshold < 256; minThreshold++)
{
coverageCount -= alphaHistogram[maxThreshold];
if (coverageCount <= targetCount)
{
break;
}
}
ezInt32 currentThreshold = ezMath::ColorFloatToByte(alphaThreshold);
// Each of the alpha test thresholds in the range [minThreshold; maxThreshold] will result in the same coverage. Pick a new threshold
// close to the old one so we scale by the smallest necessary amount.
ezInt32 newThreshold;
if (currentThreshold < minThreshold)
{
newThreshold = minThreshold;
}
else if (currentThreshold > maxThreshold)
{
newThreshold = maxThreshold;
}
else
{
// Avoid rescaling altogether if the current threshold already preserves coverage
return;
}
// Rescale alpha values
float alphaScale = alphaThreshold / (newThreshold / 255.0f);
for (ezUInt64 idx = 0; idx < totalPixels; ++idx)
{
colors[idx].a *= alphaScale;
}
}
ezResult ezImageUtils::Scale(const ezImageView& source, ezImage& target, ezUInt32 width, ezUInt32 height, const ezImageFilter* filter,
ezImageAddressMode::Enum addressModeU, ezImageAddressMode::Enum addressModeV, const ezColor& borderColor)
{
return Scale3D(source, target, width, height, 1, filter, addressModeU, addressModeV, ezImageAddressMode::Clamp, borderColor);
}
ezResult ezImageUtils::Scale3D(const ezImageView& source, ezImage& target, ezUInt32 width, ezUInt32 height, ezUInt32 depth,
const ezImageFilter* filter /*= ez_NULL*/, ezImageAddressMode::Enum addressModeU /*= ezImageAddressMode::Clamp*/,
ezImageAddressMode::Enum addressModeV /*= ezImageAddressMode::Clamp*/,
ezImageAddressMode::Enum addressModeW /*= ezImageAddressMode::Clamp*/, const ezColor& borderColor /*= ezColors::Black*/)
{
if (width == 0 || height == 0 || depth == 0)
{
ezImageHeader header;
header.SetImageFormat(source.GetImageFormat());
target.ResetAndAlloc(header);
return EZ_SUCCESS;
}
const ezImageFormat::Enum format = source.GetImageFormat();
const ezUInt32 originalWidth = source.GetWidth();
const ezUInt32 originalHeight = source.GetHeight();
const ezUInt32 originalDepth = source.GetDepth();
const ezUInt32 numFaces = source.GetNumFaces();
const ezUInt32 numArrayElements = source.GetNumArrayIndices();
if (originalWidth == width && originalHeight == height && originalDepth == depth)
{
target.ResetAndCopy(source);
return EZ_SUCCESS;
}
// Scaling down by an even factor?
const ezUInt32 downScaleFactorX = originalWidth / width;
const ezUInt32 downScaleFactorY = originalHeight / height;
if (filter == nullptr &&
(format == ezImageFormat::R8G8B8A8_UNORM || format == ezImageFormat::B8G8R8A8_UNORM || format == ezImageFormat::B8G8R8_UNORM) &&
downScaleFactorX * width == originalWidth && downScaleFactorY * height == originalHeight && depth == 1 && originalDepth == 1 &&
ezMath::IsPowerOf2(downScaleFactorX) && ezMath::IsPowerOf2(downScaleFactorY))
{
DownScaleFast(source, target, width, height);
return EZ_SUCCESS;
}
// Fallback to default filter
ezImageFilterTriangle defaultFilter;
if (!filter)
{
filter = &defaultFilter;
}
const ezImageView* stepSource;
// Manage scratch images for intermediate conversion or filtering
const ezUInt32 maxNumScratchImages = 2;
ezImage scratch[maxNumScratchImages];
bool scratchUsed[maxNumScratchImages] = {};
auto allocateScratch = [&]() -> ezImage& {
for (ezUInt32 i = 0;; ++i)
{
EZ_ASSERT_DEV(i < maxNumScratchImages, "Failed to allocate scratch image");
if (!scratchUsed[i])
{
scratchUsed[i] = true;
return scratch[i];
}
}
};
auto releaseScratch = [&](const ezImageView& image) {
for (ezUInt32 i = 0; i < maxNumScratchImages; ++i)
{
if (&scratch[i] == &image)
{
scratchUsed[i] = false;
return;
}
}
};
if (format == ezImageFormat::R32G32B32A32_FLOAT)
{
stepSource = &source;
}
else
{
ezImage& conversionScratch = allocateScratch();
if (ezImageConversion::Convert(source, conversionScratch, ezImageFormat::R32G32B32A32_FLOAT).Failed())
{
return EZ_FAILURE;
}
stepSource = &conversionScratch;
};
ezHybridArray<ezInt32, 256> firstSampleIndices;
firstSampleIndices.Reserve(ezMath::Max(width, height, depth));
if (width != originalWidth)
{
ezImageFilterWeights weights(*filter, originalWidth, width);
firstSampleIndices.SetCountUninitialized(width);
for (ezUInt32 x = 0; x < width; ++x)
{
firstSampleIndices[x] = weights.GetFirstSourceSampleIndex(x);
}
ezImage* stepTarget;
if (height == originalHeight && depth == originalDepth && format == ezImageFormat::R32G32B32A32_FLOAT)
{
stepTarget = ⌖
}
else
{
stepTarget = &allocateScratch();
}
ezImageHeader stepHeader = stepSource->GetHeader();
stepHeader.SetWidth(width);
stepTarget->ResetAndAlloc(stepHeader);
for (ezUInt32 arrayIndex = 0; arrayIndex < numArrayElements; ++arrayIndex)
{
for (ezUInt32 face = 0; face < numFaces; ++face)
{
for (ezUInt32 z = 0; z < originalDepth; ++z)
{
for (ezUInt32 y = 0; y < originalHeight; ++y)
{
const ezSimdVec4f* filterSource = stepSource->GetPixelPointer<ezSimdVec4f>(0, face, arrayIndex, 0, y, z);
ezSimdVec4f* filterTarget = stepTarget->GetPixelPointer<ezSimdVec4f>(0, face, arrayIndex, 0, y, z);
FilterLine(originalWidth, filterSource, filterTarget, 1, weights, firstSampleIndices, addressModeU,
ezSimdVec4f(borderColor.r, borderColor.g, borderColor.b, borderColor.a));
}
}
}
}
releaseScratch(*stepSource);
stepSource = stepTarget;
}
if (height != originalHeight)
{
ezImageFilterWeights weights(*filter, originalHeight, height);
firstSampleIndices.SetCount(height);
for (ezUInt32 y = 0; y < height; ++y)
{
firstSampleIndices[y] = weights.GetFirstSourceSampleIndex(y);
}
ezImage* stepTarget;
if (depth == originalDepth && format == ezImageFormat::R32G32B32A32_FLOAT)
{
stepTarget = ⌖
}
else
{
stepTarget = &allocateScratch();
}
ezImageHeader stepHeader = stepSource->GetHeader();
stepHeader.SetHeight(height);
stepTarget->ResetAndAlloc(stepHeader);
for (ezUInt32 arrayIndex = 0; arrayIndex < numArrayElements; ++arrayIndex)
{
for (ezUInt32 face = 0; face < numFaces; ++face)
{
for (ezUInt32 z = 0; z < originalDepth; ++z)
{
for (ezUInt32 x = 0; x < width; ++x)
{
const ezSimdVec4f* filterSource = stepSource->GetPixelPointer<ezSimdVec4f>(0, face, arrayIndex, x, 0, z);
ezSimdVec4f* filterTarget = stepTarget->GetPixelPointer<ezSimdVec4f>(0, face, arrayIndex, x, 0, z);
FilterLine(originalHeight, filterSource, filterTarget, width, weights, firstSampleIndices, addressModeV,
ezSimdVec4f(borderColor.r, borderColor.g, borderColor.b, borderColor.a));
}
}
}
}
releaseScratch(*stepSource);
stepSource = stepTarget;
}
if (depth != originalDepth)
{
ezImageFilterWeights weights(*filter, originalDepth, depth);
firstSampleIndices.SetCount(depth);
for (ezUInt32 z = 0; z < depth; ++z)
{
firstSampleIndices[z] = weights.GetFirstSourceSampleIndex(z);
}
ezImage* stepTarget;
if (format == ezImageFormat::R32G32B32A32_FLOAT)
{
stepTarget = ⌖
}
else
{
stepTarget = &allocateScratch();
}
ezImageHeader stepHeader = stepSource->GetHeader();
stepHeader.SetDepth(depth);
stepTarget->ResetAndAlloc(stepHeader);
for (ezUInt32 arrayIndex = 0; arrayIndex < numArrayElements; ++arrayIndex)
{
for (ezUInt32 face = 0; face < numFaces; ++face)
{
for (ezUInt32 y = 0; y < height; ++y)
{
for (ezUInt32 x = 0; x < width; ++x)
{
const ezSimdVec4f* filterSource = stepSource->GetPixelPointer<ezSimdVec4f>(0, face, arrayIndex, x, y, 0);
ezSimdVec4f* filterTarget = stepTarget->GetPixelPointer<ezSimdVec4f>(0, face, arrayIndex, x, y, 0);
FilterLine(originalHeight, filterSource, filterTarget, width * height, weights, firstSampleIndices, addressModeW,
ezSimdVec4f(borderColor.r, borderColor.g, borderColor.b, borderColor.a));
}
}
}
}
releaseScratch(*stepSource);
stepSource = stepTarget;
}
// Convert back to original format - no-op if stepSource and target are the same
return ezImageConversion::Convert(*stepSource, target, format);
}
void ezImageUtils::GenerateMipMaps(const ezImageView& source, ezImage& target, const MipMapOptions& options)
{
ezImageHeader header = source.GetHeader();
EZ_ASSERT_DEV(header.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "The source image must be a RGBA 32-bit float format.");
EZ_ASSERT_DEV(&source != &target, "Source and target must not be the same image.");
// Make a local copy to be able to tweak some of the options
ezImageUtils::MipMapOptions mipMapOptions = options;
// alpha thresholds with extreme values are not supported at the moment
mipMapOptions.m_alphaThreshold = ezMath::Clamp(mipMapOptions.m_alphaThreshold, 0.05f, 0.95f);
// Enforce CLAMP addressing mode for cubemaps
if (source.GetNumFaces() == 6)
{
mipMapOptions.m_addressModeU = ezImageAddressMode::Clamp;
mipMapOptions.m_addressModeV = ezImageAddressMode::Clamp;
}
ezUInt32 numMipMaps = header.ComputeNumberOfMipMaps();
if (mipMapOptions.m_numMipMaps > 0 && mipMapOptions.m_numMipMaps < numMipMaps)
{
numMipMaps = mipMapOptions.m_numMipMaps;
}
header.SetNumMipLevels(numMipMaps);
target.ResetAndAlloc(header);
for (ezUInt32 arrayIndex = 0; arrayIndex < source.GetNumArrayIndices(); arrayIndex++)
{
for (ezUInt32 face = 0; face < source.GetNumFaces(); face++)
{
ezImageHeader currentMipMapHeader = header;
currentMipMapHeader.SetNumMipLevels(1);
currentMipMapHeader.SetNumFaces(1);
currentMipMapHeader.SetNumArrayIndices(1);
auto sourceView = source.GetSubImageView(0, face, arrayIndex).GetByteBlobPtr();
auto targetView = target.GetSubImageView(0, face, arrayIndex).GetByteBlobPtr();
memcpy(targetView.GetPtr(), sourceView.GetPtr(), targetView.GetCount());
float targetCoverage = 0.0f;
if (mipMapOptions.m_preserveCoverage)
{
targetCoverage =
EvaluateAverageCoverage(source.GetSubImageView(0, face, arrayIndex).GetBlobPtr<ezColor>(), mipMapOptions.m_alphaThreshold);
}
for (ezUInt32 mipMapLevel = 0; mipMapLevel < numMipMaps - 1; mipMapLevel++)
{
ezImageHeader nextMipMapHeader = currentMipMapHeader;
nextMipMapHeader.SetWidth(ezMath::Max(1u, nextMipMapHeader.GetWidth() / 2));
nextMipMapHeader.SetHeight(ezMath::Max(1u, nextMipMapHeader.GetHeight() / 2));
nextMipMapHeader.SetDepth(ezMath::Max(1u, nextMipMapHeader.GetDepth() / 2));
auto sourceData = target.GetSubImageView(mipMapLevel, face, arrayIndex).GetByteBlobPtr();
ezImage currentMipMap;
currentMipMap.ResetAndUseExternalStorage(currentMipMapHeader, sourceData);
auto dstData = target.GetSubImageView(mipMapLevel + 1, face, arrayIndex).GetByteBlobPtr();
ezImage nextMipMap;
nextMipMap.ResetAndUseExternalStorage(nextMipMapHeader, dstData);
ezImageUtils::Scale3D(currentMipMap, nextMipMap, nextMipMapHeader.GetWidth(), nextMipMapHeader.GetHeight(),
nextMipMapHeader.GetDepth(), mipMapOptions.m_filter, mipMapOptions.m_addressModeU, mipMapOptions.m_addressModeV,
mipMapOptions.m_addressModeW, mipMapOptions.m_borderColor);
if (mipMapOptions.m_preserveCoverage)
{
NormalizeCoverage(nextMipMap.GetBlobPtr<ezColor>(), mipMapOptions.m_alphaThreshold, targetCoverage);
}
if (mipMapOptions.m_renormalizeNormals)
{
RenormalizeNormalMap(nextMipMap);
}
currentMipMapHeader = nextMipMapHeader;
}
}
}
}
void ezImageUtils::ReconstructNormalZ(ezImage& image)
{
EZ_ASSERT_DEV(image.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "This algorithm currently expects a RGBA 32 Float as input");
ezSimdVec4f* cur = image.GetBlobPtr<ezSimdVec4f>().GetPtr();
ezSimdVec4f* const end = image.GetBlobPtr<ezSimdVec4f>().GetEndPtr();
ezSimdFloat oneScalar = 1.0f;
ezSimdVec4f two(2.0f);
ezSimdVec4f minusOne(-1.0f);
ezSimdVec4f half(0.5f);
for (; cur < end; cur++)
{
ezSimdVec4f normal;
// unpack from [0,1] to [-1, 1]
normal = ezSimdVec4f::MulAdd(*cur, two, minusOne);
// compute Z component
normal.SetZ((oneScalar - normal.Dot<2>(normal)).GetSqrt());
// pack back to [0,1]
*cur = ezSimdVec4f::MulAdd(half, normal, half);
}
}
void ezImageUtils::RenormalizeNormalMap(ezImage& image)
{
EZ_ASSERT_DEV(image.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "This algorithm currently expects a RGBA 32 Float as input");
ezSimdVec4f* start = image.GetBlobPtr<ezSimdVec4f>().GetPtr();
ezSimdVec4f* const end = image.GetBlobPtr<ezSimdVec4f>().GetEndPtr();
ezSimdVec4f two(2.0f);
ezSimdVec4f minusOne(-1.0f);
ezSimdVec4f half(0.5f);
for (; start < end; start++)
{
ezSimdVec4f normal;
normal = ezSimdVec4f::MulAdd(*start, two, minusOne);
normal.Normalize<3>();
*start = ezSimdVec4f::MulAdd(half, normal, half);
}
}
void ezImageUtils::AdjustRoughness(ezImage& roughnessMap, const ezImageView& normalMap)
{
EZ_ASSERT_DEV(
roughnessMap.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "This algorithm currently expects a RGBA 32 Float as input");
EZ_ASSERT_DEV(
normalMap.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "This algorithm currently expects a RGBA 32 Float as input");
EZ_ASSERT_DEV(roughnessMap.GetWidth() >= normalMap.GetWidth() && roughnessMap.GetHeight() >= normalMap.GetHeight(),
"The roughness map needs to be bigger or same size than the normal map.");
ezImage filteredNormalMap;
ezImageUtils::MipMapOptions options;
// Box filter normal map without re-normalization so we have the average normal length in each mip map.
if (roughnessMap.GetWidth() != normalMap.GetWidth() || roughnessMap.GetHeight() != normalMap.GetHeight())
{
ezImage temp;
ezImageUtils::Scale(normalMap, temp, roughnessMap.GetWidth(), roughnessMap.GetHeight());
ezImageUtils::RenormalizeNormalMap(temp);
ezImageUtils::GenerateMipMaps(temp, filteredNormalMap, options);
}
else
{
ezImageUtils::GenerateMipMaps(normalMap, filteredNormalMap, options);
}
EZ_ASSERT_DEV(roughnessMap.GetNumMipLevels() == filteredNormalMap.GetNumMipLevels(),
"Roughness and normal map must have the same number of mip maps");
ezSimdVec4f two(2.0f);
ezSimdVec4f minusOne(-1.0f);
ezUInt32 numMipLevels = roughnessMap.GetNumMipLevels();
for (ezUInt32 mipLevel = 1; mipLevel < numMipLevels; ++mipLevel)
{
ezBlobPtr<ezSimdVec4f> roughnessData = roughnessMap.GetSubImageView(mipLevel, 0, 0).GetBlobPtr<ezSimdVec4f>();
ezBlobPtr<ezSimdVec4f> normalData = filteredNormalMap.GetSubImageView(mipLevel, 0, 0).GetBlobPtr<ezSimdVec4f>();
for (ezUInt64 i = 0; i < roughnessData.GetCount(); ++i)
{
ezSimdVec4f normal = ezSimdVec4f::MulAdd(normalData[i], two, minusOne);
float avgNormalLength = normal.GetLength<3>();
if (avgNormalLength < 1.0f)
{
float avgNormalLengthSquare = avgNormalLength * avgNormalLength;
float kappa = (3.0f * avgNormalLength - avgNormalLength * avgNormalLengthSquare) / (1.0f - avgNormalLengthSquare);
float variance = 1.0f / (2.0f * kappa);
float oldRoughness = roughnessData[i].GetComponent<0>();
float newRoughness = ezMath::Sqrt(oldRoughness * oldRoughness + variance);
roughnessData[i].Set(newRoughness);
}
}
}
}
void ezImageUtils::ChangeExposure(ezImage& image, float bias)
{
EZ_ASSERT_DEV(image.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "This function expects an RGBA 32 float image as input");
if (bias == 0.0f)
return;
const float multiplier = ezMath::Pow2(bias);
for (ezColor& col : image.GetBlobPtr<ezColor>())
{
col = multiplier * col;
}
}
static void CopyImageRectToFace(ezImage& dstImg, const ezImageView& srcImg, ezUInt32 offsetX, ezUInt32 offsetY, ezUInt32 faceIndex)
{
ezRectU32 r;
r.x = offsetX;
r.y = offsetY;
r.width = dstImg.GetWidth();
r.height = r.width;
ezImageUtils::Copy(srcImg, r, dstImg, ezVec3U32(0), 0, faceIndex);
}
ezResult ezImageUtils::CreateCubemapFromSingleFile(ezImage& dstImg, const ezImageView& srcImg)
{
if (srcImg.GetNumFaces() == 6)
{
dstImg.ResetAndCopy(srcImg);
return EZ_SUCCESS;
}
else if (srcImg.GetNumFaces() == 1)
{
if (srcImg.GetWidth() % 3 == 0 && srcImg.GetHeight() % 4 == 0 && srcImg.GetWidth() / 3 == srcImg.GetHeight() / 4)
{
// Vertical cube map layout
// +---+
// | Y+|
// +---+---+---+
// | X-| Z+| X+|
// +---+---+---+
// | Y-|
// +---+
// | Z-|
// +---+
const ezUInt32 faceSize = srcImg.GetWidth() / 3;
ezImageHeader imgHeader;
imgHeader.SetWidth(faceSize);
imgHeader.SetHeight(faceSize);
imgHeader.SetImageFormat(srcImg.GetImageFormat());
imgHeader.SetDepth(1);
imgHeader.SetNumFaces(6);
imgHeader.SetNumMipLevels(1);
imgHeader.SetNumArrayIndices(1);
dstImg.ResetAndAlloc(imgHeader);
// face order in dds files is: positive x, negative x, positive y, negative y, positive z, negative z
// Positive X face
CopyImageRectToFace(dstImg, srcImg, faceSize * 2, faceSize, 0);
// Negative X face
CopyImageRectToFace(dstImg, srcImg, 0, faceSize, 1);
// Positive Y face
CopyImageRectToFace(dstImg, srcImg, faceSize, 0, 2);
// Negative Y face
CopyImageRectToFace(dstImg, srcImg, faceSize, faceSize * 2, 3);
// Positive Z face
CopyImageRectToFace(dstImg, srcImg, faceSize, faceSize, 4);
// Negative Z face
CopyImageRectToFace(dstImg, srcImg, faceSize, faceSize * 3, 5);
ezImageUtils::RotateSubImage180(dstImg, 0, 5);
}
else if (srcImg.GetWidth() % 4 == 0 && srcImg.GetHeight() % 3 == 0 && srcImg.GetWidth() / 4 == srcImg.GetHeight() / 3)
{
// Horizontal cube map layout
// +---+
// | Y+|
// +---+---+---+---+
// | X-| Z+| X+| Z-|
// +---+---+---+---+
// | Y-|
// +---+
const ezUInt32 faceSize = srcImg.GetWidth() / 4;
ezImageHeader imgHeader;
imgHeader.SetWidth(faceSize);
imgHeader.SetHeight(faceSize);
imgHeader.SetImageFormat(srcImg.GetImageFormat());
imgHeader.SetDepth(1);
imgHeader.SetNumFaces(6);
imgHeader.SetNumMipLevels(1);
imgHeader.SetNumArrayIndices(1);
dstImg.ResetAndAlloc(imgHeader);
// face order in dds files is: positive x, negative x, positive y, negative y, positive z, negative z
// Positive X face
CopyImageRectToFace(dstImg, srcImg, faceSize * 2, faceSize, 0);
// Negative X face
CopyImageRectToFace(dstImg, srcImg, 0, faceSize, 1);
// Positive Y face
CopyImageRectToFace(dstImg, srcImg, faceSize, 0, 2);
// Negative Y face
CopyImageRectToFace(dstImg, srcImg, faceSize, faceSize * 2, 3);
// Positive Z face
CopyImageRectToFace(dstImg, srcImg, faceSize, faceSize, 4);
// Negative Z face
CopyImageRectToFace(dstImg, srcImg, faceSize * 3, faceSize, 5);
}
else
{
// Spherical mapping
if (srcImg.GetWidth() % 4 != 0)
{
ezLog::Error("Width of the input image should be a multiple of 4");
return EZ_FAILURE;
}
const ezUInt32 faceSize = srcImg.GetWidth() / 4;
ezImageHeader imgHeader;
imgHeader.SetWidth(faceSize);
imgHeader.SetHeight(faceSize);
imgHeader.SetImageFormat(srcImg.GetImageFormat());
imgHeader.SetDepth(1);
imgHeader.SetNumFaces(6);
imgHeader.SetNumMipLevels(1);
imgHeader.SetNumArrayIndices(1);
dstImg.ResetAndAlloc(imgHeader);
// Corners of the UV space for the respective faces in model space
const ezVec3 faceCorners[] = {
ezVec3(0.5, 0.5, 0.5), // X+
ezVec3(-0.5, 0.5, -0.5), // X-
ezVec3(-0.5, 0.5, -0.5), // Y+
ezVec3(-0.5, -0.5, 0.5), // Y-
ezVec3(-0.5, 0.5, 0.5), // Z+
ezVec3(0.5, 0.5, -0.5) // Z-
};
// UV Axis of the respective faces in model space
const ezVec3 faceAxis[] = {
ezVec3(0, 0, -1), ezVec3(0, -1, 0), // X+
ezVec3(0, 0, 1), ezVec3(0, -1, 0), // X-
ezVec3(1, 0, 0), ezVec3(0, 0, 1), // Y+
ezVec3(1, 0, 0), ezVec3(0, 0, -1), // Y-
ezVec3(1, 0, 0), ezVec3(0, -1, 0), // Z+
ezVec3(-1, 0, 0), ezVec3(0, -1, 0) // Z-
};
const float fFaceSize = (float)faceSize;
const float fHalfPixel = 0.5f / fFaceSize;
const float fPixel = 1.0f / fFaceSize;
const float fHalfSrcWidth = srcImg.GetWidth() / 2.0f;
const float fSrcHeight = (float)srcImg.GetHeight();
const ezUInt32 srcWidthMinus1 = srcImg.GetWidth() - 1;
const ezUInt32 srcHeightMinus1 = srcImg.GetHeight() - 1;
EZ_ASSERT_DEBUG(srcImg.GetRowPitch() % sizeof(ezColor) == 0, "Row pitch should be a multiple of sizeof(ezColor)");
const ezUInt64 srcRowPitch = srcImg.GetRowPitch() / sizeof(ezColor);
EZ_ASSERT_DEBUG(dstImg.GetRowPitch() % sizeof(ezColor) == 0, "Row pitch should be a multiple of sizeof(ezColor)");
const ezUInt64 faceRowPitch = dstImg.GetRowPitch() / sizeof(ezColor);
const ezColor* srcData = srcImg.GetPixelPointer<ezColor>();
const float InvPi = 1.0f / ezMath::Pi<float>();
for (ezUInt32 faceIndex = 0; faceIndex < 6; faceIndex++)
{
ezColor* faceData = dstImg.GetPixelPointer<ezColor>(0, faceIndex);
for (ezUInt32 y = 0; y < faceSize; y++)
{
const float dstV = (float)y * fPixel + fHalfPixel;
for (ezUInt32 x = 0; x < faceSize; x++)
{
const float dstU = (float)x * fPixel + fHalfPixel;
const ezVec3 modelSpacePos = faceCorners[faceIndex] + dstU * faceAxis[faceIndex * 2] + dstV * faceAxis[faceIndex * 2 + 1];
const ezVec3 modelSpaceDir = modelSpacePos.GetNormalized();
const float phi = ezMath::ATan2(modelSpaceDir.x, modelSpaceDir.z).GetRadian() + ezMath::Pi<float>();
const float r = ezMath::Sqrt(modelSpaceDir.x * modelSpaceDir.x + modelSpaceDir.z * modelSpaceDir.z);
const float theta = ezMath::ATan2(modelSpaceDir.y, r).GetRadian() + ezMath::Pi<float>() * 0.5f;
EZ_ASSERT_DEBUG(phi >= 0.0f && phi <= 2.0f * ezMath::Pi<float>(), "");
EZ_ASSERT_DEBUG(theta >= 0.0f && theta <= ezMath::Pi<float>(), "");
const float srcU = phi * InvPi * fHalfSrcWidth;
const float srcV = (1.0f - theta * InvPi) * fSrcHeight;
ezUInt32 x1 = (ezUInt32)ezMath::Floor(srcU);
ezUInt32 x2 = x1 + 1;
ezUInt32 y1 = (ezUInt32)ezMath::Floor(srcV);
ezUInt32 y2 = y1 + 1;
const float fracX = srcU - x1;
const float fracY = srcV - y1;
x1 = ezMath::Clamp(x1, 0u, srcWidthMinus1);
x2 = ezMath::Clamp(x2, 0u, srcWidthMinus1);
y1 = ezMath::Clamp(y1, 0u, srcHeightMinus1);
y2 = ezMath::Clamp(y2, 0u, srcHeightMinus1);
ezColor A = srcData[x1 + y1 * srcRowPitch];
ezColor B = srcData[x2 + y1 * srcRowPitch];
ezColor C = srcData[x1 + y2 * srcRowPitch];
ezColor D = srcData[x2 + y2 * srcRowPitch];
ezColor interpolated = A * (1 - fracX) * (1 - fracY) + B * (fracX) * (1 - fracY) + C * (1 - fracX) * fracY + D * fracX * fracY;
faceData[x + y * faceRowPitch] = interpolated;
}
}
}
}
return EZ_SUCCESS;
}
ezLog::Error("Unexpected number of faces in cubemap input image.");
return EZ_FAILURE;
}
ezResult ezImageUtils::CreateCubemapFrom6Files(ezImage& dstImg, const ezImageView* pSourceImages)
{
ezImageHeader header = pSourceImages[0].GetHeader();
header.SetNumFaces(6);
if (header.GetWidth() != header.GetHeight())
return EZ_FAILURE;
if (!ezMath::IsPowerOf2(header.GetWidth()))
return EZ_FAILURE;
dstImg.ResetAndAlloc(header);
for (ezUInt32 i = 0; i < 6; ++i)
{
if (pSourceImages[i].GetImageFormat() != dstImg.GetImageFormat())
return EZ_FAILURE;
if (pSourceImages[i].GetWidth() != dstImg.GetWidth())
return EZ_FAILURE;
if (pSourceImages[i].GetHeight() != dstImg.GetHeight())
return EZ_FAILURE;
CopyImageRectToFace(dstImg, pSourceImages[i], 0, 0, i);
}
return EZ_SUCCESS;
}
ezResult ezImageUtils::CreateVolumeTextureFromSingleFile(ezImage& dstImg, const ezImageView& srcImg)
{
const ezUInt32 uiWidthHeight = srcImg.GetHeight();
const ezUInt32 uiDepth = srcImg.GetWidth() / uiWidthHeight;
if (!ezMath::IsPowerOf2(uiWidthHeight))
return EZ_FAILURE;
if (!ezMath::IsPowerOf2(uiDepth))
return EZ_FAILURE;
ezImageHeader header;
header.SetWidth(uiWidthHeight);
header.SetHeight(uiWidthHeight);
header.SetDepth(uiDepth);
header.SetImageFormat(srcImg.GetImageFormat());
dstImg.ResetAndAlloc(header);
const ezImageView view = srcImg.GetSubImageView();
for (ezUInt32 d = 0; d < uiDepth; ++d)
{
ezRectU32 r;
r.x = uiWidthHeight * d;
r.y = 0;
r.width = uiWidthHeight;
r.height = uiWidthHeight;
EZ_SUCCEED_OR_RETURN(Copy(view, r, dstImg, ezVec3U32(0, 0, d)));
}
return EZ_SUCCESS;
}
ezColor ezImageUtils::BilinearSample(const ezImageView& image, ezImageAddressMode::Enum addressMode, ezVec2 uv)
{
EZ_ASSERT_DEBUG(image.GetDepth() == 1 && image.GetNumFaces() == 1 && image.GetNumArrayIndices() == 1, "Only 2d images are supported");
EZ_ASSERT_DEBUG(image.GetImageFormat() == ezImageFormat::R32G32B32A32_FLOAT, "Unsupported format");
ezInt32 w = image.GetWidth();
ezInt32 h = image.GetHeight();
uv = uv.CompMul(ezVec2(w, h)) - ezVec2(0.5f);
float floorX = ezMath::Floor(uv.x);
float floorY = ezMath::Floor(uv.y);
float fractionX = uv.x - floorX;
float fractionY = uv.y - floorY;
ezInt32 intX = (ezInt32)floorX;
ezInt32 intY = (ezInt32)floorY;
ezColor c[4];
for (ezUInt32 i = 0; i < 4; ++i)
{
ezInt32 x = intX + (i % 2);
ezInt32 y = intY + (i / 2);
if (addressMode == ezImageAddressMode::Clamp)
{
x = ezMath::Clamp(x, 0, w - 1);
y = ezMath::Clamp(y, 0, h - 1);
}
else
{
x = x % w;
x = x < 0 ? x + w : x;
y = y % h;
y = y < 0 ? y + w : y;
}
c[i] = *image.GetPixelPointer<ezColor>(0, 0, 0, x, y);
}
ezColor cr0 = ezMath::Lerp(c[0], c[1], fractionX);
ezColor cr1 = ezMath::Lerp(c[2], c[3], fractionX);
return ezMath::Lerp(cr0, cr1, fractionY);
}
EZ_STATICLINK_FILE(Texture, Texture_Image_Implementation_ImageUtils);
| 55,364 | 20,451 |
#include "pessoa.h"
bool Pessoa::setCodigo(string c){
codigo = c;
return 1;
}
bool Pessoa::setNome(string n){
if(n.size() > 5){
nome = n;
return 1;
}else{
cout << endl << "Nome muito curto! Escolha um nome com 5 ou mais letras. Tente novamente: ";
nome = "nome";
return 0;
}
}
bool Pessoa::setTelefone(string t){
if(t.size() == 9){
telefone = t;
return 1;
}else{
cout << endl << "Telefone invalido! Formato: 91234-5678. Tente novamente: ";
telefone = "98888-8888";
return 0;
}
}
bool Pessoa::setCep(string p){
if(p.size() == 8){
cep = p;
return 1;
}else{
cout << endl << "CEP invalido! Fomato: 12345-678. Tente novamente: ";
cep = "12345678";
return 0;
}
}
string Pessoa::getCodigo(){
return codigo;
}
string Pessoa::getNome(){
return nome;
}
string Pessoa::getTelefone(){
return telefone;
}
string Pessoa::getCep(){
return cep;
}
| 1,081 | 458 |
#ifndef DEVICE_COMMAND_HPP_
#define DEVICE_COMMAND_HPP_
namespace grl {
namespace concept {
template<typename Device>
class DeviceCommand
{
#ifndef DOXYGEN_NO_CONCEPT_MEMBERS
#endif
};
template<typename Device>
class ConstDeviceCommand
{
#ifndef DOXYGEN_NO_CONCEPT_MEMBERS
#endif
};
}}
#endif | 309 | 126 |
/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* \file ir_basic_block.cpp
*
* Basic block analysis of instruction streams.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_basic_block.h"
#include "glsl_types.h"
/**
* Calls a user function for every basic block in the instruction stream.
*
* Basic block analysis is pretty easy in our IR thanks to the lack of
* unstructured control flow. We've got:
*
* ir_loop (for () {}, while () {}, do {} while ())
* ir_loop_jump (
* ir_if () {}
* ir_return
* ir_call()
*
* Note that the basic blocks returned by this don't encompass all
* operations performed by the program -- for example, if conditions
* don't get returned, nor do the assignments that will be generated
* for ir_call parameters.
*/
void call_for_basic_blocks(exec_list *instructions,
void (*callback)(ir_instruction *first,
ir_instruction *last,
void *data),
void *data)
{
ir_instruction *leader = NULL;
ir_instruction *last = NULL;
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_if *ir_if;
ir_loop *ir_loop;
ir_function *ir_function;
if (!leader)
leader = ir;
if ((ir_if = ir->as_if())) {
callback(leader, ir, data);
leader = NULL;
call_for_basic_blocks(&ir_if->then_instructions, callback, data);
call_for_basic_blocks(&ir_if->else_instructions, callback, data);
} else if ((ir_loop = ir->as_loop())) {
callback(leader, ir, data);
leader = NULL;
call_for_basic_blocks(&ir_loop->body_instructions, callback, data);
} else if (ir->as_return() || ir->as_call()) {
callback(leader, ir, data);
leader = NULL;
} else if ((ir_function = ir->as_function())) {
/* A function definition doesn't interrupt our basic block
* since execution doesn't go into it. We should process the
* bodies of its signatures for BBs, though.
*
* Note that we miss an opportunity for producing more
* maximal BBs between the instructions that precede main()
* and the body of main(). Perhaps those instructions ought
* to live inside of main().
*/
foreach_iter(exec_list_iterator, fun_iter, *ir_function) {
ir_function_signature *ir_sig;
ir_sig = (ir_function_signature *)fun_iter.get();
call_for_basic_blocks(&ir_sig->body, callback, data);
}
}
last = ir;
}
if (leader) {
callback(leader, last, data);
}
}
| 3,589 | 1,195 |
//
// Created by robin on 06.10.21.
//
#include <sys/stat.h>
#include "PosStreamer.h"
Sample PosStreamer::get_next() {
if (ptr >= buffer_size) {
ptr = 0;
//if we reached the end of our file
//we have to wrap around
size_t read_elements = 0;
do {
if (stream.peek() == EOF) {
stream.clear();
stream.seekg(0, std::ios::beg);
}
std::istream_iterator<Sample> begin(stream);
std::istream_iterator<Sample> end;
for (; (begin != end) && read_elements < buffer_size; ++begin) {
Sample current = *begin;
if (current.position.hasJumps(current.position.getColor()))
continue;
buffer[read_elements++] = (*begin);
}
} while (read_elements < buffer_size);
//std::cout << "buffer is full now" << std::endl;
//the buffer is filled now so we can shuffle the elements
if (shuffle) {
std::shuffle(buffer.get(), buffer.get() + buffer_size, generator);
//std::cout << "buffer is shuffled" << std::endl;
}
}
return buffer[ptr++];
}
size_t PosStreamer::get_buffer_size() const {
return buffer_size;
}
size_t PosStreamer::ptr_position() {
return ptr;
}
const std::string &PosStreamer::get_file_path() {
return file_path;
}
size_t PosStreamer::get_file_size(std::string path) {
struct stat stat_buf;
int rc = stat(path.c_str(), &stat_buf);
return rc == 0 ? stat_buf.st_size : -1;
}
size_t PosStreamer::get_file_size() const {
return file_size;
}
| 1,649 | 534 |
/*
* Copyright (c) 2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestCase.h>
#include <AK/GenericLexer.h>
#include <AK/StringView.h>
TEST_CASE(should_constexpr_construct_from_empty_string_view)
{
constexpr GenericLexer sut(StringView {});
static_assert(sut.is_eof());
}
TEST_CASE(should_construct_from_string_view)
{
constexpr GenericLexer sut("abcdef"sv);
static_assert(!sut.is_eof());
}
TEST_CASE(should_constexpr_tell)
{
constexpr GenericLexer sut("abcdef"sv);
static_assert(sut.tell() == 0);
}
TEST_CASE(should_constexpr_tell_remaining)
{
constexpr GenericLexer sut("abcdef"sv);
static_assert(sut.tell_remaining() == 6);
}
TEST_CASE(should_constexpr_peek)
{
constexpr GenericLexer sut("abcdef"sv);
static_assert(sut.peek() == 'a');
static_assert(sut.peek(2) == 'c');
static_assert(sut.peek(100) == '\0');
}
TEST_CASE(should_constexpr_next_is)
{
constexpr GenericLexer sut("abcdef"sv);
static_assert(sut.next_is('a'));
static_assert(sut.next_is("abc"));
static_assert(sut.next_is("abc"sv));
}
TEST_CASE(should_constexpr_retreat)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.consume();
sut.retreat();
return sut;
}();
static_assert(sut.peek() == 'a');
}
TEST_CASE(should_constexpr_consume_1)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.consume();
return sut;
}();
static_assert(sut.peek() == 'b');
}
TEST_CASE(should_constexpr_consume_specific_char)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.consume_specific('a');
return sut;
}();
static_assert(sut.peek() == 'b');
}
TEST_CASE(should_constexpr_consume_specific_string_view)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.consume_specific("ab"sv);
return sut;
}();
static_assert(sut.peek() == 'c');
}
TEST_CASE(should_constexpr_consume_specific_cstring)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.consume_specific("abcd");
return sut;
}();
static_assert(sut.peek() == 'e');
}
TEST_CASE(should_constexpr_ignore_until)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.ignore_until('d');
return sut;
}();
static_assert(sut.peek() == 'e');
}
TEST_CASE(should_constexpr_ignore_until_cstring)
{
constexpr auto sut = [] {
GenericLexer sut("abcdef"sv);
sut.ignore_until("cde");
return sut;
}();
static_assert(sut.peek() == 'f');
}
TEST_CASE(should_constexpr_next_is_pred)
{
constexpr auto pred = [](auto c) {
return c == 'a';
};
constexpr GenericLexer sut("abcdef"sv);
static_assert(sut.next_is(pred));
}
TEST_CASE(should_constexpr_ignore_while_pred)
{
constexpr auto sut = [] {
constexpr auto pred = [](auto c) {
return c == 'a';
};
GenericLexer sut("abcdef"sv);
sut.ignore_while(pred);
return sut;
}();
static_assert(sut.peek() == 'b');
}
TEST_CASE(should_constexpr_ignore_until_pred)
{
constexpr auto sut = [] {
constexpr auto pred = [](auto c) {
return c == 'c';
};
GenericLexer sut("abcdef"sv);
sut.ignore_until(pred);
return sut;
}();
static_assert(sut.peek() == 'c');
}
TEST_CASE(consume_escaped_code_point)
{
auto test = [](StringView test, Result<u32, GenericLexer::UnicodeEscapeError> expected, bool combine_surrogate_pairs = true) {
GenericLexer lexer(test);
auto actual = lexer.consume_escaped_code_point(combine_surrogate_pairs);
EXPECT_EQ(actual.is_error(), expected.is_error());
if (actual.is_error() && expected.is_error())
EXPECT_EQ(actual.error(), expected.error());
else
EXPECT_EQ(actual.value(), expected.value());
};
test("\\u"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u{"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u{1"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u{}"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u{x}"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u{110000}"sv, GenericLexer::UnicodeEscapeError::UnicodeEscapeOverflow);
test("\\u{f00000000}"sv, GenericLexer::UnicodeEscapeError::UnicodeEscapeOverflow);
test("\\u{0}"sv, 0);
test("\\u{41}"sv, 0x41);
test("\\u{ffff}"sv, 0xffff);
test("\\u{10ffff}"sv, 0x10ffff);
test("\\u1"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u11"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u111"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u111x"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\ud800\\u"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\ud800\\u1"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\ud800\\u11"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\ud800\\u111"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\ud800\\u111x"sv, GenericLexer::UnicodeEscapeError::MalformedUnicodeEscape);
test("\\u0000"sv, 0x0);
test("\\u0041"sv, 0x41);
test("\\uffff"sv, 0xffff);
test("\\ud83d"sv, 0xd83d);
test("\\ud83d\\u1111"sv, 0xd83d);
test("\\ud83d\\ude00"sv, 0x1f600);
test("\\ud83d\\ude00"sv, 0xd83d, false);
}
| 5,694 | 2,275 |
#include "Texture.h"
#include "Base/Engine.h"
#include "Graphics/Renderer.h"
#include <D3DX11tex.h>
namespace S2DE::Render
{
Texture::Texture()
{
m_type = "Texture";
m_ex = { ".dds", ".png", ".tga", ".jpg" };
}
Texture::~Texture()
{
}
void Texture::Cleanup()
{
Core::Release(m_resource);
Core::Release(m_texture_resource);
}
bool Texture::Load(std::string path)
{
if (Core::Other::isStringEmpty(path))
return false;
ID3D11Resource* res;
S2DE_CHECK(D3DX11CreateShaderResourceViewFromFile(Core::Engine::GetRenderer()->GetDevice(), path.c_str(), NULL, NULL, &m_resource, NULL), "Can't create texture!");
m_resource->GetResource(&res);
res->QueryInterface<ID3D11Texture2D>(&m_texture_resource);
m_texture_resource->GetDesc(&m_texture_desc);
Core::Release(res);
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 0;
S2DE_CHECK(Core::Engine::GetRenderer()->GetDevice()->CreateSamplerState(&samplerDesc, &m_texture_sampler_state), "Can't create sampler state");
return true;
}
void Texture::Bind(std::uint32_t NumViews)
{
Core::Engine::GetRenderer()->GetContext()->PSSetShaderResources(0, NumViews, &m_resource);
Core::Engine::GetRenderer()->GetContext()->PSGetSamplers(0, NumViews, &m_texture_sampler_state);
}
} | 1,796 | 783 |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "forest/editor/forestBrushElement.h"
#include "console/engineAPI.h"
#include "forest/forestItem.h"
//-------------------------------------------------------------------------
// ForestBrushElement
//-------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( ForestBrushElement );
ConsoleDocClass( ForestBrushElement,
"@brief Represents a type of ForestItem and parameters for how it is placed"
" when painting with a ForestBrush that contains it.\n\n"
"@ingroup Forest"
);
ForestBrushElement::ForestBrushElement()
: mData( NULL ),
mProbability( 1 ),
mRotationRange( 360 ),
mScaleMin( 1 ),
mScaleMax( 1 ),
mScaleExponent( 1 ),
mSinkMin( 0.0f ),
mSinkMax( 0.0f ),
mSinkRadius( 1 ),
mSlopeMin( 0.0f ),
mSlopeMax( 90.0f ),
mElevationMin( -10000.0f ),
mElevationMax( 10000.0f )
{
}
void ForestBrushElement::initPersistFields()
{
Parent::initPersistFields();
addGroup( "ForestBrushElement" );
addField( "forestItemData", TYPEID< ForestItemData >(), Offset( mData, ForestBrushElement ),
"The type of ForestItem this element holds placement parameters for." );
addField( "probability", TypeF32, Offset( mProbability, ForestBrushElement ),
"The probability that this element will be created during an editor brush stroke "
"is the sum of all element probabilities in the brush divided by the probability "
"of this element." );
addField( "rotationRange", TypeF32, Offset( mRotationRange, ForestBrushElement ),
"The max rotation in degrees that items will be placed." );
addField( "scaleMin", TypeF32, Offset( mScaleMin, ForestBrushElement ),
"The minimum random size for each item." );
addField( "scaleMax", TypeF32, Offset( mScaleMax, ForestBrushElement ),
"The maximum random size of each item." );
addField( "scaleExponent", TypeF32, Offset( mScaleExponent, ForestBrushElement ),
"An exponent used to bias between the minimum and maximum random sizes." );
addField( "sinkMin", TypeF32, Offset( mSinkMin, ForestBrushElement ),
"Min variation in the sink radius." );
addField( "sinkMax", TypeF32, Offset( mSinkMax, ForestBrushElement ),
"Max variation in the sink radius." );
addField( "sinkRadius", TypeF32, Offset( mSinkRadius, ForestBrushElement ),
"This is the radius used to calculate how much to sink the trunk at "
"its base and is used to sink the tree into the ground when its on a slope." );
addField( "slopeMin", TypeF32, Offset( mSlopeMin, ForestBrushElement ),
"The min surface slope in degrees this item will be placed on." );
addField( "slopeMax", TypeF32, Offset( mSlopeMax, ForestBrushElement ),
"The max surface slope in degrees this item will be placed on." );
addField( "elevationMin", TypeF32, Offset( mElevationMin, ForestBrushElement ),
"The min world space elevation this item will be placed." );
addField( "elevationMax", TypeF32, Offset( mElevationMax, ForestBrushElement ),
"The max world space elevation this item will be placed." );
endGroup( "ForestBrushElement" );
}
//-------------------------------------------------------------------------
// ForestBrushElementSet
//-------------------------------------------------------------------------
SimObjectPtr<SimGroup> ForestBrush::smGroup = NULL;
IMPLEMENT_CONOBJECT( ForestBrush );
ConsoleDocClass( ForestBrush,
"@brief Container class for ForestBrushElements\n\n"
"Editor use only.\n\n"
"@internal"
);
ForestBrush::ForestBrush()
{
}
bool ForestBrush::onAdd()
{
if ( !Parent::onAdd() )
return false;
getGroup()->addObject( this );
return true;
}
void ForestBrush::addObject( SimObject *inObj )
{
ForestBrushElement *ele = dynamic_cast<ForestBrushElement*>( inObj );
if ( !ele )
return;
//if ( containsItemData( ele->mData ) )
// return;
Parent::addObject( inObj );
}
SimGroup* ForestBrush::getGroup()
{
if ( !smGroup )
{
SimGroup *dummy;
if ( Sim::findObject( "ForestBrushGroup", dummy ) )
{
smGroup = dummy;
return smGroup;
}
smGroup = new SimGroup;
smGroup->assignName( "ForestBrushGroup" );
smGroup->registerObject();
Sim::getRootGroup()->addObject( smGroup );
}
return smGroup;
}
bool ForestBrush::containsItemData( const ForestItemData *inData )
{
SimObjectList::iterator iter = mObjectList.begin();
for ( ; iter != mObjectList.end(); iter++ )
{
ForestBrushElement *pElement = dynamic_cast<ForestBrushElement*>(*iter);
if ( !pElement )
continue;
if ( pElement->mData == inData )
return true;
}
return false;
}
DefineEngineMethod( ForestBrush, containsItemData, bool, ( const char * obj ), , "( ForestItemData obj )" )
{
ForestItemData *data = NULL;
if ( !Sim::findObject( obj, data ) )
{
Con::warnf( "ForestBrush::containsItemData - invalid object passed" );
return false;
}
return object->containsItemData( data );
} | 6,499 | 1,979 |
// Copyright 2021 Your Name <your_email>
#include <stdexcept>
#include <gtest/gtest.h>
#include <shared_ptr.hpp>
TEST(Example, EmptyTest) {
EXPECT_THROW(example(), std::runtime_error);
}
| 195 | 80 |
#include "IO.h"
void outb(uint16_t port, uint8_t value){
asm volatile ("outb %0, %1" : : "a"(value), "Nd"(port));
}
uint8_t inb(uint16_t port){
uint8_t returnVal;
asm volatile ("inb %1, %0"
: "=a"(returnVal)
: "Nd"(port));
return returnVal;
}
void outw(uint16_t portNumber, uint16_t data) {
__asm__ volatile("outw %0, %1" : : "a"(data) , "Nd"(portNumber));
}
void io_wait(){
asm volatile ("outb %%al, $0x80" : : "a"(0));
}
uint16_t inw(uint16_t portNumber) {
uint16_t data;
__asm__ volatile("inw %1, %0" : "=a"(data) : "Nd"(portNumber));
return data;
}
uint32_t inl(uint16_t portNumber) {
uint32_t data;
__asm__ volatile("inl %1, %0" : "=a"(data) : "Nd"(portNumber));
return data;
}
void outl(uint16_t portNumber, uint32_t data) {
__asm__ volatile("outl %0, %1" : : "a"(data) , "Nd"(portNumber));
}
| 866 | 414 |
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <errno.h>
#include <poll.h>
#include <sys/timerfd.h>
#include <time.h>
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/util/file_descriptor.h"
#include "test/util/posix_error.h"
#include "test/util/test_util.h"
namespace gvisor {
namespace testing {
namespace {
// Wrapper around timerfd_create(2) that returns a FileDescriptor.
PosixErrorOr<FileDescriptor> TimerfdCreate(int clockid, int flags) {
int fd = timerfd_create(clockid, flags);
MaybeSave();
if (fd < 0) {
return PosixError(errno, "timerfd_create failed");
}
return FileDescriptor(fd);
}
// In tests that race a timerfd with a sleep, some slack is required because:
//
// - Timerfd expirations are asynchronous with respect to nanosleeps.
//
// - Because clock_gettime(CLOCK_MONOTONIC) is implemented through the VDSO,
// it technically uses a closely-related, but distinct, time domain from the
// CLOCK_MONOTONIC used to trigger timerfd expirations. The same applies to
// CLOCK_BOOTTIME which is an alias for CLOCK_MONOTONIC.
absl::Duration TimerSlack() { return absl::Milliseconds(500); }
class TimerfdTest : public ::testing::TestWithParam<int> {};
TEST_P(TimerfdTest, IsInitiallyStopped) {
auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));
struct itimerspec its = {};
ASSERT_THAT(timerfd_gettime(tfd.get(), &its), SyscallSucceeds());
EXPECT_EQ(0, its.it_value.tv_sec);
EXPECT_EQ(0, its.it_value.tv_nsec);
}
TEST_P(TimerfdTest, SingleShot) {
constexpr absl::Duration kDelay = absl::Seconds(1);
auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));
struct itimerspec its = {};
its.it_value = absl::ToTimespec(kDelay);
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
// The timer should fire exactly once since the interval is zero.
absl::SleepFor(kDelay + TimerSlack());
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallSucceedsWithValue(sizeof(uint64_t)));
EXPECT_EQ(1, val);
}
TEST_P(TimerfdTest, Periodic) {
constexpr absl::Duration kDelay = absl::Seconds(1);
constexpr int kPeriods = 3;
auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));
struct itimerspec its = {};
its.it_value = absl::ToTimespec(kDelay);
its.it_interval = absl::ToTimespec(kDelay);
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
// Expect to see at least kPeriods expirations. More may occur due to the
// timer slack, or due to delays from scheduling or save/restore.
absl::SleepFor(kPeriods * kDelay + TimerSlack());
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallSucceedsWithValue(sizeof(uint64_t)));
EXPECT_GE(val, kPeriods);
}
TEST_P(TimerfdTest, BlockingRead) {
constexpr absl::Duration kDelay = absl::Seconds(3);
auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), 0));
struct itimerspec its = {};
its.it_value.tv_sec = absl::ToInt64Seconds(kDelay);
auto const start_time = absl::Now();
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
// read should block until the timer fires.
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallSucceedsWithValue(sizeof(uint64_t)));
auto const end_time = absl::Now();
EXPECT_EQ(1, val);
EXPECT_GE((end_time - start_time) + TimerSlack(), kDelay);
}
TEST_P(TimerfdTest, NonblockingRead_NoRandomSave) {
constexpr absl::Duration kDelay = absl::Seconds(5);
auto const tfd =
ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));
// Since the timer is initially disabled and has never fired, read should
// return EAGAIN.
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallFailsWithErrno(EAGAIN));
DisableSave ds; // Timing-sensitive.
// Arm the timer.
struct itimerspec its = {};
its.it_value.tv_sec = absl::ToInt64Seconds(kDelay);
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
// Since the timer has not yet fired, read should return EAGAIN.
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallFailsWithErrno(EAGAIN));
ds.reset(); // No longer timing-sensitive.
// After the timer fires, read should indicate 1 expiration.
absl::SleepFor(kDelay + TimerSlack());
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallSucceedsWithValue(sizeof(uint64_t)));
EXPECT_EQ(1, val);
// The successful read should have reset the number of expirations.
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(TimerfdTest, BlockingPoll_SetTimeResetsExpirations) {
constexpr absl::Duration kDelay = absl::Seconds(3);
auto const tfd =
ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));
struct itimerspec its = {};
its.it_value.tv_sec = absl::ToInt64Seconds(kDelay);
auto const start_time = absl::Now();
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
// poll should block until the timer fires.
struct pollfd pfd = {};
pfd.fd = tfd.get();
pfd.events = POLLIN;
ASSERT_THAT(poll(&pfd, /* nfds = */ 1,
/* timeout = */ 2 * absl::ToInt64Seconds(kDelay) * 1000),
SyscallSucceedsWithValue(1));
auto const end_time = absl::Now();
EXPECT_EQ(POLLIN, pfd.revents);
EXPECT_GE((end_time - start_time) + TimerSlack(), kDelay);
// Call timerfd_settime again with a value of 0. This should reset the number
// of expirations to 0, causing read to return EAGAIN since the timerfd is
// non-blocking.
its.it_value.tv_sec = 0;
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallFailsWithErrno(EAGAIN));
}
TEST_P(TimerfdTest, SetAbsoluteTime) {
constexpr absl::Duration kDelay = absl::Seconds(3);
// Use a non-blocking timerfd so that if TFD_TIMER_ABSTIME is incorrectly
// non-functional, we get EAGAIN rather than a test timeout.
auto const tfd =
ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));
struct itimerspec its = {};
ASSERT_THAT(clock_gettime(GetParam(), &its.it_value), SyscallSucceeds());
its.it_value.tv_sec += absl::ToInt64Seconds(kDelay);
ASSERT_THAT(timerfd_settime(tfd.get(), TFD_TIMER_ABSTIME, &its, nullptr),
SyscallSucceeds());
absl::SleepFor(kDelay + TimerSlack());
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallSucceedsWithValue(sizeof(uint64_t)));
EXPECT_EQ(1, val);
}
TEST_P(TimerfdTest, IllegalReadWrite) {
auto const tfd =
ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(GetParam(), TFD_NONBLOCK));
uint64_t val = 0;
EXPECT_THAT(PreadFd(tfd.get(), &val, sizeof(val), 0),
SyscallFailsWithErrno(ESPIPE));
EXPECT_THAT(WriteFd(tfd.get(), &val, sizeof(val)),
SyscallFailsWithErrno(EINVAL));
EXPECT_THAT(PwriteFd(tfd.get(), &val, sizeof(val), 0),
SyscallFailsWithErrno(ESPIPE));
}
std::string PrintClockId(::testing::TestParamInfo<int> info) {
switch (info.param) {
case CLOCK_MONOTONIC:
return "CLOCK_MONOTONIC";
case CLOCK_BOOTTIME:
return "CLOCK_BOOTTIME";
default:
return absl::StrCat(info.param);
}
}
INSTANTIATE_TEST_SUITE_P(AllTimerTypes, TimerfdTest,
::testing::Values(CLOCK_MONOTONIC, CLOCK_BOOTTIME),
PrintClockId);
TEST(TimerfdClockRealtimeTest, ClockRealtime) {
// Since CLOCK_REALTIME can, by definition, change, we can't make any
// non-flaky assertions about the amount of time it takes for a
// CLOCK_REALTIME-based timer to expire. Just check that it expires at all,
// and hope it happens before the test times out.
constexpr int kDelaySecs = 1;
auto const tfd = ASSERT_NO_ERRNO_AND_VALUE(TimerfdCreate(CLOCK_REALTIME, 0));
struct itimerspec its = {};
its.it_value.tv_sec = kDelaySecs;
ASSERT_THAT(timerfd_settime(tfd.get(), /* flags = */ 0, &its, nullptr),
SyscallSucceeds());
uint64_t val = 0;
ASSERT_THAT(ReadFd(tfd.get(), &val, sizeof(uint64_t)),
SyscallSucceedsWithValue(sizeof(uint64_t)));
EXPECT_EQ(1, val);
}
} // namespace
} // namespace testing
} // namespace gvisor
| 9,281 | 3,511 |
//
// FishQuizPopup.cpp
// PehlaSchool
//
// Created by YongSoo Hong on 9/3/18.
//
//
#include <Menu/CoopScene.hpp>
#include "FishQuizPopup.hpp"
#include "ui/CocosGUI.h"
#include "Managers/UserManager.hpp"
#include "Managers/LanguageManager.hpp"
#include "Managers/GameSoundManager.h"
#include "Utils/TodoUtil.h"
#include "Common/Controls/TodoSchoolBackButton.hpp"
#include "../../Menu/CoopScene.hpp"
#include "../../Menu/Fish.hpp"
#include "EggQuizScene.hpp"
#include <time.h>
namespace FishQuizPopupSpace {
const std::string JNI_CLASS_NAME = "org/cocos2dx/cpp/AppActivity";
const string curlyFont = "fonts/chanakya.ttf";
class SwapNode : public ActionInterval {
public:
static SwapNode* create(float duration, int blinks, Node* node0, Node* node1);
virtual void update(float time) override;
virtual void startWithTarget(Node *target) override;
virtual void stop() override;
private:
int _times;
Node* _node0;
Node* _node1;
int _effectID;
bool initWithDuration(float duration, int blinks, Node* node0, Node* node1);
};
}
using namespace FishQuizPopupSpace;
using namespace cocos2d::ui;
const string partsPath = "eggquiz/parts/";
const string soundsPath = "eggquiz/sounds/";
FishQuizPopup* FishQuizPopup::create(Node* parent)
{
FishQuizPopup *popup = new (std::nothrow) FishQuizPopup();
if (popup && popup->init(parent))
{
popup->autorelease();
return popup;
}
CC_SAFE_DELETE(popup);
return nullptr;
}
FishQuizPopup* FishQuizPopup::create(Node* parent, Size size)
{
FishQuizPopup *popup = new (std::nothrow) FishQuizPopup();
if (popup && popup->init(parent, size))
{
popup->autorelease();
return popup;
}
CC_SAFE_DELETE(popup);
return nullptr;
}
void FishQuizPopup::dismiss(bool animate) {
PopupBase::dismiss(animate);
for (auto fish : _fishData) {
delete fish;
}
_fishData.clear();
}
Node* FishQuizPopup::createGlow()
{
Node *node = Node::create();
{
auto sp = Sprite::create(partsPath+"popup_window_glow_toleft.png");
node->addChild(sp);
sp->runAction(RepeatForever::create(RotateBy::create(0.5, 30)));
}
{
auto sp = Sprite::create(partsPath+"popup_window_glow_toright.png");
node->addChild(sp);
sp->runAction(RepeatForever::create(RotateBy::create(0.5, -30)));
}
{
auto sp = Sprite::create(partsPath+"popup_window_glow.png");
node->addChild(sp);
}
return node;
}
Button* FishQuizPopup::createButton(string prefix, string text) {
auto btn = Button::create(prefix+"_normal.png", prefix+"_active.png");
if (text.length()>0) {
auto localTxt = LanguageManager::getInstance()->getLocalizedString(text, false);
auto l = TodoUtil::createLabel(localTxt, 60, Size::ZERO, curlyFont, Color4B(255, 252, 236, 255));
auto lPos = btn->getContentSize()/2 + Size(0, 10);
l->setPosition(lPos);
btn->addChild(l);
btn->addTouchEventListener([btn, lPos, l](Ref*,Widget::TouchEventType) {
if (btn->isHighlighted()) l->setPosition(lPos + Size(0, -10));
else l->setPosition(lPos);
});
}
return btn;
}
void FishQuizPopup::setFishCompleted(char category, int progressLevelIndex, int progressIndex, int score)
{
CCLOG("FishQuizPopup - category : %c, progressLevelIndex : %d, progressLevelIndex : %d, score : %d", category, progressLevelIndex, progressIndex, score);
auto lang = LanguageManager::getInstance()->getCurrentLanguageTag();
int maxClearLevel = 0;
for (int i = CoopScene::LEVEL_COUNT_REGULAR_EGG - 1; i >= 0; --i) {
auto levelID = CurriculumManager::getInstance()->makeLevelID(lang, category, i);
if (UserManager::getInstance()->isLevelCleared(levelID)) {
maxClearLevel = i;
break;
}
}
CCLOG("FishQuizPopup - maxClearLevel : %d", maxClearLevel);
auto levelID = CurriculumManager::getInstance()->makeLevelID(lang, category, CoopScene::LEVEL_FISH_PRESENT);
UserManager::getInstance()->setFishPresentCurrentProgressIndex(levelID, progressLevelIndex, progressIndex + 1);
CCLOG("FishQuizPopup levelID : %s", levelID.c_str());
UserManager::getInstance()->setFishPresentEnable(levelID, false);
if (score > 60) {
UserManager::getInstance()->setFishPresentCurrentProgressLevel(levelID, (progressLevelIndex + 1) % (maxClearLevel + 1));
showSuccess(category, progressLevelIndex, progressIndex, score);
} else {
if (EggQuiz::EggQuizScene::getTryCountFishTest() != 0) {
UserManager::getInstance()->setFishPresentCurrentProgressLevel(levelID, (progressLevelIndex + 1) % (maxClearLevel + 1));
}
showFail(category, progressLevelIndex, progressIndex, score);
}
}
void FishQuizPopup::showSuccess(char category, int progressLevelIndex, int progressIndex, int score) {
auto winSize = getContentSize();
auto playWowSound = [this]() {
GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/pretest_success.m4a");
this->runAction(Sequence::create(DelayTime::create(1.0),
CallFunc::create([](){
SoundEffect::wowEffect().play();
GameSoundManager::getInstance()->playBGM(soundsPath + "congratseeyouseaworld.m4a");
}),
nullptr
));
};
if (score < 100) {
playWowSound();
}
auto bg = Sprite::create(partsPath+"pretest_image_fishbowl_result_01.png");
auto bgCenter = winSize / 2 + Size(0, 70);
auto fishCenter = bgCenter + Size(0, bg->getContentSize().height / 2 - 162 - 412 / 2);
auto glow = createGlow();
glow->setPosition(fishCenter);
this->addChild(glow);
if (score == 100) {
glow->setVisible(false);
}
bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
bg->setPosition(bgCenter);
this->addChild(bg);
auto playParticle = [this, winSize, fishCenter]() {
for (int i=0; i<60; i++) {
auto file = partsPath+StringUtils::format("popup_effect_confetti_%d.png", random(1, 8));
auto sp = Sprite::create(file);
auto posNode = Node::create();
posNode->addChild(sp);
posNode->setPosition(fishCenter);
auto rotateAction = RotateBy::create(0.3, Vec3(random(-30.f, 30.f), random(-30.f, 30.f), random(-30.f, 30.f)));
sp->runAction(RepeatForever::create(rotateAction));
auto pos = Vec2(random<float>(winSize.width*0.15, winSize.width*0.85), random(winSize.height*0.4, winSize.height*0.9));
auto speed = random(150.f, 250.f);
float delay = random(0.0, 0.2);
posNode->runAction(Sequence::create(DelayTime::create(delay), EaseOut::create(MoveTo::create(random(0.3, 0.5), pos), 2.0), MoveTo::create(pos.y / speed, Vec2(pos.x, -100)), nullptr));
this->addChild(posNode);
}
};
auto localTxt = LanguageManager::getInstance()->getLocalizedString("Congratulations!\nSee you at your sea world!", false);
auto splits = TodoUtil::split(localTxt, '\n');
auto l = TodoUtil::createLabel(localTxt, splits.size() > 2 ? 45 : 50, Size::ZERO, curlyFont, Color4B(255, 252, 236, 225));
l->setAlignment(TextHAlignment::CENTER);
l->setPosition(bgCenter + Size(0, -320));
this->addChild(l);
auto btn = createButton(partsPath+"popup_window_check", "");
btn->addClickEventListener([this](Ref*){
this->dismiss(true);
});
btn->setPosition(Vec2(winSize.width/2, winSize.height-1375));
this->addChild(btn);
if (score == 100) {
l->setVisible(false);
btn->setEnabled(false);
}
{
loadFishDataFromDB();
int skin = 1;
auto fishID = Fish::getFishID(category, progressLevelIndex + 1, false);
skin = generateFishSkin(fishID);
CCLOG("monts skin : %d", skin);
auto fish = Fish::create(category, progressLevelIndex + 1, false, skin);
fish->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
fish->setContentSize(Size(520, 412));
fish->setPosition(fishCenter);
this->addChild(fish);
if (score == 100) {
auto fish2 = Fish::create(category, progressLevelIndex + 1, true);
fish2->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
fish2->setContentSize(Size(520, 412));
fish2->setPosition(fishCenter);
this->addChild(fish2);
fish->setVisible(true);
fish2->setVisible(false);
int swapCount = random(30, 33);
runAction(Sequence::create(DelayTime::create(1.0f), EaseIn::create(SwapNode::create(8.0f, swapCount, fish, fish2), 0.15),
CallFunc::create([this, fish, fish2, glow, playWowSound, playParticle, l, btn](){
glow->setVisible(true);
playWowSound();
playParticle();
l->setVisible(true);
btn->setEnabled(true);
this->addFishToDB(fish->isVisible() ? fish : fish2);
}), nullptr));
} else {
addFishToDB(fish);
}
}
if (score < 100) {
playParticle();
}
}
void FishQuizPopup::showFail(char category, int progressLevelIndex, int progressIndex, int score) {
bool bRetry = EggQuiz::EggQuizScene::getTryCountFishTest() == 0;
auto winSize = getContentSize();
if (bRetry) {
GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/sfx_grow.m4a");
GameSoundManager::getInstance()->playBGM(soundsPath + "dontgiveupletstryagain.m4a");
} else {
GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/pretest_fail1.m4a");
GameSoundManager::getInstance()->playBGM(soundsPath + "tryagaintoaddmeseaworld.m4a");
}
auto bg = Sprite::create(partsPath+"popup_window_bg.png");
bg->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
bg->setPosition(Vec2(winSize.width/2, winSize.height));
this->addChild(bg);
this->showFromTop = true;
int level = progressLevelIndex;
_cur = CurriculumManager::getInstance()->findCurriculum(category, level);
string panelFilename = category=='L' ? "daily_window_title_panel_english_.png" : "daily_window_title_panel_math.png";
if (level==0) panelFilename = "daily_window_title_panel_prek.png";
auto panel = Sprite::create("MainScene/DaySelect/"+panelFilename);
panel->setPosition(winSize.width/2, winSize.height-320);
this->addChild(panel);
auto panelLabel = TodoUtil::createLabel(_cur->levelTitle, 70, Size::ZERO, curlyFont, Color4B(255, 252, 236, 255));
panelLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
panelLabel->setPosition(panel->getContentSize()/2);
panel->addChild(panelLabel);
{
auto fishBowl = Sprite::create(partsPath + (bRetry ? "pretest_image_fishbowl_result_02_colour.png" : "pretest_image_fishbowl_result_02.png"));
fishBowl->setPosition(bg->getContentSize() / 2 + Size(0, 0));
bg->addChild(fishBowl);
auto fish = Fish::create(category, progressLevelIndex + 1, false, 1, !bRetry);
fish->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
fish->setContentSize(Size(420, 346));
fish->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP);
fish->setPosition(Vec2(fishBowl->getContentSize().width / 2, fishBowl->getContentSize().height - 162));
fishBowl->addChild(fish);
}
{
auto s1 = LanguageManager::getInstance()->getLocalizedString((bRetry ? "Don't give up! Let's try it again!": "Try again to add me to your sea world!"), false);
auto l = TodoUtil::createLabel(s1, 50, Size::ZERO, curlyFont,
Color4B(115, 61, 19, 225), TextHAlignment::CENTER);
l->setPosition(Vec2(winSize.width / 2, winSize.height - 1120));
this->addChild(l);
}
{
auto btn = createButton(partsPath+(bRetry ? "popup_window_check" : "pretest_button_back"), "");
btn->addClickEventListener([this](Ref *) {
this->dismiss(true);
});
btn->setPosition(Vec2(winSize.width / 2, winSize.height - 1320));
this->addChild(btn);
}
EggQuiz::EggQuizScene::increaseTryCountFishTest();
}
void FishQuizPopup::loadFishDataFromDB() {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
auto strFishes = JniHelper::callStaticStringMethod(JNI_CLASS_NAME, "getFishes");
#else
string strFishes = "[]";
string path = FileUtils::getInstance()->getWritablePath() + "PehlaSchool";
if (FileUtils::getInstance()->isFileExist(path+"/fish_sample.txt")) {
strFishes = FileUtils::getInstance()->getStringFromFile(path+"/fish_sample.txt");
}
#endif
CCLOG("getFishes : \n%s", strFishes.c_str());
Json::Value values = Json::Value();
Json::Reader jsonReader;
jsonReader.parse(strFishes, values);
CCLOG("values size : %d", values.size());
for (int i = 0; i < values.size(); ++i) {
FISH_DATA* fishData = new FISH_DATA();
fishData->_id = values[i].get("_id", 0).asInt();
fishData->_userName = values[i].get("_userName", "").asString().c_str();
fishData->_fishID = values[i].get("_fishID", "").asString().c_str();
fishData->_skinNo = values[i].get("_skinNo", "").asString().c_str();
fishData->_name = values[i].get("_name", "").asString().c_str();
fishData->_createTime = values[i].get("_createTime", "").asString().c_str();
struct tm tm;
strptime(fishData->_createTime.c_str(), "%Y%m%d%H%M%S", &tm);
fishData->_time = mktime(&tm);
CCLOG("monts : fish id = %d, create = %s, time = %ld", fishData->_id, fishData->_createTime.c_str(), fishData->_time);
fishData->_position = values[i].get("_position", "").asString().c_str();
_fishData.push_back(fishData);
CCLOG("%s", fishData->toString().c_str());
}
}
void FishQuizPopup::addFishToDB(Fish* fish) {
auto position = generateFishPosition(fish->getID());
CCLOG("monts : FishQuizPopup fishID = %s, skin = %d, position = %s", fish->getID().c_str(), fish->getSkin(), position.c_str());
auto dbFish = findDeleteFish(fish->getID().c_str(), position);
if (dbFish != nullptr) {
CCLOG("monts : FishQuizPopup delete id : %d, fishID = %s, createTime : %s, position = %s", dbFish->_id, dbFish->_fishID.c_str(), dbFish->_createTime.c_str(), dbFish->_position.c_str());
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
if (dbFish != nullptr) {
JniHelper::callStaticBooleanMethod(JNI_CLASS_NAME, "deleteFish", dbFish->_id);
}
JniHelper::callStaticVoidMethod(JNI_CLASS_NAME, "addFish", fish->getID().c_str(), fish->getSkin(), "", position);
#else
#endif
}
FISH_DATA* FishQuizPopup::findDeleteFish(string fishID, string position) {
// Fish
if (TodoUtil::startsWith(fishID, "f")) {
const int MAX_FISH_COUNT = 20;
int fishCount = 0;
long oldTime = LONG_MAX;
FishData * oldData = nullptr;
for (auto fishData : _fishData) {
if (TodoUtil::startsWith(fishData->_fishID, "f")) {
++fishCount;
if (oldTime > fishData->_time) {
oldTime = fishData->_time;
oldData = fishData;
}
}
}
CCLOG("monts : fish count = %d", fishCount);
if (fishCount >= MAX_FISH_COUNT) {
CCLOG("monts : delete id = %d, fishID = %s, createTime = %s", oldData->_id, oldData->_fishID.c_str(), oldData->_createTime.c_str());
return oldData;
}
}
// Object
else {
for (auto fishData : _fishData) {
if (position == fishData->_position) {
CCLOG("monts : delete id = %d, fishID = %s, position = %s", fishData->_id, fishData->_fishID.c_str(), fishData->_position.c_str());
return fishData;
}
}
}
return nullptr;
}
int FishQuizPopup::generateFishSkin(string fishID) {
bool isSkin1 = false;
bool isSkin2 = false;
for (auto fishData : _fishData) {
if (fishID == fishData->_fishID) {
int skin = TodoUtil::stoi(fishData->_skinNo);
if (skin == 1) {
isSkin1 = true;
} else if (skin == 2) {
isSkin2 = true;
}
}
}
CCLOG("monts : isSkin1 = %d, isSkin2 = %d", isSkin1, isSkin2);
if (isSkin1 == isSkin2) {
return random(1, 2);
}
return isSkin1 ? 2 : 1;
}
string FishQuizPopup::generateFishPosition(string fishID) {
if (TodoUtil::startsWith(fishID, "d") == false) {
return "";
}
auto positions = Fish::getFishPosition(fishID);
vector<string>::iterator it;
bool bErase = false;
for(it = positions.begin(); it != positions.end(); ) {
bErase = false;
for (auto fishData : _fishData) {
if ((*it) == fishData->_position) {
it = positions.erase(it);
bErase = true;
break;
}
}
if(bErase == false) {
++it;
}
}
if (positions.size() == 0) {
positions = Fish::getFishPosition(fishID);
vector<FishData*> fishes;
for (auto position : positions) {
for (auto fishData : _fishData) {
if (position == fishData->_position) {
fishes.push_back(fishData);
break;
}
}
}
long oldTime = LONG_MAX;
FishData * oldData = nullptr;
for (auto fishData : fishes) {
if (oldTime > fishData->_time) {
oldTime = fishData->_time;
oldData = fishData;
}
}
return oldData->_position;
}
return positions.at(random(0, (int)(positions.size()) - 1));
}
SwapNode* SwapNode::create(float duration, int blinks, Node* node0, Node* node1)
{
SwapNode *swapNode = new (std::nothrow) SwapNode();
if (swapNode && swapNode->initWithDuration(duration, blinks, node0, node1)) {
swapNode->autorelease();
return swapNode;
}
delete swapNode;
return nullptr;
}
bool SwapNode::initWithDuration(float duration, int blinks, Node* node0, Node* node1) {
if (ActionInterval::initWithDuration(duration)) {
_times = blinks;
_node0 = node0;
_node1 = node1;
return true;
}
return false;
}
void SwapNode::update(float time) {
if (_target && ! isDone()) {
float slice = 1.0f / _times;
float m = fmodf(time, slice);
bool temp = _node0->isVisible();
_node0->setVisible(m > slice / 2 ? true : false);
_node1->setVisible(!_node0->isVisible());
if (temp != _node0->isVisible()) {
if (_effectID>=0) GameSoundManager::getInstance()->stopEffectSound(_effectID);
_effectID = GameSoundManager::getInstance()->playEffectSound(soundsPath+"c3.m4a");
}
}
}
void SwapNode::stop() {
if (nullptr != _target)
ActionInterval::stop();
}
void SwapNode::startWithTarget(Node *target) {
ActionInterval::startWithTarget(target);
}
| 19,971 | 6,695 |
#include <pbbam/FastqReader.h>
#include <cstddef>
#include <cstdint>
#include <gtest/gtest.h>
#include <pbbam/BamFileMerger.h>
#include <pbbam/EntireFileQuery.h>
#include <pbbam/FastqSequence.h>
#include <pbbam/FastqWriter.h>
#include "FastxTests.h"
#include "PbbamTestData.h"
using namespace PacBio;
using namespace PacBio::BAM;
namespace FastqReaderTests {
void CheckFastqSequence(const size_t index, const FastqSequence& seq)
{
SCOPED_TRACE("checking FASTA seq:" + std::to_string(index));
const auto& expected = FastxTests::ExpectedFastq.at(index);
EXPECT_EQ(expected.Name(), seq.Name());
EXPECT_EQ(expected.Bases(), seq.Bases());
EXPECT_EQ(expected.Qualities().Fastq(), seq.Qualities().Fastq());
}
void CheckManualIteration(const std::string& fn)
{
size_t count = 0;
FastqSequence seq;
FastqReader reader{fn};
while (reader.GetNext(seq)) {
CheckFastqSequence(count, seq);
++count;
}
EXPECT_EQ(FastxTests::ExpectedFastq.size(), count);
}
void CheckRangeFor(const std::string& fn)
{
size_t count = 0;
FastqReader reader{fn};
for (const auto& seq : reader) {
CheckFastqSequence(count, seq);
++count;
}
EXPECT_EQ(FastxTests::ExpectedFastq.size(), count);
}
void CheckReadAll(const std::string& fn)
{
size_t count = 0;
for (const auto& seq : FastqReader::ReadAll(fn)) {
CheckFastqSequence(count, seq);
++count;
}
EXPECT_EQ(FastxTests::ExpectedFastq.size(), count);
}
} // namespace FastqReaderTests
TEST(BAM_FastqReader, throws_on_empty_filename)
{
EXPECT_THROW(FastqReader reader{""}, std::runtime_error);
}
TEST(BAM_FastqReader, throws_on_invalid_extension)
{
EXPECT_THROW(FastqReader reader{"wrong.ext"}, std::runtime_error);
}
TEST(BAM_FastqReader, can_open_text_fastq)
{
const auto& fn = FastxTests::simpleFastqFn;
EXPECT_NO_THROW(FastqReader reader{fn});
}
TEST(BAM_FastqReader, can_open_gzip_fastq)
{
const auto& fn = FastxTests::simpleFastqGzipFn;
EXPECT_NO_THROW(FastqReader reader{fn});
}
TEST(BAM_FastqReader, can_open_bgzf_fastq)
{
const auto& fn = FastxTests::simpleFastqBgzfFn;
EXPECT_NO_THROW(FastqReader reader{fn});
}
TEST(BAM_FastqReader, can_iterate_manually_on_text_fastq)
{
FastqReaderTests::CheckManualIteration(FastxTests::simpleFastqFn);
}
TEST(BAM_FastqReader, can_iterate_manually_on_gzip_fastq)
{
FastqReaderTests::CheckManualIteration(FastxTests::simpleFastqGzipFn);
}
TEST(BAM_FastqReader, can_iterate_manually_on_bgzf_fastq)
{
FastqReaderTests::CheckManualIteration(FastxTests::simpleFastqBgzfFn);
}
TEST(BAM_FastqReader, can_iterate_using_range_for_on_text_fastq)
{
FastqReaderTests::CheckRangeFor(FastxTests::simpleFastqFn);
}
TEST(BAM_FastqReader, can_iterate_using_range_for_on_gzip_fastq)
{
FastqReaderTests::CheckRangeFor(FastxTests::simpleFastqGzipFn);
}
TEST(BAM_FastqReader, can_iterate_using_range_for_on_bgzf_fastq)
{
FastqReaderTests::CheckRangeFor(FastxTests::simpleFastqBgzfFn);
}
TEST(BAM_FastqReader, can_read_all_from_text_fastq)
{
FastqReaderTests::CheckReadAll(FastxTests::simpleFastqFn);
}
TEST(BAM_FastqReader, can_read_all_from_gzip_fastq)
{
FastqReaderTests::CheckReadAll(FastxTests::simpleFastqGzipFn);
}
TEST(BAM_FastqReader, can_read_all_from_bgzf_fastq)
{
FastqReaderTests::CheckReadAll(FastxTests::simpleFastqBgzfFn);
}
TEST(BAM_FastqReader, can_handle_windows_style_newlines)
{
FastqReader reader{FastxTests::fastxDataDir + "/windows_formatted.fastq"};
FastqSequence seq;
reader.GetNext(seq); // 1 sequence in total
EXPECT_EQ("C5", seq.Name());
EXPECT_EQ("AAGCA", seq.Bases());
EXPECT_EQ("~~~~~", seq.Qualities().Fastq());
}
TEST(BAM_FastqMerging, can_merge_bams_to_fastq_output)
{
const std::vector<std::string> bamFiles{PbbamTestsConfig::Data_Dir + "/group/test1.bam",
PbbamTestsConfig::Data_Dir + "/group/test2.bam",
PbbamTestsConfig::Data_Dir + "/group/test3.bam"};
const std::string outFastq = PbbamTestsConfig::GeneratedData_Dir + "/out.fq";
{
FastqWriter fastq{outFastq};
BamFileMerger::Merge(bamFiles, fastq);
}
const std::vector<std::string> mergedFastqNames{
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/14743/2114_2531",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/14743/2579_4055",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/14743/4101_5571",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/14743/5615_6237",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/24962/0_427",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/45203/0_893",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/45203/0_893",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/46835/3759_4005",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/46835/4052_4686",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/46835/4732_4869",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/47698/9482_9628",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/47698/9675_10333",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/47698/10378_10609",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/49050/48_1132",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/49050/48_1132",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/49194/0_798",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/49194/845_1541",
"m140905_042212_sidney_c100564852550000001823085912221377_s1_X0/49521/0_134"};
const auto seqs = FastqReader::ReadAll(outFastq);
ASSERT_EQ(mergedFastqNames.size(), seqs.size());
for (size_t i = 0; i < seqs.size(); ++i) {
EXPECT_EQ(mergedFastqNames[i], seqs[i].Name());
}
remove(outFastq.c_str());
}
| 6,152 | 3,214 |
/*
**
** $Filename: PageScaling.cpp $
** $Release: Dortmund 2004 $
** $Revision$
** $Date$
** $Author$
** $Developer: Steffen A. Mork $
**
** Blizzard III - Scaling properties
**
** (C) Copyright 2004 Steffen A. Mork
** All Rights Reserved
**
**
*/
/*************************************************************************
** **
** Lines III includes **
** **
*************************************************************************/
#include "AppLinesInclude.h"
#include "PageScaling.h"
/*************************************************************************
** **
** CPageScaling implementation **
** **
*************************************************************************/
CPageScaling::CPageScaling() : CB3PropertyPage(CPageScaling::IDD)
{
m_Scaling = null;
//{{AFX_DATA_INIT(CPageScaling)
m_ScaleMode = -1;
//}}AFX_DATA_INIT
}
CPageScaling::~CPageScaling()
{
}
void CPageScaling::DoDataExchange(CDataExchange* pDX)
{
if (!pDX->m_bSaveAndValidate)
{
m_ScaleMode = m_Scaling->b3GetScaleMode();
}
CB3PropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPageScaling)
DDX_Control(pDX, IDC_SCALE_X, m_xScaleCtrl);
DDX_Control(pDX, IDC_SCALE_Y, m_yScaleCtrl);
DDX_Control(pDX, IDC_SCALE_Z, m_zScaleCtrl);
DDX_Radio(pDX, IDC_SCALE_BOX_POLAR, m_ScaleMode);
//}}AFX_DATA_MAP
m_ScaleCtrl.b3DDX(pDX);
if (pDX->m_bSaveAndValidate)
{
m_Scaling->b3SetScaleMode(m_ScaleMode);
}
}
BEGIN_MESSAGE_MAP(CPageScaling, CB3PropertyPage)
//{{AFX_MSG_MAP(CPageScaling)
ON_EN_KILLFOCUS(IDC_SCALE_X, OnEdit)
ON_EN_KILLFOCUS(IDC_SCALE_Y, OnEdit)
ON_EN_KILLFOCUS(IDC_SCALE_Z, OnEdit)
ON_BN_CLICKED(IDC_SCALE_POLAR, OnEdit)
ON_BN_CLICKED(IDC_SCALE_OBJECT_POLAR, OnEdit)
ON_BN_CLICKED(IDC_SCALE_BOX_POLAR, OnEdit)
ON_BN_CLICKED(IDC_SCALE_IPOINT, OnEdit)
ON_BN_CLICKED(IDC_SCALE_IPOINT_ORIGINAL, OnEdit)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPageScaling message handlers
void CPageScaling::b3PreInitDialog()
{
m_ScaleCtrl.b3Init(&m_Scaling->m_Scale,&m_xScaleCtrl,&m_yScaleCtrl,&m_zScaleCtrl);
}
void CPageScaling::b3PostInitDialog()
{
m_xScaleCtrl.b3SetRange(0.0001,10000);
m_yScaleCtrl.b3SetRange(0.0001,10000);
m_zScaleCtrl.b3SetRange(0.0001,10000);
}
| 2,643 | 1,045 |
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int findDuplicate(vector<int>& nums) {
vector<bool> values(nums.size(), false);
for (int i : nums)
if (not values[i])
values[i] = true;
else
return i;
return -1;
}
}; | 283 | 103 |
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <unity/toolkits/ml_data_2/metadata.hpp>
#include <unity/lib/variant_deep_serialize.hpp>
namespace turi { namespace v2 {
/** Returns a vector giving the column names of all columns present.
*/
std::vector<std::string> ml_metadata::column_names(bool include_side_columns_if_present) const {
size_t n_columns = include_side_columns_if_present ? num_columns() : columns.size();
std::vector<std::string> column_names(n_columns);
for(size_t c_idx = 0; c_idx < n_columns; ++c_idx)
column_names[c_idx] = column_name(c_idx);
return column_names;
}
void ml_metadata::set_training_index_sizes_to_current_column_sizes() {
for(size_t c_idx = 0; c_idx < num_columns(); ++c_idx)
get_column_metadata(c_idx)->set_training_index_size();
if(has_target()) {
target->set_training_index_size();
}
// Set the global index offsets; the last bit of the ride.
size_t cum_sum = 0;
for(size_t c_idx = 0; c_idx < num_columns(); ++c_idx) {
auto cm = get_column_metadata(c_idx);
cm->set_training_index_offset(cum_sum);
cum_sum += cm->index_size();
}
setup_cached_values();
}
/**
* Returns the feature name of a specific feature present in the metadata.
*
* Numeric columns are represented by the column name.
*
* Categorical / Categorical List / Dictionary columns are represented by
* "name[category]".
*
* Vectors are represented by "vector[index]", where index is numerical.
*
* \returns Names of features
*/
std::string ml_metadata::feature_name(size_t column_idx, size_t index) const {
const std::string& name = column_name(column_idx);
switch (column_mode(column_idx)) {
case ml_column_mode::NUMERIC:
case ml_column_mode::UNTRANSLATED:
DASSERT_EQ(index, 0);
return name;
case ml_column_mode::CATEGORICAL:
case ml_column_mode::DICTIONARY:
case ml_column_mode::CATEGORICAL_VECTOR:
return name + "[" +
(indexer(column_idx)
->map_index_to_value(index)
.template to<std::string>()) +
"]";
case ml_column_mode::NUMERIC_VECTOR:
DASSERT_LT(index, column_size(column_idx));
return name + "[" + std::to_string(index) + "]";
default:
return name;
}
}
/**
* Returns a list of all the feature names present in the metadata.
*
* Numeric columns are represented by the column name.
*
* Categorical / Categorical List / Dictionary columns are represented by
* "name[category]".
*
* Vectors are represented by "vector[index]", where index is numerical.
*
* ND vectors are represented by "nd_vector[idx1,idx2]" etc.
*
* If unpack_categorical_columns is false, then purely categorical columns (not
* lists or dictionaries) are called out only by their column name instead of
* their categories.
*
* \returns Names of features
*/
std::vector<std::string> ml_metadata::feature_names(bool unpack_categorical_columns) const {
std::vector<std::string> feature_names;
feature_names.reserve(num_dimensions());
for(size_t i = 0; i < num_columns(); ++i) {
if (column_mode(i) == ml_column_mode::CATEGORICAL &&
!unpack_categorical_columns) {
feature_names.push_back(column_name(i));
} else {
for (size_t j = 0; j < index_size(i); ++j) {
feature_names.push_back(feature_name(i, j));
}
}
}
return feature_names;
}
/** Some of the data statistics are cached. This function computes
* these, making it possible to use nearly all the metadata functions
* in the inner loop of something with no concerns about speed.
*/
void ml_metadata::setup_cached_values() {
////////////////////////////////////////
// The number of untranslated columns.
_num_untranslated_columns = 0;
for(size_t i = 0; i < columns.size(); ++i)
if(is_untranslated_column(i))
++_num_untranslated_columns;
////////////////////////////////////////
// The total number of dimensions present
_num_dimensions = 0;
for(size_t c_idx = 0; c_idx < num_columns(); ++c_idx)
_num_dimensions += get_column_metadata(c_idx)->index_size();
////////////////////////////////////////
// The map of column names to indices
_column_name_to_index_map.clear();
for(size_t c_idx = 0; c_idx < num_columns(); ++c_idx) {
_column_name_to_index_map[column_name(c_idx)] = c_idx;
}
}
/** Serialization -- save.
*/
void ml_metadata::save(turi::oarchive& oarc) const {
oarc << get_version();
std::map<std::string, variant_type> data;
data["original_column_names"] = to_variant(original_column_names);
data["options"] = to_variant(options);
variant_deep_save(data, oarc);
oarc << columns << target;
// Finally, save the side data
if(side_features != nullptr) {
oarc << bool(true);
side_features->save_without_metadata(oarc);
} else {
oarc << bool(false);
}
}
/** Serialization -- load.
*/
void ml_metadata::load(turi::iarchive& iarc) {
size_t version = 0;
iarc >> version;
ASSERT_EQ(version, 2);
std::map<std::string, variant_type> data;
variant_deep_load(data, iarc);
#define __EXTRACT(var) var = variant_get_value<decltype(var)>(data.at(#var));
__EXTRACT(original_column_names);
__EXTRACT(options);
#undef __EXTRACT
iarc >> columns >> target;
////////////////////////////////////////////////////////////////////////////////
// Now load the side features
bool _has_side_features;
iarc >> _has_side_features;
if(_has_side_features) {
side_features.reset(new ml_data_side_features(columns));
side_features->load_with_metadata_present(iarc);
}
////////////////////////////////////////////////////////////
// Set the global index offsets. Annoying to do it here, but need
// to for backwards compatibility of model serialization. If the
// individual global offsets are size_t(-1), which is what happens
// when the model is loaded, this sets them to the correct value.
size_t cum_sum = 0;
for(size_t c_idx = 0; c_idx < num_columns(); ++c_idx) {
auto cm = get_column_metadata(c_idx);
cm->set_training_index_offset(cum_sum);
cum_sum += cm->index_size();
}
// Finalize by setting up all the cached values now that everything
// is present.
setup_cached_values();
}
/** Create a new metadata object that shares the same indexing as
* the previous one, but has possibly different and possibly
* subsetted columns.
*/
std::shared_ptr<ml_metadata> ml_metadata::select_columns(
const std::vector<std::string>& new_columns, bool include_target,
const std::vector<std::string>& clr_columns) const {
if(std::set<std::string>(new_columns.begin(), new_columns.end()).size() != new_columns.size()) {
ASSERT_MSG(false, "Duplicates in the column selection not allowed.");
}
////////////////////////////////////////////////////////////////////////////////
// Step 1. Deal with the columns.
// See which columns have to be cleared on copy.
std::set<std::string> clear_set(clr_columns.begin(), clr_columns.end());
// Go through and copy over all the individual column_metadata pointers.
auto m = std::make_shared<ml_metadata>();
m->columns.resize(new_columns.size());
for(size_t i = 0; i < new_columns.size(); ++i) {
const std::string& c = new_columns[i];
// Find that column
size_t column_idx = size_t(-1);
for(size_t j = 0; j < columns.size(); ++j) {
if(columns[j]->name == c) {
column_idx = j;
break;
}
}
if(column_idx == size_t(-1))
ASSERT_MSG(false, (std::string("Column ") + new_columns[i] + " not found.").c_str());
if(clear_set.count(c)) {
m->columns[i] = columns[column_idx]->create_cleared_copy();
clear_set.erase(c);
} else {
m->columns[i] = columns[column_idx];
}
}
////////////////////////////////////////////////////////////////////////////////
// Step 2. Deal with the target
if(include_target)
m->target = target;
////////////////////////////////////////////////////////////////////////////////
// Step 3: Deal with the original_column_names. This may be in a
// different order than the columns above (e.g. user and items are
// moved to index 0 and 1 in the recommender). Here, we just choose
// the subset based on the previous columns.
m->original_column_names.clear();
m->original_column_names.reserve(new_columns.size());
for(size_t i = 0; i < original_column_names.size(); ++i) {
const std::string& c = original_column_names[i];
// See if that column is in the new set
size_t column_idx = size_t(-1);
for(size_t j = 0; j < new_columns.size(); ++j) {
if(new_columns[j] == c) {
column_idx = j;
break;
}
}
if(column_idx != size_t(-1))
m->original_column_names.push_back(c);
}
////////////////////////////////////////////////////////////////////////////////
// Step 4: deal with the side data
if(side_features != nullptr)
m->side_features = side_features->copy_with_new_main_columns(m->columns);
////////////////////////////////////////////////////////////////////////////////
// Step 5: Other details.
m->options = options;
// Set the cached values
m->setup_cached_values();
return m;
}
}}
| 9,485 | 3,160 |
/**
* Copyright (C) 2016, Canonical Ltd.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Author: Justin McPherson <justin.mcpherson@canonical.com>
*
*/
#include "reactevents.h"
QString normalizeInputEventName(const QString& eventName)
{
QString tmp = eventName;
if (eventName.startsWith("top"))
return tmp;
if (eventName.startsWith("on")) {
tmp.replace(0, 2, "top");
} else {
tmp[0] = tmp[0].toUpper();
tmp = "top" + tmp;
}
return tmp;
}
| 687 | 240 |
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <ros/ros.h>
#include <nodelet/nodelet.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <image_transport/subscriber_filter.h>
#include <message_filters/subscriber.h>
#include <message_filters/synchronizer.h>
#include <message_filters/sync_policies/exact_time.h>
#include <image_geometry/pinhole_camera_model.h>
#include <opencv2/calib3d/calib3d.hpp>
#include <boost/thread.hpp>
#include <depth_image_proc/depth_traits.h>
#include <sensor_msgs/point_cloud2_iterator.h>
namespace depth_image_proc {
using namespace message_filters::sync_policies;
namespace enc = sensor_msgs::image_encodings;
typedef ExactTime<sensor_msgs::Image, sensor_msgs::Image, sensor_msgs::CameraInfo> SyncPolicy;
class PointCloudXyziRadialNodelet : public nodelet::Nodelet
{
ros::NodeHandlePtr intensity_nh_;
// Subscriptions
boost::shared_ptr<image_transport::ImageTransport> intensity_it_, depth_it_;
image_transport::SubscriberFilter sub_depth_, sub_intensity_;
message_filters::Subscriber<sensor_msgs::CameraInfo> sub_info_;
int queue_size_;
// Publications
boost::mutex connect_mutex_;
typedef sensor_msgs::PointCloud2 PointCloud;
ros::Publisher pub_point_cloud_;
typedef message_filters::Synchronizer<SyncPolicy> Synchronizer;
boost::shared_ptr<Synchronizer> sync_;
std::vector<double> D_;
boost::array<double, 9> K_;
int width_;
int height_;
cv::Mat transform_;
virtual void onInit();
void connectCb();
void imageCb(const sensor_msgs::ImageConstPtr& depth_msg,
const sensor_msgs::ImageConstPtr& intensity_msg_in,
const sensor_msgs::CameraInfoConstPtr& info_msg);
// Handles float or uint16 depths
template<typename T>
void convert_depth(const sensor_msgs::ImageConstPtr& depth_msg, PointCloud::Ptr& cloud_msg);
template<typename T>
void convert_intensity(const sensor_msgs::ImageConstPtr &inten_msg, PointCloud::Ptr& cloud_msg);
cv::Mat initMatrix(cv::Mat cameraMatrix, cv::Mat distCoeffs, int width, int height, bool radial);
};
cv::Mat PointCloudXyziRadialNodelet::initMatrix(cv::Mat cameraMatrix, cv::Mat distCoeffs, int width, int height, bool radial)
{
int i,j;
int totalsize = width*height;
cv::Mat pixelVectors(1,totalsize,CV_32FC3);
cv::Mat dst(1,totalsize,CV_32FC3);
cv::Mat sensorPoints(cv::Size(height,width), CV_32FC2);
cv::Mat undistortedSensorPoints(1,totalsize, CV_32FC2);
std::vector<cv::Mat> ch;
for(j = 0; j < height; j++)
{
for(i = 0; i < width; i++)
{
cv::Vec2f &p = sensorPoints.at<cv::Vec2f>(i,j);
p[0] = i;
p[1] = j;
}
}
sensorPoints = sensorPoints.reshape(2,1);
cv::undistortPoints(sensorPoints, undistortedSensorPoints, cameraMatrix, distCoeffs);
ch.push_back(undistortedSensorPoints);
ch.push_back(cv::Mat::ones(1,totalsize,CV_32FC1));
cv::merge(ch,pixelVectors);
if(radial)
{
for(i = 0; i < totalsize; i++)
{
normalize(pixelVectors.at<cv::Vec3f>(i),
dst.at<cv::Vec3f>(i));
}
pixelVectors = dst;
}
return pixelVectors.reshape(3,width);
}
void PointCloudXyziRadialNodelet::onInit()
{
ros::NodeHandle& nh = getNodeHandle();
ros::NodeHandle& private_nh = getPrivateNodeHandle();
intensity_nh_.reset( new ros::NodeHandle(nh, "intensity") );
ros::NodeHandle depth_nh(nh, "depth");
intensity_it_ .reset( new image_transport::ImageTransport(*intensity_nh_) );
depth_it_.reset( new image_transport::ImageTransport(depth_nh) );
// Read parameters
private_nh.param("queue_size", queue_size_, 5);
// Synchronize inputs. Topic subscriptions happen on demand in the connection callback.
sync_.reset( new Synchronizer(SyncPolicy(queue_size_), sub_depth_, sub_intensity_, sub_info_) );
sync_->registerCallback(boost::bind(&PointCloudXyziRadialNodelet::imageCb, this, _1, _2, _3));
// Monitor whether anyone is subscribed to the output
ros::SubscriberStatusCallback connect_cb =
boost::bind(&PointCloudXyziRadialNodelet::connectCb, this);
// Make sure we don't enter connectCb() between advertising and assigning to pub_point_cloud_
boost::lock_guard<boost::mutex> lock(connect_mutex_);
pub_point_cloud_ = nh.advertise<PointCloud>("points", 20, connect_cb, connect_cb);
}
// Handles (un)subscribing when clients (un)subscribe
void PointCloudXyziRadialNodelet::connectCb()
{
boost::lock_guard<boost::mutex> lock(connect_mutex_);
if (pub_point_cloud_.getNumSubscribers() == 0)
{
sub_depth_.unsubscribe();
sub_intensity_.unsubscribe();
sub_info_.unsubscribe();
}
else if (!sub_depth_.getSubscriber())
{
ros::NodeHandle& private_nh = getPrivateNodeHandle();
// parameter for depth_image_transport hint
std::string depth_image_transport_param = "depth_image_transport";
// depth image can use different transport.(e.g. compressedDepth)
image_transport::TransportHints depth_hints("raw",ros::TransportHints(), private_nh, depth_image_transport_param);
sub_depth_.subscribe(*depth_it_, "image_raw", 5, depth_hints);
// intensity uses normal ros transport hints.
image_transport::TransportHints hints("raw", ros::TransportHints(), private_nh);
sub_intensity_.subscribe(*intensity_it_, "image_raw", 5, hints);
sub_info_.subscribe(*intensity_nh_, "camera_info", 5);
}
}
void PointCloudXyziRadialNodelet::imageCb(const sensor_msgs::ImageConstPtr& depth_msg,
const sensor_msgs::ImageConstPtr& intensity_msg,
const sensor_msgs::CameraInfoConstPtr& info_msg)
{
PointCloud::Ptr cloud_msg(new PointCloud);
cloud_msg->header = depth_msg->header;
cloud_msg->height = depth_msg->height;
cloud_msg->width = depth_msg->width;
cloud_msg->is_dense = false;
cloud_msg->is_bigendian = false;
sensor_msgs::PointCloud2Modifier pcd_modifier(*cloud_msg);
pcd_modifier.setPointCloud2Fields(4,
"x", 1, sensor_msgs::PointField::FLOAT32,
"y", 1, sensor_msgs::PointField::FLOAT32,
"z", 1, sensor_msgs::PointField::FLOAT32,
"intensity", 1, sensor_msgs::PointField::FLOAT32);
if(info_msg->D != D_ || info_msg->K != K_ || width_ != info_msg->width ||
height_ != info_msg->height)
{
D_ = info_msg->D;
K_ = info_msg->K;
width_ = info_msg->width;
height_ = info_msg->height;
transform_ = initMatrix(cv::Mat_<double>(3, 3, &K_[0]),cv::Mat(D_),width_,height_,true);
}
if (depth_msg->encoding == enc::TYPE_16UC1)
{
convert_depth<uint16_t>(depth_msg, cloud_msg);
}
else if (depth_msg->encoding == enc::TYPE_32FC1)
{
convert_depth<float>(depth_msg, cloud_msg);
}
else
{
NODELET_ERROR_THROTTLE(5, "Depth image has unsupported encoding [%s]", depth_msg->encoding.c_str());
return;
}
if(intensity_msg->encoding == enc::TYPE_16UC1)
{
convert_intensity<uint16_t>(intensity_msg, cloud_msg);
}
else if(intensity_msg->encoding == enc::MONO8)
{
convert_intensity<uint8_t>(intensity_msg, cloud_msg);
}
else if(intensity_msg->encoding == enc::TYPE_32FC1)
{
convert_intensity<float>(intensity_msg, cloud_msg);
}
else
{
NODELET_ERROR_THROTTLE(5, "Intensity image has unsupported encoding [%s]", intensity_msg->encoding.c_str());
return;
}
pub_point_cloud_.publish (cloud_msg);
}
template<typename T>
void PointCloudXyziRadialNodelet::convert_depth(const sensor_msgs::ImageConstPtr& depth_msg,
PointCloud::Ptr& cloud_msg)
{
// Combine unit conversion (if necessary) with scaling by focal length for computing (X,Y)
double unit_scaling = DepthTraits<T>::toMeters( T(1) );
float bad_point = std::numeric_limits<float>::quiet_NaN();
sensor_msgs::PointCloud2Iterator<float> iter_x(*cloud_msg, "x");
sensor_msgs::PointCloud2Iterator<float> iter_y(*cloud_msg, "y");
sensor_msgs::PointCloud2Iterator<float> iter_z(*cloud_msg, "z");
const T* depth_row = reinterpret_cast<const T*>(&depth_msg->data[0]);
int row_step = depth_msg->step / sizeof(T);
for (int v = 0; v < (int)cloud_msg->height; ++v, depth_row += row_step)
{
for (int u = 0; u < (int)cloud_msg->width; ++u, ++iter_x, ++iter_y, ++iter_z)
{
T depth = depth_row[u];
// Missing points denoted by NaNs
if (!DepthTraits<T>::valid(depth))
{
*iter_x = *iter_y = *iter_z = bad_point;
continue;
}
const cv::Vec3f &cvPoint = transform_.at<cv::Vec3f>(u,v) * DepthTraits<T>::toMeters(depth);
// Fill in XYZ
*iter_x = cvPoint(0);
*iter_y = cvPoint(1);
*iter_z = cvPoint(2);
}
}
}
template<typename T>
void PointCloudXyziRadialNodelet::convert_intensity(const sensor_msgs::ImageConstPtr& intensity_msg,
PointCloud::Ptr& cloud_msg)
{
sensor_msgs::PointCloud2Iterator<float> iter_i(*cloud_msg, "intensity");
const T* inten_row = reinterpret_cast<const T*>(&intensity_msg->data[0]);
const int i_row_step = intensity_msg->step/sizeof(T);
for (int v = 0; v < (int)cloud_msg->height; ++v, inten_row += i_row_step)
{
for (int u = 0; u < (int)cloud_msg->width; ++u, ++iter_i)
{
*iter_i = inten_row[u];
}
}
}
} // namespace depth_image_proc
// Register as nodelet
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(depth_image_proc::PointCloudXyziRadialNodelet,nodelet::Nodelet);
| 11,077 | 4,184 |
#include "spark_precompiled.h"
#include "DynamicSliceWrapper.h"
using namespace spark;
using namespace AzFramework;
//DynamicSliceWrapper implementation
bool DynamicSliceWrapper::IsReady() const {
return m_id.IsValid();
}
AZ::EntityId DynamicSliceWrapper::GetId() const {
return m_id;
}
AZ::Data::AssetId DynamicSliceWrapper::GetAssetId() const {
return m_asset.GetId();
}
void DynamicSliceWrapper::Load()
{
if (m_state != waiting)
{
AZ_Error("DynamicSliceWrapper", false, "called Load, but asset is not specified");
return;
}
//AZ_Printf(0, "DynamicSliceWrapper::Load()");
EBUS_EVENT_RESULT(m_ticket, AzFramework::GameEntityContextRequestBus, InstantiateDynamicSlice, m_asset, transform, nullptr);
AzFramework::SliceInstantiationResultBus::Handler::BusConnect(m_ticket);
m_state = loading;
}
bool DynamicSliceWrapper::Loaded() const
{
return m_state == loaded;
}
DynamicSliceWrapper::DynamicSliceWrapper(const DynamicSliceAsset &asset) {
m_state = waiting;
m_asset = asset;
}
spark::DynamicSliceWrapper::~DynamicSliceWrapper()
{
if(m_state == loading)AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect();
}
void DynamicSliceWrapper::OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& instance) {
m_id = (*(instance.second->GetInstantiated()->m_entities.begin()))->GetId();
AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect();
AZ::Entity *e = (*(instance.second->GetInstantiated()->m_entities.begin()));
m_state = loaded;
//AZ_Printf(0, "DynamicSliceWrapper::OnSliceInstantiated entity's state is %d", e->GetState());
if (onInstantiated)onInstantiated(e);
}
void DynamicSliceWrapper::OnSlicePreInstantiate(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& instance) {
AZ::Entity *e = (*(instance.second->GetInstantiated()->m_entities.begin()));
//AZ_Printf(0, "DynamicSliceWrapper::OnSlicePreInstantiate entity's state is %d", e->GetState());
if (onPreInstantiate)onPreInstantiate(e);
}
void DynamicSliceWrapper::OnSliceInstantiationFailed(const AZ::Data::AssetId& /*sliceAssetId*/)
{
AZ_Printf(0, "DynamicSliceWrapper::OnSliceInstantiationFailed");
AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect();
m_state = loaded;
}
void DynamicSliceWrapper::OnSliceInstantiationFailedOrCanceled(const AZ::Data::AssetId& /*sliceAssetId*/, bool /*canceled*/)
{
AZ_Printf(0, "DynamicSliceWrapper::OnSliceInstantiationFailedOrCanceled");
AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect();
m_state = loaded;
} | 2,609 | 898 |
#include "moviesdelegate.h"
#include <QApplication>
#include <QPainter>
MoviesDelegate::MoviesDelegate(QObject *parent, MovieTypes type)
: HoverRowDelegate(parent)
{
setMovieType(type);
}
void MoviesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
HoverRowDelegate::paint(painter, option, index);
if (index.row() == _hoveredRow) {
QRect r = option.rect;//getting the rect of the cell
int x,y, fontSize;
fontSize = 18;
QString text;
if (index.column() == _moveColumn) {
painter->setPen("#7a7d7d");
text = "⇐";
if (_hoveredColumn == _moveColumn) {
QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor));
painter->setPen("#b3b3b3");
}
}
if (index.column() == _editColumn) {
painter->setPen("#7a7d7d");
text = "⛭";
fontSize = 14;
if (_hoveredColumn == _editColumn) {
QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor));
painter->setPen("#b3b3b3");
}
}
if (index.column() == _deleteColumn) {
painter->setPen("#7a7d7d");
text = "×";
if (_hoveredColumn == _deleteColumn) {
QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor));
painter->setPen("#ff0000");
}
}
x = r.left() + r.width()/2 - fontSize/2;//the X coordinate
y = r.top() + r.height()/2 + fontSize/2;//the Y coordinate
painter->setFont({"Roboto", fontSize});
painter->drawText(x, y, text);
QStyledItemDelegate::paint(painter, option, index);
}
if (_hoveredColumn != _moveColumn &&
_hoveredColumn != _editColumn &&
_hoveredColumn != _deleteColumn)
QApplication::restoreOverrideCursor();
}
void MoviesDelegate::setMovieType(MovieTypes type)
{
switch (type) {
case MovieTypes::movieSeen:
_moveColumn = -1;
_editColumn = 0;
_deleteColumn = 7;
break;
case MovieTypes::movieToSee:
_moveColumn = 0;
_editColumn = 1;
_deleteColumn = 6;
break;
case MovieTypes::unknown:
default:
_moveColumn = -1;
_editColumn = -1;
_deleteColumn = -1;
}
}
| 2,480 | 777 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017-2019 The WaykiChain Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coinminttx.h"
#include "main.h"
bool CCoinMintTx::CheckTx(CTxExecuteContext &context) {
// Only used in stable coin genesis.
return ( context.height == (int32_t) SysCfg().GetVer2GenesisHeight() );
}
bool CCoinMintTx::ExecuteTx(CTxExecuteContext &context) {
IMPLEMENT_DEFINE_CW_STATE;
CRegID newRegid = CRegID(context.height, context.index);
sp_tx_account = make_shared<CAccount>();
if (txUid.IsEmpty()) {
sp_tx_account = NewAccount(cw, Hash160(newRegid.GetRegIdRaw()));
sp_tx_account->regid = newRegid; // generate new regid
if (!RegisterAccount(context, /*pubkey*/nullptr, *sp_tx_account)) // generate new regid for the account
return false;
} else if (txUid.is<CPubKey>()) {
const CPubKey &pubkey = txUid.get<CPubKey>();
const CKeyID &keyid = pubkey.GetKeyId();
sp_tx_account = GetAccount(*context.pCw, txUid);
if (!sp_tx_account) {
sp_tx_account = NewAccount(cw, keyid); // genrate new keyid from regid
}
if (!sp_tx_account->IsRegistered()) {
if (!RegisterAccount(context, &pubkey, *sp_tx_account)) // generate new regid for the account
return false;
}
} else {
return state.DoS(100, ERRORMSG("%s(), unsupported txUid type=%s",
TX_ERR_TITLE, txUid.GetIDName()), READ_ACCOUNT_FAIL, "unsupported-txUid-type");
}
if (!sp_tx_account->OperateBalance(coin_symbol, ADD_FREE, coin_amount, ReceiptType::COIN_MINT_ONCHAIN, receipts))
return state.DoS(100, ERRORMSG("CCoinMintTx::ExecuteTx, operate account failed"), UPDATE_ACCOUNT_FAIL,
"operate-account-failed");
return true;
}
string CCoinMintTx::ToString(CAccountDBCache &accountCache) {
assert(txUid.is<CPubKey>() || txUid.is<CNullID>());
string toAddr = txUid.is<CPubKey>() ? txUid.get<CPubKey>().GetKeyId().ToAddress() : "";
return strprintf("txType=%s, hash=%s, ver=%d, txUid=%s, addr=%s, coin_symbol=%s, coin_amount=%llu, valid_height=%d",
GetTxType(nTxType), GetHash().ToString(), nVersion, txUid.ToString(), toAddr, coin_symbol,
coin_amount, valid_height);
}
Object CCoinMintTx::ToJson(CCacheWrapper &cw) const {
assert(txUid.is<CPubKey>() || txUid.is<CNullID>());
Object result;
string toAddr = txUid.is<CPubKey>() ? txUid.get<CPubKey>().GetKeyId().ToAddress() : "";
result.push_back(Pair("txid", GetHash().GetHex()));
result.push_back(Pair("tx_type", GetTxType(nTxType)));
result.push_back(Pair("ver", nVersion));
result.push_back(Pair("tx_uid", txUid.ToString()));
result.push_back(Pair("to_addr", toAddr));
result.push_back(Pair("coin_symbol", coin_symbol));
result.push_back(Pair("coin_amount", coin_amount));
result.push_back(Pair("valid_height", valid_height));
return result;
}
| 3,187 | 1,145 |