text
stringlengths 5
1.04M
|
|---|
/* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* 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 names of Stanford University or Willow Garage, Inc. 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.
*/
/**
* @file walker_gazeno.cpp
* @author Sandra Tinta
* @copyright 2019 BSD License
*
* @brief This node subcribes to laserScan topic from the turtleBot simulation
* in order to track distance to wall and/or obstacle.
* If a wall/obtacle is not detected, the robot keeps moving forward
* If a wall/obsatavle is detected, the robot rotates until it can keep
* moving forward.
**/
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "geometry_msgs/Twist.h"
#include "walker_gazebo/laserReadHelper.h"
int main(int argc, char **argv) {
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line.
* For programmatic remappings you can use a different version of init() which takes
* remappings directly, but for most command-line programs, passing argc and argv is
* the easiest way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "walker_gazebo");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n = ros::NodeHandle();
/**
* Class that implement the calback function
*/
auto lrhelper = LaserReadHelper();
/**
* The subscribe() call is how you tell ROS that you want to receive messages
* on a given topic. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. Messages are passed to a callback function, here
* called chatterCallback. subscribe() returns a Subscriber object that you
* must hold on to until you want to unsubscribe. When all copies of the Subscriber
* object go out of scope, this callback will automatically be unsubscribed from
* this topic.
*
* The second parameter to the subscribe() function is the size of the message
* queue. If messages are arriving faster than they are being processed, this
* is the number of messages that will be buffered up before beginning to throw
* away the oldest ones.
*/
auto sub = n.subscribe<sensor_msgs::LaserScan>("/scan", 1000,
&LaserReadHelper::processLaserScan, &lrhelper);
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
auto vel_pub = n.advertise<geometry_msgs::Twist>
("/mobile_base/commands/velocity", 1000);
double lcl_rate = 10;
geometry_msgs::Twist vel_msg;
ros::Rate loop_rate(lcl_rate);
while (ros::ok()) {
ROS_DEBUG_STREAM("node walker_gazebo in ROS is running");
/**
* if the wall was detected rotate robot
*/
if (lrhelper.getWallInFront()) {
ROS_DEBUG_STREAM("Obstacle Detected; turning ...");
// stop moving forward
vel_msg.linear.x = 0.0;
// rotate laser
vel_msg.angular.z = 1.0;
} else {
// no obstacle detected
// move forward
vel_msg.linear.x = 0.5;
// go straight
vel_msg.angular.z = 0;
}
/**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
vel_pub.publish(vel_msg);
ROS_DEBUG_STREAM("velocity command was published");
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xls/tools/null_io_strategy.h"
namespace xls {
namespace verilog {
absl::Status NullIoStrategy::AddTopLevelDependencies(LogicRef1* clk,
Reset reset, Module* m) {
byte_in_ = m->AddPort(Direction::kInput, "byte_in", 8);
byte_in_ready_ = m->AddOutput("byte_in_ready");
byte_in_valid_ = m->AddInput("byte_in_valid");
byte_out_ = m->AddPort(Direction::kOutput, "byte_out", 8);
byte_out_ready_ = m->AddInput("byte_out_ready");
byte_out_valid_ = m->AddOutput("byte_out_valid");
return absl::OkStatus();
}
absl::Status NullIoStrategy::InstantiateIoBlocks(Input input, Output output,
Module* m) {
m->Add<ContinuousAssignment>(input.rx_byte, byte_in_);
m->Add<ContinuousAssignment>(byte_in_ready_, input.rx_byte_done);
m->Add<ContinuousAssignment>(input.rx_byte_valid, byte_in_valid_);
m->Add<ContinuousAssignment>(byte_out_, output.tx_byte);
m->Add<ContinuousAssignment>(output.tx_byte_ready, byte_out_ready_);
m->Add<ContinuousAssignment>(byte_out_valid_, output.tx_byte_valid);
return absl::OkStatus();
}
} // namespace verilog
} // namespace xls
|
#include <aws/logs/model/DescribeLogGroupsRequest.h>
#include <aws/logs/model/CreateLogGroupRequest.h>
#include <aws/logs/model/PutRetentionPolicyRequest.h>
#include <aws/logs/model/DescribeLogStreamsRequest.h>
#include <aws/logs/model/CreateLogStreamRequest.h>
#include <aws/logs/model/PutLogEventsRequest.h>
#include <aws/core/utils/Outcome.h>
#include "AwsLogWriter.h"
using namespace std;
Aws::Client::ClientConfiguration AwsLogWriter::getClientConfig(string region) {
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = region;
return clientConfig;
}
AwsLogWriter::AwsLogWriter(string region, string logGroup, string logStream, bool realTime) :
client(getClientConfig(region))
{
this->logGroup = logGroup;
this->logStream = logStream;
this->realTime = realTime;
this->sequenceToken = "";
createLogGroupIfNotExists();
createLogStream();
}
AwsLogWriter::~AwsLogWriter() = default;
void AwsLogWriter::write(string message) {
long long timestamp = time(nullptr) * 1000;
if (!batch.addEvent(message, timestamp)) {
flushBatch();
batch.addEvent(message, timestamp);
}
if (realTime) {
flushBatch();
}
}
void AwsLogWriter::flush() {
flushBatch();
}
void AwsLogWriter::createLogGroupIfNotExists() {
Aws::CloudWatchLogs::Model::DescribeLogGroupsRequest request;
request.SetLogGroupNamePrefix(logGroup);
request.SetLimit(1);
auto outcome = client.DescribeLogGroups(request);
auto groups = outcome.GetResult().GetLogGroups();
if (!groups.empty()) {
return;
}
Aws::CloudWatchLogs::Model::CreateLogGroupRequest createRequest;
createRequest.SetLogGroupName(logGroup);
client.CreateLogGroup(createRequest);
Aws::CloudWatchLogs::Model::PutRetentionPolicyRequest retentionRequest;
retentionRequest.SetLogGroupName(logGroup);
retentionRequest.SetRetentionInDays(30);
client.PutRetentionPolicy(retentionRequest);
}
void AwsLogWriter::createLogStream() {
Aws::CloudWatchLogs::Model::DescribeLogStreamsRequest request;
request.SetLogGroupName(logGroup);
request.SetLogStreamNamePrefix(logStream);
request.SetLimit(1);
auto outcome = client.DescribeLogStreams(request);
auto streams = outcome.GetResult().GetLogStreams();
if (!streams.empty()) {
sequenceToken = streams.front().GetUploadSequenceToken();
return;
}
Aws::CloudWatchLogs::Model::CreateLogStreamRequest createRequest;
createRequest.SetLogGroupName(logGroup);
createRequest.SetLogStreamName(logStream);
client.CreateLogStream(createRequest);
}
void AwsLogWriter::refreshSequenceToken() {
Aws::CloudWatchLogs::Model::DescribeLogStreamsRequest request;
request.SetLogGroupName(logGroup);
request.SetLogStreamNamePrefix(logStream);
request.SetLimit(1);
auto outcome = client.DescribeLogStreams(request);
sequenceToken = outcome.GetResult().GetLogStreams().front().GetUploadSequenceToken();
}
void AwsLogWriter::flushBatch() {
if (!batch.hasEvents()) {
return;
}
putEvents();
batch.reset();
}
void AwsLogWriter::putEvents(int attempt) {
Aws::CloudWatchLogs::Model::PutLogEventsRequest request;
request.SetLogGroupName(logGroup);
request.SetLogStreamName(logStream);
if (!sequenceToken.empty()) {
request.SetSequenceToken(sequenceToken);
}
auto events = batch.getEvents();
for(const auto &event : events) {
request.AddLogEvents(event);
}
auto result = client.PutLogEvents(request);
if (!result.IsSuccess() && result.GetError().GetErrorType() == Aws::CloudWatchLogs::CloudWatchLogsErrors::INVALID_SEQUENCE_TOKEN && attempt < 5) {
refreshSequenceToken();
putEvents(attempt + 1);
return;
} else if (!result.IsSuccess()) {
exit(1);
}
sequenceToken = result.GetResult().GetNextSequenceToken();
}
|
// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_TESTPROPERTYHDF5_HPP
#define NIX_TESTPROPERTYHDF5_HPP
#include "BaseTestProperty.hpp"
class TestPropertyHDF5 : public BaseTestProperty {
CPPUNIT_TEST_SUITE(TestPropertyHDF5);
CPPUNIT_TEST(testValidate);
CPPUNIT_TEST(testId);
CPPUNIT_TEST(testName);
CPPUNIT_TEST(testDefinition);
CPPUNIT_TEST(testMapping);
CPPUNIT_TEST(testValues);
CPPUNIT_TEST(testDataType);
CPPUNIT_TEST(testUnit);
CPPUNIT_TEST(testOperators);
CPPUNIT_TEST(testUpdatedAt);
CPPUNIT_TEST(testCreatedAt);
CPPUNIT_TEST(testIsValidEntity);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
startup_time = time(NULL);
file = nix::File::open("test_property.h5", nix::FileMode::Overwrite);
section = file.createSection("cool section", "metadata");
int_dummy = nix::Value(10);
str_dummy = nix::Value("test");
property = section.createProperty("prop", int_dummy);
property_other = section.createProperty("other", int_dummy);
property_null = nix::none;
}
void tearDown() {
file.close();
}
};
#endif //NIX_TESTPROPERTYHDF5_HPP
|
/************************************************************************
* *
* Copyright (C) 2007 Christina Warrender and Drew Levin *
* *
* This file is part of QtCyCells. *
* *
* QtCyCells 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. *
* *
* QtCyCells 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 QtCyCells; if not, write to the Free Software Foundation, *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* *
************************************************************************/
/************************************************************************
* File simView3D.cc *
* render() routine for SimView3D *
* Allows 3D display of tissue model *
************************************************************************/
#include <GL/gl.h>
#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include "simView3D.h"
#include "tissue.h"
#include "cellType.h"
using namespace std;
#define MAX(x,y) x > y ? x : y
#define TURN_SENSITIVITY 200.0
#define ZOOM_SENSITIVITY 2400.0
/************************************************************************
* SimView3D() *
* Constructor *
* *
* Parameters *
* QWidget *parent: Window containing this view *
* int x, y, w, h: Position (x,y) and size (w,h) of view *
* const Tissue *t; Pointer to model tissue *
* *
* Returns - nothing *
************************************************************************/
SimView3D::SimView3D(QWidget *parent, int x, int y, int w, int h,
const Tissue *t)
: SimView(parent, x, y, w, h),
m_tissuep(t), m_first(true), m_mousedown(false), oldPos(0,0),
m_anglex(0.0), m_angley(0.0), m_zoom(1.0), frame(0)
{
// Get tissue size info (do once at beginning rather than repeatedly)
m_xsize = m_tissuep->getXSize();
m_ysize = m_tissuep->getYSize();
m_zsize = m_tissuep->getZSize();
m_maxlength = MAX(MAX(m_xsize, m_ysize), m_zsize);
// Get some info about types of cells & molecules to display
int numCellTypes = m_tissuep->getNumCellTypes();
m_cellSizes = new double[numCellTypes];
for (int i=0; i<numCellTypes; i++)
m_cellSizes[i] = m_tissuep->getCellType(i)->getRadius();
// For drawing cells as spheres
quadratic=gluNewQuadric();
gluQuadricNormals(quadratic, GLU_SMOOTH); // Create Smooth Normals
gluQuadricTexture(quadratic, GL_TRUE); // Create Texture Coords ( NEW )
}
/************************************************************************
* render() *
* OpenGL code to draw current view of model *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::render()
{
if (m_first)
{
// set up lighting
GLfloat light_position[] = { 1.0, 1.0, m_zsize*2, 0.0 };
GLfloat light_position2[] = { m_xsize, m_ysize, m_zsize*2, 0.0};
GLfloat white_light[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat lmodel_ambient[] = { 0.9, 0.9, 0.9, 0.9 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);
glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);
glLightfv(GL_LIGHT1, GL_POSITION, light_position2);
glLightfv(GL_LIGHT1, GL_DIFFUSE, white_light);
glLightfv(GL_LIGHT1, GL_SPECULAR, white_light);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
glClearColor(1.0, 1.0, 1.0, 0.0); // set white background; no blending
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
// set size/projection - should be in resize routine?
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-m_xsize/2*m_zoom, m_xsize/2*m_zoom, -m_ysize/2*m_zoom, m_ysize/2*m_zoom, 9*m_maxlength, 11*m_maxlength);
m_first = false;
}
// clear; get ready to do model/view transformations
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Position and orient the camera
gluLookAt(10*m_maxlength*sin(m_anglex)*cos(m_angley)+m_xsize/2,
10*m_maxlength*sin(m_angley)+m_ysize/2,
-10*m_maxlength*cos(m_anglex)*cos(m_angley)+m_zsize/2,
m_xsize/2, m_ysize/2, m_zsize/2, 0.0, 1.0, 0.0);
// gluLookAt(10*m_maxlength*sin(m_anglex)*cos(m_angley)+m_xsize*(7.0/16),
// 10*m_maxlength*sin(m_angley)+m_ysize*(7.0/16),
// -10*m_maxlength*cos(m_anglex)*cos(m_angley)+m_zsize/2,
// m_xsize*(7.0/16), m_ysize*(7.0/16), m_zsize/2, 0.0, 1.0, 0.0);
renderCells();
renderMolecules();
drawBorder();
if (draw_time) drawTime();
glFlush();
if (save_image) saveImage();
swapBuffers();
frame++;
}
/************************************************************************
* saveImage() *
* private function to save current frame as an image file. *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::saveImage()
{
makeCurrent();
int pid = (int)getpid();
printf("Frame: %5d\n", frame);
QImage *screen = new QImage(grabFrameBuffer());
screen->save(QString("/nfs/adaptive/drew/cycells2/cycells/frames/frame_%1_%2.png").arg(pid).arg(frame, 6, 10, QChar('0')), "PNG");
delete screen;
}
/************************************************************************
* renderCells() *
* OpenGL code to draw visible cells in model *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::renderCells()
{
glPolygonMode(GL_FRONT, GL_FILL);
// set blending for opaque cells
glBlendFunc(GL_ONE, GL_ZERO);
// we want cell's material properties to be determined by color setting
glEnable(GL_COLOR_MATERIAL);
// get current list of cells
vector<Cell *> cell_list = m_tissuep->getCellList();
// display each cell in list
for (unsigned int i=0; i<cell_list.size(); i++)
{
// get necessary info
Cell *pc = cell_list[i];
int type_index = pc->getTypeIndex();
SimPoint pos = pc->getPosition();
double radius = m_cellSizes[type_index];
Color color = cell_palette[type_index];
// set color, translate, scale & display
glColor3fv(color.getfv());
glPushMatrix();
glTranslatef(pos.getX(), pos.getY(), pos.getZ());
glScalef(radius, radius, radius);
gluSphere(quadratic,1,12,12);
// gluDisk(quadratic,0,1,12,1);
glPopMatrix();
}
glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* renderMolecules() *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::renderMolecules()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// set blending for translucent molecules
glEnable(GL_BLEND);
glEnable(GL_COLOR_MATERIAL);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
int numTypes = m_tissuep->getNumMolTypes();
double max = 1E-18;
// double max = 1.0;
int xnum = m_tissuep->getXSize()/m_tissuep->getGridSize();
int ynum = m_tissuep->getYSize()/m_tissuep->getGridSize();
int znum = m_tissuep->getZSize()/m_tissuep->getGridSize();
for (int n=0; n<numTypes; n++)
{
// get concentration data for this molecule type
const Array3D<Molecule::Conc>& conc = m_tissuep->getConc(n);
// get base color
Color color = mol_palette[n];
// loop through grid cells
for (int i=1; i<=xnum; i++)
for (int j=1; j<=ynum; j++)
for (int k=1; k<=znum; k++)
{
double c = conc.at(i, j, k);
// scale color according to concentration
if (c == 0) // nothing to draw
continue;
else if (c >= max) // use unadjusted base color
glColor4fv((color).getfv());
else // scale color by concentration
{
glColor4fv((color*(c/max)).getfv());
}
// scale, translate by grid cell indices & draw
glPushMatrix();
glScalef(m_tissuep->getGridSize(), m_tissuep->getGridSize(), m_tissuep->getGridSize());
glTranslatef(i-1.0, j-1.0, k-1.0);
drawGrid();
glPopMatrix();
}
} // end for each molecule type
glDisable(GL_BLEND);
glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* drawGrid() *
* OpenGL code to draw a grid cell; calling routine must handle *
* translation to appropriate location *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::drawGrid()
{
// glPolygonMode(GL_FRONT);
glBegin(GL_QUADS);
// back
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
// top
glVertex3f(0.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
// left
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 1.0, 1.0);
glVertex3f(0.0, 1.0, 0.0);
// right
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 0.0);
// bottom
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(1.0, 0.0, 1.0);
glVertex3f(1.0, 0.0, 0.0);
// front
glVertex3f(0.0, 0.0, 1.0);
glVertex3f(1.0, 0.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(0.0, 1.0, 1.0);
glEnd();
// glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* drawBorder() *
* OpenGL code to draw border box around the limits of the simulation *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::drawBorder()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glEnable(GL_COLOR_MATERIAL);
glColor3f(0.4, 0.4, 0.4);
glBegin(GL_QUADS);
// back
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(m_xsize, 0.0, 0.0);
glVertex3f(m_xsize, m_ysize, 0.0);
glVertex3f(0.0, m_ysize, 0.0);
// top
glVertex3f(0.0, m_ysize, m_zsize);
glVertex3f(m_xsize, m_ysize, m_zsize);
glVertex3f(m_xsize, m_ysize, 0.0);
glVertex3f(0.0, m_ysize, 0.0);
// left
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, m_zsize);
glVertex3f(0.0, m_ysize, m_zsize);
glVertex3f(0.0, m_ysize, 0.0);
// right
glVertex3f(m_xsize, 0.0, 0.0);
glVertex3f(m_xsize, 0.0, m_zsize);
glVertex3f(m_xsize, m_ysize, m_zsize);
glVertex3f(m_xsize, m_ysize, 0.0);
// bottom
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, m_zsize);
glVertex3f(m_xsize, 0.0, m_zsize);
glVertex3f(m_xsize, 0.0, 0.0);
// front
glVertex3f(0.0, 0.0, m_zsize);
glVertex3f(m_xsize, 0.0, m_zsize);
glVertex3f(m_xsize, m_ysize, m_zsize);
glVertex3f(0.0, m_ysize, m_zsize);
glEnd();
glDisable(GL_COLOR_MATERIAL);
}
/************************************************************************
* drawTime () *
* OpenGL code to draw the simulation time in the upper left corner. *
* *
* Parameters - none *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::drawTime()
{
const char *c;
double time;
int days, hours, minutes, seconds;
char str_days[256];
time = m_tissuep->getTime();
days = (int)floor(time/86400);
time -= days*86400;
hours = (int)floor(time/3600);
time -= hours*3600;
minutes = (int)floor(time/60);
seconds = (int)time-(minutes*60);
if (days > 0) {
sprintf(str_days, "Day %d ", days);
} else {
sprintf(str_days, "");
}
sprintf(time_string, "%s %d:%02d:%02d", str_days, hours, minutes, seconds);
glEnable(GL_COLOR_MATERIAL);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0, width, 0, height);
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glColor3d(0.1, 0.1, 0.1);
glRasterPos2f(10, 28);
for (c=time_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glColor3d(0.9, 0.9, 0.9);
glRasterPos2f(11, 29);
for (c=time_string; *c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
}
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
/************************************************************************
* mousePressEvent() *
* QT4 function to track mouse dragging. *
* *
* Parameters - event *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::mousePressEvent(QMouseEvent *event)
{
oldPos = event->pos();
}
/************************************************************************
* mouseMoveEvent() *
* QT4 function to track mouse dragging. Only functions if the *
* mouse button is pressed. Reorients the OpenGL view. *
* *
* Parameters - event *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::mouseMoveEvent(QMouseEvent *event)
{
// Only react to mouse dragging, not regular movement.
if ((event->buttons() & Qt::LeftButton))
{
QPoint dxy = event->pos() - oldPos;
oldPos = event->pos();
m_anglex += dxy.x() / TURN_SENSITIVITY;
m_angley += dxy.y() / TURN_SENSITIVITY;
render();
}
}
/************************************************************************
* wheelEvent() *
* QT4 function to track the mouse wheel. Zooms in and out by *
* narrowing or widening the view frustum. *
* *
* Parameters - event *
* *
* Returns - nothing *
************************************************************************/
void SimView3D::wheelEvent(QWheelEvent *event)
{
// Get mouse wheel rotation in 1/8 of a degree.
// Most mouse wheels click every 15 degrees, or 120 delta units.
double delta = (double)(event->delta());
if (delta > 0) // Zoom in
m_zoom *= 1 - (delta / ZOOM_SENSITIVITY);
else // Zoom Out
m_zoom /= 1 - (-delta / ZOOM_SENSITIVITY);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-m_xsize/2*m_zoom, m_xsize/2*m_zoom, -m_ysize/2*m_zoom, m_ysize/2*m_zoom, 9*m_maxlength, 11*m_maxlength);
render();
}
|
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <aslam/cameras/GridCalibrationTargetCheckerboard.hpp>
#include <sm/eigen/serialization.hpp>
namespace aslam {
namespace cameras {
/// \brief Construct a calibration target
/// rows: number of internal corners (8x8 chessboard would be 7x7 internal corners)
/// cols: number of internal corners
/// rowSpacingMeters: spacing in y-direction [m]
/// colSpacingMeters: spacing in x-direction [m]
///
/// point ordering in _points: (e.g. 2x2 grid)
/// *-------*-------*-------*
/// | BLACK | WHITE | BLACK |
/// *------(3)-----(4)------*
/// | WHITE | BLACK | WHITE |
/// *------(1)-----(2)------*
/// y | BLACK | WHITE | BLACK |
/// ^ *-------*-------*-------*
/// |-->x
GridCalibrationTargetCheckerboard::GridCalibrationTargetCheckerboard(
size_t rows, size_t cols, double rowSpacingMeters, double colSpacingMeters,
const CheckerboardOptions &options)
: GridCalibrationTargetBase(rows, cols),
_rowSpacingMeters(rowSpacingMeters),
_colSpacingMeters(colSpacingMeters),
_options(options) {
SM_ASSERT_GT(Exception, rowSpacingMeters, 0.0,
"rowSpacingMeters has to be positive");
SM_ASSERT_GT(Exception, colSpacingMeters, 0.0,
"colSpacingMeters has to be positive");
// allocate memory for the grid points
_points.resize(size(), 3);
//initialize a normal grid (checkerboard and circlegrids)
createGridPoints();
//start the output window if requested
initialize();
}
/// \brief initialize the object
void GridCalibrationTargetCheckerboard::initialize()
{
if (_options.showExtractionVideo) {
cv::namedWindow("Checkerboard corners", cv::WINDOW_AUTOSIZE);
cv::startWindowThread();
}
}
/// \brief initialize a checkerboard grid (cols*rows = (cols)*(rows) internal grid points)
/// point ordering: (e.g. 2x2 grid)
/// *-------*-------*-------*
/// | BLACK | WHITE | BLACK |
/// *------(3)-----(4)------*
/// | WHITE | BLACK | WHITE |
/// *------(1)-----(2)------*
/// y | BLACK | WHITE | BLACK |
/// ^ *-------*-------*-------*
/// |-->x
///
void GridCalibrationTargetCheckerboard::createGridPoints() {
for (unsigned int r = 0; r < _rows; r++)
for (unsigned int c = 0; c < _cols; c++)
_points.row(gridCoordinatesToPoint(r, c)) = Eigen::Matrix<double, 1, 3>(
_rowSpacingMeters * r, _colSpacingMeters * c, 0.0);
}
/// \brief extract the calibration target points from an image and write to an observation
bool GridCalibrationTargetCheckerboard::computeObservation(const cv::Mat & image,
Eigen::MatrixXd & outImagePoints, std::vector<bool> &outCornerObserved) const {
// set the open cv flags
int flags = 0;
if (_options.performFastCheck)
flags += cv::CALIB_CB_FAST_CHECK;
if (_options.useAdaptiveThreshold)
flags += cv::CALIB_CB_ADAPTIVE_THRESH;
if ( _options.normalizeImage)
flags += cv::CALIB_CB_NORMALIZE_IMAGE;
if (_options.filterQuads)
flags += cv::CALIB_CB_FILTER_QUADS;
// extract the checkerboard corners
cv::Size patternSize(cols(), rows());
cv::Mat centers(size(), 2, CV_64FC1);
bool success = cv::findChessboardCorners(image, patternSize, centers, flags);
// do optional subpixel refinement
if (_options.doSubpixelRefinement && success) {
cv::cornerSubPix(
image, centers, cv::Size(_options.windowWidth, _options.windowWidth), cv::Size(-1, -1),
cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::MAX_ITER, 30, 0.1));
}
//draw corners
if (_options.showExtractionVideo) {
//image with refined (blue) and raw corners (red)
cv::Mat imageCopy1 = image.clone();
cv::cvtColor(imageCopy1, imageCopy1, cv::COLOR_GRAY2RGB);
cv::drawChessboardCorners(imageCopy1, cv::Size(rows(), cols()), centers,
true);
// write error msg
if (!success)
cv::putText(imageCopy1, "Detection failed! (frame not used)",
cv::Point(50, 50), cv::FONT_HERSHEY_SIMPLEX, 0.8,
CV_RGB(255,0,0), 3, 8, false);
cv::imshow("Checkerboard corners", imageCopy1); // OpenCV call
cv::waitKey(1);
}
//exit here if there is an error
if (!success)
return success;
//set all points as observed (checkerboard is only usable in that case)
std::vector<bool> allGood(size(), true);
outCornerObserved = allGood;
//convert to eigen for output
outImagePoints.resize(size(), 2);
for (unsigned int i = 0; i < size(); i++)
outImagePoints.row(i) = Eigen::Matrix<double, 1, 2>(
centers.row(i).at<float>(0), centers.row(i).at<float>(1));
return success;
}
} // namespace cameras
} // namespace aslam
//export explicit instantions for all included archives
#include <sm/boost/serialization.hpp>
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridCalibrationTargetCheckerboard);
BOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridCalibrationTargetCheckerboard::CheckerboardOptions);
|
/*
* Copyright (c) 2020-2022, Liav A. <liavalb@hotmail.co.il>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/AllOf.h>
#include <AK/Array.h>
#include <Kernel/Debug.h>
#include <Kernel/Storage/Partition/GUIDPartitionTable.h>
namespace Kernel {
#define GPT_SIGNATURE2 0x54524150
#define GPT_SIGNATURE 0x20494645
#define BytesPerSector 512
struct [[gnu::packed]] GPTPartitionEntry {
u8 partition_guid[16];
u8 unique_guid[16];
u64 first_lba;
u64 last_lba;
u64 attributes;
char partition_name[72];
};
struct [[gnu::packed]] GUIDPartitionHeader {
u32 sig[2];
u32 revision;
u32 header_size;
u32 crc32_header;
u32 reserved;
u64 current_lba;
u64 backup_lba;
u64 first_usable_lba;
u64 last_usable_lba;
u64 disk_guid1[2];
u64 partition_array_start_lba;
u32 entries_count;
u32 partition_entry_size;
u32 crc32_entries_array;
};
ErrorOr<NonnullOwnPtr<GUIDPartitionTable>> GUIDPartitionTable::try_to_initialize(StorageDevice const& device)
{
auto table = TRY(adopt_nonnull_own_or_enomem(new (nothrow) GUIDPartitionTable(device)));
if (!table->is_valid())
return Error::from_errno(EINVAL);
return table;
}
GUIDPartitionTable::GUIDPartitionTable(StorageDevice const& device)
: MBRPartitionTable(device)
{
// FIXME: Handle OOM failure here.
m_cached_header = ByteBuffer::create_zeroed(m_device->block_size()).release_value_but_fixme_should_propagate_errors();
VERIFY(partitions_count() == 0);
if (!initialize())
m_valid = false;
}
GUIDPartitionHeader const& GUIDPartitionTable::header() const
{
return *(GUIDPartitionHeader const*)m_cached_header.data();
}
bool GUIDPartitionTable::initialize()
{
VERIFY(m_cached_header.data() != nullptr);
auto first_gpt_block = (m_device->block_size() == 512) ? 1 : 0;
auto buffer = UserOrKernelBuffer::for_kernel_buffer(m_cached_header.data());
if (!m_device->read_block(first_gpt_block, buffer)) {
return false;
}
dbgln_if(GPT_DEBUG, "GUIDPartitionTable: signature - {:#08x} {:#08x}", header().sig[1], header().sig[0]);
if (header().sig[0] != GPT_SIGNATURE && header().sig[1] != GPT_SIGNATURE2) {
dbgln("GUIDPartitionTable: bad signature {:#08x} {:#08x}", header().sig[1], header().sig[0]);
return false;
}
auto entries_buffer_result = ByteBuffer::create_zeroed(m_device->block_size());
if (entries_buffer_result.is_error()) {
dbgln("GUIPartitionTable: not enough memory for entries buffer");
return false;
}
auto entries_buffer = entries_buffer_result.release_value();
auto raw_entries_buffer = UserOrKernelBuffer::for_kernel_buffer(entries_buffer.data());
size_t raw_byte_index = header().partition_array_start_lba * m_device->block_size();
for (size_t entry_index = 0; entry_index < header().entries_count; entry_index++) {
if (!m_device->read_block((raw_byte_index / m_device->block_size()), raw_entries_buffer)) {
return false;
}
auto* entries = (GPTPartitionEntry const*)entries_buffer.data();
auto& entry = entries[entry_index % (m_device->block_size() / (size_t)header().partition_entry_size)];
Array<u8, 16> partition_type {};
partition_type.span().overwrite(0, entry.partition_guid, partition_type.size());
if (is_unused_entry(partition_type)) {
raw_byte_index += header().partition_entry_size;
continue;
}
Array<u8, 16> unique_guid {};
unique_guid.span().overwrite(0, entry.unique_guid, unique_guid.size());
dbgln("Detected GPT partition (entry={}), offset={}, limit={}", entry_index, entry.first_lba, entry.last_lba);
m_partitions.append({ entry.first_lba, entry.last_lba, partition_type, unique_guid, entry.attributes });
raw_byte_index += header().partition_entry_size;
}
return true;
}
bool GUIDPartitionTable::is_unused_entry(Array<u8, 16> partition_type) const
{
return all_of(partition_type, [](auto const octet) { return octet == 0; });
}
}
|
// 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 "chrome/browser/ui/search/instant_search_prerenderer.h"
#include <stdint.h>
#include <memory>
#include <tuple>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/prerender/prerender_handle.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/browser/prerender/prerender_origin.h"
#include "chrome/browser/prerender/prerender_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/instant_unittest_base.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/ui/browser_instant_controller.h"
#include "chrome/browser/ui/search/search_ipc_router.h"
#include "chrome/browser/ui/search/search_tab_helper.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/search/instant_types.h"
#include "chrome/common/search/mock_searchbox.h"
#include "components/omnibox/browser/autocomplete_match.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "content/public/test/mock_render_process_host.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_test_sink.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/gfx/geometry/size.h"
using base::ASCIIToUTF16;
using testing::_;
using testing::AllOf;
using testing::Eq;
using testing::Field;
using testing::Return;
namespace {
class MockSearchBoxClientFactory
: public SearchIPCRouter::SearchBoxClientFactory {
public:
MOCK_METHOD0(GetSearchBox, chrome::mojom::SearchBox*(void));
};
using content::Referrer;
using prerender::Origin;
using prerender::PrerenderContents;
using prerender::PrerenderHandle;
using prerender::PrerenderManager;
using prerender::PrerenderManagerFactory;
using prerender::PrerenderTabHelper;
class DummyPrerenderContents : public PrerenderContents {
public:
DummyPrerenderContents(PrerenderManager* prerender_manager,
Profile* profile,
const GURL& url,
const Referrer& referrer,
Origin origin,
bool call_did_finish_load,
chrome::mojom::SearchBox* search_box);
void StartPrerendering(
const gfx::Rect& bounds,
content::SessionStorageNamespace* session_storage_namespace) override;
bool GetChildId(int* child_id) const override;
bool GetRouteId(int* route_id) const override;
private:
Profile* profile_;
const GURL url_;
bool call_did_finish_load_;
chrome::mojom::SearchBox* search_box_;
DISALLOW_COPY_AND_ASSIGN(DummyPrerenderContents);
};
class DummyPrerenderContentsFactory : public PrerenderContents::Factory {
public:
DummyPrerenderContentsFactory(bool call_did_finish_load,
chrome::mojom::SearchBox* search_box)
: call_did_finish_load_(call_did_finish_load), search_box_(search_box) {}
PrerenderContents* CreatePrerenderContents(
PrerenderManager* prerender_manager,
Profile* profile,
const GURL& url,
const Referrer& referrer,
Origin origin) override;
private:
bool call_did_finish_load_;
chrome::mojom::SearchBox* search_box_;
DISALLOW_COPY_AND_ASSIGN(DummyPrerenderContentsFactory);
};
DummyPrerenderContents::DummyPrerenderContents(
PrerenderManager* prerender_manager,
Profile* profile,
const GURL& url,
const Referrer& referrer,
Origin origin,
bool call_did_finish_load,
chrome::mojom::SearchBox* search_box)
: PrerenderContents(prerender_manager, profile, url, referrer, origin),
profile_(profile),
url_(url),
call_did_finish_load_(call_did_finish_load),
search_box_(search_box) {}
void DummyPrerenderContents::StartPrerendering(
const gfx::Rect& bounds,
content::SessionStorageNamespace* session_storage_namespace) {
content::SessionStorageNamespaceMap session_storage_namespace_map;
session_storage_namespace_map[std::string()] = session_storage_namespace;
prerender_contents_.reset(content::WebContents::CreateWithSessionStorage(
content::WebContents::CreateParams(profile_),
session_storage_namespace_map));
PrerenderTabHelper::CreateForWebContents(prerender_contents_.get());
content::NavigationController::LoadURLParams params(url_);
prerender_contents_->GetController().LoadURLWithParams(params);
SearchTabHelper::CreateForWebContents(prerender_contents_.get());
auto* search_tab =
SearchTabHelper::FromWebContents(prerender_contents_.get());
auto factory = base::MakeUnique<MockSearchBoxClientFactory>();
ON_CALL(*factory, GetSearchBox()).WillByDefault(Return(search_box_));
search_tab->ipc_router_for_testing()
.set_search_box_client_factory_for_testing(std::move(factory));
prerendering_has_started_ = true;
DCHECK(session_storage_namespace);
session_storage_namespace_id_ = session_storage_namespace->id();
NotifyPrerenderStart();
if (call_did_finish_load_)
DidFinishLoad(prerender_contents_->GetMainFrame(), url_);
}
bool DummyPrerenderContents::GetChildId(int* child_id) const {
*child_id = 1;
return true;
}
bool DummyPrerenderContents::GetRouteId(int* route_id) const {
*route_id = 1;
return true;
}
PrerenderContents* DummyPrerenderContentsFactory::CreatePrerenderContents(
PrerenderManager* prerender_manager,
Profile* profile,
const GURL& url,
const Referrer& referrer,
Origin origin) {
return new DummyPrerenderContents(prerender_manager, profile, url, referrer,
origin, call_did_finish_load_, search_box_);
}
} // namespace
class InstantSearchPrerendererTest : public InstantUnitTestBase {
public:
InstantSearchPrerendererTest() {}
protected:
void SetUp() override {
ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
"Group1 strk:20"));
InstantUnitTestBase::SetUp();
}
void Init(bool prerender_search_results_base_page,
bool call_did_finish_load) {
AddTab(browser(), GURL(url::kAboutBlankURL));
PrerenderManagerFactory::GetForBrowserContext(browser()->profile())
->SetPrerenderContentsFactoryForTest(new DummyPrerenderContentsFactory(
call_did_finish_load, &mock_search_box_));
if (prerender_search_results_base_page) {
content::SessionStorageNamespace* session_storage_namespace =
GetActiveWebContents()->GetController().
GetDefaultSessionStorageNamespace();
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
prerenderer->Init(session_storage_namespace, gfx::Size(640, 480));
EXPECT_NE(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
}
InstantSearchPrerenderer* GetInstantSearchPrerenderer() {
return instant_service_->GetInstantSearchPrerenderer();
}
const GURL& GetPrerenderURL() {
return GetInstantSearchPrerenderer()->prerender_url();
}
void SetLastQuery(const base::string16& query) {
GetInstantSearchPrerenderer()->last_instant_suggestion_ =
InstantSuggestion(query, std::string());
}
content::WebContents* prerender_contents() {
return GetInstantSearchPrerenderer()->prerender_contents();
}
content::WebContents* GetActiveWebContents() const {
return browser()->tab_strip_model()->GetWebContentsAt(0);
}
PrerenderHandle* prerender_handle() {
return GetInstantSearchPrerenderer()->prerender_handle_.get();
}
void PrerenderSearchQuery(const base::string16& query) {
Init(true, true);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
prerenderer->Prerender(InstantSuggestion(query, std::string()));
CommitPendingLoad(&prerender_contents()->GetController());
EXPECT_TRUE(prerenderer->CanCommitQuery(GetActiveWebContents(), query));
EXPECT_NE(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
MockSearchBox* mock_search_box() { return &mock_search_box_; }
private:
MockSearchBox mock_search_box_;
};
TEST_F(InstantSearchPrerendererTest, GetSearchTermsFromPrerenderedPage) {
Init(false, false);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
GURL url(GetPrerenderURL());
EXPECT_EQ(GURL("https://www.google.com/instant?ion=1&foo=foo#foo=foo&strk"),
url);
EXPECT_EQ(
base::UTF16ToASCII(prerenderer->get_last_query()),
base::UTF16ToASCII(search::ExtractSearchTermsFromURL(profile(), url)));
// Assume the prerendered page prefetched search results for the query
// "flowers".
SetLastQuery(ASCIIToUTF16("flowers"));
EXPECT_EQ("flowers", base::UTF16ToASCII(prerenderer->get_last_query()));
EXPECT_EQ(
base::UTF16ToASCII(prerenderer->get_last_query()),
base::UTF16ToASCII(search::ExtractSearchTermsFromURL(profile(), url)));
}
TEST_F(InstantSearchPrerendererTest, PrefetchSearchResults) {
Init(true, true);
EXPECT_TRUE(prerender_handle()->IsFinishedLoading());
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
EXPECT_CALL(*mock_search_box(), SetSuggestionToPrefetch(_));
prerenderer->Prerender(
InstantSuggestion(ASCIIToUTF16("flowers"), std::string()));
EXPECT_EQ("flowers", base::UTF16ToASCII(prerenderer->get_last_query()));
}
TEST_F(InstantSearchPrerendererTest, DoNotPrefetchSearchResults) {
Init(true, false);
// Page hasn't finished loading yet.
EXPECT_FALSE(prerender_handle()->IsFinishedLoading());
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
EXPECT_CALL(*mock_search_box(), SetSuggestionToPrefetch(_)).Times(0);
prerenderer->Prerender(
InstantSuggestion(ASCIIToUTF16("flowers"), std::string()));
EXPECT_EQ("", base::UTF16ToASCII(prerenderer->get_last_query()));
}
TEST_F(InstantSearchPrerendererTest, CanCommitQuery) {
Init(true, true);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
base::string16 query = ASCIIToUTF16("flowers");
prerenderer->Prerender(InstantSuggestion(query, std::string()));
EXPECT_TRUE(prerenderer->CanCommitQuery(GetActiveWebContents(), query));
// Make sure InstantSearchPrerenderer::CanCommitQuery() returns false for
// invalid search queries.
EXPECT_TRUE(prerenderer->CanCommitQuery(GetActiveWebContents(),
ASCIIToUTF16("joy")));
EXPECT_FALSE(prerenderer->CanCommitQuery(GetActiveWebContents(),
base::string16()));
}
TEST_F(InstantSearchPrerendererTest, CommitQuery) {
base::string16 query = ASCIIToUTF16("flowers");
PrerenderSearchQuery(query);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
EXPECT_CALL(*mock_search_box(), Submit(_));
prerenderer->Commit(EmbeddedSearchRequestParams());
}
TEST_F(InstantSearchPrerendererTest, CancelPrerenderRequestOnTabChangeEvent) {
Init(true, true);
EXPECT_NE(static_cast<PrerenderHandle*>(NULL), prerender_handle());
// Add a new tab to deactivate the current tab.
AddTab(browser(), GURL(url::kAboutBlankURL));
EXPECT_EQ(2, browser()->tab_strip_model()->count());
// Make sure the pending prerender request is cancelled.
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(InstantSearchPrerendererTest, CancelPendingPrerenderRequest) {
Init(true, true);
EXPECT_NE(static_cast<PrerenderHandle*>(NULL), prerender_handle());
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
prerenderer->Cancel();
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(InstantSearchPrerendererTest, PrerenderingAllowed) {
Init(true, true);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
content::WebContents* active_tab = GetActiveWebContents();
EXPECT_EQ(GURL(url::kAboutBlankURL), active_tab->GetURL());
// Allow prerendering only for search type AutocompleteMatch suggestions.
AutocompleteMatch search_type_match(NULL, 1100, false,
AutocompleteMatchType::SEARCH_SUGGEST);
search_type_match.keyword = ASCIIToUTF16("{google:baseurl}");
EXPECT_TRUE(AutocompleteMatch::IsSearchType(search_type_match.type));
EXPECT_TRUE(prerenderer->IsAllowed(search_type_match, active_tab));
// Do not allow prerendering for custom search provider requests.
TemplateURLData data;
data.SetURL("https://www.dummyurl.com/search?q=%s&img=1");
data.SetShortName(ASCIIToUTF16("t"));
data.SetKeyword(ASCIIToUTF16("k"));
TemplateURLService* service =
TemplateURLServiceFactory::GetForProfile(profile());
service->Add(base::MakeUnique<TemplateURL>(data));
service->Load();
AutocompleteMatch custom_search_type_match(
NULL, 1100, false, AutocompleteMatchType::SEARCH_SUGGEST);
custom_search_type_match.keyword = ASCIIToUTF16("k");
custom_search_type_match.destination_url =
GURL("https://www.dummyurl.com/search?q=fan&img=1");
const TemplateURL* template_url =
custom_search_type_match.GetTemplateURL(service, false);
EXPECT_TRUE(template_url);
EXPECT_TRUE(AutocompleteMatch::IsSearchType(custom_search_type_match.type));
EXPECT_FALSE(prerenderer->IsAllowed(custom_search_type_match, active_tab));
AutocompleteMatch url_type_match(NULL, 1100, true,
AutocompleteMatchType::URL_WHAT_YOU_TYPED);
EXPECT_FALSE(AutocompleteMatch::IsSearchType(url_type_match.type));
EXPECT_FALSE(prerenderer->IsAllowed(url_type_match, active_tab));
}
TEST_F(InstantSearchPrerendererTest, UsePrerenderPage) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Open a search results page. A prerendered page exists for |url|. Make sure
// the browser swaps the current tab contents with the prerendered contents.
GURL url("https://www.google.com/alt#quux=foo&strk");
browser()->OpenURL(content::OpenURLParams(url, Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false));
EXPECT_EQ(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(InstantSearchPrerendererTest, PrerenderRequestCancelled) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Cancel the prerender request.
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
prerenderer->Cancel();
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
// Open a search results page. Prerendered page does not exists for |url|.
// Make sure the browser navigates the current tab to this |url|.
GURL url("https://www.google.com/alt#quux=foo&strk");
browser()->OpenURL(content::OpenURLParams(url, Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false));
EXPECT_NE(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(url, GetActiveWebContents()->GetURL());
}
TEST_F(InstantSearchPrerendererTest,
UsePrerenderedPage_SearchQueryMistmatch) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Open a search results page. Committed query("pen") doesn't match with the
// prerendered search query("foo"). Make sure the browser swaps the current
// tab contents with the prerendered contents.
GURL url("https://www.google.com/alt#quux=pen&strk");
browser()->OpenURL(content::OpenURLParams(url, Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false));
EXPECT_EQ(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(InstantSearchPrerendererTest,
CancelPrerenderRequest_EmptySearchQueryCommitted) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Open a search results page. Make sure the InstantSearchPrerenderer cancels
// the active prerender request upon the receipt of empty search query.
GURL url("https://www.google.com/alt#quux=&strk");
browser()->OpenURL(content::OpenURLParams(url, Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false));
EXPECT_NE(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(url, GetActiveWebContents()->GetURL());
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(InstantSearchPrerendererTest,
CancelPrerenderRequest_UnsupportedDispositions) {
PrerenderSearchQuery(ASCIIToUTF16("pen"));
// Open a search results page. Make sure the InstantSearchPrerenderer cancels
// the active prerender request for unsupported window dispositions.
GURL url("https://www.google.com/alt#quux=pen&strk");
browser()->OpenURL(content::OpenURLParams(
url, Referrer(), WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui::PAGE_TRANSITION_TYPED, false));
content::WebContents* new_tab =
browser()->tab_strip_model()->GetWebContentsAt(1);
EXPECT_NE(GetPrerenderURL(), new_tab->GetURL());
EXPECT_EQ(url, new_tab->GetURL());
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
class ReuseInstantSearchBasePageTest : public InstantSearchPrerendererTest {
public:
ReuseInstantSearchBasePageTest() {}
protected:
void SetUp() override {
ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
"Group1 strk:20"));
InstantSearchPrerendererTest::SetUp();
}
};
TEST_F(ReuseInstantSearchBasePageTest, CanCommitQuery) {
Init(true, true);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
base::string16 query = ASCIIToUTF16("flowers");
prerenderer->Prerender(InstantSuggestion(query, std::string()));
EXPECT_TRUE(prerenderer->CanCommitQuery(GetActiveWebContents(), query));
// When the Instant search base page has finished loading,
// InstantSearchPrerenderer can commit any search query to the prerendered
// page (even if it doesn't match the last known suggestion query).
EXPECT_TRUE(prerenderer->CanCommitQuery(GetActiveWebContents(),
ASCIIToUTF16("joy")));
// Invalid search query committed.
EXPECT_FALSE(prerenderer->CanCommitQuery(GetActiveWebContents(),
base::string16()));
}
TEST_F(ReuseInstantSearchBasePageTest,
CanCommitQuery_InstantSearchBasePageLoadInProgress) {
Init(true, false);
InstantSearchPrerenderer* prerenderer = GetInstantSearchPrerenderer();
base::string16 query = ASCIIToUTF16("flowers");
prerenderer->Prerender(InstantSuggestion(query, std::string()));
// When the Instant search base page hasn't finished loading,
// InstantSearchPrerenderer cannot commit any search query to the base page.
EXPECT_FALSE(prerenderer->CanCommitQuery(GetActiveWebContents(), query));
EXPECT_FALSE(prerenderer->CanCommitQuery(GetActiveWebContents(),
ASCIIToUTF16("joy")));
}
#if !defined(OS_ANDROID)
class TestUsePrerenderPage : public InstantSearchPrerendererTest {
};
TEST_F(TestUsePrerenderPage, ExtractSearchTermsAndUsePrerenderPage) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Open a search results page. Query extraction flag is disabled in field
// trials. Search results page URL does not contain search terms replacement
// key. Make sure UsePrerenderedPage() extracts the search terms from the URL
// and uses the prerendered page contents.
GURL url("https://www.google.com/alt#quux=foo");
browser()->OpenURL(content::OpenURLParams(url, Referrer(),
WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_TYPED, false));
EXPECT_EQ(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(TestUsePrerenderPage, DoNotUsePrerenderPage) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
// Do not use prerendered page for renderer initiated search request.
GURL url("https://www.google.com/alt#quux=foo");
browser()->OpenURL(content::OpenURLParams(
url, Referrer(), WindowOpenDisposition::CURRENT_TAB,
ui::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */));
EXPECT_NE(GetPrerenderURL(), GetActiveWebContents()->GetURL());
EXPECT_EQ(static_cast<PrerenderHandle*>(NULL), prerender_handle());
}
TEST_F(TestUsePrerenderPage, SetEmbeddedSearchRequestParams) {
PrerenderSearchQuery(ASCIIToUTF16("foo"));
EXPECT_TRUE(browser()->instant_controller());
EXPECT_CALL(
*mock_search_box(),
Submit(AllOf(Field(&EmbeddedSearchRequestParams::original_query,
Eq(base::ASCIIToUTF16("f"))),
Field(&EmbeddedSearchRequestParams::input_encoding,
Eq(base::ASCIIToUTF16("utf-8"))),
Field(&EmbeddedSearchRequestParams::rlz_parameter_value,
Eq(base::ASCIIToUTF16(""))),
Field(&EmbeddedSearchRequestParams::assisted_query_stats,
Eq(base::ASCIIToUTF16("chrome...0"))))));
// Open a search results page. Query extraction flag is disabled in field
// trials. Search results page URL does not contain search terms replacement
// key.
GURL url("https://www.google.com/url?bar=foo&aqs=chrome...0&ie=utf-8&oq=f");
browser()->instant_controller()->OpenInstant(
WindowOpenDisposition::CURRENT_TAB, url);
}
#endif
|
// Copyright (c) 2014-2018, The Monero Project
// Copyright (c) 2018, The sevabit Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <vector>
#include <boost/math/special_functions/round.hpp>
#include "common/int-util.h"
#include "common/round.h"
#include "crypto/hash.h"
#include "cryptonote_config.h"
#include "difficulty.h"
#undef sevabit_DEFAULT_LOG_CATEGORY
#define sevabit_DEFAULT_LOG_CATEGORY "difficulty"
namespace cryptonote {
using std::size_t;
using std::uint64_t;
using std::vector;
#if defined(__x86_64__)
static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
low = mul128(a, b, &high);
}
#else
static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
// __int128 isn't part of the standard, so the previous function wasn't portable. mul128() in Windows is fine,
// but this portable function should be used elsewhere. Credit for this function goes to latexi95.
uint64_t aLow = a & 0xFFFFFFFF;
uint64_t aHigh = a >> 32;
uint64_t bLow = b & 0xFFFFFFFF;
uint64_t bHigh = b >> 32;
uint64_t res = aLow * bLow;
uint64_t lowRes1 = res & 0xFFFFFFFF;
uint64_t carry = res >> 32;
res = aHigh * bLow + carry;
uint64_t highResHigh1 = res >> 32;
uint64_t highResLow1 = res & 0xFFFFFFFF;
res = aLow * bHigh;
uint64_t lowRes2 = res & 0xFFFFFFFF;
carry = res >> 32;
res = aHigh * bHigh + carry;
uint64_t highResHigh2 = res >> 32;
uint64_t highResLow2 = res & 0xFFFFFFFF;
//Addition
uint64_t r = highResLow1 + lowRes2;
carry = r >> 32;
low = (r << 32) | lowRes1;
r = highResHigh1 + highResLow2 + carry;
uint64_t d3 = r & 0xFFFFFFFF;
carry = r >> 32;
r = highResHigh2 + carry;
high = d3 | (r << 32);
}
#endif
static inline bool cadd(uint64_t a, uint64_t b) {
return a + b < a;
}
static inline bool cadc(uint64_t a, uint64_t b, bool c) {
return a + b < a || (c && a + b == (uint64_t) -1);
}
bool check_hash(const crypto::hash &hash, difficulty_type difficulty) {
uint64_t low, high, top, cur;
// First check the highest word, this will most likely fail for a random hash.
mul(swap64le(((const uint64_t *) &hash)[3]), difficulty, top, high);
if (high != 0) {
return false;
}
mul(swap64le(((const uint64_t *) &hash)[0]), difficulty, low, cur);
mul(swap64le(((const uint64_t *) &hash)[1]), difficulty, low, high);
bool carry = cadd(cur, low);
cur = high;
mul(swap64le(((const uint64_t *) &hash)[2]), difficulty, low, high);
carry = cadc(cur, low, carry);
carry = cadc(high, top, carry);
return !carry;
}
// LWMA difficulty algorithm
// Background: https://github.com/zawy12/difficulty-algorithms/issues/3
// Copyright (c) 2017-2018 Zawy (pseudocode)
// MIT license http://www.opensource.org/licenses/mit-license.php
// Copyright (c) 2018 Wownero Inc., a Monero Enterprise Alliance partner company
// Copyright (c) 2018 The Karbowanec developers (initial code)
// Copyright (c) 2018 Haven Protocol (refinements)
// Degnr8, Karbowanec, Masari, Bitcoin Gold, Bitcoin Candy, and Haven have contributed.
// This algorithm is: next_difficulty = harmonic_mean(Difficulties) * T / LWMA(Solvetimes)
// The harmonic_mean(Difficulties) = 1/average(Targets) so it is also:
// next_target = avg(Targets) * LWMA(Solvetimes) / T.
// This is "the best algorithm" because it has lowest root-mean-square error between
// needed & actual difficulty during hash attacks while having the lowest standard
// deviation during stable hashrate. That is, it's the fastest for a given stability and vice versa.
// Do not use "if solvetime < 1 then solvetime = 1" which allows a catastrophic exploit.
// Do not sort timestamps. "Solvetimes" and "LWMA" variables must allow negatives.
// Do not use MTP as most recent block. Do not use (POW)Limits, filtering, or tempering.
// Do not forget to set N (aka DIFFICULTY_WINDOW in Cryptonote) to recommendation below.
// The nodes' future time limit (FTL) aka CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT needs to
// be reduced from 60*60*2 to 500 seconds to prevent timestamp manipulation from miner's with
// > 50% hash power. If this is too small, it can be increased to 1000 at a cost in protection.
// Cryptonote clones: #define DIFFICULTY_BLOCKS_COUNT_V2 DIFFICULTY_WINDOW_V2 + 1
difficulty_type next_difficulty_v2(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {
const int64_t T = static_cast<int64_t>(target_seconds);
size_t N = DIFFICULTY_WINDOW_V2 - 1;
// Return a difficulty of 1 for first 4 blocks if it's the start of the chain.
if (timestamps.size() < 4) {
return 1;
}
// Otherwise, use a smaller N if the start of the chain is less than N+1.
else if ( timestamps.size()-1 < N ) {
N = timestamps.size() - 1;
}
// Otherwise make sure timestamps and cumulative_difficulties are correct size.
else {
// TODO: put asserts here, so that the difficulty algorithm is never called with an oversized window
// OR make this use the last N+1 timestamps and cum_diff, not the first.
timestamps.resize(N+1);
cumulative_difficulties.resize(N+1);
}
// To get an average solvetime to within +/- ~0.1%, use an adjustment factor.
// adjust=0.999 for 80 < N < 120(?)
const double adjust = 0.998;
// The divisor k normalizes the LWMA sum to a standard LWMA.
const double k = N * (N + 1) / 2;
double LWMA(0), sum_inverse_D(0), harmonic_mean_D(0), nextDifficulty(0);
int64_t solveTime(0);
uint64_t difficulty(0), next_difficulty(0);
// Loop through N most recent blocks. N is most recently solved block.
for (int64_t i = 1; i <= (int64_t)N; i++) {
solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i - 1]);
solveTime = std::min<int64_t>((T * 7), std::max<int64_t>(solveTime, (-7 * T)));
difficulty = cumulative_difficulties[i] - cumulative_difficulties[i - 1];
LWMA += (solveTime * i) / k;
sum_inverse_D += 1 / static_cast<double>(difficulty);
}
harmonic_mean_D = N / sum_inverse_D;
// Keep LWMA sane in case something unforeseen occurs.
if (static_cast<int64_t>(sevabit_round(LWMA)) < T / 20)
LWMA = static_cast<double>(T / 20);
nextDifficulty = harmonic_mean_D * T / LWMA * adjust;
// No limits should be employed, but this is correct way to employ a 20% symmetrical limit:
// nextDifficulty=max(previous_Difficulty*0.8,min(previous_Difficulty/0.8, next_Difficulty));
next_difficulty = static_cast<uint64_t>(nextDifficulty);
if (next_difficulty == 0)
next_difficulty = 1;
return next_difficulty;
}
}
|
#include <string>
#include <fstream>
#include "TkrNoiseRep.h"
int main(int argc, char** argv)
{
std::string svacRootFile, reportDir, prefix;
std::string optionFileName;
if (argc==4) {
svacRootFile = argv[1];
reportDir = argv[2];
prefix = argv[3];
}
else {
if (argc==1) {
optionFileName = "../src/ReportOption.txt";
} else {
optionFileName = argv[1];
}
std::ifstream optionFile(optionFileName.c_str());
optionFile >> svacRootFile >> reportDir >> prefix;
}
std::cout << "svacRootFile = " << svacRootFile.c_str() << std::endl;
std::cout << "reportDir = " << reportDir.c_str() << std::endl;
std::cout << "prefix = " << prefix.c_str() << std::endl;
TkrNoiseRep *tkrNoiseRep = new TkrNoiseRep();
tkrNoiseRep->openSvacFile(svacRootFile.c_str());
tkrNoiseRep->setReportDirName(reportDir.c_str());
tkrNoiseRep->setPrefix(prefix.c_str());
tkrNoiseRep->generateSummary();
tkrNoiseRep->writeSummaryXML();
tkrNoiseRep->generateNoisyLayerReport();
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "mcrouter/lib/network/gen/MemcacheMessages.h"
#include "mcrouter/lib/test/RouteHandleTestUtil.h"
#include "mcrouter/lib/test/TestRouteHandle.h"
#include "mcrouter/routes/MissFailoverRoute.h"
using namespace facebook::memcache;
using namespace facebook::memcache::mcrouter;
using std::make_shared;
using std::vector;
using TestHandle = TestHandleImpl<TestRouteHandleIf>;
TEST(missMissFailoverRouteTest, success) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::FOUND, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::FOUND, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::FOUND, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles));
auto reply = rh.route(McGetRequest("0"));
EXPECT_EQ("a", carbon::valueRangeSlow(reply).str());
}
TEST(missMissFailoverRouteTest, once) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::FOUND, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::FOUND, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles));
auto reply = rh.route(McGetRequest("0"));
EXPECT_EQ("b", carbon::valueRangeSlow(reply).str());
}
TEST(missMissFailoverRouteTest, twice) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::FOUND, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles));
auto reply = rh.route(McGetRequest("0"));
EXPECT_EQ("c", carbon::valueRangeSlow(reply).str());
}
TEST(missMissFailoverRouteTest, fail) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles));
auto reply = rh.route(McGetRequest("0"));
// Should get the last reply
EXPECT_EQ("c", carbon::valueRangeSlow(reply).str());
EXPECT_EQ(carbon::Result::TIMEOUT, reply.result());
}
TEST(missMissFailoverRouteTest, bestOnError1) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles), true);
auto reply = rh.route(McGetRequest("0"));
// Should return the first and the only healthy reply
EXPECT_EQ("a", carbon::valueRangeSlow(reply).str());
EXPECT_EQ(carbon::Result::NOTFOUND, reply.result());
}
TEST(missMissFailoverRouteTest, bestOnError2) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles), true);
auto reply = rh.route(McGetRequest("0"));
// Should return the only failover-healthy reply
EXPECT_EQ("b", carbon::valueRangeSlow(reply).str());
EXPECT_EQ(carbon::Result::NOTFOUND, reply.result());
}
TEST(missMissFailoverRouteTest, bestOnError3) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(GetRouteTestData(carbon::Result::TIMEOUT, "a")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "b")),
make_shared<TestHandle>(GetRouteTestData(carbon::Result::NOTFOUND, "c"))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles), true);
auto reply = rh.route(McGetRequest("0"));
// Should get the LAST healthy reply
EXPECT_EQ("c", carbon::valueRangeSlow(reply).str());
EXPECT_EQ(carbon::Result::NOTFOUND, reply.result());
}
TEST(missMissFailoverRouteTest, nonGetLike) {
vector<std::shared_ptr<TestHandle>> test_handles{
make_shared<TestHandle>(UpdateRouteTestData(carbon::Result::NOTSTORED)),
make_shared<TestHandle>(UpdateRouteTestData(carbon::Result::STORED)),
make_shared<TestHandle>(UpdateRouteTestData(carbon::Result::STORED))};
TestRouteHandle<MissFailoverRoute<TestRouterInfo>> rh(
get_route_handles(test_handles));
McSetRequest req("0");
req.value() = folly::IOBuf(folly::IOBuf::COPY_BUFFER, "a");
auto reply = rh.route(std::move(req));
EXPECT_EQ(carbon::Result::NOTSTORED, reply.result());
// only first handle sees the key
EXPECT_EQ(vector<std::string>{"0"}, test_handles[0]->saw_keys);
EXPECT_TRUE(test_handles[1]->saw_keys.empty());
EXPECT_TRUE(test_handles[2]->saw_keys.empty());
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestSmartPointer.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.
=========================================================================*/
// .NAME Test of vtkSmartPointer.
// .SECTION Description
// Tests instantiations of the vtkSmartPointer class template.
#include "vtkDebugLeaks.h"
#include "vtkFloatArray.h"
#include "vtkIntArray.h"
#include "vtkSmartPointer.h"
int TestSmartPointer(int,char *[])
{
int rval = 0;
vtkIntArray* ia = vtkIntArray::New();
// Coverage:
unsigned int testbits = 0;
unsigned int correctbits = 0x004d3953;
const char *tests[] = {
"da2 == da3", "da2 != da3", "da2 < da3", "da2 <= da3", "da2 > da3",
"da2 >= da3",
"ia == da3", "ia != da3", "ia < da3", "ia <= da3", "ia > da3", "ia >= da3",
"da2 == ia", "da2 != ia", "da2 < ia", "da2 <= ia", "da2 > ia", "da2 <= ia",
"da2 > ia", "da2 >= ia",
"da1 == 0", "da1 != 0", "da1 < 0", "da1 <= 0", "da1 > 0", "da1 >= 0",
NULL };
vtkSmartPointer<vtkIntArray> da2(ia);
vtkSmartPointer<vtkFloatArray> da3;
vtkSmartPointer<vtkDataArray> da1(da2);
da1 = ia;
da1 = da2;
testbits = (testbits << 1) | ((da2 == da3) ? 1 : 0);
testbits = (testbits << 1) | ((da2 != da3) ? 1 : 0);
testbits = (testbits << 1) | ((da2 < da3) ? 1 : 0);
testbits = (testbits << 1) | ((da2 <= da3) ? 1 : 0);
testbits = (testbits << 1) | ((da2 > da3) ? 1 : 0);
testbits = (testbits << 1) | ((da2 >= da3) ? 1 : 0);
testbits = (testbits << 1) | ((ia == da3) ? 1 : 0);
testbits = (testbits << 1) | ((ia != da3) ? 1 : 0);
testbits = (testbits << 1) | ((ia < da3) ? 1 : 0);
testbits = (testbits << 1) | ((ia <= da3) ? 1 : 0);
testbits = (testbits << 1) | ((ia > da3) ? 1 : 0);
testbits = (testbits << 1) | ((ia >= da3) ? 1 : 0);
testbits = (testbits << 1) | ((da2 == ia) ? 1 : 0);
testbits = (testbits << 1) | ((da2 != ia) ? 1 : 0);
testbits = (testbits << 1) | ((da2 < ia) ? 1 : 0);
testbits = (testbits << 1) | ((da2 <= ia) ? 1 : 0);
testbits = (testbits << 1) | ((da2 > ia) ? 1 : 0);
testbits = (testbits << 1) | ((da2 >= ia) ? 1 : 0);
testbits = (testbits << 1) | ((da1 == 0) ? 1 : 0);
testbits = (testbits << 1) | ((da1 != 0) ? 1 : 0);
testbits = (testbits << 1) | ((da1 < 0) ? 1 : 0);
testbits = (testbits << 1) | ((da1 <= 0) ? 1 : 0);
testbits = (testbits << 1) | ((da1 > 0) ? 1 : 0);
testbits = (testbits << 1) | ((da1 >= 0) ? 1 : 0);
if (testbits != correctbits)
{
unsigned int diffbits = (testbits ^ correctbits);
int bitcount = 0;
while (tests[bitcount] != NULL)
{
bitcount++;
}
for (int ib = 0; ib < bitcount; ++ib)
{
if (((diffbits >> (bitcount - ib - 1)) & 1) != 0)
{
cerr << "comparison (" << tests[ib] << ") failed!\n";
}
}
rval = 1;
}
(*da1).SetNumberOfComponents(1);
if(da2)
{
da2->SetNumberOfComponents(1);
}
if(!da2)
{
cerr << "da2 is NULL!" << "\n";
rval = 1;
}
cout << "IntArray: " << da2 << "\n";
da1 = vtkSmartPointer<vtkDataArray>::NewInstance(ia);
da1.TakeReference(vtkIntArray::New());
vtkSmartPointer<vtkIntArray> da4 =
vtkSmartPointer<vtkIntArray>::Take(vtkIntArray::New());
(void)da4;
ia->Delete();
return rval;
}
|
#include "hoCuNDArray_utils.h"
#include "radial_utilities.h"
#include "hoNDArray_fileio.h"
#include "cuNDArray.h"
#include "imageOperator.h"
#include "identityOperator.h"
#include "hoPartialDerivativeOperator.h"
#include "hoCuConebeamProjectionOperator.h"
#include "cuConvolutionOperator.h"
#include "hoCuNDArray_blas.h"
#include "hoCuNDArray_elemwise.h"
#include "hoCuNDArray_blas.h"
#include "cgSolver.h"
#include "CBCT_acquisition.h"
#include "complext.h"
#include "encodingOperatorContainer.h"
#include "vector_td_io.h"
#include "hoPartialDerivativeOperator.h"
#include "hoCuGPBBSolver.h"
#include "hoCuTvOperator.h"
#include "hoCuTvPicsOperator.h"
#include "hoCuNCGSolver.h"
#include "hoCuCgDescentSolver.h"
#include "hoNDArray_utils.h"
#include "hoCuPartialDerivativeOperator.h"
#include <iostream>
#include <algorithm>
#include <sstream>
#include <math_constants.h>
#include <boost/program_options.hpp>
using namespace std;
using namespace Gadgetron;
namespace po = boost::program_options;
boost::shared_ptr<hoCuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning> binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){
std::cout << "Calculating FDK prior" << std::endl;
boost::shared_ptr<CBCT_binning> binning_pics =binning->get_3d_binning();
std::vector<size_t> is_dims3d = is_dims;
is_dims3d.pop_back();
boost::shared_ptr< hoCuConebeamProjectionOperator >
Ep( new hoCuConebeamProjectionOperator() );
Ep->setup(ps,binning_pics,imageDimensions);
Ep->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());
Ep->set_domain_dimensions(&is_dims3d);
Ep->set_use_filtered_backprojection(true);
boost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));
Ep->mult_MH(&projections,prior3d.get());
hoCuNDArray<float> tmp_proj(*ps->get_projections());
Ep->mult_M(prior3d.get(),&tmp_proj);
float s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);
*prior3d *= s;
boost::shared_ptr<hoCuNDArray<float> > prior(new hoCuNDArray<float>(*expand( prior3d.get(), is_dims.back() )));
std::cout << "Prior complete" << std::endl;
return prior;
}
int main(int argc, char** argv)
{
string acquisition_filename;
string outputFile;
uintd3 imageSize;
floatd3 voxelSize;
int device;
unsigned int downsamples;
unsigned int iterations;
float rho;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("acquisition,a", po::value<string>(&acquisition_filename)->default_value("acquisition.hdf5"), "Acquisition data")
("samples,n",po::value<unsigned int>(),"Number of samples per ray")
("output,f", po::value<string>(&outputFile)->default_value("reconstruction.real"), "Output filename")
("size,s",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),"Image size in pixels")
("binning,b",po::value<string>(),"Binning file for 4d reconstruction")
("SAG","Use exact SAG correction if present")
("voxelSize,v",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),"Voxel size in mm")
("dimensions,d",po::value<floatd3>(),"Image dimensions in mm. Overwrites voxelSize.")
("iterations,i",po::value<unsigned int>(&iterations)->default_value(10),"Number of iterations")
("TV,T",po::value<float>(),"TV Weight ")
("PICS",po::value<float>(),"TV Weight of the prior image (Prior image compressed sensing)")
("device",po::value<int>(&device)->default_value(0),"Number of the device to use (0 indexed)")
("downsample,D",po::value<unsigned int>(&downsamples)->default_value(0),"Downsample projections this factor")
("rho",po::value<float>(&rho)->default_value(0.5f),"Rho-value for line search. Must be between 0 and 1. Smaller value means faster runtime, but less stable algorithm.")
("use_prior","Use an FDK prior")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
std::cout << "Command line options:" << std::endl;
for (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){
boost::any a = it->second.value();
std::cout << it->first << ": ";
if (a.type() == typeid(std::string)) std::cout << it->second.as<std::string>();
else if (a.type() == typeid(int)) std::cout << it->second.as<int>();
else if (a.type() == typeid(unsigned int)) std::cout << it->second.as<unsigned int>();
else if (a.type() == typeid(float)) std::cout << it->second.as<float>();
else if (a.type() == typeid(vector_td<float,3>)) std::cout << it->second.as<vector_td<float,3> >();
else if (a.type() == typeid(vector_td<int,3>)) std::cout << it->second.as<vector_td<int,3> >();
else if (a.type() == typeid(vector_td<unsigned int,3>)) std::cout << it->second.as<vector_td<unsigned int,3> >();
else std::cout << "Unknown type" << std::endl;
std::cout << std::endl;
}
cudaSetDevice(device);
cudaDeviceReset();
//Really weird stuff. Needed to initialize the device?? Should find real bug.
cudaDeviceManager::Instance()->lockHandle();
cudaDeviceManager::Instance()->unlockHandle();
boost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());
ps->load(acquisition_filename);
ps->get_geometry()->print(std::cout);
ps->downsample(downsamples);
boost::shared_ptr<CBCT_binning> binning(new CBCT_binning());
if (vm.count("binning")){
std::cout << "Loading binning data" << std::endl;
binning->load(vm["binning"].as<string>());
} else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));
binning->print(std::cout);
floatd3 imageDimensions;
if (vm.count("dimensions")){
imageDimensions = vm["dimensions"].as<floatd3>();
voxelSize = imageDimensions/imageSize;
}
else imageDimensions = voxelSize*imageSize;
float lengthOfRay_in_mm = norm(imageDimensions);
unsigned int numSamplesPerPixel = 3;
float minSpacing = min(voxelSize)/numSamplesPerPixel;
unsigned int numSamplesPerRay;
if (vm.count("samples")) numSamplesPerRay = vm["samples"].as<unsigned int>();
else numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );
float step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;
size_t numProjs = ps->get_projections()->get_size(2);
size_t needed_bytes = 2 * prod(imageSize) * sizeof(float);
std::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);
std::cout << "IS dimensions " << is_dims[0] << " " << is_dims[1] << " " << is_dims[2] << std::endl;
std::cout << "Image size " << imageDimensions << std::endl;
is_dims.push_back(binning->get_number_of_bins());
// Define encoding matrix
boost::shared_ptr< hoCuConebeamProjectionOperator >
E( new hoCuConebeamProjectionOperator() );
E->setup(ps,binning,imageDimensions);
E->set_domain_dimensions(&is_dims);
E->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());
hoCuGPBBSolver<float> solver;
//hoCuNCGSolver<float> solver;
//hoCuCgDescentSolver<float> solver;
solver.set_encoding_operator(E);
solver.set_domain_dimensions(&is_dims);
solver.set_max_iterations(iterations);
solver.set_output_mode(hoCuGPBBSolver<float>::OUTPUT_VERBOSE);
solver.set_non_negativity_constraint(true);
//solver.set_rho(rho);
hoCuNDArray<float> projections = *ps->get_projections();
std::cout << "Projection nrm" << nrm2(&projections) << std::endl;
if (E->get_use_offset_correction())
E->offset_correct(&projections);
std::cout << "Projection nrm" << nrm2(&projections) << std::endl;
boost::shared_ptr<hoCuNDArray<float> > prior;
if (vm.count("use_prior")) {
prior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);
solver.set_x0(prior);
}
if (vm.count("TV")){
std::cout << "Total variation regularization in use" << std::endl;
boost::shared_ptr<hoCuTvOperator<float,4> > tv(new hoCuTvOperator<float,4>);
tv->set_weight(vm["TV"].as<float>());
solver.add_nonlinear_operator(tv);
/*
boost::shared_ptr<hoCuTvOperator<float,4> > tv2(new hoCuTvOperator<float,4>);
tv2->set_step(2);
tv2->set_weight(vm["TV"].as<float>());
solver.add_nonlinear_operator(tv2);
boost::shared_ptr<hoCuTvOperator<float,4> > tv3(new hoCuTvOperator<float,4>);
tv3->set_step(3);
tv3->set_weight(vm["TV"].as<float>());
solver.add_nonlinear_operator(tv3);
*/
}
if (vm.count("PICS")){
std::cout << "PICS in use" << std::endl;
if (!prior.get()) prior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);
boost::shared_ptr<hoCuTvPicsOperator<float,3> > pics (new hoCuTvPicsOperator<float,3>);
pics->set_prior(prior);
pics->set_weight(vm["PICS"].as<float>());
solver.add_nonlinear_operator(pics);
solver.set_x0(prior);
}
boost::shared_ptr< hoCuNDArray<float> > result = solver.solve(&projections);
write_nd_array<float>( result.get(), outputFile.c_str());
}
|
//https://vjudge.net/contest/419722#problem/D
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef long long ll;
typedef long double ld;
ll mod = 1e9 + 7;
vector<ll> dp(1500);
void init ()
{
vector<ll> p;
p.push_back (2);
function<bool (ll)> f = [] (ll x) {for (ll i = 2; i * i <= x; ++i) if (x % i == 0) return false; return true;};
for (ll i = 3; i <= 999; i += 2) if (f (i)) p.push_back (i);
for (ll i = 0; i < p.size () - 1; ++i) if (f (p[i] + p[i + 1] + 1)) dp[p[i] + p[i + 1] + 1]++;
for (ll i = 1; i < 1500; ++i) dp[i] += dp[i - 1];
}
int main ()
{
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
init ();
ll n, k;
cin >> n >> k;
if (dp[n] >= k) cout << "YES";
else cout << "NO";
}
|
/*Class for code options*/
#include "option_class.hpp"
#include <boost/program_options.hpp>
namespace po = boost::program_options;
void Option::version(double version_number) {
// Function that prints current code version.
std::cout<<"Version: "<<std::fixed<<std::setprecision(1)
<<version_number<<std::endl;
exit(0);
}
void Option::print_parameters() {
// Function that prints current code parameter values.
std::cout<<"=================================================="<<std::endl;
std::cout<<"Code Parameters:"<<std::endl;
std::cout<<" - input_file = "<<input_file<<std::endl;
std::cout<<" - output_clusters = "<<output_clusters<<std::endl;
std::cout<<" - output_members = "<<output_members<<std::endl;
std::cout<<" - link_r = "<<link_r<<std::endl;
std::cout<<" - link_z = "<<link_z<<std::endl;
std::cout<<" - input_mode = "<<input_mode<<std::endl;
std::cout<<" - output_mode = "<<output_mode<<std::endl;
std::cout<<" - output_option = "<<output_option<<std::endl;
std::cout<<" - fof_mode = "<<fof_mode<<std::endl;
std::cout<<" - link_mode = "<<link_mode<<std::endl;
std::cout<<" - size_units = "<<size_units<<std::endl;
std::cout<<" - min_ngal = "<<min_ngal<<std::endl;
std::cout<<" - max_ngal = "<<max_ngal<<std::endl;
std::cout<<" - z_min = "<<z_min<<std::endl;
std::cout<<" - z_max = "<<z_max<<std::endl;
std::cout<<" - z_bin_size = "<<z_bin_size<<std::endl;
std::cout<<" - z_ref = "<<z_ref<<std::endl;
std::cout<<" - z_err_max = "<<z_err_max<<std::endl;
std::cout<<" - nz_data = "<<nz_data<<std::endl;
std::cout<<" - c = "<<c<<std::endl;
std::cout<<" - H0 = "<<H0<<std::endl;
std::cout<<" - omega_m = "<<omega_m<<std::endl;
std::cout<<" - omega_l = "<<omega_l<<std::endl;
}
void Option::read_opts(int argc, char *argv[], double version_number) {
/* Define Help Options */
po::options_description helps("Help options");
helps.add_options()
("help,h", "Produce help message.")
("version,v", "Print code version.")
("parameters,p", "Print all parameter values.")
("config,c", po::value<std::string>(&config_file)->default_value("param_file.ini"),
"Configuration file name.");
/* Define Run Options */
po::options_description runs("Run options");
runs.add_options()
("input_file,i", po::value<std::string>(&input_file),
"Input file name.")
("output_clusters", po::value<std::string>(&output_clusters),
"Output clusters file name.")
("output_members", po::value<std::string>(&output_members),
"Output members file name.")
("link_r", po::value<double>(&link_r),
"Transverse linking parameter value.")
("link_z", po::value<double>(&link_z),
"Line-of-sight linking parameter value.");
/* Define Configuration Options */
po::options_description config("Configuration Options");
config.add_options()
("input_mode", po::value<std::string>(&input_mode)->default_value("ascii"),
"File input mode [ascii/fits].")
("output_mode", po::value<std::string>(&output_mode)->default_value("ascii"),
"File output mode [ascii/fits].")
("output_option", po::value<std::string>(&output_option)->default_value("no"),
"File output or NOT [yes/no].")
("fof_mode", po::value<std::string>(&fof_mode)->default_value("phot"),
"Friends-of-friends redshift mode [spec/phot].")
("link_mode", po::value<std::string>(&link_mode)->default_value("dynamic"),
"Friends-of-friends linking mode [fixed/dynamic].")
("size_units", po::value<std::string>(&size_units)->default_value("arcmin"),
"Cluster size units [arcmin/deg/Mpc].")
("min_ngal", po::value<int>(&min_ngal)->default_value(10, "10"),
"Minimum number of cluster galaxies members.")
("max_ngal", po::value<int>(&max_ngal)->default_value(10000, "10000"),
"Maximum number of cluster galaxies members.")
("z_min", po::value<double>(&z_min)->default_value(0.0, "0.00"),
"Minimum redshift of sample.")
("z_max", po::value<double>(&z_max)->default_value(3.0, "3.00"),
"Maximum redshift of sample.")
("z_bin_size", po::value<double>(&z_bin_size)->default_value(0.01, "0.01"),
"Size of redshift bins.")
("z_ref", po::value<double>(&z_ref)->default_value(0.50, "0.50"),
"Reference redshift for calculations.")
("z_err_max", po::value<double>(&z_err_max)->default_value(0.06, "0.06"),
"Maxmimum photo-z error allowed.")
("nz_data", po::value<std::string>(&nz_data),
"Input file name for N(z) data.")
("c", po::value<double>(&c)->default_value(2.997e5, "2.997e5"),
"Speed of light in km/s.")
("H0", po::value<double>(&H0)->default_value(100, "100.00"),
"Hubble parameter in km/s/Mpc.")
("omega_m", po::value<double>(&omega_m)->default_value(0.30, "0.30"),
"Matter density.")
("omega_l", po::value<double>(&omega_l)->default_value(0.70, "0.70"),
"Dark energy density.");
/* Define Additional Options */
po::options_description adds("Additional Options");
adds.add_options()
("print_bin_data", "Print redshift bin data.")
("print_kdtree_data", "Print kd-tree data.")
("print_bg_data", "Print background data.");
/* Command Line Options */
po::options_description cmdline_options("\nFRIENDS-OF-FRIENDS CLUSTER DETECTION ALGORITHM\n\nCode Options");
cmdline_options.add(helps).add(runs).add(config).add(adds);
/* Configuration File Options */
po::options_description config_file_options;
config_file_options.add(runs).add(config);
/* Define Variables Map */
po::variables_map v_map;
store(po::command_line_parser(argc, argv).options(cmdline_options).run(), v_map);
notify(v_map);
/* Read Configuration File */
std::ifstream read_config(config_file.c_str());
if(read_config.good()) {
store(parse_config_file(read_config, config_file_options), v_map);
notify(v_map);
}
else
std::cout<<"Warning: configuration file ["<<config_file.c_str()<<"] not found."<<std::endl;
/* Print Help */
if (v_map.count("help")) {
std::cout << cmdline_options << "\n";
exit(0);
}
/* Print Version */
if (v_map.count("version"))
version(version_number);
/* Print Parameters */
if (v_map.count("parameters"))
print_parameters();
/* Print Bin Data */
if (v_map.count("print_bin_data"))
print_bin_data = true;
else
print_bin_data = false;
/* Print kd-tree Data */
if (v_map.count("print_kdtree_data"))
print_kdtree_data = true;
else
print_kdtree_data = false;
/* Print Background Data */
if (v_map.count("print_bg_data"))
print_bg_data = true;
else
print_bg_data = false;
}
void Option::read_merge_opts(int argc, char *argv[], double version_number) {
/* Define Options */
po::options_description opts("Code options");
opts.add_options()
("help,h", "Produce help message.")
("version,v", "Print code version.")
("input_file,i", po::value<std::string>(&input_file),
"Input file name.")
("output_file,o", po::value<std::string>(&output_file),
"Output file name.")
("input_mode", po::value<std::string>(&input_mode)->default_value("ascii"),
"File input mode [ascii/fits].")
("output_mode", po::value<std::string>(&output_mode)->default_value("ascii"),
"File output mode [ascii/fits].")
("size_units", po::value<std::string>(&size_units)->default_value("arcmin"),
"Cluster size units [arcmin/deg/Mpc].")
("bg_data", po::value<std::string>(&bg_data),
"Input file name for background data.");
/* Define Variables Map */
po::variables_map v_map;
store(po::command_line_parser(argc, argv).options(opts).run(), v_map);
notify(v_map);
/* Print Help */
if (v_map.count("help")) {
std::cout << opts << "\n";
exit(0);
}
/* Print Version */
if (v_map.count("version"))
version(version_number);
}
void Option::read_split_opts(int argc, char *argv[], double version_number) {
/* Define Options */
po::options_description opts("Code options");
opts.add_options()
("help,h", "Produce help message.")
("version,v", "Print code version.")
("input_file,i", po::value<std::string>(&input_file),
"Input file name.")
("ra_lower", po::value<double>(&ra_lower)->default_value(0),
"Lower limit in right ascension.")
("ra_upper", po::value<double>(&ra_upper)->default_value(0),
"Upper limit in right ascension.")
("dec_lower", po::value<double>(&dec_lower)->default_value(0),
"Lower limit in declination.")
("dec_upper", po::value<double>(&dec_upper)->default_value(0),
"Upper limit in declination.")
("ra_overlap", po::value<double>(&ra_overlap)->default_value(0.5),
"Overlap in right ascension.")
("dec_overlap", po::value<double>(&dec_overlap)->default_value(0.5),
"Overlap in declination.")
("n_ra_bins", po::value<int>(&n_ra_bins)->default_value(0),
"Number of right ascension bins.")
("n_dec_bins", po::value<int>(&n_dec_bins)->default_value(0),
"Number of declination bins.")
("n_procs", po::value<int>(&n_procs)->default_value(0),
"Number of processes.");
/* Define Variables Map */
po::variables_map v_map;
store(po::command_line_parser(argc, argv).options(opts).run(), v_map);
notify(v_map);
/* Print Help */
if (v_map.count("help")) {
std::cout << opts << "\n";
exit(0);
}
/* Print Version */
if (v_map.count("version"))
version(version_number);
}
|
// $Id$
#include "ace/OS_main.h"
#include "ace/OS_Memory.h"
#include "ace/SPIPE_Addr.h"
#include "ace/SPIPE_Connector.h"
#include "ace/Log_Msg.h"
#include "ace/OS_NS_stdio.h"
#include "ace/OS_NS_stdlib.h"
#include "ace/OS_NS_unistd.h"
#include "ace/Time_Value.h"
#if defined (ACE_HAS_STREAM_PIPES)
#include "shared.h"
const int DEFAULT_SIZE = 4 * 1024;
const int DEFAULT_COUNT = 100;
int
ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
int size = argc > 1 ? ACE_OS::atoi (argv[1]) : DEFAULT_SIZE;
int iterations = argc > 2 ? ACE_OS::atoi (argv[2]) : DEFAULT_COUNT;
char *buf;
ACE_NEW_RETURN (buf, char[size], -1);
if (argc > 3)
rendezvous = argv[3];
ACE_SPIPE_Stream cli_stream;
ACE_SPIPE_Connector con;
int i;
if (con.connect (cli_stream, ACE_SPIPE_Addr (rendezvous)) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", rendezvous), 1);
for (i = 0; i < size; i++)
buf[i] = 'a';
ACE_Str_Buf buffer (buf, size);
for (i = 0; i < iterations; i++)
if (cli_stream.send ((ACE_Str_Buf *) 0,
&buffer,
1,
MSG_BAND) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "send"), 1);
if (cli_stream.close () == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "close"), 1);
delete buf;
return 0;
}
#else
#include <stdio.h>
int ACE_TMAIN (int, ACE_TCHAR *[])
{
ACE_OS::fprintf (stderr, "This feature is not supported\n");
return 0;
}
#endif /* ACE_HAS_STREAM_PIPES */
|
#ifndef FCQUEUE_H
#define FCQUEUE_H
#include "app_utils.hh" // ulong_t
#include "utils.hh"
#include <stdio.h>
#include <errno.h>
#include <algorithm>
#define UNUSED_SLOT_THRESHOLD 10
#define LOCKED 1
#define UNLOCKED 0
#if 0
struct QNode {
QNode* volatile next;
ulong_t val;
QNode() :
val(0), next(NULL) {
}
QNode(ulong_t v) :
val(v), next(NULL) {
}
~QNode() {
}
};
#endif
#define MAX_INDEX 1048576
#define NEXT_INDEX(_x) ((_x+1) % MAX_INDEX)
class Queue {
public:
struct SlotInfo {
char volatile is_request_valid;
int volatile operation;
ulong_t volatile parameter;
int volatile ret_val;
int volatile op_timestamp;
char volatile is_slot_linked;
SlotInfo *volatile next_slot;
SlotInfo() {
is_request_valid = FALSE;
operation = 0;
parameter = 0;
ret_val = 0;
op_timestamp = 0;
is_slot_linked = FALSE;
next_slot = NULL;
}
};
Queue(); // constructor
~Queue(); // destructor
int fc_operation(int thread_id, int operation_type, ulong_t parameter, SlotInfo *slot);
void print();
private:
SlotInfo *tail_slot;
//pthread_mutex_t combine_lock;
ulong_t combine_cas;
//int combine_lock_status;
pthread_mutex_t tail_slot_lock; // used in place of atomic compare and swap operations
int volatile operation_timestamp;
#if 0
QNode *head_node;
QNode *tail_node;
#endif
ulong_t head_index;
ulong_t tail_index;
ulong_t queue_array[MAX_INDEX];
void enq_slot(SlotInfo *slot_to_enq);
void flat_combine();
ulong_t q_size;
};
Queue::Queue()
{
#if 0
tail_node = NULL;
head_node = NULL;
#endif
head_index = 0;
tail_index = 0;
//pthread_mutex_init(&combine_lock, NULL);
//combine_lock_status = UNLOCKED;
combine_cas = 0;
pthread_mutex_init(&tail_slot_lock, NULL);
tail_slot = NULL;
q_size = 0;
}
Queue::~Queue()
{
#if 0
QNode *curr = head_node;
QNode *next = NULL;
while (curr != NULL) {
next = curr->next;
delete curr;
curr = next;
}
#endif
//pthread_mutex_destroy(&combine_lock);
pthread_mutex_destroy(&tail_slot_lock);
}
void Queue::enq_slot(SlotInfo *slot_to_enq)
{
SlotInfo *curr_tail_slot = NULL;
slot_to_enq->is_slot_linked = TRUE;
slot_to_enq->op_timestamp = operation_timestamp;
do {
curr_tail_slot = tail_slot;
slot_to_enq->next_slot = curr_tail_slot;
} while (__sync_bool_compare_and_swap(&tail_slot, curr_tail_slot, slot_to_enq) == false);
#if 0
pthread_mutex_lock(&tail_slot_lock);
slot_to_enq->next_slot = tail_slot;
tail_slot = slot_to_enq;
pthread_mutex_unlock(&tail_slot_lock);
#endif
}
void Queue::flat_combine()
{
SlotInfo *curr_slot = NULL;
SlotInfo *prev_slot = NULL;
int op = 0;
ulong_t param = 0;
// QNode *old_head = head_node;
pthread_mutex_lock(&tail_slot_lock);
curr_slot = tail_slot;
pthread_mutex_unlock(&tail_slot_lock);
prev_slot = curr_slot;
while (curr_slot != NULL) {
if (curr_slot->is_request_valid == TRUE) {
// execute operation
op = curr_slot->operation;
param = curr_slot->parameter;
curr_slot->ret_val = FALSE;
if (op == PUSH_OP) {
#if 0
QNode *new_node = new QNode(param);
if (q_size++ == 0) { // if queue was empty
head_node = new_node;
}
else {
tail_node->next = new_node;
}
tail_node = new_node;
curr_slot->ret_val = param;
#endif
queue_array[tail_index] = param;
tail_index = NEXT_INDEX(tail_index);
curr_slot->ret_val = param;
}
else { // POP_OP
#if 0
if (q_size == 0) {
curr_slot->ret_val = 0;
}
else {
old_head = head_node;
QNode *nxt = head_node->next;
curr_slot->ret_val = head_node->val;
head_node = nxt;
if (--q_size == 0) {
tail_node = NULL;
}
delete old_head;
}
#endif
curr_slot->ret_val = queue_array[head_index];
head_index = NEXT_INDEX(head_index);
}
curr_slot->is_request_valid = FALSE;
curr_slot->op_timestamp = operation_timestamp;
operation_timestamp++;
} else {
// unlink slot if it has not been used for long
if (curr_slot != prev_slot) { // if curr_slot is not tail_slot
if ((operation_timestamp - curr_slot->op_timestamp) > UNUSED_SLOT_THRESHOLD) {
prev_slot->next_slot = curr_slot->next_slot;
curr_slot->is_slot_linked = FALSE;
curr_slot = prev_slot->next_slot;
continue;
}
}
}
prev_slot = curr_slot;
curr_slot = curr_slot->next_slot;
}
}
int Queue::fc_operation(int thread_id, int operation_type, ulong_t parameter, SlotInfo *slot)
{
//int lock_acquired = 0;
bool lock_acquired = false;
slot->operation = operation_type;
slot->parameter = parameter;
slot->is_request_valid = TRUE;
if ((slot->is_slot_linked == FALSE) && (slot->is_request_valid == TRUE)) {
enq_slot(slot);
}
while (1) {
//lock_acquired = pthread_mutex_trylock(&combine_lock);
lock_acquired = __sync_bool_compare_and_swap(&combine_cas, 0, 0xffff);
//if (lock_acquired == 0) { // acquired lock
if (lock_acquired) { // acquired lock
//combine_lock_status = LOCKED;
if ((slot->is_slot_linked == FALSE) && (slot->is_request_valid == TRUE)) {
enq_slot(slot);
}
flat_combine();
//combine_lock_status = UNLOCKED;
//pthread_mutex_unlock(&combine_lock);
combine_cas = 0;
return slot->ret_val;
} else {
#ifdef HOST_DEBUG_ON
/*if (lock_acquired != EBUSY) {
perror("pthread_mutex_trylock");
}*/
#endif
//while ((slot->is_request_valid == TRUE) && combine_lock_status == LOCKED) {
while ((slot->is_request_valid == TRUE) && combine_cas == 0xffff) {
if (slot->is_slot_linked == FALSE) {
enq_slot(slot);
}
}
if (slot->is_request_valid == FALSE) {
return slot->ret_val;
}
}
}
}
void Queue::print()
{
#if 0
QNode *curr = head_node;
cout << "linked list contents: " << endl;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << "\n" << endl;
#endif
ulong_t i = head_index;
while (i != tail_index) {
cout << queue_array[i] << " ";
i = NEXT_INDEX(i);
}
cout << "\n" << endl;
}
#endif // ifndef FCQUEUE_H
|
No-one has translated the mdwrkapi example into C++ yet. Be the first to create
mdwrkapi in C++ and get one free Internet! If you're the author of the C++
binding, this is a great way to get people to use 0MQ in C++.
To submit a new translation email it to zeromq-dev@lists.zeromq.org. Please:
* Stick to identical functionality and naming used in examples so that readers
can easily compare languages.
* You MUST place your name as author in the examples so readers can contact you.
* You MUST state in the email that you license your code under the MIT/X11
license.
Subscribe to the email list at http://lists.zeromq.org/mailman/listinfo/zeromq-dev.
|
// Copyright 2017 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 "content/browser/indexed_db/indexed_db_dispatcher_host.h"
#include "base/barrier_closure.h"
#include "base/callback.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_offset_string_conversions.h"
#include "base/test/test_simple_task_runner.h"
#include "base/threading/thread.h"
#include "content/browser/indexed_db/indexed_db_callbacks.h"
#include "content/browser/indexed_db/indexed_db_context_impl.h"
#include "content/browser/indexed_db/indexed_db_database_callbacks.h"
#include "content/browser/indexed_db/indexed_db_factory.h"
#include "content/browser/indexed_db/indexed_db_pending_connection.h"
#include "content/browser/indexed_db/mock_mojo_indexed_db_callbacks.h"
#include "content/browser/indexed_db/mock_mojo_indexed_db_database_callbacks.h"
#include "content/common/indexed_db/indexed_db.mojom.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/strong_associated_binding.h"
#include "net/url_request/url_request_test_util.h"
#include "storage/browser/test/mock_quota_manager.h"
#include "storage/browser/test/mock_quota_manager_proxy.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/modules/indexeddb/web_idb_database_exception.h"
#include "url/origin.h"
using indexed_db::mojom::Callbacks;
using indexed_db::mojom::CallbacksAssociatedPtrInfo;
using indexed_db::mojom::DatabaseAssociatedPtr;
using indexed_db::mojom::DatabaseAssociatedPtrInfo;
using indexed_db::mojom::DatabaseAssociatedRequest;
using indexed_db::mojom::DatabaseCallbacks;
using indexed_db::mojom::DatabaseCallbacksAssociatedPtrInfo;
using indexed_db::mojom::Factory;
using indexed_db::mojom::FactoryAssociatedPtr;
using indexed_db::mojom::FactoryAssociatedRequest;
using indexed_db::mojom::KeyPath;
using indexed_db::mojom::Value;
using indexed_db::mojom::ValuePtr;
using mojo::StrongAssociatedBindingPtr;
using testing::_;
using testing::StrictMock;
namespace content {
namespace {
ACTION_TEMPLATE(MoveArg,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(out)) {
*out = std::move(*::testing::get<k>(args));
};
ACTION_P(RunClosure, closure) {
closure.Run();
}
MATCHER_P(IsAssociatedInterfacePtrInfoValid,
tf,
std::string(negation ? "isn't" : "is") + " " +
std::string(tf ? "valid" : "invalid")) {
return tf == arg->is_valid();
}
MATCHER_P(MatchesIDBKey, key, "") {
return arg.Equals(key);
}
typedef void (base::Closure::*ClosureRunFcn)() const &;
static const char kDatabaseName[] = "db";
static const char kOrigin[] = "https://www.example.com";
static const int kFakeProcessId = 2;
static const int64_t kTemporaryQuota = 50 * 1024 * 1024;
base::FilePath CreateAndReturnTempDir(base::ScopedTempDir* temp_dir) {
CHECK(temp_dir->CreateUniqueTempDir());
return temp_dir->GetPath();
}
// Stores data specific to a connection.
struct TestDatabaseConnection {
TestDatabaseConnection(url::Origin origin,
base::string16 db_name,
int64_t version,
int64_t upgrade_txn_id)
: origin(std::move(origin)),
db_name(std::move(db_name)),
version(version),
upgrade_txn_id(upgrade_txn_id),
open_callbacks(new StrictMock<MockMojoIndexedDBCallbacks>()),
connection_callbacks(
new StrictMock<MockMojoIndexedDBDatabaseCallbacks>()){};
~TestDatabaseConnection() {}
void Open(Factory* factory) {
factory->Open(open_callbacks->CreateInterfacePtrAndBind(),
connection_callbacks->CreateInterfacePtrAndBind(), origin,
db_name, version, upgrade_txn_id);
}
url::Origin origin;
base::string16 db_name;
int64_t version;
int64_t upgrade_txn_id;
DatabaseAssociatedPtr database;
std::unique_ptr<MockMojoIndexedDBCallbacks> open_callbacks;
std::unique_ptr<MockMojoIndexedDBDatabaseCallbacks> connection_callbacks;
private:
DISALLOW_COPY_AND_ASSIGN(TestDatabaseConnection);
};
void StatusCallback(const base::Closure& callback,
::indexed_db::mojom::Status* status_out,
::indexed_db::mojom::Status status) {
*status_out = status;
callback.Run();
}
class TestIndexedDBObserver : public IndexedDBContextImpl::Observer {
public:
void OnIndexedDBListChanged(const url::Origin& origin) override {
++notify_list_changed_count;
}
void OnIndexedDBContentChanged(
const url::Origin& origin,
const base::string16& database_name,
const base::string16& object_store_name) override {
++notify_content_changed_count;
}
int notify_list_changed_count = 0;
int notify_content_changed_count = 0;
};
} // namespace
class IndexedDBDispatcherHostTest : public testing::Test {
public:
IndexedDBDispatcherHostTest()
: thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP),
special_storage_policy_(
base::MakeRefCounted<MockSpecialStoragePolicy>()),
quota_manager_(base::MakeRefCounted<MockQuotaManager>(
false /*is_incognito*/,
browser_context_.GetPath(),
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO),
special_storage_policy_)),
context_impl_(base::MakeRefCounted<IndexedDBContextImpl>(
CreateAndReturnTempDir(&temp_dir_),
special_storage_policy_,
quota_manager_->proxy())),
host_(new IndexedDBDispatcherHost(
kFakeProcessId,
base::MakeRefCounted<net::TestURLRequestContextGetter>(
BrowserThread::GetTaskRunnerForThread(BrowserThread::IO)),
context_impl_,
ChromeBlobStorageContext::GetFor(&browser_context_))) {
quota_manager_->SetQuota(
GURL(kOrigin), blink::mojom::StorageType::kTemporary, kTemporaryQuota);
}
void TearDown() override {
host_.reset();
context_impl_ = nullptr;
quota_manager_ = nullptr;
RunAllTasksUntilIdle();
// File are leaked if this doesn't return true.
ASSERT_TRUE(temp_dir_.Delete());
}
void SetUp() override {
FactoryAssociatedRequest request =
::mojo::MakeRequestAssociatedWithDedicatedPipe(&idb_mojo_factory_);
host_->AddBinding(std::move(request));
}
protected:
TestBrowserThreadBundle thread_bundle_;
TestBrowserContext browser_context_;
base::ScopedTempDir temp_dir_;
scoped_refptr<MockSpecialStoragePolicy> special_storage_policy_;
scoped_refptr<MockQuotaManager> quota_manager_;
scoped_refptr<IndexedDBContextImpl> context_impl_;
std::unique_ptr<IndexedDBDispatcherHost, BrowserThread::DeleteOnIOThread>
host_;
FactoryAssociatedPtr idb_mojo_factory_;
DISALLOW_COPY_AND_ASSIGN(IndexedDBDispatcherHostTest);
};
TEST_F(IndexedDBDispatcherHostTest, CloseConnectionBeforeUpgrade) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(""), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
connection.Open(idb_mojo_factory_.get());
loop.Run();
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
}
TEST_F(IndexedDBDispatcherHostTest, CloseAfterUpgrade) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
const int64_t kObjectStoreId = 10;
const char kObjectStoreName[] = "os";
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(""), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
ASSERT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection.connection_callbacks, Complete(kTransactionId))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection.database.is_bound());
connection.database->CreateObjectStore(kTransactionId, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
connection.database->Commit(kTransactionId);
loop.Run();
}
}
TEST_F(IndexedDBDispatcherHostTest, OpenNewConnectionWhileUpgrading) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
const int64_t kObjectStoreId = 10;
const char kObjectStoreName[] = "os";
// Open connection 1, and expect the upgrade needed.
TestDatabaseConnection connection1(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
DatabaseAssociatedPtrInfo database_info1;
{
base::RunLoop loop;
IndexedDBDatabaseMetadata metadata;
EXPECT_CALL(
*connection1.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(""), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info1),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection1.Open(idb_mojo_factory_.get());
loop.Run();
}
connection1.database.Bind(std::move(database_info1));
// Open connection 2, but expect that we won't be called back.
DatabaseAssociatedPtrInfo database_info2;
IndexedDBDatabaseMetadata metadata2;
TestDatabaseConnection connection2(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, 0);
connection2.Open(idb_mojo_factory_.get());
// Check that we're called in order and the second connection gets it's
// database after the first connection completes.
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(3, loop.QuitClosure());
EXPECT_CALL(*connection1.connection_callbacks, Complete(kTransactionId))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection1.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection2.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(true), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info2),
testing::SaveArg<1>(&metadata2),
RunClosure(std::move(quit_closure))));
// Create object store.
ASSERT_TRUE(connection1.database.is_bound());
connection1.database->CreateObjectStore(kTransactionId, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
connection1.database->Commit(kTransactionId);
loop.Run();
}
EXPECT_TRUE(database_info2.is_valid());
EXPECT_EQ(connection2.version, metadata2.version);
EXPECT_EQ(connection2.db_name, metadata2.name);
}
TEST_F(IndexedDBDispatcherHostTest, PutWithInvalidBlob) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
const int64_t kObjectStoreId = 10;
const char kObjectStoreName[] = "os";
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(""), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
ASSERT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(3, loop.QuitClosure());
auto put_callbacks =
std::make_unique<StrictMock<MockMojoIndexedDBCallbacks>>();
EXPECT_CALL(*put_callbacks,
Error(blink::kWebIDBDatabaseExceptionUnknownError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection.connection_callbacks,
Abort(kTransactionId, blink::kWebIDBDatabaseExceptionUnknownError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.open_callbacks,
Error(blink::kWebIDBDatabaseExceptionAbortError, _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection.database.is_bound());
connection.database->CreateObjectStore(kTransactionId, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
// Call Put with an invalid blob.
std::vector<::indexed_db::mojom::BlobInfoPtr> blobs;
blink::mojom::BlobPtrInfo blob;
// Ignore the result of MakeRequest, to end up with an invalid blob.
mojo::MakeRequest(&blob);
blobs.push_back(::indexed_db::mojom::BlobInfo::New(
std::move(blob), "fakeUUID", base::string16(), 100, nullptr));
connection.database->Put(kTransactionId, kObjectStoreId,
Value::New("hello", std::move(blobs)),
content::IndexedDBKey(base::UTF8ToUTF16("hello")),
blink::kWebIDBPutModeAddOnly,
std::vector<content::IndexedDBIndexKeys>(),
put_callbacks->CreateInterfacePtrAndBind());
connection.database->Commit(kTransactionId);
loop.Run();
}
}
TEST_F(IndexedDBDispatcherHostTest, CompactDatabaseWithConnection) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
::indexed_db::mojom::Status callback_result =
::indexed_db::mojom::Status::IOError;
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(3, loop.QuitClosure());
const url::Origin origin = url::Origin::Create(GURL(kOrigin));
EXPECT_CALL(*connection.connection_callbacks, Complete(kTransactionId))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
connection.database->Commit(kTransactionId);
idb_mojo_factory_->AbortTransactionsAndCompactDatabase(
origin, base::BindOnce(&StatusCallback, std::move(quit_closure),
&callback_result));
loop.Run();
}
EXPECT_EQ(::indexed_db::mojom::Status::OK, callback_result);
}
TEST_F(IndexedDBDispatcherHostTest, CompactDatabaseWhileDoingTransaction) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
const int64_t kObjectStoreId = 10;
const char kObjectStoreName[] = "os";
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
::indexed_db::mojom::Status callback_result =
::indexed_db::mojom::Status::IOError;
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(4, loop.QuitClosure());
const url::Origin origin = url::Origin::Create(GURL(kOrigin));
EXPECT_CALL(
*connection.connection_callbacks,
Abort(kTransactionId, blink::kWebIDBDatabaseExceptionUnknownError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.open_callbacks,
Error(blink::kWebIDBDatabaseExceptionAbortError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.connection_callbacks, ForcedClose())
.Times(1)
.WillOnce(RunClosure(quit_closure));
ASSERT_TRUE(connection.database.is_bound());
connection.database->CreateObjectStore(kTransactionId, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
idb_mojo_factory_->AbortTransactionsAndCompactDatabase(
origin, base::BindOnce(&StatusCallback, std::move(quit_closure),
&callback_result));
loop.Run();
}
EXPECT_EQ(::indexed_db::mojom::Status::OK, callback_result);
}
TEST_F(IndexedDBDispatcherHostTest, CompactDatabaseWhileUpgrading) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
::indexed_db::mojom::Status callback_result =
::indexed_db::mojom::Status::IOError;
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(4, loop.QuitClosure());
const url::Origin origin = url::Origin::Create(GURL(kOrigin));
EXPECT_CALL(
*connection.connection_callbacks,
Abort(kTransactionId, blink::kWebIDBDatabaseExceptionUnknownError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.open_callbacks,
Error(blink::kWebIDBDatabaseExceptionAbortError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.connection_callbacks, ForcedClose())
.Times(1)
.WillOnce(RunClosure(quit_closure));
ASSERT_TRUE(connection.database.is_bound());
idb_mojo_factory_->AbortTransactionsAndCompactDatabase(
origin, base::BindOnce(&StatusCallback, std::move(quit_closure),
&callback_result));
loop.Run();
}
EXPECT_EQ(::indexed_db::mojom::Status::OK, callback_result);
}
TEST_F(IndexedDBDispatcherHostTest,
AbortTransactionsAfterCompletingTransaction) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
::indexed_db::mojom::Status callback_result =
::indexed_db::mojom::Status::IOError;
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(4, loop.QuitClosure());
const url::Origin origin = url::Origin::Create(GURL(kOrigin));
EXPECT_CALL(*connection.connection_callbacks, Complete(kTransactionId))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.connection_callbacks, ForcedClose())
.Times(1)
.WillOnce(RunClosure(quit_closure));
connection.database->Commit(kTransactionId);
idb_mojo_factory_->AbortTransactionsForDatabase(
origin, base::BindOnce(&StatusCallback, std::move(quit_closure),
&callback_result));
loop.Run();
}
EXPECT_EQ(::indexed_db::mojom::Status::OK, callback_result);
}
TEST_F(IndexedDBDispatcherHostTest, AbortTransactionsWhileDoingTransaction) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
const int64_t kObjectStoreId = 10;
const char kObjectStoreName[] = "os";
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
::indexed_db::mojom::Status callback_result =
::indexed_db::mojom::Status::IOError;
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(4, loop.QuitClosure());
const url::Origin origin = url::Origin::Create(GURL(kOrigin));
EXPECT_CALL(
*connection.connection_callbacks,
Abort(kTransactionId, blink::kWebIDBDatabaseExceptionUnknownError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.open_callbacks,
Error(blink::kWebIDBDatabaseExceptionAbortError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.connection_callbacks, ForcedClose())
.Times(1)
.WillOnce(RunClosure(quit_closure));
ASSERT_TRUE(connection.database.is_bound());
connection.database->CreateObjectStore(kTransactionId, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
idb_mojo_factory_->AbortTransactionsForDatabase(
origin, base::BindOnce(&StatusCallback, std::move(quit_closure),
&callback_result));
loop.Run();
}
EXPECT_EQ(::indexed_db::mojom::Status::OK, callback_result);
}
TEST_F(IndexedDBDispatcherHostTest, AbortTransactionsWhileUpgrading) {
const int64_t kDBVersion = 1;
const int64_t kTransactionId = 1;
// Open connection.
TestDatabaseConnection connection(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion, kTransactionId);
IndexedDBDatabaseMetadata metadata;
DatabaseAssociatedPtrInfo database_info;
{
base::RunLoop loop;
EXPECT_CALL(
*connection.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info),
testing::SaveArg<4>(&metadata),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info.is_valid());
EXPECT_EQ(connection.version, metadata.version);
EXPECT_EQ(connection.db_name, metadata.name);
connection.database.Bind(std::move(database_info));
::indexed_db::mojom::Status callback_result =
::indexed_db::mojom::Status::IOError;
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(4, loop.QuitClosure());
const url::Origin origin = url::Origin::Create(GURL(kOrigin));
EXPECT_CALL(
*connection.connection_callbacks,
Abort(kTransactionId, blink::kWebIDBDatabaseExceptionUnknownError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.open_callbacks,
Error(blink::kWebIDBDatabaseExceptionAbortError, _))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection.connection_callbacks, ForcedClose())
.Times(1)
.WillOnce(RunClosure(quit_closure));
ASSERT_TRUE(connection.database.is_bound());
idb_mojo_factory_->AbortTransactionsForDatabase(
origin, base::BindOnce(&StatusCallback, std::move(quit_closure),
&callback_result));
loop.Run();
}
EXPECT_EQ(::indexed_db::mojom::Status::OK, callback_result);
}
// Flaky: crbug.com/772067
TEST_F(IndexedDBDispatcherHostTest, DISABLED_NotifyIndexedDBListChanged) {
const int64_t kDBVersion1 = 1;
const int64_t kDBVersion2 = 2;
const int64_t kDBVersion3 = 3;
const int64_t kTransactionId1 = 1;
const int64_t kTransactionId2 = 2;
const int64_t kTransactionId3 = 3;
const int64_t kObjectStoreId = 10;
const int64_t kIndexId = 100;
const char kObjectStoreName[] = "os";
const char kIndexName[] = "index";
TestIndexedDBObserver observer;
context_impl_->AddObserver(&observer);
// Open connection 1.
TestDatabaseConnection connection1(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion1, kTransactionId1);
IndexedDBDatabaseMetadata metadata1;
DatabaseAssociatedPtrInfo database_info1;
EXPECT_EQ(0, observer.notify_list_changed_count);
{
base::RunLoop loop;
EXPECT_CALL(
*connection1.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info1),
testing::SaveArg<4>(&metadata1),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection1.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info1.is_valid());
EXPECT_EQ(connection1.version, metadata1.version);
EXPECT_EQ(connection1.db_name, metadata1.name);
// Create object store and index.
connection1.database.Bind(std::move(database_info1));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection1.connection_callbacks, Complete(kTransactionId1))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection1.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection1.database.is_bound());
connection1.database->CreateObjectStore(kTransactionId1, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
connection1.database->CreateIndex(kTransactionId1, kObjectStoreId, kIndexId,
base::UTF8ToUTF16(kIndexName),
content::IndexedDBKeyPath(), false,
false);
connection1.database->Commit(kTransactionId1);
loop.Run();
}
EXPECT_EQ(2, observer.notify_list_changed_count);
connection1.database->Close();
// Open connection 2.
TestDatabaseConnection connection2(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion2, kTransactionId2);
IndexedDBDatabaseMetadata metadata2;
DatabaseAssociatedPtrInfo database_info2;
{
::testing::InSequence dummy;
base::RunLoop loop;
EXPECT_CALL(*connection2.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
kDBVersion1, blink::kWebIDBDataLossNone,
std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info2),
testing::SaveArg<4>(&metadata2),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection2.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info2.is_valid());
EXPECT_EQ(connection2.version, metadata2.version);
EXPECT_EQ(connection2.db_name, metadata2.name);
// Delete index.
connection2.database.Bind(std::move(database_info2));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection2.connection_callbacks, Complete(kTransactionId2))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection2.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection2.database.is_bound());
connection2.database->DeleteIndex(kTransactionId2, kObjectStoreId,
kIndexId);
connection2.database->Commit(kTransactionId2);
loop.Run();
}
EXPECT_EQ(3, observer.notify_list_changed_count);
connection2.database->Close();
// Open connection 3.
TestDatabaseConnection connection3(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion3, kTransactionId3);
IndexedDBDatabaseMetadata metadata3;
DatabaseAssociatedPtrInfo database_info3;
{
::testing::InSequence dummy;
base::RunLoop loop;
EXPECT_CALL(*connection3.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
kDBVersion2, blink::kWebIDBDataLossNone,
std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info3),
testing::SaveArg<4>(&metadata3),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection3.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info3.is_valid());
EXPECT_EQ(connection3.version, metadata3.version);
EXPECT_EQ(connection3.db_name, metadata3.name);
// Delete object store.
connection3.database.Bind(std::move(database_info3));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(2, loop.QuitClosure());
EXPECT_CALL(*connection3.connection_callbacks, Complete(kTransactionId3))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection3.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection3.database.is_bound());
connection3.database->DeleteObjectStore(kTransactionId3, kObjectStoreId);
connection3.database->Commit(kTransactionId3);
loop.Run();
}
EXPECT_EQ(4, observer.notify_list_changed_count);
context_impl_->RemoveObserver(&observer);
}
TEST_F(IndexedDBDispatcherHostTest, NotifyIndexedDBContentChanged) {
const int64_t kDBVersion1 = 1;
const int64_t kDBVersion2 = 2;
const int64_t kTransactionId1 = 1;
const int64_t kTransactionId2 = 2;
const int64_t kObjectStoreId = 10;
const char kObjectStoreName[] = "os";
TestIndexedDBObserver observer;
context_impl_->AddObserver(&observer);
// Open connection 1.
TestDatabaseConnection connection1(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion1, kTransactionId1);
IndexedDBDatabaseMetadata metadata1;
DatabaseAssociatedPtrInfo database_info1;
EXPECT_EQ(0, observer.notify_list_changed_count);
EXPECT_EQ(0, observer.notify_content_changed_count);
{
base::RunLoop loop;
EXPECT_CALL(
*connection1.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
IndexedDBDatabaseMetadata::NO_VERSION,
blink::kWebIDBDataLossNone, std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info1),
testing::SaveArg<4>(&metadata1),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection1.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info1.is_valid());
EXPECT_EQ(connection1.version, metadata1.version);
EXPECT_EQ(connection1.db_name, metadata1.name);
// Add object store entry.
connection1.database.Bind(std::move(database_info1));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(3, loop.QuitClosure());
auto put_callbacks =
std::make_unique<StrictMock<MockMojoIndexedDBCallbacks>>();
EXPECT_CALL(*put_callbacks, SuccessKey(_))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection1.connection_callbacks, Complete(kTransactionId1))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection1.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection1.database.is_bound());
connection1.database->CreateObjectStore(kTransactionId1, kObjectStoreId,
base::UTF8ToUTF16(kObjectStoreName),
content::IndexedDBKeyPath(), false);
connection1.database->Put(
kTransactionId1, kObjectStoreId,
::indexed_db::mojom::Value::New(
"value", std::vector<::indexed_db::mojom::BlobInfoPtr>()),
content::IndexedDBKey(base::UTF8ToUTF16("key")),
blink::kWebIDBPutModeAddOnly,
std::vector<content::IndexedDBIndexKeys>(),
put_callbacks->CreateInterfacePtrAndBind());
connection1.database->Commit(kTransactionId1);
loop.Run();
}
EXPECT_EQ(2, observer.notify_list_changed_count);
EXPECT_EQ(1, observer.notify_content_changed_count);
connection1.database->Close();
// Open connection 2.
TestDatabaseConnection connection2(url::Origin::Create(GURL(kOrigin)),
base::UTF8ToUTF16(kDatabaseName),
kDBVersion2, kTransactionId2);
IndexedDBDatabaseMetadata metadata2;
DatabaseAssociatedPtrInfo database_info2;
{
::testing::InSequence dummy;
base::RunLoop loop;
EXPECT_CALL(*connection2.open_callbacks,
MockedUpgradeNeeded(IsAssociatedInterfacePtrInfoValid(true),
kDBVersion1, blink::kWebIDBDataLossNone,
std::string(), _))
.WillOnce(testing::DoAll(MoveArg<0>(&database_info2),
testing::SaveArg<4>(&metadata2),
RunClosure(loop.QuitClosure())));
// Queue open request message.
connection2.Open(idb_mojo_factory_.get());
loop.Run();
}
EXPECT_TRUE(database_info2.is_valid());
EXPECT_EQ(connection2.version, metadata2.version);
EXPECT_EQ(connection2.db_name, metadata2.name);
// Clear object store.
connection2.database.Bind(std::move(database_info2));
{
::testing::InSequence dummy;
base::RunLoop loop;
base::Closure quit_closure = base::BarrierClosure(3, loop.QuitClosure());
auto clear_callbacks =
std::make_unique<StrictMock<MockMojoIndexedDBCallbacks>>();
EXPECT_CALL(*clear_callbacks, Success())
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(*connection2.connection_callbacks, Complete(kTransactionId2))
.Times(1)
.WillOnce(RunClosure(quit_closure));
EXPECT_CALL(
*connection2.open_callbacks,
MockedSuccessDatabase(IsAssociatedInterfacePtrInfoValid(false), _))
.Times(1)
.WillOnce(RunClosure(std::move(quit_closure)));
ASSERT_TRUE(connection2.database.is_bound());
connection2.database->Clear(kTransactionId2, kObjectStoreId,
clear_callbacks->CreateInterfacePtrAndBind());
connection2.database->Commit(kTransactionId2);
loop.Run();
}
EXPECT_EQ(3, observer.notify_list_changed_count);
EXPECT_EQ(2, observer.notify_content_changed_count);
context_impl_->RemoveObserver(&observer);
}
} // namespace content
|
/*
* 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.
*
*/
#include <string.h>
#include "math/Helpers.hh"
#include "math/Matrix4.hh"
#include "math/Quaternion.hh"
#include "math/Pose.hh"
using namespace gazebo;
using namespace math;
const Matrix4 Matrix4::IDENTITY(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
const Matrix4 Matrix4::ZERO(
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0);
//////////////////////////////////////////////////
Matrix4::Matrix4()
{
memset(this->m, 0, sizeof(this->m[0][0])*16);
}
//////////////////////////////////////////////////
Matrix4::Matrix4(const Matrix4 &_m)
{
memcpy(this->m, _m.m, sizeof(this->m[0][0])*16);
}
//////////////////////////////////////////////////
Matrix4::Matrix4(double _v00, double _v01, double _v02, double _v03,
double _v10, double _v11, double _v12, double _v13,
double _v20, double _v21, double _v22, double _v23,
double _v30, double _v31, double _v32, double _v33)
{
this->Set(_v00, _v01, _v02, _v03,
_v10, _v11, _v12, _v13,
_v20, _v21, _v22, _v23,
_v30, _v31, _v32, _v33);
}
//////////////////////////////////////////////////
Matrix4::~Matrix4()
{
}
//////////////////////////////////////////////////
void Matrix4::Set(double _v00, double _v01, double _v02, double _v03,
double _v10, double _v11, double _v12, double _v13,
double _v20, double _v21, double _v22, double _v23,
double _v30, double _v31, double _v32, double _v33)
{
this->m[0][0] = _v00;
this->m[0][1] = _v01;
this->m[0][2] = _v02;
this->m[0][3] = _v03;
this->m[1][0] = _v10;
this->m[1][1] = _v11;
this->m[1][2] = _v12;
this->m[1][3] = _v13;
this->m[2][0] = _v20;
this->m[2][1] = _v21;
this->m[2][2] = _v22;
this->m[2][3] = _v23;
this->m[3][0] = _v30;
this->m[3][1] = _v31;
this->m[3][2] = _v32;
this->m[3][3] = _v33;
}
//////////////////////////////////////////////////
void Matrix4::SetTranslate(const Vector3 &_t)
{
this->m[0][3] = _t.x;
this->m[1][3] = _t.y;
this->m[2][3] = _t.z;
}
//////////////////////////////////////////////////
Vector3 Matrix4::GetTranslation() const
{
return Vector3(this->m[0][3], this->m[1][3], this->m[2][3]);
}
//////////////////////////////////////////////////
Quaternion Matrix4::GetRotation() const
{
Quaternion q;
/// algorithm from Ogre::Quaternion source, which in turn is based on
/// Ken Shoemake's article "Quaternion Calculus and Fast Animation".
double trace = this->m[0][0] + this->m[1][1] + this->m[2][2];
double root;
if (trace > 0)
{
root = sqrt(trace + 1.0);
q.w = root / 2.0;
root = 1.0 / (2.0 * root);
q.x = (this->m[2][1] - this->m[1][2]) * root;
q.y = (this->m[0][2] - this->m[2][0]) * root;
q.z = (this->m[1][0] - this->m[0][1]) * root;
}
else
{
static unsigned int s_iNext[3] = {1, 2, 0};
unsigned int i = 0;
if (this->m[1][1] > this->m[0][0])
i = 1;
if (this->m[2][2] > this->m[i][i])
i = 2;
unsigned int j = s_iNext[i];
unsigned int k = s_iNext[j];
root = sqrt(this->m[i][i] - this->m[j][j] - this->m[k][k] + 1.0);
double* xyzQ[3] = { &q.x, &q.y, &q.z};
*xyzQ[i] = root / 2.0;
root = 1.0 / (2.0 * root);
q.w = (this->m[k][j] - this->m[j][k]) * root;
*xyzQ[j] = (this->m[j][i] + this->m[i][j]) * root;
*xyzQ[k] = (this->m[k][i] + this->m[i][k]) * root;
}
return q;
}
//////////////////////////////////////////////////
Vector3 Matrix4::GetEulerRotation(unsigned int solution_number) const
{
Vector3 euler;
Vector3 euler2;
double m31 = this->m[2][0];
double m11 = this->m[0][0];
double m12 = this->m[0][1];
double m13 = this->m[0][2];
double m32 = this->m[2][1];
double m33 = this->m[2][2];
double m21 = this->m[1][0];
if (fabs(m31) >= 1.0)
{
euler.z = 0.0;
euler2.z = 0.0;
if (m31 < 0.0)
{
euler.y = M_PI / 2.0;
euler2.y = M_PI / 2.0;
euler.x = atan2(m12, m13);
euler2.x = atan2(m12, m13);
}
else
{
euler.y = -M_PI / 2.0;
euler2.y = -M_PI / 2.0;
euler.x = atan2(-m12, -m13);
euler2.x = atan2(-m12, -m13);
}
}
else
{
euler.y = -asin(m31);
euler2.y = M_PI - euler.y;
euler.x = atan2(m32 / cos(euler.y), m33 / cos(euler.y));
euler2.x = atan2(m32 / cos(euler2.y), m33 / cos(euler2.y));
euler.z = atan2(m21 / cos(euler.y), m11 / cos(euler.y));
euler2.z = atan2(m21 / cos(euler2.y), m11 / cos(euler2.y));
}
if (solution_number == 1)
return euler;
else
return euler2;
}
//////////////////////////////////////////////////
void Matrix4::SetScale(const Vector3 &_s)
{
this->m[0][0] = _s.x;
this->m[1][1] = _s.y;
this->m[2][2] = _s.z;
this->m[3][3] = 1.0;
}
//////////////////////////////////////////////////
Matrix4 &Matrix4::operator =(const Matrix4 &_mat)
{
memcpy(this->m, _mat.m, sizeof(this->m[0][0])*16);
return *this;
}
//////////////////////////////////////////////////
const Matrix4 &Matrix4::operator =(const Matrix3 &mat)
{
this->m[0][0] = mat.m[0][0];
this->m[0][1] = mat.m[0][1];
this->m[0][2] = mat.m[0][2];
this->m[1][0] = mat.m[1][0];
this->m[1][1] = mat.m[1][1];
this->m[1][2] = mat.m[1][2];
this->m[2][0] = mat.m[2][0];
this->m[2][1] = mat.m[2][1];
this->m[2][2] = mat.m[2][2];
return *this;
}
//////////////////////////////////////////////////
Matrix4 Matrix4::operator*(const Matrix3 &m2) const
{
Matrix4 r;
r = *this;
r.m[0][0] = m[0][0]*m2.m[0][0] + m[0][1]*m2.m[1][0] + m[0][2] * m2.m[2][0];
r.m[0][1] = m[0][0]*m2.m[0][1] + m[0][1]*m2.m[1][1] + m[0][2] * m2.m[2][1];
r.m[0][2] = m[0][0]*m2.m[0][2] + m[0][1]*m2.m[1][2] + m[0][2] * m2.m[2][2];
r.m[1][0] = m[1][0]*m2.m[0][0] + m[1][1]*m2.m[1][0] + m[1][2] * m2.m[2][0];
r.m[1][1] = m[1][0]*m2.m[0][1] + m[1][1]*m2.m[1][1] + m[1][2] * m2.m[2][1];
r.m[1][2] = m[1][0]*m2.m[0][2] + m[1][1]*m2.m[1][2] + m[1][2] * m2.m[2][2];
r.m[2][0] = m[2][0]*m2.m[0][0] + m[2][1]*m2.m[1][0] + m[2][2] * m2.m[2][0];
r.m[2][1] = m[2][0]*m2.m[0][1] + m[2][1]*m2.m[1][1] + m[2][2] * m2.m[2][1];
r.m[2][2] = m[2][0]*m2.m[0][2] + m[2][1]*m2.m[1][2] + m[2][2] * m2.m[2][2];
return r;
}
//////////////////////////////////////////////////
Matrix4 Matrix4::operator*(const Matrix4 &m2) const
{
Matrix4 r;
r.m[0][0] = this->m[0][0] * m2.m[0][0] +
this->m[0][1] * m2.m[1][0] +
this->m[0][2] * m2.m[2][0] +
this->m[0][3] * m2.m[3][0];
r.m[0][1] = this->m[0][0] * m2.m[0][1] +
this->m[0][1] * m2.m[1][1] +
this->m[0][2] * m2.m[2][1] +
this->m[0][3] * m2.m[3][1];
r.m[0][2] = this->m[0][0] * m2.m[0][2] +
this->m[0][1] * m2.m[1][2] +
this->m[0][2] * m2.m[2][2] +
this->m[0][3] * m2.m[3][2];
r.m[0][3] = this->m[0][0] * m2.m[0][3] +
this->m[0][1] * m2.m[1][3] +
this->m[0][2] * m2.m[2][3] +
this->m[0][3] * m2.m[3][3];
r.m[1][0] = this->m[1][0] * m2.m[0][0] +
this->m[1][1] * m2.m[1][0] +
this->m[1][2] * m2.m[2][0] +
this->m[1][3] * m2.m[3][0];
r.m[1][1] = this->m[1][0] * m2.m[0][1] +
this->m[1][1] * m2.m[1][1] +
this->m[1][2] * m2.m[2][1] +
this->m[1][3] * m2.m[3][1];
r.m[1][2] = this->m[1][0] * m2.m[0][2] +
this->m[1][1] * m2.m[1][2] +
this->m[1][2] * m2.m[2][2] +
this->m[1][3] * m2.m[3][2];
r.m[1][3] = this->m[1][0] * m2.m[0][3] +
this->m[1][1] * m2.m[1][3] +
this->m[1][2] * m2.m[2][3] +
this->m[1][3] * m2.m[3][3];
r.m[2][0] = this->m[2][0] * m2.m[0][0] +
this->m[2][1] * m2.m[1][0] +
this->m[2][2] * m2.m[2][0] +
this->m[2][3] * m2.m[3][0];
r.m[2][1] = this->m[2][0] * m2.m[0][1] +
this->m[2][1] * m2.m[1][1] +
this->m[2][2] * m2.m[2][1] +
this->m[2][3] * m2.m[3][1];
r.m[2][2] = this->m[2][0] * m2.m[0][2] +
this->m[2][1] * m2.m[1][2] +
this->m[2][2] * m2.m[2][2] +
this->m[2][3] * m2.m[3][2];
r.m[2][3] = this->m[2][0] * m2.m[0][3] +
this->m[2][1] * m2.m[1][3] +
this->m[2][2] * m2.m[2][3] +
this->m[2][3] * m2.m[3][3];
r.m[3][0] = this->m[3][0] * m2.m[0][0] +
this->m[3][1] * m2.m[1][0] +
this->m[3][2] * m2.m[2][0] +
this->m[3][3] * m2.m[3][0];
r.m[3][1] = this->m[3][0] * m2.m[0][1] +
this->m[3][1] * m2.m[1][1] +
this->m[3][2] * m2.m[2][1] +
this->m[3][3] * m2.m[3][1];
r.m[3][2] = this->m[3][0] * m2.m[0][2] +
this->m[3][1] * m2.m[1][2] +
this->m[3][2] * m2.m[2][2] +
this->m[3][3] * m2.m[3][2];
r.m[3][3] = this->m[3][0] * m2.m[0][3] +
this->m[3][1] * m2.m[1][3] +
this->m[3][2] * m2.m[2][3] +
this->m[3][3] * m2.m[3][3];
return r;
}
//////////////////////////////////////////////////
Vector3 Matrix4::operator*(const Vector3 &_vec) const
{
Vector3 result;
result.x = this->m[0][0]*_vec.x + this->m[0][1]*_vec.y +
this->m[0][2]*_vec.z + this->m[0][3];
result.y = this->m[1][0]*_vec.x + this->m[1][1]*_vec.y +
this->m[1][2]*_vec.z + this->m[1][3];
result.z = this->m[2][0]*_vec.x + this->m[2][1]*_vec.y +
this->m[2][2]*_vec.z + this->m[2][3];
return result;
}
//////////////////////////////////////////////////
bool Matrix4::IsAffine() const
{
return equal(this->m[3][0], 0.0) && equal(this->m[3][1], 0.0) &&
equal(this->m[3][2], 0.0) && equal(this->m[3][3], 1.0);
}
//////////////////////////////////////////////////
Vector3 Matrix4::TransformAffine(const Vector3 &_v) const
{
if (!this->IsAffine())
{
throw(std::string("Not and affine matrix"));
}
return Vector3(this->m[0][0]*_v.x + this->m[0][1]*_v.y +
this->m[0][2]*_v.z + this->m[0][3],
this->m[1][0]*_v.x + this->m[1][1]*_v.y +
this->m[1][2]*_v.z + this->m[1][3],
this->m[2][0]*_v.x + this->m[2][1]*_v.y +
this->m[2][2]*_v.z + this->m[2][3]);
}
//////////////////////////////////////////////////
bool Matrix4::operator==(const Matrix4 &_m) const
{
return math::equal(this->m[0][0], _m[0][0]) &&
math::equal(this->m[0][1], _m[0][1]) &&
math::equal(this->m[0][2], _m[0][2]) &&
math::equal(this->m[0][3], _m[0][3]) &&
math::equal(this->m[1][0], _m[1][0]) &&
math::equal(this->m[1][1], _m[1][1]) &&
math::equal(this->m[1][2], _m[1][2]) &&
math::equal(this->m[1][3], _m[1][3]) &&
math::equal(this->m[2][0], _m[2][0]) &&
math::equal(this->m[2][1], _m[2][1]) &&
math::equal(this->m[2][2], _m[2][2]) &&
math::equal(this->m[2][3], _m[2][3]) &&
math::equal(this->m[3][0], _m[3][0]) &&
math::equal(this->m[3][1], _m[3][1]) &&
math::equal(this->m[3][2], _m[3][2]) &&
math::equal(this->m[3][3], _m[3][3]);
}
//////////////////////////////////////////////////
Matrix4 Matrix4::Inverse() const
{
double v0 = this->m[2][0] * this->m[3][1] - this->m[2][1] * this->m[3][0];
double v1 = this->m[2][0] * this->m[3][2] - this->m[2][2] * this->m[3][0];
double v2 = this->m[2][0] * this->m[3][3] - this->m[2][3] * this->m[3][0];
double v3 = this->m[2][1] * this->m[3][2] - this->m[2][2] * this->m[3][1];
double v4 = this->m[2][1] * this->m[3][3] - this->m[2][3] * this->m[3][1];
double v5 = this->m[2][2] * this->m[3][3] - this->m[2][3] * this->m[3][2];
double t00 = + (v5 * this->m[1][1] - v4 * this->m[1][2] + v3 * this->m[1][3]);
double t10 = - (v5 * this->m[1][0] - v2 * this->m[1][2] + v1 * this->m[1][3]);
double t20 = + (v4 * this->m[1][0] - v2 * this->m[1][1] + v0 * this->m[1][3]);
double t30 = - (v3 * this->m[1][0] - v1 * this->m[1][1] + v0 * this->m[1][2]);
double invDet = 1 / (t00 * this->m[0][0] + t10 * this->m[0][1] +
t20 * this->m[0][2] + t30 * this->m[0][3]);
double d00 = t00 * invDet;
double d10 = t10 * invDet;
double d20 = t20 * invDet;
double d30 = t30 * invDet;
double d01 = - (v5 * this->m[0][1] - v4 * this->m[0][2] + v3 * this->m[0][3])
* invDet;
double d11 = + (v5 * this->m[0][0] - v2 * this->m[0][2] + v1 * this->m[0][3])
* invDet;
double d21 = - (v4 * this->m[0][0] - v2 * this->m[0][1] + v0 * this->m[0][3])
* invDet;
double d31 = + (v3 * this->m[0][0] - v1 * this->m[0][1] + v0 * this->m[0][2])
* invDet;
v0 = this->m[1][0] * this->m[3][1] - this->m[1][1] * this->m[3][0];
v1 = this->m[1][0] * this->m[3][2] - this->m[1][2] * this->m[3][0];
v2 = this->m[1][0] * this->m[3][3] - this->m[1][3] * this->m[3][0];
v3 = this->m[1][1] * this->m[3][2] - this->m[1][2] * this->m[3][1];
v4 = this->m[1][1] * this->m[3][3] - this->m[1][3] * this->m[3][1];
v5 = this->m[1][2] * this->m[3][3] - this->m[1][3] * this->m[3][2];
double d02 = + (v5 * this->m[0][1] - v4 * this->m[0][2] + v3 * this->m[0][3])
* invDet;
double d12 = - (v5 * this->m[0][0] - v2 * this->m[0][2] + v1 * this->m[0][3])
* invDet;
double d22 = + (v4 * this->m[0][0] - v2 * this->m[0][1] + v0 * this->m[0][3])
* invDet;
double d32 = - (v3 * this->m[0][0] - v1 * this->m[0][1] + v0 * this->m[0][2])
* invDet;
v0 = this->m[2][1] * this->m[1][0] - this->m[2][0] * this->m[1][1];
v1 = this->m[2][2] * this->m[1][0] - this->m[2][0] * this->m[1][2];
v2 = this->m[2][3] * this->m[1][0] - this->m[2][0] * this->m[1][3];
v3 = this->m[2][2] * this->m[1][1] - this->m[2][1] * this->m[1][2];
v4 = this->m[2][3] * this->m[1][1] - this->m[2][1] * this->m[1][3];
v5 = this->m[2][3] * this->m[1][2] - this->m[2][2] * this->m[1][3];
double d03 = - (v5 * this->m[0][1] - v4 * this->m[0][2] + v3 * this->m[0][3])
* invDet;
double d13 = + (v5 * this->m[0][0] - v2 * this->m[0][2] + v1 * this->m[0][3])
* invDet;
double d23 = - (v4 * this->m[0][0] - v2 * this->m[0][1] + v0 * this->m[0][3])
* invDet;
double d33 = + (v3 * this->m[0][0] - v1 * this->m[0][1] + v0 * this->m[0][2])
* invDet;
return Matrix4(d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33);
}
//////////////////////////////////////////////////
math::Pose Matrix4::GetAsPose() const
{
return math::Pose(this->GetTranslation(), this->GetRotation());
}
|
/**
\file stringutils.cpp
\maintainer Morgan McGuire, http://graphics.cs.williams.edu
\created 2000-09-09
\edited 2011-08-20
*/
#include "G3D/platform.h"
#include "G3D/stringutils.h"
#include "G3D/BinaryInput.h"
#include <algorithm>
#ifdef G3D_WINDOWS
extern "C" {
// Define functions for ffmpeg since we don't link in gcc's c library
extern int strncasecmp(const char *string1, const char *string2, size_t count) { return _strnicmp(string1, string2, count); }
extern int strcasecmp(const char *string1, const char *string2) { return _stricmp(string1, string2); }
}
#endif
namespace G3D {
#ifdef _MSC_VER
// disable: "C++ exception handler used"
# pragma warning (push)
# pragma warning (disable : 4530)
#endif
#ifdef G3D_WINDOWS
const char* NEWLINE = "\r\n";
#else
const char* NEWLINE = "\n";
static bool iswspace(int ch) { return (ch==' ' || ch=='\t' || ch=='\n' || ch=='\r'); }
#endif
void parseCommaSeparated(const std::string s, Array<std::string>& array, bool stripQuotes) {
array.fastClear();
if (s == "") {
return;
}
size_t begin = 0;
const char delimiter = ',';
const char quote = '\"';
do {
size_t end = begin;
// Find the next comma, or the end of the string
bool inQuotes = false;
while ((end < s.length()) && (inQuotes || (s[end] != delimiter))) {
if (s[end] == quote) {
if ((end < s.length() - 2) && (s[end + 1] == quote) && (s[end + 2]) == quote) {
// Skip over the superquote
end += 2;
}
inQuotes = ! inQuotes;
}
++end;
}
array.append(s.substr(begin, end - begin));
begin = end + 1;
} while (begin < s.length());
if (stripQuotes) {
for (int i = 0; i < array.length(); ++i) {
std::string& t = array[i];
size_t L = t.length();
if ((L > 1) && (t[0] == quote) && (t[L - 1] == quote)) {
if ((L > 6) && (t[1] == quote) && (t[2] == quote) && (t[L - 3] == quote) && (t[L - 2] == quote)) {
// Triple-quote
t = t.substr(3, L - 6);
} else {
// Double-quote
t = t.substr(1, L - 2);
}
}
}
}
}
bool beginsWith(
const std::string& test,
const std::string& pattern) {
if (test.size() >= pattern.size()) {
for (int i = 0; i < (int)pattern.size(); ++i) {
if (pattern[i] != test[i]) {
return false;
}
}
return true;
} else {
return false;
}
}
std::string replace(const std::string& s, const std::string& pattern, const std::string& replacement) {
if (pattern.length() == 0) {
return s;
}
std::string temp = "";
size_t lastindex = 0;
size_t nextindex = 0;
do {
nextindex = s.find(pattern, lastindex);
if (nextindex == std::string::npos) {
break;
}
temp += s.substr(lastindex, nextindex - lastindex) + replacement;
lastindex = nextindex + pattern.length();
} while (lastindex + pattern.length() <= s.length());
return temp + (lastindex < s.length() ? s.substr(lastindex) : "");
}
bool isValidIdentifier(const std::string& s) {
if (s.length() > 0 && (isLetter(s[0]) || s[0] == '_')) {
for (size_t i = 1; i < s.length() ; ++i) {
if (!( isLetter(s[i]) || (s[i] == '_') || isDigit(s[i]) )) {
return false;
}
}
return true;
}
return false;
}
bool endsWith(
const std::string& test,
const std::string& pattern) {
if (test.size() >= pattern.size()) {
size_t te = test.size() - 1;
size_t pe = pattern.size() - 1;
for (int i = (int)pattern.size() - 1; i >= 0; --i) {
if (pattern[pe - i] != test[te - i]) {
return false;
}
}
return true;
} else {
return false;
}
}
std::string wordWrap(
const std::string& input,
int numCols) {
std::string output;
size_t c = 0;
int len;
// Don't make lines less than this length
int minLength = numCols / 4;
size_t inLen = input.size();
bool first = true;
while (c < inLen) {
if (first) {
first = false;
} else {
output += NEWLINE;
}
if ((int)inLen - (int)c - 1 < numCols) {
// The end
output += input.substr(c, inLen - c);
break;
}
len = numCols;
// Look at character c + numCols, see if it is a space.
while ((len > minLength) &&
(input[c + len] != ' ')) {
len--;
}
if (len == minLength) {
// Just crop
len = numCols;
}
output += input.substr(c, len);
c += len;
if (c < input.size()) {
// Collapse multiple spaces.
while ((input[c] == ' ') && (c < input.size())) {
++c;
}
}
}
return output;
}
int stringCompare(
const std::string& s1,
const std::string& s2) {
return stringPtrCompare(&s1, &s2);
}
int stringPtrCompare(
const std::string* s1,
const std::string* s2) {
return s1->compare(*s2);
}
std::string toUpper(const std::string& x) {
std::string result = x;
std::transform(result.begin(), result.end(), result.begin(), toupper);
return result;
}
std::string toLower(const std::string& x) {
std::string result = x;
std::transform(result.begin(), result.end(), result.begin(), tolower);
return result;
}
Array<std::string> stringSplit(
const std::string& x,
char splitChar) {
Array<std::string> out;
// Pointers to the beginning and end of the substring
const char* start = x.c_str();
const char* stop = start;
while ((stop = strchr(start, splitChar))) {
out.append(std::string(start, stop - start));
start = stop + 1;
}
// Append the last one
out.append(std::string(start));
return out;
}
std::string stringJoin(
const Array<std::string>& a,
char joinChar) {
std::string out;
for (int i = 0; i < (int)a.size() - 1; ++i) {
out += a[i] + joinChar;
}
if (a.size() > 0) {
return out + a.last();
} else {
return out;
}
}
std::string stringJoin(
const Array<std::string>& a,
const std::string& joinStr) {
std::string out;
for (int i = 0; i < (int)a.size() - 1; ++i) {
out += a[i] + joinStr;
}
if (a.size() > 0) {
return out + a.last();
} else {
return out;
}
}
std::string trimWhitespace(const std::string& s) {
if (s.length() == 0) {
return s;
}
size_t left = 0;
// Trim from left
while ((left < s.length()) && iswspace(s[left])) {
++left;
}
size_t right = s.length() - 1;
// Trim from right
while ((right > left) && iswspace(s[right])) {
--right;
}
return s.substr(left, right - left + 1);
}
}; // namespace
#undef NEWLINE
#ifdef _MSC_VER
# pragma warning (pop)
#endif
|
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gtest/gtest.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The TorkilCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientmodel.h"
#include "guiconstants.h"
#include "peertablemodel.h"
#include "alert.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "main.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "net.h"
#include "ui_interface.h"
#include "util.h"
#include <stdint.h>
#include <QDateTime>
#include <QDebug>
#include <QTimer>
static const int64_t nClientStartupTime = GetTime();
ClientModel::ClientModel(OptionsModel* optionsModel, QObject* parent) : QObject(parent),
optionsModel(optionsModel),
peerTableModel(0),
cachedNumBlocks(0),
cachedMasternodeCountString(""),
cachedReindexing(0), cachedImporting(0),
numBlocksAtStartup(-1), pollTimer(0)
{
peerTableModel = new PeerTableModel(this);
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
pollTimer->start(MODEL_UPDATE_DELAY);
pollMnTimer = new QTimer(this);
connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer()));
// no need to update as frequent as data for balances/txes/blocks
pollMnTimer->start(MODEL_UPDATE_DELAY * 4);
subscribeToCoreSignals();
}
ClientModel::~ClientModel()
{
unsubscribeFromCoreSignals();
}
int ClientModel::getNumConnections(unsigned int flags) const
{
LOCK(cs_vNodes);
if (flags == CONNECTIONS_ALL) // Shortcut if we want total
return vNodes.size();
int nNum = 0;
BOOST_FOREACH (CNode* pnode, vNodes)
if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT))
nNum++;
return nNum;
}
QString ClientModel::getMasternodeCountString() const
{
return tr("Total: %1 (OBF compatible: %2 / Enabled: %3)").arg(QString::number((int)mnodeman.size())).arg(QString::number((int)mnodeman.CountEnabled(ActiveProtocol()))).arg(QString::number((int)mnodeman.CountEnabled()));
}
int ClientModel::getNumBlocks() const
{
LOCK(cs_main);
return chainActive.Height();
}
int ClientModel::getNumBlocksAtStartup()
{
if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
return numBlocksAtStartup;
}
quint64 ClientModel::getTotalBytesRecv() const
{
return CNode::GetTotalBytesRecv();
}
quint64 ClientModel::getTotalBytesSent() const
{
return CNode::GetTotalBytesSent();
}
QDateTime ClientModel::getLastBlockDate() const
{
LOCK(cs_main);
if (chainActive.Tip())
return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime());
else
return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network
}
double ClientModel::getVerificationProgress() const
{
LOCK(cs_main);
return Checkpoints::GuessVerificationProgress(chainActive.Tip());
}
void ClientModel::updateTimer()
{
// Get required lock upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if (!lockMain)
return;
// Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
// Periodically check and update with a timer.
int newNumBlocks = getNumBlocks();
static int prevAttempt = -1;
static int prevAssets = -1;
// check for changed number of blocks we have, number of blocks peers claim to have, reindexing state and importing state
if (cachedNumBlocks != newNumBlocks ||
cachedReindexing != fReindex || cachedImporting != fImporting ||
masternodeSync.RequestedMasternodeAttempt != prevAttempt || masternodeSync.RequestedMasternodeAssets != prevAssets) {
cachedNumBlocks = newNumBlocks;
cachedReindexing = fReindex;
cachedImporting = fImporting;
prevAttempt = masternodeSync.RequestedMasternodeAttempt;
prevAssets = masternodeSync.RequestedMasternodeAssets;
emit numBlocksChanged(newNumBlocks);
}
emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}
void ClientModel::updateMnTimer()
{
// Get required lock upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if (!lockMain)
return;
QString newMasternodeCountString = getMasternodeCountString();
if (cachedMasternodeCountString != newMasternodeCountString) {
cachedMasternodeCountString = newMasternodeCountString;
emit strMasternodesChanged(cachedMasternodeCountString);
}
}
void ClientModel::updateNumConnections(int numConnections)
{
emit numConnectionsChanged(numConnections);
}
void ClientModel::updateAlert(const QString& hash, int status)
{
// Show error message notification for new alert
if (status == CT_NEW) {
uint256 hash_256;
hash_256.SetHex(hash.toStdString());
CAlert alert = CAlert::getAlertByHash(hash_256);
if (!alert.IsNull()) {
emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR);
}
}
emit alertsChanged(getStatusBarWarnings());
}
bool ClientModel::inInitialBlockDownload() const
{
return IsInitialBlockDownload();
}
enum BlockSource ClientModel::getBlockSource() const
{
if (fReindex)
return BLOCK_SOURCE_REINDEX;
else if (fImporting)
return BLOCK_SOURCE_DISK;
else if (getNumConnections() > 0)
return BLOCK_SOURCE_NETWORK;
return BLOCK_SOURCE_NONE;
}
QString ClientModel::getStatusBarWarnings() const
{
return QString::fromStdString(GetWarnings("statusbar"));
}
OptionsModel* ClientModel::getOptionsModel()
{
return optionsModel;
}
PeerTableModel* ClientModel::getPeerTableModel()
{
return peerTableModel;
}
QString ClientModel::formatFullVersion() const
{
return QString::fromStdString(FormatFullVersion());
}
QString ClientModel::formatBuildDate() const
{
return QString::fromStdString(CLIENT_DATE);
}
bool ClientModel::isReleaseVersion() const
{
return CLIENT_VERSION_IS_RELEASE;
}
QString ClientModel::clientName() const
{
return QString::fromStdString(CLIENT_NAME);
}
QString ClientModel::formatClientStartupTime() const
{
return QDateTime::fromTime_t(nClientStartupTime).toString();
}
// Handlers for core signals
static void ShowProgress(ClientModel* clientmodel, const std::string& title, int nProgress)
{
// emits signal "showProgress"
QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(title)),
Q_ARG(int, nProgress));
}
static void NotifyNumConnectionsChanged(ClientModel* clientmodel, int newNumConnections)
{
// Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections);
QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
Q_ARG(int, newNumConnections));
}
static void NotifyAlertChanged(ClientModel* clientmodel, const uint256& hash, ChangeType status)
{
qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status);
QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(hash.GetHex())),
Q_ARG(int, status));
}
void ClientModel::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
void ClientModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
|
//
// Copyright (c) 2014-present, Facebook, Inc.
// Copyright (c) 2015, Jakub Klama <jakub@ixsystems.com>
// All rights reserved.
//
// This source code is licensed under the University of Illinois/NCSA Open
// Source 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.
//
#include "DebugServer2/Host/NetBSD/PTrace.h"
#include "DebugServer2/Architecture/X86/RegisterCopy.h"
#include "DebugServer2/Host/Platform.h"
#include <elf.h>
#include <machine/fpu.h>
#include <machine/reg.h>
#include <sys/ptrace.h>
#include <sys/uio.h>
#include <sys/user.h>
#define super ds2::Host::POSIX::PTrace
namespace ds2 {
namespace Host {
namespace NetBSD {
//
// 32-bits helpers
//
static inline void user_to_state32(ds2::Architecture::X86_64::CPUState32 &state,
struct fpreg const &user) {
//
// X87 State
//
struct env87 *x87 = (struct env87 *)&user;
state.x87.fstw = x87->en_sw;
state.x87.fctw = x87->en_cw;
state.x87.ftag = x87->en_tw;
state.x87.fioff = x87->en_fip;
state.x87.fiseg = x87->en_fcs;
state.x87.fop = x87->en_opcode;
state.x87.fooff = x87->en_foo;
state.x87.foseg = x87->en_fos;
uint8_t const *st_space = reinterpret_cast<uint8_t const *>(user.fpr_acc);
for (size_t n = 0; n < 8; n++) {
memcpy(state.x87.regs[n].data, st_space + n * 10,
sizeof(state.x87.regs[n].data));
}
//
// SSE State
//
struct envxmm *xmm = (struct envxmm *)&user.fpr_env;
state.sse.mxcsr = xmm->en_mxcsr;
state.sse.mxcsrmask = xmm->en_mxcsr_mask;
uint8_t const *xmm_space = reinterpret_cast<uint8_t const *>(user.fpr_xacc);
for (size_t n = 0; n < 8; n++) {
memcpy(&state.sse.regs[n], xmm_space + n * 16, sizeof(state.sse.regs[n]));
}
}
static inline void
state32_to_user(struct fpreg &user,
ds2::Architecture::X86_64::CPUState32 const &state) {
//
// X87 State
//
struct env87 *x87 = (struct env87 *)&user.fpr_env;
x87->en_sw = state.x87.fstw;
x87->en_cw = state.x87.fctw;
x87->en_tw = state.x87.ftag;
x87->en_fip = state.x87.fioff;
x87->en_fcs = state.x87.fiseg;
x87->en_opcode = state.x87.fop;
x87->en_foo = state.x87.fooff;
x87->en_fos = state.x87.foseg;
uint8_t *st_space = reinterpret_cast<uint8_t *>(user.fpr_acc);
for (size_t n = 0; n < 8; n++) {
memcpy(st_space + n * 10, state.x87.regs[n].data,
sizeof(state.x87.regs[n].data));
}
//
// SSE State
//
struct envxmm *xmm = (struct envxmm *)&user.fpr_env;
xmm->en_mxcsr = state.sse.mxcsr;
xmm->en_mxcsr_mask = state.sse.mxcsrmask;
uint8_t *xmm_space = reinterpret_cast<uint8_t *>(user.fpr_xacc);
for (size_t n = 0; n < 8; n++) {
memcpy(xmm_space + n * 16, &state.sse.regs[n], sizeof(state.sse.regs[n]));
}
}
//
// 64-bit helpers
//
static inline void user_to_state64(ds2::Architecture::X86_64::CPUState64 &state,
struct fpreg const &user) {
//
// X87 State
//
struct env87 *x87 = (struct env87 *)&user;
state.x87.fstw = x87->en_sw;
state.x87.fctw = x87->en_cw;
state.x87.ftag = x87->en_tw;
// state.x87.fop = user.r_fop;
// state.x87.firip = user.r_rip;
// state.x87.forip = user.r_rdp;
uint8_t const *st_space = reinterpret_cast<uint8_t const *>(user.fpr_acc);
for (size_t n = 0; n < 8; n++) {
memcpy(state.x87.regs[n].data, st_space + n * 10,
sizeof(state.x87.regs[n].data));
}
//
// SSE State
//
struct envxmm *xmm = (struct envxmm *)&user.fpr_env;
state.sse.mxcsr = xmm->en_mxcsr;
state.sse.mxcsrmask = xmm->en_mxcsr_mask;
uint8_t const *xmm_space = reinterpret_cast<uint8_t const *>(user.fpr_xacc);
for (size_t n = 0; n < 16; n++) {
memcpy(&state.sse.regs[n], xmm_space + n * 16, sizeof(state.sse.regs[n]));
}
}
static inline void
state64_to_user(struct fpreg &user,
ds2::Architecture::X86_64::CPUState64 const &state) {
//
// X87 State
//
struct env87 *x87 = (struct env87 *)&user;
x87->en_sw = state.x87.fstw;
x87->en_cw = state.x87.fctw;
x87->en_tw = state.x87.ftag;
// user.r_fop = state.x87.fop;
// user.r_rip = state.x87.firip;
// user.r_rdp = state.x87.forip;
uint8_t *st_space = reinterpret_cast<uint8_t *>(user.fpr_acc);
for (size_t n = 0; n < 8; n++) {
memcpy(st_space + n * 16, state.x87.regs[n].data,
sizeof(state.x87.regs[n].data));
}
//
// SSE State
//
struct envxmm *xmm = (struct envxmm *)&user.fpr_env;
xmm->en_mxcsr = state.sse.mxcsr;
xmm->en_mxcsr_mask = state.sse.mxcsrmask;
uint8_t *xmm_space = reinterpret_cast<uint8_t *>(user.fpr_xacc);
for (size_t n = 0; n < 16; n++) {
memcpy(xmm_space + n * 16, &state.sse.regs[n], sizeof(state.sse.regs[n]));
}
}
ErrorCode PTrace::readCPUState(ProcessThreadId const &ptid,
ProcessInfo const &pinfo,
Architecture::CPUState &state) {
pid_t pid;
CHK(ptidToPid(ptid, pid));
//
// Read GPRs
//
struct reg gprs;
if (wrapPtrace(PT_GETREGS, pid, &gprs, nullptr) < 0)
return Platform::TranslateError();
if (pinfo.pointerSize == sizeof(uint32_t)) {
state.is32 = true;
Architecture::X86::user_to_state32(state.state32, gprs);
} else {
state.is32 = false;
Architecture::X86::user_to_state64(state.state64, gprs);
}
//
// Read X87 and SSE state
//
struct fpreg fprs;
if (wrapPtrace(PT_GETFPREGS, pid, &fprs, nullptr) == 0) {
if (pinfo.pointerSize == sizeof(uint32_t)) {
user_to_state32(state.state32, fprs);
} else {
user_to_state64(state.state64, fprs);
}
}
return kSuccess;
}
ErrorCode PTrace::writeCPUState(ProcessThreadId const &ptid,
ProcessInfo const &pinfo,
Architecture::CPUState const &state) {
pid_t pid;
CHK(ptidToPid(ptid, pid));
if (pinfo.pointerSize == sizeof(uint32_t) && !state.is32)
return kErrorInvalidArgument;
else if (pinfo.pointerSize != sizeof(uint32_t) && state.is32)
return kErrorInvalidArgument;
//
// Write GPRs
//
struct reg gprs;
if (state.is32) {
Architecture::X86::state32_to_user(gprs, state.state32);
} else {
Architecture::X86::state64_to_user(gprs, state.state64);
}
if (wrapPtrace(PT_SETREGS, pid, &gprs, nullptr) < 0)
return Platform::TranslateError();
//
// Write X87 and SSE state
//
struct fpreg fprs;
if (state.is32) {
state32_to_user(fprs, state.state32);
} else {
state64_to_user(fprs, state.state64);
}
wrapPtrace(PT_SETFPREGS, pid, &fprs, nullptr);
return kSuccess;
}
} // namespace NetBSD
} // namespace Host
} // namespace ds2
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_BENCH_MODULE "nt2 trigonometric toolbox - tand/simd Mode"
//////////////////////////////////////////////////////////////////////////////
// timing Test behavior of trigonometric components in simd mode
//////////////////////////////////////////////////////////////////////////////
#include <nt2/toolbox/trigonometric/include/functions/tand.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <nt2/sdk/bench/benchmark.hpp>
#include <nt2/sdk/bench/timing.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <cmath>
typedef NT2_SIMD_DEFAULT_EXTENSION ext_t;
//////////////////////////////////////////////////////////////////////////////
// simd runtime benchmark for functor<tand_> from trigonometric
//////////////////////////////////////////////////////////////////////////////
using nt2::tag::tand_;
//////////////////////////////////////////////////////////////////////////////
// range macro
//////////////////////////////////////////////////////////////////////////////
#define RS(T,V1,V2) (T, (V1) ,(V2))
namespace n1 {
typedef float T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(tand_,(RS(vT,T(-79),T(79))))
}
namespace n2 {
typedef double T;
typedef boost::dispatch::meta::as_integer<T>::type iT;
typedef boost::simd::native<T,ext_t> vT;
NT2_TIMING(tand_,(RS(vT,T(-79),T(79))))
}
#undef RS
|
#include "renderer/material.h"
#include "engine/crc32.h"
#include "engine/fs/file_system.h"
#include "engine/json_serializer.h"
#include "engine/log.h"
#include "engine/path_utils.h"
#include "engine/profiler.h"
#include "engine/resource_manager.h"
#include "engine/resource_manager_base.h"
#include "renderer/material_manager.h"
#include "renderer/pipeline.h"
#include "renderer/renderer.h"
#include "renderer/shader.h"
#include "renderer/texture.h"
namespace Lumix
{
static const uint32 SHADOWMAP_HASH = crc32("shadowmap");
static const ResourceType TEXTURE_TYPE("texture");
static const ResourceType SHADER_TYPE("shader");
static const ResourceType MATERIAL_TYPE("material");
static const float DEFAULT_ALPHA_REF_VALUE = 0.3f;
static struct CustomFlags
{
char flags[32][32];
int count;
} s_custom_flags = {};
static uint8 DEFAULT_COMMAND_BUFFER = 0;
Material::Material(const Path& path, ResourceManagerBase& resource_manager, IAllocator& allocator)
: Resource(path, resource_manager, allocator)
, m_shader(nullptr)
, m_uniforms(allocator)
, m_allocator(allocator)
, m_texture_count(0)
, m_render_states(BGFX_STATE_CULL_CW)
, m_color(1, 1, 1)
, m_shininess(4)
, m_shader_instance(nullptr)
, m_define_mask(0)
, m_command_buffer(&DEFAULT_COMMAND_BUFFER)
, m_custom_flags(0)
{
for (auto& l : m_layer_count) l = 1;
setAlphaRef(DEFAULT_ALPHA_REF_VALUE);
for (int i = 0; i < MAX_TEXTURE_COUNT; ++i)
{
m_textures[i] = nullptr;
}
setShader(nullptr);
}
Material::~Material()
{
ASSERT(isEmpty());
}
const char* Material::getCustomFlagName(int index)
{
return s_custom_flags.flags[index];
}
int Material::getCustomFlagCount()
{
return s_custom_flags.count;
}
uint32 Material::getCustomFlag(const char* flag_name)
{
for (int i = 0; i < s_custom_flags.count; ++i)
{
if (equalStrings(s_custom_flags.flags[i], flag_name)) return 1 << i;
}
if (s_custom_flags.count >= lengthOf(s_custom_flags.flags))
{
ASSERT(false);
return 0;
}
copyString(s_custom_flags.flags[s_custom_flags.count], flag_name);
++s_custom_flags.count;
return 1 << (s_custom_flags.count - 1);
}
bool Material::isDefined(uint8 define_idx) const
{
return (m_define_mask & (1 << define_idx)) != 0;
}
bool Material::hasDefine(uint8 define_idx) const
{
return m_shader->hasDefine(define_idx) != 0;
}
void Material::setDefine(uint8 define_idx, bool enabled)
{
uint32 old_mask = m_define_mask;
if (enabled)
{
m_define_mask |= 1 << define_idx;
}
else
{
m_define_mask &= ~(1 << define_idx);
}
if (!isReady()) return;
if (!m_shader) return;
if (old_mask != m_define_mask)
{
m_shader_instance = &m_shader->getInstance(m_define_mask);
}
}
void Material::unload(void)
{
if(m_command_buffer != &DEFAULT_COMMAND_BUFFER) m_allocator.deallocate(m_command_buffer);
m_command_buffer = &DEFAULT_COMMAND_BUFFER;
m_uniforms.clear();
setShader(nullptr);
ResourceManagerBase* texture_manager = m_resource_manager.getOwner().get(TEXTURE_TYPE);
for (int i = 0; i < m_texture_count; i++)
{
if (m_textures[i])
{
removeDependency(*m_textures[i]);
texture_manager->unload(*m_textures[i]);
}
}
m_texture_count = 0;
m_define_mask = 0;
}
bool Material::save(JsonSerializer& serializer)
{
if(!isReady()) return false;
if(!m_shader) return false;
auto& renderer = static_cast<MaterialManager&>(m_resource_manager).getRenderer();
serializer.beginObject();
serializer.serialize("shader", m_shader ? m_shader->getPath() : Path(""));
for (int i = 0; i < lengthOf(m_layer_count); ++i)
{
if (m_layer_count[i] != 1)
{
serializer.beginObject("layer");
serializer.serialize("pass", renderer.getPassName(i));
serializer.serialize("count", m_layer_count[i]);
serializer.endObject();
}
}
for (int i = 0; i < m_texture_count; ++i)
{
char path[MAX_PATH_LENGTH];
int flags = 0;
if (m_textures[i])
{
flags = m_textures[i]->bgfx_flags;
path[0] = '/';
Lumix::copyString(path + 1, MAX_PATH_LENGTH - 1, m_textures[i]->getPath().c_str());
}
else
{
path[0] = '\0';
}
serializer.beginObject("texture");
serializer.serialize("source", path);
if (flags & BGFX_TEXTURE_SRGB) serializer.serialize("srgb", true);
if (flags & BGFX_TEXTURE_U_CLAMP) serializer.serialize("u_clamp", true);
if (flags & BGFX_TEXTURE_V_CLAMP) serializer.serialize("v_clamp", true);
if (flags & BGFX_TEXTURE_W_CLAMP) serializer.serialize("w_clamp", true);
if (flags & BGFX_TEXTURE_MIN_POINT) serializer.serialize("min_filter", "point");
if (flags & BGFX_TEXTURE_MIN_ANISOTROPIC) serializer.serialize("min_filter", "anisotropic");
if (flags & BGFX_TEXTURE_MAG_POINT) serializer.serialize("mag_filter", "point");
if (flags & BGFX_TEXTURE_MAG_ANISOTROPIC) serializer.serialize("mag_filter", "anisotropic");
if (m_textures[i] && m_textures[i]->getData()) serializer.serialize("keep_data", true);
serializer.endObject();
}
if (m_custom_flags != 0)
{
serializer.beginArray("custom_flags");
for (int i = 0; i < 32; ++i)
{
if (m_custom_flags & (1 << i)) serializer.serializeArrayItem(s_custom_flags.flags[i]);
}
serializer.endArray();
}
serializer.beginArray("defines");
for (int i = 0; i < sizeof(m_define_mask) * 8; ++i)
{
if (m_define_mask & (1 << i)) serializer.serializeArrayItem(renderer.getShaderDefine(i));
}
serializer.endArray();
serializer.beginArray("uniforms");
for (int i = 0; i < m_shader->m_uniforms.size(); ++i)
{
serializer.beginObject();
const auto& uniform = m_shader->m_uniforms[i];
serializer.serialize("name", uniform.name);
switch (uniform.type)
{
case Shader::Uniform::FLOAT:
serializer.serialize("float_value", m_uniforms[i].float_value);
break;
case Shader::Uniform::COLOR:
serializer.beginArray("color");
serializer.serializeArrayItem(m_uniforms[i].vec3[0]);
serializer.serializeArrayItem(m_uniforms[i].vec3[1]);
serializer.serializeArrayItem(m_uniforms[i].vec3[2]);
serializer.endArray();
break;
case Shader::Uniform::VEC3:
serializer.beginArray("vec3");
serializer.serializeArrayItem(m_uniforms[i].vec3[0]);
serializer.serializeArrayItem(m_uniforms[i].vec3[1]);
serializer.serializeArrayItem(m_uniforms[i].vec3[2]);
serializer.endArray();
break;
case Shader::Uniform::TIME:
serializer.serialize("time", 0);
break;
case Shader::Uniform::INT:
serializer.serialize("int_value", m_uniforms[i].int_value);
break;
case Shader::Uniform::MATRIX4:
serializer.beginArray("matrix_value");
for (int j = 0; j < 16; ++j)
{
serializer.serializeArrayItem(m_uniforms[i].matrix[j]);
}
serializer.endArray();
break;
default:
ASSERT(false);
break;
}
serializer.endObject();
}
serializer.endArray();
serializer.serialize("shininess", m_shininess);
serializer.serialize("alpha_ref", m_alpha_ref);
serializer.beginArray("color");
serializer.serializeArrayItem(m_color.x);
serializer.serializeArrayItem(m_color.y);
serializer.serializeArrayItem(m_color.z);
serializer.endArray();
serializer.endObject();
return true;
}
void Material::deserializeCustomFlags(JsonSerializer& serializer)
{
m_custom_flags = 0;
serializer.deserializeArrayBegin();
while (!serializer.isArrayEnd())
{
char tmp[32];
serializer.deserializeArrayItem(tmp, lengthOf(tmp), "");
setCustomFlag(getCustomFlag(tmp));
}
serializer.deserializeArrayEnd();
}
void Material::deserializeDefines(JsonSerializer& serializer)
{
auto& renderer = static_cast<MaterialManager&>(m_resource_manager).getRenderer();
serializer.deserializeArrayBegin();
m_define_mask = 0;
while (!serializer.isArrayEnd())
{
char tmp[32];
serializer.deserializeArrayItem(tmp, lengthOf(tmp), "");
m_define_mask |= 1 << renderer.getShaderDefineIdx(tmp);
}
serializer.deserializeArrayEnd();
}
void Material::deserializeUniforms(JsonSerializer& serializer)
{
serializer.deserializeArrayBegin();
m_uniforms.clear();
while (!serializer.isArrayEnd())
{
Uniform& uniform = m_uniforms.emplace();
serializer.nextArrayItem();
serializer.deserializeObjectBegin();
char label[256];
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (equalStrings(label, "name"))
{
char name[32];
serializer.deserialize(name, lengthOf(name), "");
uniform.name_hash = crc32(name);
}
else if (equalStrings(label, "int_value"))
{
serializer.deserialize(uniform.int_value, 0);
}
else if (equalStrings(label, "float_value"))
{
serializer.deserialize(uniform.float_value, 0);
}
else if (equalStrings(label, "matrix_value"))
{
serializer.deserializeArrayBegin();
for (int i = 0; i < 16; ++i)
{
serializer.deserializeArrayItem(uniform.matrix[i], 0);
}
serializer.deserializeArrayEnd();
}
else if (equalStrings(label, "time"))
{
serializer.deserialize(uniform.float_value, 0);
}
else if (equalStrings(label, "color"))
{
serializer.deserializeArrayBegin();
serializer.deserializeArrayItem(uniform.vec3[0], 0);
serializer.deserializeArrayItem(uniform.vec3[1], 0);
serializer.deserializeArrayItem(uniform.vec3[2], 0);
serializer.deserializeArrayEnd();
}
else if (equalStrings(label, "vec3"))
{
serializer.deserializeArrayBegin();
serializer.deserializeArrayItem(uniform.vec3[0], 0);
serializer.deserializeArrayItem(uniform.vec3[1], 0);
serializer.deserializeArrayItem(uniform.vec3[2], 0);
serializer.deserializeArrayEnd();
}
else
{
g_log_warning.log("Renderer") << "Unknown label \"" << label << "\"";
}
}
serializer.deserializeObjectEnd();
}
serializer.deserializeArrayEnd();
}
void Material::setTexturePath(int i, const Path& path)
{
if (path.length() == 0)
{
setTexture(i, nullptr);
}
else
{
Texture* texture = static_cast<Texture*>(m_resource_manager.getOwner().get(TEXTURE_TYPE)->load(path));
setTexture(i, texture);
}
}
void Material::setTexture(int i, Texture* texture)
{
Texture* old_texture = i < m_texture_count ? m_textures[i] : nullptr;
if (texture) addDependency(*texture);
m_textures[i] = texture;
if (i >= m_texture_count) m_texture_count = i + 1;
if (old_texture)
{
removeDependency(*old_texture);
m_resource_manager.getOwner().get(TEXTURE_TYPE)->unload(*old_texture);
}
if (isReady() && m_shader)
{
int define_idx = m_shader->m_texture_slots[i].define_idx;
if(define_idx >= 0)
{
if(m_textures[i])
{
m_define_mask |= 1 << define_idx;
}
else
{
m_define_mask &= ~(1 << define_idx);
}
}
createCommandBuffer();
m_shader_instance = &m_shader->getInstance(m_define_mask);
}
}
void Material::setShader(const Path& path)
{
Shader* shader = static_cast<Shader*>(m_resource_manager.getOwner().get(SHADER_TYPE)->load(path));
setShader(shader);
}
void Material::createCommandBuffer()
{
if (m_command_buffer != &DEFAULT_COMMAND_BUFFER) m_allocator.deallocate(m_command_buffer);
m_command_buffer = &DEFAULT_COMMAND_BUFFER;
if (!m_shader) return;
CommandBufferGenerator generator;
for (int i = 0; i < m_shader->m_uniforms.size(); ++i)
{
const Material::Uniform& uniform = m_uniforms[i];
const Shader::Uniform& shader_uniform = m_shader->m_uniforms[i];
switch (shader_uniform.type)
{
case Shader::Uniform::FLOAT:
generator.setUniform(shader_uniform.handle, Vec4(uniform.float_value, 0, 0, 0));
break;
case Shader::Uniform::VEC3:
case Shader::Uniform::COLOR:
generator.setUniform(shader_uniform.handle, Vec4(*(Vec3*)uniform.vec3, 0));
break;
case Shader::Uniform::TIME: generator.setTimeUniform(shader_uniform.handle); break;
default: ASSERT(false); break;
}
}
for (int i = 0; i < m_shader->m_texture_slot_count; ++i)
{
if (i >= m_texture_count || !m_textures[i]) continue;
generator.setTexture(i, m_shader->m_texture_slots[i].uniform_handle, m_textures[i]->handle);
}
Vec4 color_shininess(m_color, m_shininess);
auto& renderer = static_cast<MaterialManager&>(m_resource_manager).getRenderer();
auto& uniform = renderer.getMaterialColorShininessUniform();
generator.setUniform(uniform, color_shininess);
generator.end();
m_command_buffer = (uint8*)m_allocator.allocate(generator.getSize());
generator.getData(m_command_buffer);
}
void Material::onBeforeReady()
{
if (!m_shader) return;
for(int i = 0; i < m_shader->m_uniforms.size(); ++i)
{
auto& shader_uniform = m_shader->m_uniforms[i];
bool found = false;
for(int j = i; j < m_uniforms.size(); ++j)
{
if(m_uniforms[j].name_hash == shader_uniform.name_hash)
{
auto tmp = m_uniforms[i];
m_uniforms[i] = m_uniforms[j];
m_uniforms[j] = tmp;
found = true;
break;
}
}
if(found) continue;
if(i < m_uniforms.size())
{
m_uniforms.emplace(m_uniforms[i]);
}
else
{
m_uniforms.emplace();
}
m_uniforms[i].name_hash = shader_uniform.name_hash;
}
uint8 alpha_ref = uint8(m_alpha_ref * 255.0f);
m_render_states = (m_render_states & ~BGFX_STATE_ALPHA_REF_MASK) | BGFX_STATE_ALPHA_REF(alpha_ref);
m_render_states |= m_shader->m_render_states;
for(int i = 0; i < m_shader->m_texture_slot_count; ++i)
{
int define_idx = m_shader->m_texture_slots[i].define_idx;
if(define_idx >= 0)
{
if(m_textures[i])
{
m_define_mask |= 1 << define_idx;
}
else
{
m_define_mask &= ~(1 << define_idx);
}
}
}
createCommandBuffer();
m_shader_instance = &m_shader->getInstance(m_define_mask);
}
void Material::setShader(Shader* shader)
{
auto& mat_manager = static_cast<MaterialManager&>(m_resource_manager);
if (m_shader && m_shader != mat_manager.getRenderer().getDefaultShader())
{
Shader* shader = m_shader;
m_shader = nullptr;
removeDependency(*shader);
m_resource_manager.getOwner().get(SHADER_TYPE)->unload(*shader);
}
m_shader = shader;
if (m_shader)
{
addDependency(*m_shader);
if (m_shader->isReady()) onBeforeReady();
}
else
{
m_shader = mat_manager.getRenderer().getDefaultShader();
m_shader_instance = m_shader->m_instances.empty() ? nullptr : &m_shader->m_instances[0];
}
}
const char* Material::getTextureUniform(int i)
{
if (i < m_shader->m_texture_slot_count) return m_shader->m_texture_slots[i].uniform;
return "";
}
Texture* Material::getTextureByUniform(const char* uniform) const
{
if (!m_shader) return nullptr;
for (int i = 0, c = m_shader->m_texture_slot_count; i < c; ++i)
{
if (equalStrings(m_shader->m_texture_slots[i].uniform, uniform))
{
return m_textures[i];
}
}
return nullptr;
}
bool Material::isTextureDefine(uint8 define_idx) const
{
if (!m_shader) return false;
for (int i = 0, c = m_shader->m_texture_slot_count; i < c; ++i)
{
if (m_shader->m_texture_slots[i].define_idx == define_idx)
{
return true;
}
}
return false;
}
bool Material::deserializeTexture(JsonSerializer& serializer, const char* material_dir)
{
char path[MAX_PATH_LENGTH];
serializer.deserializeObjectBegin();
char label[256];
bool keep_data = false;
uint32 flags = 0;
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, sizeof(label));
if (equalStrings(label, "source"))
{
serializer.deserialize(path, MAX_PATH_LENGTH, "");
if (path[0] != '\0')
{
char texture_path[MAX_PATH_LENGTH];
if (path[0] != '/' && path[0] != '\\')
{
copyString(texture_path, material_dir);
catString(texture_path, path);
}
else
{
copyString(texture_path, path);
}
auto* mng = m_resource_manager.getOwner().get(TEXTURE_TYPE);
m_textures[m_texture_count] = static_cast<Texture*>(mng->load(Path(texture_path)));
addDependency(*m_textures[m_texture_count]);
}
}
else if (equalStrings(label, "min_filter"))
{
serializer.deserialize(label, sizeof(label), "");
if (equalStrings(label, "point"))
{
flags |= BGFX_TEXTURE_MIN_POINT;
}
else if (equalStrings(label, "anisotropic"))
{
flags |= BGFX_TEXTURE_MIN_ANISOTROPIC;
}
else
{
g_log_error.log("Renderer") << "Unknown texture filter \"" << label
<< "\" in material " << getPath();
}
}
else if (equalStrings(label, "mag_filter"))
{
serializer.deserialize(label, sizeof(label), "");
if (equalStrings(label, "point"))
{
flags |= BGFX_TEXTURE_MAG_POINT;
}
else if (equalStrings(label, "anisotropic"))
{
flags |= BGFX_TEXTURE_MAG_ANISOTROPIC;
}
else
{
g_log_error.log("Renderer") << "Unknown texture filter \"" << label
<< "\" in material " << getPath();
}
}
else if (equalStrings(label, "u_clamp"))
{
bool b;
serializer.deserialize(b, false);
if (b)
{
flags |= BGFX_TEXTURE_U_CLAMP;
}
}
else if (equalStrings(label, "v_clamp"))
{
bool b;
serializer.deserialize(b, false);
if (b)
{
flags |= BGFX_TEXTURE_V_CLAMP;
}
}
else if (equalStrings(label, "w_clamp"))
{
bool b;
serializer.deserialize(b, false);
if (b)
{
flags |= BGFX_TEXTURE_W_CLAMP;
}
}
else if (equalStrings(label, "keep_data"))
{
serializer.deserialize(keep_data, false);
}
else if (equalStrings(label, "srgb"))
{
bool is_srgb;
serializer.deserialize(is_srgb, false);
if(is_srgb) flags |= BGFX_TEXTURE_SRGB;
}
else
{
g_log_warning.log("Renderer") << "Unknown data \"" << label << "\" in material "
<< getPath();
return false;
}
}
if (m_textures[m_texture_count])
{
m_textures[m_texture_count]->setFlags(flags);
if (keep_data)
{
m_textures[m_texture_count]->addDataReference();
}
}
serializer.deserializeObjectEnd();
++m_texture_count;
return true;
}
void Material::setAlphaRef(float value)
{
m_alpha_ref = value;
uint8 val = uint8(value * 255.0f);
m_render_states &= ~BGFX_STATE_ALPHA_REF_MASK;
m_render_states |= BGFX_STATE_ALPHA_REF(val);
}
void Material::enableBackfaceCulling(bool enable)
{
if (enable)
{
m_render_states |= BGFX_STATE_CULL_CW;
}
else
{
m_render_states &= ~BGFX_STATE_CULL_MASK;
}
}
bool Material::isBackfaceCulling() const
{
return (m_render_states & BGFX_STATE_CULL_MASK) != 0;
}
bool Material::load(FS::IFile& file)
{
PROFILE_FUNCTION();
auto& renderer = static_cast<MaterialManager&>(m_resource_manager).getRenderer();
m_render_states = BGFX_STATE_CULL_CW;
setAlphaRef(DEFAULT_ALPHA_REF_VALUE);
m_uniforms.clear();
JsonSerializer serializer(file, JsonSerializer::READ, getPath(), m_allocator);
serializer.deserializeObjectBegin();
char label[256];
char material_dir[MAX_PATH_LENGTH];
PathUtils::getDir(material_dir, MAX_PATH_LENGTH, getPath().c_str());
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (equalStrings(label, "defines"))
{
deserializeDefines(serializer);
}
else if (equalStrings(label, "custom_flags"))
{
deserializeCustomFlags(serializer);
}
else if (equalStrings(label, "uniforms"))
{
deserializeUniforms(serializer);
}
else if (equalStrings(label, "texture"))
{
if (!deserializeTexture(serializer, material_dir))
{
return false;
}
}
else if (equalStrings(label, "alpha_ref"))
{
serializer.deserialize(m_alpha_ref, 0.3f);
}
else if (equalStrings(label, "backface_culling"))
{
bool b = true;
serializer.deserialize(b, true);
if (b)
{
m_render_states |= BGFX_STATE_CULL_CW;
}
else
{
m_render_states &= ~BGFX_STATE_CULL_MASK;
}
}
else if (equalStrings(label, "layer"))
{
serializer.deserializeObjectBegin();
int pass = 0;
int layers_count = 1;
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (equalStrings(label, "pass"))
{
char pass_name[50];
serializer.deserialize(pass_name, lengthOf(pass_name), "");
pass = renderer.getPassIdx(pass_name);
}
else if (equalStrings(label, "count"))
{
serializer.deserialize(layers_count, 1);
}
}
m_layer_count[pass] = layers_count;
serializer.deserializeObjectEnd();
}
else if (equalStrings(label, "color"))
{
serializer.deserializeArrayBegin();
serializer.deserializeArrayItem(m_color.x, 1.0f);
serializer.deserializeArrayItem(m_color.y, 1.0f);
serializer.deserializeArrayItem(m_color.z, 1.0f);
serializer.deserializeArrayEnd();
}
else if (equalStrings(label, "shininess"))
{
serializer.deserialize(m_shininess, 4.0f);
}
else if (equalStrings(label, "shader"))
{
Path path;
serializer.deserialize(path, Path(""));
auto* manager = m_resource_manager.getOwner().get(SHADER_TYPE);
setShader(static_cast<Shader*>(manager->load(Path(path))));
}
else
{
g_log_error.log("Renderer") << "Unknown parameter " << label << " in material "
<< getPath();
}
}
serializer.deserializeObjectEnd();
if (!m_shader)
{
g_log_error.log("Renderer") << "Material " << getPath() << " without a shader";
return false;
}
m_size = file.size();
return true;
}
} // ~namespace Lumix
|
#ifndef JULES_VECTOR_FUNCTIONAL_H
#define JULES_VECTOR_FUNCTIONAL_H
#include <vlite/binary_expr_vector.hpp>
#include <vlite/unary_expr_vector.hpp>
#include <functional>
namespace vlite
{
template <typename Vector, typename Op>
static auto apply(const common_vector_base<Vector>& operand, Op op)
{
return unary_expr_vector(operand.begin(), operand.end(), std::move(op), operand.size());
}
template <typename VectorA, typename VectorB, typename Op>
static auto apply(const common_vector_base<VectorA>& lhs,
const common_vector_base<VectorB>& rhs, Op op)
{
return binary_expr_vector(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), std::move(op),
lhs.size());
}
#define OPERATIONS_LIST \
UNARY_OPERATIONS_LIST \
BINARY_OPERATIONS_LIST
#define BINARY_OPERATIONS_LIST \
BINARY_COMBINATIONS(+, std::plus<>) \
BINARY_COMBINATIONS(-, std::minus<>) \
BINARY_COMBINATIONS(*, std::multiplies<>) \
BINARY_COMBINATIONS(/, std::divides<>) \
BINARY_COMBINATIONS(%, std::modulus<>) \
BINARY_COMBINATIONS(&&, std::logical_and<>) \
BINARY_COMBINATIONS(||, std::logical_or<>) \
BINARY_COMBINATIONS(==, std::equal_to<>) \
BINARY_COMBINATIONS(!=, std::not_equal_to<>) \
BINARY_COMBINATIONS(<, std::less<>) \
BINARY_COMBINATIONS(<=, std::less_equal<>) \
BINARY_COMBINATIONS(>, std::greater<>) \
BINARY_COMBINATIONS(>=, std::greater_equal<>)
#define BINARY_COMBINATIONS(OP__, FUNCTOR__) \
BINARY_OPERATION(OP__, FUNCTOR__) \
BINARY_RIGHT_TYPE_OPERATION(OP__, FUNCTOR__) \
BINARY_LEFT_TYPE_OPERATION(OP__, FUNCTOR__)
#define BINARY_OPERATION(OP__, FUNCTOR__) \
template <typename VectorA, typename VectorB> \
auto operator OP__(const common_vector_base<VectorA>& lhs, \
const common_vector_base<VectorB>& rhs) \
{ \
return apply(lhs, rhs, (FUNCTOR__){}); \
}
#define BINARY_RIGHT_TYPE_OPERATION(OP__, FUNCTOR__) \
template <typename Vector, typename T, typename = meta::fallback<CommonVector<T>>> \
auto operator OP__(const common_vector_base<Vector>& lhs, T rhs) \
{ \
return apply(lhs, [ rhs = std::move(rhs), op = (FUNCTOR__){} ](auto&& value) { \
return op(std::forward<decltype(value)>(value), rhs); \
}); \
}
#define BINARY_LEFT_TYPE_OPERATION(OP__, FUNCTOR__) \
template <typename T, typename Vector, typename = meta::fallback<CommonVector<T>>> \
auto operator OP__(T lhs, const common_vector_base<Vector>& rhs) \
{ \
return apply(rhs, [ lhs = std::move(lhs), op = (FUNCTOR__){} ](auto&& value) { \
return op(lhs, std::forward<decltype(value)>(value)); \
}); \
}
#define UNARY_OPERATIONS_LIST \
UNARY_OPERATION(-, std::negate<>) \
UNARY_OPERATION(!, std::logical_not<>)
#define UNARY_OPERATION(OP__, FUNCTOR__) \
template <typename Vector> \
auto operator OP__(const common_vector_base<Vector>& operand) \
{ \
return apply(operand, (FUNCTOR__){}); \
}
OPERATIONS_LIST
#undef UNARY_OPERATION
#undef UNARY_OPERATIONS_LIST
#undef BINARY_OPERATION
#undef BINARY_LEFT_TYPE_OPERATION
#undef BINARY_RIGHT_TYPE_OPERATION
#undef BINARY_COMBINATIONS
#undef BINARY_OPERATIONS_LIST
#undef OPERATIONS_LIST
} // namespace vlite
#endif // JULES_VECTOR_FUNCTIONAL_H
|
// ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2018.3
// Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved.
//
// ===========================================================
#include "grad_vertical_Mat_s.h"
#include "AESL_pkg.h"
using namespace std;
namespace ap_rtl {
const sc_logic grad_vertical_Mat_s::ap_const_logic_1 = sc_dt::Log_1;
const sc_logic grad_vertical_Mat_s::ap_const_logic_0 = sc_dt::Log_0;
const sc_lv<2> grad_vertical_Mat_s::ap_ST_fsm_state1 = "1";
const sc_lv<2> grad_vertical_Mat_s::ap_ST_fsm_state2 = "10";
const sc_lv<32> grad_vertical_Mat_s::ap_const_lv32_0 = "00000000000000000000000000000000";
const sc_lv<32> grad_vertical_Mat_s::ap_const_lv32_1 = "1";
const sc_lv<6> grad_vertical_Mat_s::ap_const_lv6_10 = "10000";
const sc_lv<7> grad_vertical_Mat_s::ap_const_lv7_20 = "100000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_0 = "00000000";
const sc_lv<7> grad_vertical_Mat_s::ap_const_lv7_60 = "1100000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_40 = "1000000";
const sc_lv<7> grad_vertical_Mat_s::ap_const_lv7_40 = "1000000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_60 = "1100000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_C0 = "11000000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_A0 = "10100000";
const sc_lv<7> grad_vertical_Mat_s::ap_const_lv7_0 = "0000000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_20 = "100000";
const sc_lv<8> grad_vertical_Mat_s::ap_const_lv8_E0 = "11100000";
const sc_lv<6> grad_vertical_Mat_s::ap_const_lv6_30 = "110000";
const bool grad_vertical_Mat_s::ap_const_boolean_1 = true;
grad_vertical_Mat_s::grad_vertical_Mat_s(sc_module_name name) : sc_module(name), mVcdFile(0) {
grp_Filter2D_fu_122 = new Filter2D("grp_Filter2D_fu_122");
grp_Filter2D_fu_122->ap_clk(ap_clk);
grp_Filter2D_fu_122->ap_rst(ap_rst);
grp_Filter2D_fu_122->ap_start(grp_Filter2D_fu_122_ap_start);
grp_Filter2D_fu_122->ap_done(grp_Filter2D_fu_122_ap_done);
grp_Filter2D_fu_122->ap_idle(grp_Filter2D_fu_122_ap_idle);
grp_Filter2D_fu_122->ap_ready(grp_Filter2D_fu_122_ap_ready);
grp_Filter2D_fu_122->p_src_data_stream_0_V_dout(img_in_data_stream_0_V_dout);
grp_Filter2D_fu_122->p_src_data_stream_0_V_empty_n(img_in_data_stream_0_V_empty_n);
grp_Filter2D_fu_122->p_src_data_stream_0_V_read(grp_Filter2D_fu_122_p_src_data_stream_0_V_read);
grp_Filter2D_fu_122->p_src_data_stream_1_V_dout(img_in_data_stream_1_V_dout);
grp_Filter2D_fu_122->p_src_data_stream_1_V_empty_n(img_in_data_stream_1_V_empty_n);
grp_Filter2D_fu_122->p_src_data_stream_1_V_read(grp_Filter2D_fu_122_p_src_data_stream_1_V_read);
grp_Filter2D_fu_122->p_src_data_stream_2_V_dout(img_in_data_stream_2_V_dout);
grp_Filter2D_fu_122->p_src_data_stream_2_V_empty_n(img_in_data_stream_2_V_empty_n);
grp_Filter2D_fu_122->p_src_data_stream_2_V_read(grp_Filter2D_fu_122_p_src_data_stream_2_V_read);
grp_Filter2D_fu_122->p_dst_data_stream_0_V_din(grp_Filter2D_fu_122_p_dst_data_stream_0_V_din);
grp_Filter2D_fu_122->p_dst_data_stream_0_V_full_n(img_out_data_stream_0_V_full_n);
grp_Filter2D_fu_122->p_dst_data_stream_0_V_write(grp_Filter2D_fu_122_p_dst_data_stream_0_V_write);
grp_Filter2D_fu_122->p_dst_data_stream_1_V_din(grp_Filter2D_fu_122_p_dst_data_stream_1_V_din);
grp_Filter2D_fu_122->p_dst_data_stream_1_V_full_n(img_out_data_stream_1_V_full_n);
grp_Filter2D_fu_122->p_dst_data_stream_1_V_write(grp_Filter2D_fu_122_p_dst_data_stream_1_V_write);
grp_Filter2D_fu_122->p_dst_data_stream_2_V_din(grp_Filter2D_fu_122_p_dst_data_stream_2_V_din);
grp_Filter2D_fu_122->p_dst_data_stream_2_V_full_n(img_out_data_stream_2_V_full_n);
grp_Filter2D_fu_122->p_dst_data_stream_2_V_write(grp_Filter2D_fu_122_p_dst_data_stream_2_V_write);
grp_Filter2D_fu_122->p_kernel_val_0_V_0_read(ap_var_for_const0);
grp_Filter2D_fu_122->p_kernel_val_0_V_1_read(ap_var_for_const1);
grp_Filter2D_fu_122->p_kernel_val_0_V_2_read(ap_var_for_const2);
grp_Filter2D_fu_122->p_kernel_val_0_V_3_read(ap_var_for_const3);
grp_Filter2D_fu_122->p_kernel_val_1_V_0_read(ap_var_for_const4);
grp_Filter2D_fu_122->p_kernel_val_1_V_2_read(ap_var_for_const2);
grp_Filter2D_fu_122->p_kernel_val_1_V_4_read(ap_var_for_const5);
grp_Filter2D_fu_122->p_kernel_val_2_V_0_read(ap_var_for_const6);
grp_Filter2D_fu_122->p_kernel_val_2_V_1_read(ap_var_for_const7);
grp_Filter2D_fu_122->p_kernel_val_2_V_3_read(ap_var_for_const4);
grp_Filter2D_fu_122->p_kernel_val_2_V_4_read(ap_var_for_const8);
grp_Filter2D_fu_122->p_kernel_val_3_V_0_read(ap_var_for_const4);
grp_Filter2D_fu_122->p_kernel_val_3_V_2_read(ap_var_for_const9);
grp_Filter2D_fu_122->p_kernel_val_3_V_4_read(ap_var_for_const5);
grp_Filter2D_fu_122->p_kernel_val_4_V_1_read(ap_var_for_const10);
grp_Filter2D_fu_122->p_kernel_val_4_V_2_read(ap_var_for_const2);
grp_Filter2D_fu_122->p_kernel_val_4_V_3_read(ap_var_for_const11);
grp_Filter2D_fu_122->p_kernel_val_4_V_4_read(ap_var_for_const12);
SC_METHOD(thread_ap_clk_no_reset_);
dont_initialize();
sensitive << ( ap_clk.pos() );
SC_METHOD(thread_ap_CS_fsm_state1);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state2);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_block_state1);
sensitive << ( real_start );
sensitive << ( ap_done_reg );
SC_METHOD(thread_ap_block_state1_ignore_call6);
sensitive << ( real_start );
sensitive << ( ap_done_reg );
SC_METHOD(thread_ap_done);
sensitive << ( ap_done_reg );
sensitive << ( grp_Filter2D_fu_122_ap_done );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_ap_idle);
sensitive << ( real_start );
sensitive << ( ap_CS_fsm_state1 );
SC_METHOD(thread_ap_ready);
sensitive << ( internal_ap_ready );
SC_METHOD(thread_grp_Filter2D_fu_122_ap_start);
sensitive << ( grp_Filter2D_fu_122_ap_start_reg );
SC_METHOD(thread_img_in_data_stream_0_V_read);
sensitive << ( grp_Filter2D_fu_122_p_src_data_stream_0_V_read );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_in_data_stream_1_V_read);
sensitive << ( grp_Filter2D_fu_122_p_src_data_stream_1_V_read );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_in_data_stream_2_V_read);
sensitive << ( grp_Filter2D_fu_122_p_src_data_stream_2_V_read );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_out_data_stream_0_V_din);
sensitive << ( grp_Filter2D_fu_122_p_dst_data_stream_0_V_din );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_out_data_stream_0_V_write);
sensitive << ( grp_Filter2D_fu_122_p_dst_data_stream_0_V_write );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_out_data_stream_1_V_din);
sensitive << ( grp_Filter2D_fu_122_p_dst_data_stream_1_V_din );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_out_data_stream_1_V_write);
sensitive << ( grp_Filter2D_fu_122_p_dst_data_stream_1_V_write );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_out_data_stream_2_V_din);
sensitive << ( grp_Filter2D_fu_122_p_dst_data_stream_2_V_din );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_img_out_data_stream_2_V_write);
sensitive << ( grp_Filter2D_fu_122_p_dst_data_stream_2_V_write );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_internal_ap_ready);
sensitive << ( grp_Filter2D_fu_122_ap_done );
sensitive << ( ap_CS_fsm_state2 );
SC_METHOD(thread_real_start);
sensitive << ( ap_start );
sensitive << ( start_full_n );
sensitive << ( start_once_reg );
SC_METHOD(thread_start_out);
sensitive << ( real_start );
SC_METHOD(thread_start_write);
sensitive << ( real_start );
sensitive << ( start_once_reg );
SC_METHOD(thread_ap_NS_fsm);
sensitive << ( real_start );
sensitive << ( ap_done_reg );
sensitive << ( ap_CS_fsm );
sensitive << ( ap_CS_fsm_state1 );
sensitive << ( grp_Filter2D_fu_122_ap_done );
sensitive << ( ap_CS_fsm_state2 );
SC_THREAD(thread_ap_var_for_const0);
SC_THREAD(thread_ap_var_for_const1);
SC_THREAD(thread_ap_var_for_const2);
SC_THREAD(thread_ap_var_for_const3);
SC_THREAD(thread_ap_var_for_const4);
SC_THREAD(thread_ap_var_for_const5);
SC_THREAD(thread_ap_var_for_const6);
SC_THREAD(thread_ap_var_for_const7);
SC_THREAD(thread_ap_var_for_const8);
SC_THREAD(thread_ap_var_for_const9);
SC_THREAD(thread_ap_var_for_const10);
SC_THREAD(thread_ap_var_for_const11);
SC_THREAD(thread_ap_var_for_const12);
start_once_reg = SC_LOGIC_0;
ap_done_reg = SC_LOGIC_0;
ap_CS_fsm = "01";
grp_Filter2D_fu_122_ap_start_reg = SC_LOGIC_0;
static int apTFileNum = 0;
stringstream apTFilenSS;
apTFilenSS << "grad_vertical_Mat_s_sc_trace_" << apTFileNum ++;
string apTFn = apTFilenSS.str();
mVcdFile = sc_create_vcd_trace_file(apTFn.c_str());
mVcdFile->set_time_unit(1, SC_PS);
if (1) {
#ifdef __HLS_TRACE_LEVEL_PORT_HIER__
sc_trace(mVcdFile, ap_clk, "(port)ap_clk");
sc_trace(mVcdFile, ap_rst, "(port)ap_rst");
sc_trace(mVcdFile, ap_start, "(port)ap_start");
sc_trace(mVcdFile, start_full_n, "(port)start_full_n");
sc_trace(mVcdFile, ap_done, "(port)ap_done");
sc_trace(mVcdFile, ap_continue, "(port)ap_continue");
sc_trace(mVcdFile, ap_idle, "(port)ap_idle");
sc_trace(mVcdFile, ap_ready, "(port)ap_ready");
sc_trace(mVcdFile, start_out, "(port)start_out");
sc_trace(mVcdFile, start_write, "(port)start_write");
sc_trace(mVcdFile, img_in_data_stream_0_V_dout, "(port)img_in_data_stream_0_V_dout");
sc_trace(mVcdFile, img_in_data_stream_0_V_empty_n, "(port)img_in_data_stream_0_V_empty_n");
sc_trace(mVcdFile, img_in_data_stream_0_V_read, "(port)img_in_data_stream_0_V_read");
sc_trace(mVcdFile, img_in_data_stream_1_V_dout, "(port)img_in_data_stream_1_V_dout");
sc_trace(mVcdFile, img_in_data_stream_1_V_empty_n, "(port)img_in_data_stream_1_V_empty_n");
sc_trace(mVcdFile, img_in_data_stream_1_V_read, "(port)img_in_data_stream_1_V_read");
sc_trace(mVcdFile, img_in_data_stream_2_V_dout, "(port)img_in_data_stream_2_V_dout");
sc_trace(mVcdFile, img_in_data_stream_2_V_empty_n, "(port)img_in_data_stream_2_V_empty_n");
sc_trace(mVcdFile, img_in_data_stream_2_V_read, "(port)img_in_data_stream_2_V_read");
sc_trace(mVcdFile, img_out_data_stream_0_V_din, "(port)img_out_data_stream_0_V_din");
sc_trace(mVcdFile, img_out_data_stream_0_V_full_n, "(port)img_out_data_stream_0_V_full_n");
sc_trace(mVcdFile, img_out_data_stream_0_V_write, "(port)img_out_data_stream_0_V_write");
sc_trace(mVcdFile, img_out_data_stream_1_V_din, "(port)img_out_data_stream_1_V_din");
sc_trace(mVcdFile, img_out_data_stream_1_V_full_n, "(port)img_out_data_stream_1_V_full_n");
sc_trace(mVcdFile, img_out_data_stream_1_V_write, "(port)img_out_data_stream_1_V_write");
sc_trace(mVcdFile, img_out_data_stream_2_V_din, "(port)img_out_data_stream_2_V_din");
sc_trace(mVcdFile, img_out_data_stream_2_V_full_n, "(port)img_out_data_stream_2_V_full_n");
sc_trace(mVcdFile, img_out_data_stream_2_V_write, "(port)img_out_data_stream_2_V_write");
#endif
#ifdef __HLS_TRACE_LEVEL_INT__
sc_trace(mVcdFile, real_start, "real_start");
sc_trace(mVcdFile, start_once_reg, "start_once_reg");
sc_trace(mVcdFile, ap_done_reg, "ap_done_reg");
sc_trace(mVcdFile, ap_CS_fsm, "ap_CS_fsm");
sc_trace(mVcdFile, ap_CS_fsm_state1, "ap_CS_fsm_state1");
sc_trace(mVcdFile, internal_ap_ready, "internal_ap_ready");
sc_trace(mVcdFile, grp_Filter2D_fu_122_ap_start, "grp_Filter2D_fu_122_ap_start");
sc_trace(mVcdFile, grp_Filter2D_fu_122_ap_done, "grp_Filter2D_fu_122_ap_done");
sc_trace(mVcdFile, grp_Filter2D_fu_122_ap_idle, "grp_Filter2D_fu_122_ap_idle");
sc_trace(mVcdFile, grp_Filter2D_fu_122_ap_ready, "grp_Filter2D_fu_122_ap_ready");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_src_data_stream_0_V_read, "grp_Filter2D_fu_122_p_src_data_stream_0_V_read");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_src_data_stream_1_V_read, "grp_Filter2D_fu_122_p_src_data_stream_1_V_read");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_src_data_stream_2_V_read, "grp_Filter2D_fu_122_p_src_data_stream_2_V_read");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_dst_data_stream_0_V_din, "grp_Filter2D_fu_122_p_dst_data_stream_0_V_din");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_dst_data_stream_0_V_write, "grp_Filter2D_fu_122_p_dst_data_stream_0_V_write");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_dst_data_stream_1_V_din, "grp_Filter2D_fu_122_p_dst_data_stream_1_V_din");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_dst_data_stream_1_V_write, "grp_Filter2D_fu_122_p_dst_data_stream_1_V_write");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_dst_data_stream_2_V_din, "grp_Filter2D_fu_122_p_dst_data_stream_2_V_din");
sc_trace(mVcdFile, grp_Filter2D_fu_122_p_dst_data_stream_2_V_write, "grp_Filter2D_fu_122_p_dst_data_stream_2_V_write");
sc_trace(mVcdFile, grp_Filter2D_fu_122_ap_start_reg, "grp_Filter2D_fu_122_ap_start_reg");
sc_trace(mVcdFile, ap_block_state1_ignore_call6, "ap_block_state1_ignore_call6");
sc_trace(mVcdFile, ap_CS_fsm_state2, "ap_CS_fsm_state2");
sc_trace(mVcdFile, ap_NS_fsm, "ap_NS_fsm");
sc_trace(mVcdFile, ap_block_state1, "ap_block_state1");
#endif
}
}
grad_vertical_Mat_s::~grad_vertical_Mat_s() {
if (mVcdFile)
sc_close_vcd_trace_file(mVcdFile);
delete grp_Filter2D_fu_122;
}
void grad_vertical_Mat_s::thread_ap_var_for_const0() {
ap_var_for_const0 = ap_const_lv6_10;
}
void grad_vertical_Mat_s::thread_ap_var_for_const1() {
ap_var_for_const1 = ap_const_lv7_20;
}
void grad_vertical_Mat_s::thread_ap_var_for_const2() {
ap_var_for_const2 = ap_const_lv8_0;
}
void grad_vertical_Mat_s::thread_ap_var_for_const3() {
ap_var_for_const3 = ap_const_lv7_60;
}
void grad_vertical_Mat_s::thread_ap_var_for_const4() {
ap_var_for_const4 = ap_const_lv8_40;
}
void grad_vertical_Mat_s::thread_ap_var_for_const5() {
ap_var_for_const5 = ap_const_lv7_40;
}
void grad_vertical_Mat_s::thread_ap_var_for_const6() {
ap_var_for_const6 = ap_const_lv8_60;
}
void grad_vertical_Mat_s::thread_ap_var_for_const7() {
ap_var_for_const7 = ap_const_lv8_C0;
}
void grad_vertical_Mat_s::thread_ap_var_for_const8() {
ap_var_for_const8 = ap_const_lv8_A0;
}
void grad_vertical_Mat_s::thread_ap_var_for_const9() {
ap_var_for_const9 = ap_const_lv7_0;
}
void grad_vertical_Mat_s::thread_ap_var_for_const10() {
ap_var_for_const10 = ap_const_lv8_20;
}
void grad_vertical_Mat_s::thread_ap_var_for_const11() {
ap_var_for_const11 = ap_const_lv8_E0;
}
void grad_vertical_Mat_s::thread_ap_var_for_const12() {
ap_var_for_const12 = ap_const_lv6_30;
}
void grad_vertical_Mat_s::thread_ap_clk_no_reset_() {
if ( ap_rst.read() == ap_const_logic_1) {
ap_CS_fsm = ap_ST_fsm_state1;
} else {
ap_CS_fsm = ap_NS_fsm.read();
}
if ( ap_rst.read() == ap_const_logic_1) {
ap_done_reg = ap_const_logic_0;
} else {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_continue.read())) {
ap_done_reg = ap_const_logic_0;
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(grp_Filter2D_fu_122_ap_done.read(), ap_const_logic_1))) {
ap_done_reg = ap_const_logic_1;
}
}
if ( ap_rst.read() == ap_const_logic_1) {
grp_Filter2D_fu_122_ap_start_reg = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
!(esl_seteq<1,1,1>(ap_const_logic_0, real_start.read()) || esl_seteq<1,1,1>(ap_done_reg.read(), ap_const_logic_1)))) {
grp_Filter2D_fu_122_ap_start_reg = ap_const_logic_1;
} else if (esl_seteq<1,1,1>(ap_const_logic_1, grp_Filter2D_fu_122_ap_ready.read())) {
grp_Filter2D_fu_122_ap_start_reg = ap_const_logic_0;
}
}
if ( ap_rst.read() == ap_const_logic_1) {
start_once_reg = ap_const_logic_0;
} else {
if ((esl_seteq<1,1,1>(ap_const_logic_1, real_start.read()) &&
esl_seteq<1,1,1>(ap_const_logic_0, internal_ap_ready.read()))) {
start_once_reg = ap_const_logic_1;
} else if (esl_seteq<1,1,1>(ap_const_logic_1, internal_ap_ready.read())) {
start_once_reg = ap_const_logic_0;
}
}
}
void grad_vertical_Mat_s::thread_ap_CS_fsm_state1() {
ap_CS_fsm_state1 = ap_CS_fsm.read()[0];
}
void grad_vertical_Mat_s::thread_ap_CS_fsm_state2() {
ap_CS_fsm_state2 = ap_CS_fsm.read()[1];
}
void grad_vertical_Mat_s::thread_ap_block_state1() {
ap_block_state1 = (esl_seteq<1,1,1>(ap_const_logic_0, real_start.read()) || esl_seteq<1,1,1>(ap_done_reg.read(), ap_const_logic_1));
}
void grad_vertical_Mat_s::thread_ap_block_state1_ignore_call6() {
ap_block_state1_ignore_call6 = (esl_seteq<1,1,1>(ap_const_logic_0, real_start.read()) || esl_seteq<1,1,1>(ap_done_reg.read(), ap_const_logic_1));
}
void grad_vertical_Mat_s::thread_ap_done() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(grp_Filter2D_fu_122_ap_done.read(), ap_const_logic_1))) {
ap_done = ap_const_logic_1;
} else {
ap_done = ap_done_reg.read();
}
}
void grad_vertical_Mat_s::thread_ap_idle() {
if ((esl_seteq<1,1,1>(ap_const_logic_0, real_start.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()))) {
ap_idle = ap_const_logic_1;
} else {
ap_idle = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_ap_ready() {
ap_ready = internal_ap_ready.read();
}
void grad_vertical_Mat_s::thread_grp_Filter2D_fu_122_ap_start() {
grp_Filter2D_fu_122_ap_start = grp_Filter2D_fu_122_ap_start_reg.read();
}
void grad_vertical_Mat_s::thread_img_in_data_stream_0_V_read() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) {
img_in_data_stream_0_V_read = grp_Filter2D_fu_122_p_src_data_stream_0_V_read.read();
} else {
img_in_data_stream_0_V_read = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_img_in_data_stream_1_V_read() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) {
img_in_data_stream_1_V_read = grp_Filter2D_fu_122_p_src_data_stream_1_V_read.read();
} else {
img_in_data_stream_1_V_read = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_img_in_data_stream_2_V_read() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) {
img_in_data_stream_2_V_read = grp_Filter2D_fu_122_p_src_data_stream_2_V_read.read();
} else {
img_in_data_stream_2_V_read = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_img_out_data_stream_0_V_din() {
img_out_data_stream_0_V_din = grp_Filter2D_fu_122_p_dst_data_stream_0_V_din.read();
}
void grad_vertical_Mat_s::thread_img_out_data_stream_0_V_write() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) {
img_out_data_stream_0_V_write = grp_Filter2D_fu_122_p_dst_data_stream_0_V_write.read();
} else {
img_out_data_stream_0_V_write = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_img_out_data_stream_1_V_din() {
img_out_data_stream_1_V_din = grp_Filter2D_fu_122_p_dst_data_stream_1_V_din.read();
}
void grad_vertical_Mat_s::thread_img_out_data_stream_1_V_write() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) {
img_out_data_stream_1_V_write = grp_Filter2D_fu_122_p_dst_data_stream_1_V_write.read();
} else {
img_out_data_stream_1_V_write = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_img_out_data_stream_2_V_din() {
img_out_data_stream_2_V_din = grp_Filter2D_fu_122_p_dst_data_stream_2_V_din.read();
}
void grad_vertical_Mat_s::thread_img_out_data_stream_2_V_write() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read())) {
img_out_data_stream_2_V_write = grp_Filter2D_fu_122_p_dst_data_stream_2_V_write.read();
} else {
img_out_data_stream_2_V_write = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_internal_ap_ready() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(grp_Filter2D_fu_122_ap_done.read(), ap_const_logic_1))) {
internal_ap_ready = ap_const_logic_1;
} else {
internal_ap_ready = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_real_start() {
if ((esl_seteq<1,1,1>(ap_const_logic_0, start_full_n.read()) &&
esl_seteq<1,1,1>(ap_const_logic_0, start_once_reg.read()))) {
real_start = ap_const_logic_0;
} else {
real_start = ap_start.read();
}
}
void grad_vertical_Mat_s::thread_start_out() {
start_out = real_start.read();
}
void grad_vertical_Mat_s::thread_start_write() {
if ((esl_seteq<1,1,1>(ap_const_logic_0, start_once_reg.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, real_start.read()))) {
start_write = ap_const_logic_1;
} else {
start_write = ap_const_logic_0;
}
}
void grad_vertical_Mat_s::thread_ap_NS_fsm() {
switch (ap_CS_fsm.read().to_uint64()) {
case 1 :
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && !(esl_seteq<1,1,1>(ap_const_logic_0, real_start.read()) || esl_seteq<1,1,1>(ap_done_reg.read(), ap_const_logic_1)))) {
ap_NS_fsm = ap_ST_fsm_state2;
} else {
ap_NS_fsm = ap_ST_fsm_state1;
}
break;
case 2 :
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(grp_Filter2D_fu_122_ap_done.read(), ap_const_logic_1))) {
ap_NS_fsm = ap_ST_fsm_state1;
} else {
ap_NS_fsm = ap_ST_fsm_state2;
}
break;
default :
ap_NS_fsm = "XX";
break;
}
}
}
|
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
/**
* This module is off by default, but can be enabled to facilitate the display of
* extra debug information during code development.
*
* Just connect up 5V and GND to give it power, then connect up the pins assigned
* in Configuration_adv.h. For example, on the Re-ARM you could use:
*
* #define MAX7219_CLK_PIN 77
* #define MAX7219_DIN_PIN 78
* #define MAX7219_LOAD_PIN 79
*
* Max7219_init() is called automatically at startup, and then there are a number of
* support functions available to control the LEDs in the 8x8 grid.
*/
#include "MarlinConfig.h"
#if ENABLED(MAX7219_DEBUG)
#define MAX7219_ERRORS // Disable to save 406 bytes of Program Memory
#include "Max7219_Debug_LEDs.h"
#include "planner.h"
#include "stepper.h"
#include "Marlin.h"
#include "delay.h"
uint8_t LEDs[8*MAX7219_NUMBER_UNITS] = { 0 };
// Delay for 0.1875µs (16MHz AVR) or 0.15µs (20MHz AVR)
#define SIG_DELAY() DELAY_NS(188)
void Max7219_PutByte(uint8_t data) {
CRITICAL_SECTION_START;
for (uint8_t i = 8; i--;) {
SIG_DELAY();
WRITE(MAX7219_CLK_PIN, LOW); // tick
SIG_DELAY();
WRITE(MAX7219_DIN_PIN, (data & 0x80) ? HIGH : LOW); // send 1 or 0 based on data bit
SIG_DELAY();
WRITE(MAX7219_CLK_PIN, HIGH); // tock
SIG_DELAY();
data <<= 1;
}
CRITICAL_SECTION_END;
}
void Max7219_pulse_load() {
SIG_DELAY();
WRITE(MAX7219_LOAD_PIN, LOW); // tell the chip to load the data
SIG_DELAY();
WRITE(MAX7219_LOAD_PIN, HIGH);
SIG_DELAY();
}
void Max7219(const uint8_t reg, const uint8_t data) {
SIG_DELAY();
CRITICAL_SECTION_START;
SIG_DELAY();
Max7219_PutByte(reg); // specify register
SIG_DELAY();
Max7219_PutByte(data); // put data
CRITICAL_SECTION_END;
}
#if ENABLED(MAX7219_NUMERIC)
// Draw an integer with optional leading zeros and optional decimal point
void Max7219_Print(const uint8_t start, int16_t value, uint8_t size, const bool leadzero=false, bool dec=false) {
constexpr uint8_t led_numeral[10] = { 0x7E, 0x60, 0x6D, 0x79, 0x63, 0x5B, 0x5F, 0x70, 0x7F, 0x7A },
led_decimal = 0x80, led_minus = 0x01;
bool blank = false, neg = value < 0;
if (neg) value *= -1;
while (size--) {
const bool minus = neg && blank;
if (minus) neg = false;
Max7219(
max7219_reg_digit0 + start + size,
minus ? led_minus : blank ? 0x00 : led_numeral[value % 10] | (dec ? led_decimal : 0x00)
);
Max7219_pulse_load(); // tell the chips to load the clocked out data
value /= 10;
if (!value && !leadzero) blank = true;
dec = false;
}
}
// Draw a float with a decimal point and optional digits
void Max7219_Print(const uint8_t start, const float value, const uint8_t pre_size, const uint8_t post_size, const bool leadzero=false) {
if (pre_size) Max7219_Print(start, value, pre_size, leadzero, !!post_size);
if (post_size) {
const int16_t after = ABS(value) * (10 ^ post_size);
Max7219_Print(start + pre_size, after, post_size, true);
}
}
#endif // MAX7219_NUMERIC
inline void Max7219_Error(const char * const func, const int32_t v1, const int32_t v2=-1) {
#if ENABLED(MAX7219_ERRORS)
SERIAL_ECHOPGM("??? ");
serialprintPGM(func);
SERIAL_CHAR('(');
SERIAL_ECHO(v1);
if (v2 > 0) SERIAL_ECHOPAIR(", ", v2);
SERIAL_CHAR(')');
SERIAL_EOL();
#else
UNUSED(func); UNUSED(v1); UNUSED(v2);
#endif
}
/**
* uint32_t flipped(const uint32_t bits, const uint8_t n_bytes) operates on the number
* of bytes specified in n_bytes. The lower order bits of the supplied bits are flipped.
* flipped( x, 1) flips the low 8 bits of x.
* flipped( x, 2) flips the low 16 bits of x.
* flipped( x, 3) flips the low 24 bits of x.
* flipped( x, 4) flips the low 32 bits of x.
*/
inline uint32_t flipped(const uint32_t bits, const uint8_t n_bytes) {
uint32_t mask = 1, outbits = 0;
for (uint8_t b = 0; b < n_bytes * 8; b++) {
outbits = (outbits << 1);
if (bits & mask)
outbits |= 1;
mask <<= 1;
}
return outbits;
}
// Modify a single LED bit and send the changed line
void Max7219_LED_Set(const uint8_t x, const uint8_t y, const bool on) {
if (x > (MAX7219_X_LEDS - 1) || y > (MAX7219_Y_LEDS - 1)) return Max7219_Error(PSTR("Max7219_LED_Set"), x, y);
if (BIT_7219(x, y) == on) return;
XOR_7219(x, y);
SEND_7219(MAX7219_UPDATE_AXIS);
}
void Max7219_LED_On(const uint8_t x, const uint8_t y) {
if (x > (MAX7219_X_LEDS - 1) || y > (MAX7219_Y_LEDS - 1)) return Max7219_Error(PSTR("Max7219_LED_On"), x, y);
Max7219_LED_Set(x, y, true);
}
void Max7219_LED_Off(const uint8_t x, const uint8_t y) {
if (x > (MAX7219_X_LEDS - 1) || y > (MAX7219_Y_LEDS - 1)) return Max7219_Error(PSTR("Max7219_LED_Off"), x, y);
Max7219_LED_Set(x, y, false);
}
void Max7219_LED_Toggle(const uint8_t x, const uint8_t y) {
if (x > (MAX7219_X_LEDS - 1) || y > (MAX7219_Y_LEDS - 1)) return Max7219_Error(PSTR("Max7219_LED_Toggle"), x, y);
Max7219_LED_Set(x, y, !BIT_7219(x, y));
}
inline void _Max7219_Set_Digit_Segments(const uint8_t digit, const uint8_t val) {
LEDs[digit] = val;
SEND_7219(digit);
}
/*
* void Max7219_Set_Row( const uint8_t col, const uint32_t val) plots the low order bits of
* val to the specified row of the Max7219 matrix. With 4 Max7219 units in the chain, it
* is possible to display an entire 32-bit number with one call to the function (if appropriately
* orientated).
*/
void Max7219_Set_Row(const uint8_t row, const uint32_t val) {
if (row >= MAX7219_Y_LEDS) return Max7219_Error(PSTR("Max7219_Set_Row"), row);
uint32_t mask = 0x0000001;
for(uint8_t x = 0; x < MAX7219_X_LEDS; x++) {
if (val & mask)
SET_PIXEL_7219(MAX7219_X_LEDS-1-x, row);
else
CLEAR_PIXEL_7219(MAX7219_X_LEDS-1-x, row);
mask <<= 1;
}
#if _ROT == 90 || _ROT == 270
for(uint8_t x = 0; x < 8; x++)
SEND_7219(x); // force all columns out to the Max7219 chips and strobe them
#else
SEND_7219(row); // force the single column out to the Max7219 chips and strobe them
#endif
return;
}
void Max7219_Clear_Row(const uint8_t row) {
if (row > 7) return Max7219_Error(PSTR("Max7219_Clear_Row"), row);
#if _ROT == 90 || _ROT == 270
for (uint8_t col = 0; col < 8; col++) Max7219_LED_Off(col, row);
#else
_Max7219_Set_Digit_Segments(row, 0);
#endif
}
/*
* void Max7219_Set_Column( const uint8_t col, const uint32_t val) plots the low order bits of
* val to the specified column of the Max7219 matrix. With 4 Max7219 units in the chain, it
* is possible to display an entire 32-bit number with one call to the function (if appropriately
* orientated).
*/
void Max7219_Set_Column(const uint8_t col, const uint32_t val) {
if (col >= MAX7219_X_LEDS) return Max7219_Error(PSTR("Max7219_Set_Column"), col);
uint32_t mask = 0x0000001;
for(uint8_t y = 0; y < MAX7219_Y_LEDS; y++) {
if (val & mask)
SET_PIXEL_7219(col, MAX7219_Y_LEDS-1-y);
else
CLEAR_PIXEL_7219(col, MAX7219_Y_LEDS-1-y);
mask <<= 1;
}
#if _ROT == 90 || _ROT == 270
SEND_7219(col); // force the column out to the Max7219 chips and strobe them
#else
for(uint8_t yy = 0; yy < 8; yy++)
SEND_7219(yy); // force all columns out to the Max7219 chips and strobe them
#endif
return;
}
void Max7219_Clear_Column(const uint8_t col) {
if (col >= MAX7219_X_LEDS) return Max7219_Error(PSTR("Max7219_Clear_Column"), col);
for(uint8_t yy = 0; yy < MAX7219_Y_LEDS; yy++)
CLEAR_PIXEL_7219(col, yy);
#if _ROT == 90 || _ROT == 270
SEND_7219(col); // force the column out to the Max7219 chips and strobe them
#else
for(uint8_t y = 0; y < 8; y++)
SEND_7219(y); // force all columns out to the Max7219 chips and strobe them
#endif
return;
}
void Max7219_Clear() {
for (uint8_t i = 0; i <= 7; i++) { // Clear LED bitmap
for (uint8_t j = 0; j < MAX7219_NUMBER_UNITS; j++)
LEDs[i + j * 8] = 0x00;
SEND_7219(i);
}
}
void Max7219_Set_Rows_16bits(const uint8_t y, uint32_t val) {
#if MAX7219_X_LEDS == 8
if (y > MAX7219_Y_LEDS - 2) return Max7219_Error(PSTR("Max7219_Set_Rows_16bits"), y, val);
Max7219_Set_Row(y + 1, val); val >>= 8;
Max7219_Set_Row(y + 0, val);
#else // at least 16 bits on each row
if (y > MAX7219_Y_LEDS - 1) return Max7219_Error(PSTR("Max7219_Set_Rows_16bits"), y, val);
Max7219_Set_Row(y, val);
#endif
}
void Max7219_Set_Rows_32bits(const uint8_t y, uint32_t val) {
#if MAX7219_X_LEDS == 8
if (y > MAX7219_Y_LEDS - 4) return Max7219_Error(PSTR("Max7219_Set_Rows_32bits"), y, val);
Max7219_Set_Row(y + 3, val); val >>= 8;
Max7219_Set_Row(y + 2, val); val >>= 8;
Max7219_Set_Row(y + 1, val); val >>= 8;
Max7219_Set_Row(y + 0, val);
#elif MAX7219_X_LEDS == 16
if (y > MAX7219_Y_LEDS - 2) return Max7219_Error(PSTR("Max7219_Set_Rows_32bits"), y, val);
Max7219_Set_Row(y + 1, val); val >>= 16;
Max7219_Set_Row(y + 0, val);
#else // at least 24 bits on each row. In the 3 matrix case, just display the low 24 bits
if (y > MAX7219_Y_LEDS - 1) return Max7219_Error(PSTR("Max7219_Set_Rows_32bits"), y, val);
Max7219_Set_Row(y, val);
#endif
}
void Max7219_Set_Columns_16bits(const uint8_t x, uint32_t val) {
#if MAX7219_Y_LEDS == 8
if (x > MAX7219_X_LEDS - 2) return Max7219_Error(PSTR("Max7219_Set_Columns_16bits"), x, val);
Max7219_Set_Column(x + 0, val); val >>= 8;
Max7219_Set_Column(x + 1, val);
#else // at least 16 bits in each column
if (x > MAX7219_X_LEDS - 1) return Max7219_Error(PSTR("Max7219_Set_Columns_16bits"), x, val);
Max7219_Set_Column(x, val);
#endif
}
void Max7219_Set_Columns_32bits(const uint8_t x, uint32_t val) {
#if MAX7219_Y_LEDS == 8
if (x > MAX7219_X_LEDS - 4) return Max7219_Error(PSTR("Max7219_Set_Rows_32bits"), x, val);
Max7219_Set_Column(x + 3, val); val >>= 8;
Max7219_Set_Column(x + 2, val); val >>= 8;
Max7219_Set_Column(x + 1, val); val >>= 8;
Max7219_Set_Column(x + 0, val);
#elif MAX7219_Y_LEDS == 16
if (x > MAX7219_X_LEDS - 2) return Max7219_Error(PSTR("Max7219_Set_Rows_32bits"), x, val);
Max7219_Set_Column(x + 1, val); val >>= 16;
Max7219_Set_Column(x + 0, val);
#else // at least 24 bits on each row. In the 3 matrix case, just display the low 24 bits
if (x > MAX7219_X_LEDS - 1) return Max7219_Error(PSTR("Max7219_Set_Rows_32bits"), x, val);
Max7219_Set_Column(x, val);
#endif
}
void Max7219_register_setup() {
// Initialize the Max7219
for(int i=0; i < MAX7219_NUMBER_UNITS; i++)
Max7219(max7219_reg_scanLimit, 0x07);
Max7219_pulse_load(); // tell the chips to load the clocked out data
for(int i=0; i < MAX7219_NUMBER_UNITS; i++)
Max7219(max7219_reg_decodeMode, 0x00); // using an led matrix (not digits)
Max7219_pulse_load(); // tell the chips to load the clocked out data
for(int i=0; i < MAX7219_NUMBER_UNITS; i++)
Max7219(max7219_reg_shutdown, 0x01); // not in shutdown mode
Max7219_pulse_load(); // tell the chips to load the clocked out data
for(int i=0; i < MAX7219_NUMBER_UNITS; i++)
Max7219(max7219_reg_displayTest, 0x00); // no display test
Max7219_pulse_load(); // tell the chips to load the clocked out data
for(int i=0; i < MAX7219_NUMBER_UNITS; i++)
Max7219(max7219_reg_intensity, 0x01 & 0x0F); // the first 0x0F is the value you can set
// range: 0x00 to 0x0F
Max7219_pulse_load(); // tell the chips to load the clocked out data
}
#ifdef MAX7219_INIT_TEST
#if (MAX7219_INIT_TEST + 0) == 2
inline void Max7219_spiral(const bool on, const uint16_t del) {
constexpr int8_t way[] = { 1, 0, 0, 1, -1, 0, 0, -1 };
int8_t px = 0, py = 0, dir = 0;
for (uint8_t i = MAX7219_X_LEDS * MAX7219_Y_LEDS; i--;) {
Max7219_LED_Set(px, py, on);
delay(del);
const int8_t x = px + way[dir], y = py + way[dir + 1];
if (!WITHIN(x, 0, MAX7219_X_LEDS-1) || !WITHIN(y, 0, MAX7219_Y_LEDS-1) || BIT_7219(x, y) == on) dir = (dir + 2) & 0x7;
px += way[dir]; py += way[dir + 1];
}
}
#else
inline void Max7219_sweep(const int8_t dir, const uint16_t ms, const bool on) {
uint8_t x = dir > 0 ? 0 : MAX7219_X_LEDS-1;
for (uint8_t i = MAX7219_X_LEDS; i--; x += dir) {
Max7219_Set_Column(x, on ? 0xFFFFFFFF : 0x00000000);
delay(ms);
}
}
#endif
#endif // MAX7219_INIT_TEST
void Max7219_init() {
SET_OUTPUT(MAX7219_DIN_PIN);
SET_OUTPUT(MAX7219_CLK_PIN);
OUT_WRITE(MAX7219_LOAD_PIN, HIGH);
delay(1);
Max7219_register_setup();
for (uint8_t i = 0; i <= 7; i++) { // Empty registers to turn all LEDs off
LEDs[i] = 0x00;
Max7219(max7219_reg_digit0 + i, 0);
Max7219_pulse_load(); // tell the chips to load the clocked out data
}
#ifdef MAX7219_INIT_TEST
#if (MAX7219_INIT_TEST + 0) == 2
Max7219_spiral(true, 8);
delay(150);
Max7219_spiral(false, 8);
#else
// Do an aesthetically-pleasing pattern to fully test the Max7219 module and LEDs.
// Light up and turn off columns, both forward and backward.
Max7219_sweep(1, 20, true);
Max7219_sweep(1, 20, false);
delay(150);
Max7219_sweep(-1, 20, true);
Max7219_sweep(-1, 20, false);
#endif
#endif
}
/**
* This code demonstrates some simple debugging using a single 8x8 LED Matrix. If your feature could
* benefit from matrix display, add its code here. Very little processing is required, so the 7219 is
* ideal for debugging when realtime feedback is important but serial output can't be used.
*/
// Apply changes to update a marker
inline void Max7219_Mark16(const uint8_t y, const uint8_t v1, const uint8_t v2) {
#if MAX7219_X_LEDS == 8
#if MAX7219_Y_LEDS == 8
Max7219_LED_Off(v1 & 0x7, y + (v1 >= 8));
Max7219_LED_On(v2 & 0x7, y + (v2 >= 8));
#else
Max7219_LED_Off(y, v1 & 0xF); // The Max7219 Y-Axis has at least 16 LED's. So use a single column
Max7219_LED_On(y, v2 & 0xF);
#endif
#else // LED matrix has at least 16 LED's on the X-Axis. Use single line of LED's
Max7219_LED_Off(v1 & 0xf, y);
Max7219_LED_On(v2 & 0xf, y);
#endif
}
// Apply changes to update a tail-to-head range
inline void Max7219_Range16(const uint8_t y, const uint8_t ot, const uint8_t nt, const uint8_t oh, const uint8_t nh) {
#if MAX7219_X_LEDS == 8
#if MAX7219_Y_LEDS == 8
if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF)
Max7219_LED_Off(n & 0x7, y + (n >= 8));
if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF)
Max7219_LED_On(n & 0x7, y + (n >= 8));
#else // The Max7219 Y-Axis has at least 16 LED's. So use a single column
if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF)
Max7219_LED_Off(y, n & 0xF);
if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF)
Max7219_LED_On(y, n & 0xF);
#endif
#else // LED matrix has at least 16 LED's on the X-Axis. Use single line of LED's
if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF)
Max7219_LED_Off(n & 0xf, y);
if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF)
Max7219_LED_On(n & 0xf, y);
#endif
}
// Apply changes to update a quantity
inline void Max7219_Quantity16(const uint8_t y, const uint8_t ov, const uint8_t nv) {
for (uint8_t i = MIN(nv, ov); i < MAX(nv, ov); i++)
#if MAX7219_X_LEDS == 8
#if MAX7219_Y_LEDS == 8
Max7219_LED_Set(i >> 1, y + (i & 1), nv >= ov); // single 8x8 LED matrix. Use two lines to get 16 LED's
#else
Max7219_LED_Set(y, i, nv >= ov); // The Max7219 Y-Axis has at least 16 LED's. So use a single column
#endif
#else
Max7219_LED_Set(i, y, nv >= ov); // LED matrix has at least 16 LED's on the X-Axis. Use single line of LED's
#endif
}
void Max7219_idle_tasks() {
#define MAX7219_USE_HEAD (defined(MAX7219_DEBUG_PLANNER_HEAD) || defined(MAX7219_DEBUG_PLANNER_QUEUE))
#define MAX7219_USE_TAIL (defined(MAX7219_DEBUG_PLANNER_TAIL) || defined(MAX7219_DEBUG_PLANNER_QUEUE))
#if MAX7219_USE_HEAD || MAX7219_USE_TAIL
CRITICAL_SECTION_START;
#if MAX7219_USE_HEAD
const uint8_t head = planner.block_buffer_head;
#endif
#if MAX7219_USE_TAIL
const uint8_t tail = planner.block_buffer_tail;
#endif
CRITICAL_SECTION_END;
#endif
#if ENABLED(MAX7219_DEBUG_PRINTER_ALIVE)
static uint8_t refresh_cnt; // = 0
constexpr uint16_t refresh_limit = 5;
static millis_t next_blink = 0;
const millis_t ms = millis();
const bool do_blink = ELAPSED(ms, next_blink);
#else
static uint16_t refresh_cnt; // = 0
constexpr bool do_blink = true;
constexpr uint16_t refresh_limit = 50000;
#endif
// Some Max7219 units are vulnerable to electrical noise, especially
// with long wires next to high current wires. If the display becomes
// corrupted, this will fix it within a couple seconds.
if (do_blink && ++refresh_cnt >= refresh_limit) {
refresh_cnt = 0;
Max7219_register_setup();
}
#if ENABLED(MAX7219_DEBUG_PRINTER_ALIVE)
if (do_blink) {
Max7219_LED_Toggle(MAX7219_X_LEDS - 1, MAX7219_Y_LEDS - 1);
next_blink = ms + 1000;
}
#endif
#if defined(MAX7219_DEBUG_PLANNER_HEAD) && defined(MAX7219_DEBUG_PLANNER_TAIL) && MAX7219_DEBUG_PLANNER_HEAD == MAX7219_DEBUG_PLANNER_TAIL
static int16_t last_head_cnt = 0xF, last_tail_cnt = 0xF;
if (last_head_cnt != head || last_tail_cnt != tail) {
Max7219_Range16(MAX7219_DEBUG_PLANNER_HEAD, last_tail_cnt, tail, last_head_cnt, head);
last_head_cnt = head;
last_tail_cnt = tail;
}
#else
#ifdef MAX7219_DEBUG_PLANNER_HEAD
static int16_t last_head_cnt = 0x1;
if (last_head_cnt != head) {
Max7219_Mark16(MAX7219_DEBUG_PLANNER_HEAD, last_head_cnt, head);
last_head_cnt = head;
}
#endif
#ifdef MAX7219_DEBUG_PLANNER_TAIL
static int16_t last_tail_cnt = 0x1;
if (last_tail_cnt != tail) {
Max7219_Mark16(MAX7219_DEBUG_PLANNER_TAIL, last_tail_cnt, tail);
last_tail_cnt = tail;
}
#endif
#endif
#ifdef MAX7219_DEBUG_PLANNER_QUEUE
static int16_t last_depth = 0;
const int16_t current_depth = (head - tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1) & 0xF;
if (current_depth != last_depth) {
Max7219_Quantity16(MAX7219_DEBUG_PLANNER_QUEUE, last_depth, current_depth);
last_depth = current_depth;
}
#endif
}
#endif // MAX7219_DEBUG
|
#include "physical_device.h"
using namespace VulkanUtils;
void PhysicalDevice::PickPhysicalDevice(VulkanApp& app) {
uint32_t deviceCount;
vkEnumeratePhysicalDevices(app.instance, &deviceCount, nullptr);
if (deviceCount == 0) {
throw std::runtime_error("There is no gpu that support vulkan !");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(app.instance, &deviceCount, devices.data());
for (const auto& device : devices) {
if (IsDeviceSuitable(device, app.surface, app.deviceExtensions)) {
app.physicalDevice = device;
app.indices = FindQueueFamilies(device, app.surface);
#ifndef NDEBUG
VkPhysicalDeviceProperties properties;
vkGetPhysicalDeviceProperties(app.physicalDevice, &properties);
std::cout << "Selected gpu name : \033[1;34m" << properties.deviceName << "\033[0m" << std::endl;
#endif
break;
}
}
if (app.physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("There is no suitable gpu for this app !");
}
}
const bool PhysicalDevice::IsDeviceSuitable(const VkPhysicalDevice& device, const VkSurfaceKHR& surface, const std::vector<const char*>& extensions) {
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
auto indices = FindQueueFamilies(device, surface);
auto extensionsSupported = CheckDeviceExtensionSupport(device, extensions);
auto swapChainAdequate = false;
if (extensionsSupported) {
auto swapChainSupport = SwapChainSupportDetails::QuerySwapChainSupport(device, surface);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
}
// deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU
return indices.IsComplete() && extensionsSupported && swapChainAdequate;
}
const bool PhysicalDevice::CheckDeviceExtensionSupport(const VkPhysicalDevice& device, const std::vector<const char*>& extensions) {
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
for (const auto& extension : extensions) {
auto found = false;
for (const auto& availableExtension : availableExtensions) {
if (strcmp(extension, availableExtension.extensionName) == 0) {
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
QueueFamilyIndices PhysicalDevice::FindQueueFamilies(const VkPhysicalDevice& device, const VkSurfaceKHR& surface) {
QueueFamilyIndices indices;
uint32_t queueFamilyCount;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies) {
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (presentSupport) {
indices.presentFamily = i;
}
if (indices.IsComplete()) {
break;
}
i++;
}
return indices;
}
|
#include <iostream>
using namespace std;
// Verifica se o sistema eh possivel e determinado
bool spd(double a1, double b1, double a2, double b2) {
if ((a1 * b2) - (a2 * b1) != 0) {
return true;
} else {
return false;
}
}
int main() {
double x1, y1, x2, y2, coordenadaConhecida, coordenadaDesconhecida, a1, b1, a2, b2, det;
char caractere;
cin >> x1 >> y1 >> x2 >> y2 >> caractere >> coordenadaConhecida;
a1 = y2 - y1;
b1 = x2 - x1;
if (caractere == 'x') {
a2 = 1;
b2 = 0;
if (spd(a1, b1, a2, b2)) {
coordenadaDesconhecida = y1 + (coordenadaConhecida - x1) * (y2 - y1) / (x2 - x1);
cout << coordenadaDesconhecida << endl;
} else {
cout << "nenhuma" << endl;
}
} else {
a2 = 0;
b2 = 1;
if (spd(a1, b1, a2, b2)) {
coordenadaDesconhecida = x1 + (coordenadaConhecida - y1) * (x2 - x1) / (y2 - y1);
cout << coordenadaDesconhecida << endl;
} else {
cout << "nenhuma" << endl;
}
}
}
|
// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// Copyright (C) 2020 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// This file incorporates work covered by the following copyright and permission
// notice:
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
//
//===----------------------------------------------------------------------===//
#include "support/pstl_test_config.h"
#include _PSTL_TEST_HEADER(execution)
#if _ONEDPL_USE_RANGES
#include _PSTL_TEST_HEADER(ranges)
#endif
#include "support/utils.h"
#include <iostream>
int32_t
main()
{
#if _ONEDPL_USE_RANGES
constexpr int max_n = 10;
int data[max_n] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto lambda1 = [](auto& val) { return val = val * val; };
using namespace oneapi::dpl::experimental::ranges;
{
sycl::buffer<int> A(data, sycl::range<1>(max_n));
auto view = all_view<int, sycl::access::mode::read_write>(A);
for_each(TestUtils::default_dpcpp_policy, view, lambda1);
}
//check result
int expected[max_n];
::std::transform(data, data + max_n, expected, lambda1);
EXPECT_EQ_N(expected, data, max_n, "wrong effect from for_each with sycl ranges");
#endif //_ONEDPL_USE_RANGES
::std::cout << TestUtils::done() << ::std::endl;
return 0;
}
|
#ifdef ONLINE_JUDGE
#include <bits/stdc++.h>
#else
#include <algorithm>
#include <bitset>
#include <list>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#endif
using namespace std;
// lambda : [] (int a, int b) -> bool { body return }
// string r_str = R"(raw string)"
#define mp make_pair
#define mt make_tuple
#define eb emplace_back
#define pb push_back
#define fi first
#define se second
#define LL long long
#define ULL unsigned long long
#define PI (atan(1) * 4)
#define BASE 73
#define NMAX 10000
#define NMAX2 20001
#define MOD1 1000000007
#define ALL(V) (V).begin(), (V).end()
#define ALLR(V) (V).rbegin(), (V).rend()
#define CRLINE Duxar(__LINE__);
#define SHOWME(x) cerr << __LINE__ << ": " << #x << " = " << (x) << endl;
#define ENTER putchar('\n');
#define step(i) (i & (i - 1)) ^ i
int dx4[] = {-1, 0, 1, 0};
int dy4[] = {0, 1, 0, -1};
int dx8[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1};
void Duxar(int _this_line) {
#ifndef ONLINE_JUDGE
printf("\n . . . . . . . . . . . . . Passed line - %d\n", _this_line);
#endif
}
bool AreEqual(double a, double b) {
return (fabs(a - b) < 1e-10);
}
template <class T>
bool GetNr(T &_value) {
T _sign = 1;
char ch;
_value = 0;
while(!isdigit(ch = getchar())) {
if (ch == -1) {
return false;
}
ch == '-' ? _sign = -1 : _sign = 1 ;
}
do {
_value = _value * 10 + (ch - '0');
} while(isdigit(ch = getchar()));
_value *= _sign;
return true;
}
int N, M;
char mat[500][501];
int dp[500][500];
int main(){
string fileInput = "tort3";
#ifdef INFOARENA
freopen((fileInput + ".in").c_str(), "r", stdin);
freopen((fileInput + ".out").c_str(), "w", stdout);
#else
#ifndef ONLINE_JUDGE
freopen("/Users/duxar/Workplace/Xcode Projects/Selectie/Selectie/input", "r", stdin);
freopen("/Users/duxar/Workplace/Xcode Projects/Selectie/Selectie/result", "w", stdout);
#endif
#endif
int i, j, x, y;
GetNr(N); GetNr(M);
for (i = 0; i < N; ++i) {
for (j = 0; j < M; ++j) {
dp[i][j] = 1;
}
scanf("%s", mat[i]);
}
for (i = 1; i < N; ++i) {
for (j = 1; j < M; ++j) {
if (mat[i][j] == mat[i - 1][j] && mat[i][j] == mat[i - 1][j - 1] && mat[i][j] == mat[i][j - 1]) {
dp[i][j] = max(dp[i][j], 1 + min({dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]}));
}
}
}
for (int lg = min(N, M); lg; --lg) {
for (i = 0; i < N; ++i) {
for (j = 0; j < M; ++j) {
if (dp[i][j] >= lg) {
if (mat[i][j] != '-' && mat[i - lg + 1][j] != '-' && mat[i - lg + 1][j - lg + 1] != '-' && mat[i][j - lg + 1] != '-') {
printf("%d %d %d\n", lg, i + 1, j + 1);
for (x = i - lg + 1; x <= i; ++x) {
for (y = j - lg + 1; y <= j; ++y) {
mat[x][y] = '-';
dp[x][y] = 0;
}
}
}
}
}
}
}
return 0;
}
|
//$Id: ErrorModel.hpp 1398 2015-01-07 20:39:37Z tdnguyen $
//------------------------------------------------------------------------------
// ErrorModel
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2020 United States Government as represented by the
// Administrator of The National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract
// number NNG06CA54C
//
// Author: Tuan Dang Nguyen, NASA/GSFC.
// Created: 2015/01/07
//
/**
* Definition for the ErrorModel class used to define an error model for a measurement model
*/
//------------------------------------------------------------------------------
#ifndef ErrorModel_hpp
#define ErrorModel_hpp
#include "estimation_defs.hpp"
#include "GmatBase.hpp"
class ESTIMATION_API ErrorModel : public GmatBase
//class GMAT_API ErrorModel : public GmatBase
{
public:
ErrorModel(const std::string name);
virtual ~ErrorModel();
ErrorModel(const ErrorModel& em);
ErrorModel& operator=(const ErrorModel& em);
bool operator==(const ErrorModel& em);
virtual GmatBase* Clone() const;
virtual bool Initialize();
virtual bool Finalize();
// Access methods derived classes can override
virtual std::string GetParameterText(const Integer id) const;
virtual std::string GetParameterUnit(const Integer id) const;
virtual Integer GetParameterID(const std::string &str) const;
virtual Gmat::ParameterType
GetParameterType(const Integer id) const;
virtual std::string GetParameterTypeString(const Integer id) const;
virtual bool IsParameterReadOnly(const Integer id) const;
virtual bool IsParameterReadOnly(const std::string &label) const;
virtual std::string GetStringParameter(const Integer id) const;
virtual bool SetStringParameter(const Integer id,
const std::string &value);
virtual std::string GetStringParameter(const Integer id,
const Integer index) const;
virtual bool SetStringParameter(const Integer id,
const std::string &value,
const Integer index);
virtual std::string GetStringParameter(const std::string &label) const;
virtual bool SetStringParameter(const std::string &label,
const std::string &value);
virtual std::string GetStringParameter(const std::string &label,
const Integer index) const;
virtual bool SetStringParameter(const std::string &label,
const std::string &value,
const Integer index);
virtual const StringArray&
GetStringArrayParameter(const Integer id) const;
virtual const StringArray&
GetStringArrayParameter(const std::string &label) const;
virtual Real GetRealParameter(const Integer id) const;
virtual Real SetRealParameter(const Integer id,
const Real value);
virtual Real GetRealParameter(const std::string& label) const;
virtual Real SetRealParameter(const std::string& label,
const Real value);
virtual Integer GetIntegerParameter(const Integer id) const;
virtual Integer SetIntegerParameter(const Integer id,
const Integer value);
virtual Integer GetIntegerParameter(const std::string &label) const;
virtual Integer SetIntegerParameter(const std::string &label,
const Integer value);
//virtual bool SetRefObject(GmatBase *obj, const UnsignedInt type,
// const std::string &name = "");
virtual bool IsEstimationParameterValid(const Integer id);
virtual Integer GetEstimationParameterSize(const Integer id);
virtual Real* GetEstimationParameterValue(const Integer id);
virtual Integer HasParameterCovariances(Integer parameterId);
virtual Rmatrix* GetParameterCovariances(Integer parameterId);
/// @todo: Check this
DEFAULT_TO_NO_CLONES
DEFAULT_TO_NO_REFOBJECTS
protected:
/// Measurement type
std::string measurementType; // Its value to be ("Range_KM") "Range", SN_Range", "DSN_SeqRange", ("Doppler_RangeRate") "RangeRate", "DSN_TCP", ("TDRSDoppler_HZ") "SN_Doppler", etc
///// Measurement trip
//Integer measurementTrip; // specify number of ways of a measurement. It would be 1 for one-way, 2 for two-ways, 3 for three-ways, and so on. It is 0 for all trips
///// Participant name list
//StringArray participantNameList; // It contains a list of participant name
/// Measurement noise sigma
Real noiseSigma; // specify noise sigma of a measurement
///// Noise Model
//std::string noiseModel; // specify noise model. It will be "RandomConstant" for Gausian noise model.
/// Measurement bias
Real bias; // specify bias of a measurement
/// Measurement bias sigma
Real biasSigma; // specify bias sigma of a measurement
/// Solve-for parameters
StringArray solveforNames; // It contains a name list of solve-for parameters
/// ErrorModel ID
std::string modelId; // Similar to the instanceName, but uses object ids instead of object names
/// Class parameter ID enumeration
enum
{
TYPE = GmatBaseParamCount,
//TRIP,
//STRAND,
NOISE_SIGMA,
//NOISE_MODEL,
BIAS,
BIAS_SIGMA,
SOLVEFORS,
MODEL_ID,
ErrorModelParamCount
};
// Start with the parameter IDs and associates strings
/// Strings associated with the ErrorModel parameters
static const std::string
PARAMETER_TEXT[ErrorModelParamCount - GmatBaseParamCount];
/// Types of the ErrorModel parameters
static const Gmat::ParameterType
PARAMETER_TYPE[ErrorModelParamCount - GmatBaseParamCount];
private:
StringArray GetAllAvailableTypes();
// std::string CheckTypeDeprecation(const std::string datatype);
// std::map<std::string, std::string> depTypeMap;
};
#endif /* ErrorModel_hpp */
|
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 25;
typedef unsigned long long ll;
char str[maxn];
ll dp[maxn][maxn][maxn];
ll solve () {
int n = strlen(str), c = 0;
for (int i = 0; i < n; i++) if (str[i] == '-') c++;
memset(dp, 0, sizeof(dp));
dp[0][0][0] = 1;
for (int i = 0; i < n; i++) {
if (str[i] == '+') {
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
if (dp[i][x][y] == 0) continue;
dp[i+1][x][y+1] += dp[i][x][y]; // 当前位置不变
if (i - x - y > 0) // 和1~i之间满足+的位置交换
dp[i+1][x][y+1] += dp[i][x][y] * (i-x-y);
dp[i+1][x][y] += dp[i][x][y] * y; // 和1~i之间不满足+的位置交换
}
}
} else {
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
if (dp[i][x][y] == 0) continue;
if (i - x - y > 0) // 和1~i之间满足+的位置交换
dp[i+1][x+1][y] += dp[i][x][y] * (i-x-y);
if (y) // 和1~i之间不满足+的位置交换
dp[i+1][x+1][y-1] += dp[i][x][y] * y;
}
}
}
}
return dp[n][c][0];
}
int main () {
while (scanf("%s", str) == 1) {
printf("%llu\n", solve());
}
return 0;
}
|
#include <cstdio>
#include <vector>
void dfs(long node, const std::vector<std::vector<long> > &g, std::vector<bool> &visited, const std::vector<int> &colors, long col){
if(visited[node]){return;}
visited[node] = true;
for(long p = 0; p < g[node].size(); p++){
long u = g[node][p];
if(visited[u] || colors[u] != col){continue;}
dfs(u, g, visited, colors, col);
}
return;
}
int main(){
long n; scanf("%ld", &n);
std::vector<int> color(n, 0);
for(long p = 0; p < n; p++){scanf("%d", &color[p]);}
std::vector<std::vector<long> > g(n);
for(long p = 1; p < n; p++){
long x, y; scanf("%ld %ld", &x, &y);
--x; --y;
g[x].push_back(y); g[y].push_back(x);
}
std::vector<bool> markWB(n, 0);
long countWB(0);
for(long p = 0; p < n; p++){
if(markWB[p] || color[p] == 1){continue;}
++countWB;
dfs(p, g, markWB, color, 0);
}
std::vector<bool> markBW(n, 0);
long countBW(0);
for(long p = 0; p < n; p++){
if(markBW[p] || color[p] == 0){continue;}
++countBW;
dfs(p, g, markBW, color, 1);
}
long count = (countBW < countWB) ? countBW : countWB;
printf("%ld\n", countBW);
printf("%ld\n", countWB);
printf("%ld\n", count);
return 0;
}
|
//a cpp file for the global functions implementation
//If two students are equal the return value of such a function will be 0.
//If the first student is bigger than the second one, the return value will be 1, otherwise - 1.
#define _CRT_SECURE_NO_WARNINGS
#include "compara_studenti.h"
#include "student.h"
#include <iostream>
#include <string.h>
int compara_nume(Student s1, Student s2)
{
char n1[50], n2[50];
strcpy(n1, s1.getname());
strcpy(n2, s2.getname());
if (strcmp(n1, n2) > 0)
return 1;
if (strcmp(n1, n2) < 0)
return -1;
if (strcmp(n1, n2) == 0)
return 0;
}
int compara_mate(Student s1, Student s2)
{
if (s1.getmate() > s2.getmate())
return 1;
if (s1.getmate() < s2.getmate())
return -1;
if (s1.getmate() == s2.getmate())
return 0;
}
int compara_eng(Student s1, Student s2)
{
if (s1.geteng() > s2.geteng())
return 1;
if (s1.geteng() < s2.geteng())
return -1;
if (s1.geteng() == s2.geteng())
return 0;
}
int compara_ist(Student s1, Student s2)
{
if (s1.getist() > s2.getist())
return 1;
if (s1.getist() < s2.getist())
return -1;
if (s1.getist() == s2.getist())
return 0;
}
int compara_medie(Student s1, Student s2)
{
if (s1.calculare_medie() > s2.calculare_medie())
return 1;
if (s1.calculare_medie() < s2.calculare_medie())
return -1;
if (s1.calculare_medie() == s2.calculare_medie())
return 0;
}
|
//
// Copyright (C) 2004-2008 Maciej Sobczak, Stephen Hutton
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#define SOCI_POSTGRESQL_SOURCE
#include "soci/postgresql/soci-postgresql.h"
#include "soci/blob.h"
#include "soci/rowid.h"
#include "soci/type-wrappers.h"
#include "soci/soci-platform.h"
#include "soci-dtocstr.h"
#include "soci-exchange-cast.h"
#include <libpq/libpq-fs.h> // libpq
#include <cctype>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <limits>
#include <sstream>
#include <stdint.h>
using namespace soci;
using namespace soci::details;
void postgresql_standard_use_type_backend::bind_by_pos(
int & position, void * data, exchange_type type, bool /* readOnly */)
{
// readOnly is ignored, because PostgreSQL does not support
// any data to be written back to used (bound) objects.
data_ = data;
type_ = type;
position_ = position++;
}
void postgresql_standard_use_type_backend::bind_by_name(
std::string const & name, void * data, exchange_type type, bool /* readOnly */)
{
// readOnly is ignored, because PostgreSQL does not support
// any data to be written back to used (bound) objects.
data_ = data;
type_ = type;
name_ = name;
}
void postgresql_standard_use_type_backend::pre_use(indicator const * ind)
{
if (ind != NULL && *ind == i_null)
{
// leave the working buffer as NULL
}
else
{
// allocate and fill the buffer with text-formatted client data
switch (type_)
{
case x_char:
{
buf_ = new char[2];
buf_[0] = exchange_type_cast<x_char>(data_);
buf_[1] = '\0';
}
break;
case x_stdstring:
copy_from_string(exchange_type_cast<x_stdstring>(data_));
break;
case x_int8:
{
std::size_t const bufSize
= std::numeric_limits<int8_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%d",
static_cast<int>(exchange_type_cast<x_int8>(data_)));
}
break;
case x_uint8:
{
std::size_t const bufSize
= std::numeric_limits<uint8_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%u",
static_cast<unsigned int>(exchange_type_cast<x_uint8>(data_)));
}
break;
case x_int16:
{
std::size_t const bufSize
= std::numeric_limits<int16_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%d",
static_cast<int>(exchange_type_cast<x_int16>(data_)));
}
break;
case x_uint16:
{
std::size_t const bufSize
= std::numeric_limits<uint16_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%u",
static_cast<unsigned int>(exchange_type_cast<x_uint16>(data_)));
}
break;
case x_int32:
{
std::size_t const bufSize
= std::numeric_limits<int32_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%d",
static_cast<int>(exchange_type_cast<x_int32>(data_)));
}
break;
case x_uint32:
{
std::size_t const bufSize
= std::numeric_limits<uint32_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%u",
static_cast<unsigned int>(exchange_type_cast<x_uint32>(data_)));
}
break;
case x_int64:
{
std::size_t const bufSize
= std::numeric_limits<int64_t>::digits10 + 3;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%" LL_FMT_FLAGS "d",
static_cast<long long>(exchange_type_cast<x_int64>(data_)));
}
break;
case x_uint64:
{
std::size_t const bufSize
= std::numeric_limits<uint64_t>::digits10 + 2;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%" LL_FMT_FLAGS "u",
static_cast<unsigned long long>(exchange_type_cast<x_uint64>(data_)));
}
break;
case x_double:
copy_from_string(double_to_cstring(exchange_type_cast<x_double>(data_)));
break;
case x_stdtm:
{
std::size_t const bufSize = 80;
buf_ = new char[bufSize];
std::tm const& t = exchange_type_cast<x_stdtm>(data_);
snprintf(buf_, bufSize, "%d-%02d-%02d %02d:%02d:%02d",
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday,
t.tm_hour, t.tm_min, t.tm_sec);
}
break;
case x_rowid:
{
// RowID is internally identical to unsigned long
rowid * rid = static_cast<rowid *>(data_);
postgresql_rowid_backend * rbe
= static_cast<postgresql_rowid_backend *>(
rid->get_backend());
std::size_t const bufSize
= std::numeric_limits<unsigned long>::digits10 + 2;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%lu", rbe->value_);
}
break;
case x_blob:
{
blob * b = static_cast<blob *>(data_);
postgresql_blob_backend * bbe =
static_cast<postgresql_blob_backend *>(b->get_backend());
std::size_t const bufSize
= std::numeric_limits<unsigned long>::digits10 + 2;
buf_ = new char[bufSize];
snprintf(buf_, bufSize, "%lu", bbe->oid_);
}
break;
case x_xmltype:
copy_from_string(exchange_type_cast<x_xmltype>(data_).value);
break;
case x_longstring:
copy_from_string(exchange_type_cast<x_longstring>(data_).value);
break;
default:
throw soci_error("Use element used with non-supported type.");
}
}
if (position_ > 0)
{
// binding by position
statement_.useByPosBuffers_[position_] = &buf_;
}
else
{
// binding by name
statement_.useByNameBuffers_[name_] = &buf_;
}
}
void postgresql_standard_use_type_backend::post_use(
bool /* gotData */, indicator * /* ind */)
{
// PostgreSQL does not support any data moving back the same channel,
// so there is nothing to do here.
// In particular, there is nothing to protect, because both const and non-const
// objects will never be modified.
// clean up the working buffer, it might be allocated anew in
// the next run of preUse
clean_up();
}
void postgresql_standard_use_type_backend::clean_up()
{
if (buf_ != NULL)
{
delete [] buf_;
buf_ = NULL;
}
}
void postgresql_standard_use_type_backend::copy_from_string(std::string const& s)
{
buf_ = new char[s.size() + 1];
std::strcpy(buf_, s.c_str());
}
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/base/adapters.h"
#include "src/compiler/instruction-selector-impl.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/node-properties.h"
#include "src/ppc/frames-ppc.h"
namespace v8 {
namespace internal {
namespace compiler {
enum ImmediateMode {
kInt16Imm,
kInt16Imm_Unsigned,
kInt16Imm_Negate,
kInt16Imm_4ByteAligned,
kShift32Imm,
kShift64Imm,
kNoImmediate
};
// Adds PPC-specific methods for generating operands.
class PPCOperandGenerator final : public OperandGenerator {
public:
explicit PPCOperandGenerator(InstructionSelector* selector)
: OperandGenerator(selector) {}
InstructionOperand UseOperand(Node* node, ImmediateMode mode) {
if (CanBeImmediate(node, mode)) {
return UseImmediate(node);
}
return UseRegister(node);
}
bool CanBeImmediate(Node* node, ImmediateMode mode) {
int64_t value;
if (node->opcode() == IrOpcode::kInt32Constant)
value = OpParameter<int32_t>(node);
else if (node->opcode() == IrOpcode::kInt64Constant)
value = OpParameter<int64_t>(node);
else
return false;
return CanBeImmediate(value, mode);
}
bool CanBeImmediate(int64_t value, ImmediateMode mode) {
switch (mode) {
case kInt16Imm:
return is_int16(value);
case kInt16Imm_Unsigned:
return is_uint16(value);
case kInt16Imm_Negate:
return is_int16(-value);
case kInt16Imm_4ByteAligned:
return is_int16(value) && !(value & 3);
case kShift32Imm:
return 0 <= value && value < 32;
case kShift64Imm:
return 0 <= value && value < 64;
case kNoImmediate:
return false;
}
return false;
}
};
namespace {
void VisitRR(InstructionSelector* selector, InstructionCode opcode,
Node* node) {
PPCOperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void VisitRRR(InstructionSelector* selector, InstructionCode opcode,
Node* node) {
PPCOperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(1)));
}
void VisitRRO(InstructionSelector* selector, InstructionCode opcode, Node* node,
ImmediateMode operand_mode) {
PPCOperandGenerator g(selector);
selector->Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)),
g.UseOperand(node->InputAt(1), operand_mode));
}
#if V8_TARGET_ARCH_PPC64
void VisitTryTruncateDouble(InstructionSelector* selector,
InstructionCode opcode, Node* node) {
PPCOperandGenerator g(selector);
InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))};
InstructionOperand outputs[2];
size_t output_count = 0;
outputs[output_count++] = g.DefineAsRegister(node);
Node* success_output = NodeProperties::FindProjection(node, 1);
if (success_output) {
outputs[output_count++] = g.DefineAsRegister(success_output);
}
selector->Emit(opcode, output_count, outputs, 1, inputs);
}
#endif
// Shared routine for multiple binary operations.
template <typename Matcher>
void VisitBinop(InstructionSelector* selector, Node* node,
InstructionCode opcode, ImmediateMode operand_mode,
FlagsContinuation* cont) {
PPCOperandGenerator g(selector);
Matcher m(node);
InstructionOperand inputs[4];
size_t input_count = 0;
InstructionOperand outputs[2];
size_t output_count = 0;
inputs[input_count++] = g.UseRegister(m.left().node());
inputs[input_count++] = g.UseOperand(m.right().node(), operand_mode);
if (cont->IsBranch()) {
inputs[input_count++] = g.Label(cont->true_block());
inputs[input_count++] = g.Label(cont->false_block());
}
if (cont->IsDeoptimize()) {
// If we can deoptimize as a result of the binop, we need to make sure that
// the deopt inputs are not overwritten by the binop result. One way
// to achieve that is to declare the output register as same-as-first.
outputs[output_count++] = g.DefineSameAsFirst(node);
} else {
outputs[output_count++] = g.DefineAsRegister(node);
}
if (cont->IsSet()) {
outputs[output_count++] = g.DefineAsRegister(cont->result());
}
DCHECK_NE(0u, input_count);
DCHECK_NE(0u, output_count);
DCHECK_GE(arraysize(inputs), input_count);
DCHECK_GE(arraysize(outputs), output_count);
opcode = cont->Encode(opcode);
if (cont->IsDeoptimize()) {
selector->EmitDeoptimize(opcode, output_count, outputs, input_count, inputs,
cont->reason(), cont->frame_state());
} else {
selector->Emit(opcode, output_count, outputs, input_count, inputs);
}
}
// Shared routine for multiple binary operations.
template <typename Matcher>
void VisitBinop(InstructionSelector* selector, Node* node,
InstructionCode opcode, ImmediateMode operand_mode) {
FlagsContinuation cont;
VisitBinop<Matcher>(selector, node, opcode, operand_mode, &cont);
}
} // namespace
void InstructionSelector::VisitLoad(Node* node) {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
PPCOperandGenerator g(this);
Node* base = node->InputAt(0);
Node* offset = node->InputAt(1);
ArchOpcode opcode = kArchNop;
ImmediateMode mode = kInt16Imm;
switch (load_rep.representation()) {
case MachineRepresentation::kFloat32:
opcode = kPPC_LoadFloat32;
break;
case MachineRepresentation::kFloat64:
opcode = kPPC_LoadDouble;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kWord8:
opcode = load_rep.IsSigned() ? kPPC_LoadWordS8 : kPPC_LoadWordU8;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsSigned() ? kPPC_LoadWordS16 : kPPC_LoadWordU16;
break;
#if !V8_TARGET_ARCH_PPC64
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
#endif
case MachineRepresentation::kWord32:
opcode = kPPC_LoadWordU32;
break;
#if V8_TARGET_ARCH_PPC64
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
case MachineRepresentation::kWord64:
opcode = kPPC_LoadWord64;
mode = kInt16Imm_4ByteAligned;
break;
#else
case MachineRepresentation::kWord64: // Fall through.
#endif
case MachineRepresentation::kSimd128: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
return;
}
if (g.CanBeImmediate(offset, mode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), g.UseRegister(base), g.UseImmediate(offset));
} else if (g.CanBeImmediate(base, mode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), g.UseRegister(offset), g.UseImmediate(base));
} else {
Emit(opcode | AddressingModeField::encode(kMode_MRR),
g.DefineAsRegister(node), g.UseRegister(base), g.UseRegister(offset));
}
}
void InstructionSelector::VisitProtectedLoad(Node* node) {
// TODO(eholk)
UNIMPLEMENTED();
}
void InstructionSelector::VisitStore(Node* node) {
PPCOperandGenerator g(this);
Node* base = node->InputAt(0);
Node* offset = node->InputAt(1);
Node* value = node->InputAt(2);
StoreRepresentation store_rep = StoreRepresentationOf(node->op());
WriteBarrierKind write_barrier_kind = store_rep.write_barrier_kind();
MachineRepresentation rep = store_rep.representation();
if (write_barrier_kind != kNoWriteBarrier) {
DCHECK_EQ(MachineRepresentation::kTagged, rep);
AddressingMode addressing_mode;
InstructionOperand inputs[3];
size_t input_count = 0;
inputs[input_count++] = g.UseUniqueRegister(base);
// OutOfLineRecordWrite uses the offset in an 'add' instruction as well as
// for the store itself, so we must check compatibility with both.
if (g.CanBeImmediate(offset, kInt16Imm)
#if V8_TARGET_ARCH_PPC64
&& g.CanBeImmediate(offset, kInt16Imm_4ByteAligned)
#endif
) {
inputs[input_count++] = g.UseImmediate(offset);
addressing_mode = kMode_MRI;
} else {
inputs[input_count++] = g.UseUniqueRegister(offset);
addressing_mode = kMode_MRR;
}
inputs[input_count++] = g.UseUniqueRegister(value);
RecordWriteMode record_write_mode = RecordWriteMode::kValueIsAny;
switch (write_barrier_kind) {
case kNoWriteBarrier:
UNREACHABLE();
break;
case kMapWriteBarrier:
record_write_mode = RecordWriteMode::kValueIsMap;
break;
case kPointerWriteBarrier:
record_write_mode = RecordWriteMode::kValueIsPointer;
break;
case kFullWriteBarrier:
record_write_mode = RecordWriteMode::kValueIsAny;
break;
}
InstructionOperand temps[] = {g.TempRegister(), g.TempRegister()};
size_t const temp_count = arraysize(temps);
InstructionCode code = kArchStoreWithWriteBarrier;
code |= AddressingModeField::encode(addressing_mode);
code |= MiscField::encode(static_cast<int>(record_write_mode));
Emit(code, 0, nullptr, input_count, inputs, temp_count, temps);
} else {
ArchOpcode opcode = kArchNop;
ImmediateMode mode = kInt16Imm;
switch (rep) {
case MachineRepresentation::kFloat32:
opcode = kPPC_StoreFloat32;
break;
case MachineRepresentation::kFloat64:
opcode = kPPC_StoreDouble;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kWord8:
opcode = kPPC_StoreWord8;
break;
case MachineRepresentation::kWord16:
opcode = kPPC_StoreWord16;
break;
#if !V8_TARGET_ARCH_PPC64
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
#endif
case MachineRepresentation::kWord32:
opcode = kPPC_StoreWord32;
break;
#if V8_TARGET_ARCH_PPC64
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
case MachineRepresentation::kWord64:
opcode = kPPC_StoreWord64;
mode = kInt16Imm_4ByteAligned;
break;
#else
case MachineRepresentation::kWord64: // Fall through.
#endif
case MachineRepresentation::kSimd128: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
return;
}
if (g.CanBeImmediate(offset, mode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
g.UseRegister(base), g.UseImmediate(offset), g.UseRegister(value));
} else if (g.CanBeImmediate(base, mode)) {
Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
g.UseRegister(offset), g.UseImmediate(base), g.UseRegister(value));
} else {
Emit(opcode | AddressingModeField::encode(kMode_MRR), g.NoOutput(),
g.UseRegister(base), g.UseRegister(offset), g.UseRegister(value));
}
}
}
// Architecture supports unaligned access, therefore VisitLoad is used instead
void InstructionSelector::VisitUnalignedLoad(Node* node) { UNREACHABLE(); }
// Architecture supports unaligned access, therefore VisitStore is used instead
void InstructionSelector::VisitUnalignedStore(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitCheckedLoad(Node* node) {
CheckedLoadRepresentation load_rep = CheckedLoadRepresentationOf(node->op());
PPCOperandGenerator g(this);
Node* const base = node->InputAt(0);
Node* const offset = node->InputAt(1);
Node* const length = node->InputAt(2);
ArchOpcode opcode = kArchNop;
switch (load_rep.representation()) {
case MachineRepresentation::kWord8:
opcode = load_rep.IsSigned() ? kCheckedLoadInt8 : kCheckedLoadUint8;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsSigned() ? kCheckedLoadInt16 : kCheckedLoadUint16;
break;
case MachineRepresentation::kWord32:
opcode = kCheckedLoadWord32;
break;
#if V8_TARGET_ARCH_PPC64
case MachineRepresentation::kWord64:
opcode = kCheckedLoadWord64;
break;
#endif
case MachineRepresentation::kFloat32:
opcode = kCheckedLoadFloat32;
break;
case MachineRepresentation::kFloat64:
opcode = kCheckedLoadFloat64;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
#if !V8_TARGET_ARCH_PPC64
case MachineRepresentation::kWord64: // Fall through.
#endif
case MachineRepresentation::kSimd128: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
return;
}
AddressingMode addressingMode = kMode_MRR;
Emit(opcode | AddressingModeField::encode(addressingMode),
g.DefineAsRegister(node), g.UseRegister(base), g.UseRegister(offset),
g.UseOperand(length, kInt16Imm_Unsigned));
}
void InstructionSelector::VisitCheckedStore(Node* node) {
MachineRepresentation rep = CheckedStoreRepresentationOf(node->op());
PPCOperandGenerator g(this);
Node* const base = node->InputAt(0);
Node* const offset = node->InputAt(1);
Node* const length = node->InputAt(2);
Node* const value = node->InputAt(3);
ArchOpcode opcode = kArchNop;
switch (rep) {
case MachineRepresentation::kWord8:
opcode = kCheckedStoreWord8;
break;
case MachineRepresentation::kWord16:
opcode = kCheckedStoreWord16;
break;
case MachineRepresentation::kWord32:
opcode = kCheckedStoreWord32;
break;
#if V8_TARGET_ARCH_PPC64
case MachineRepresentation::kWord64:
opcode = kCheckedStoreWord64;
break;
#endif
case MachineRepresentation::kFloat32:
opcode = kCheckedStoreFloat32;
break;
case MachineRepresentation::kFloat64:
opcode = kCheckedStoreFloat64;
break;
case MachineRepresentation::kBit: // Fall through.
case MachineRepresentation::kTaggedSigned: // Fall through.
case MachineRepresentation::kTaggedPointer: // Fall through.
case MachineRepresentation::kTagged: // Fall through.
#if !V8_TARGET_ARCH_PPC64
case MachineRepresentation::kWord64: // Fall through.
#endif
case MachineRepresentation::kSimd128: // Fall through.
case MachineRepresentation::kNone:
UNREACHABLE();
return;
}
AddressingMode addressingMode = kMode_MRR;
Emit(opcode | AddressingModeField::encode(addressingMode), g.NoOutput(),
g.UseRegister(base), g.UseRegister(offset),
g.UseOperand(length, kInt16Imm_Unsigned), g.UseRegister(value));
}
template <typename Matcher>
static void VisitLogical(InstructionSelector* selector, Node* node, Matcher* m,
ArchOpcode opcode, bool left_can_cover,
bool right_can_cover, ImmediateMode imm_mode) {
PPCOperandGenerator g(selector);
// Map instruction to equivalent operation with inverted right input.
ArchOpcode inv_opcode = opcode;
switch (opcode) {
case kPPC_And:
inv_opcode = kPPC_AndComplement;
break;
case kPPC_Or:
inv_opcode = kPPC_OrComplement;
break;
default:
UNREACHABLE();
}
// Select Logical(y, ~x) for Logical(Xor(x, -1), y).
if ((m->left().IsWord32Xor() || m->left().IsWord64Xor()) && left_can_cover) {
Matcher mleft(m->left().node());
if (mleft.right().Is(-1)) {
selector->Emit(inv_opcode, g.DefineAsRegister(node),
g.UseRegister(m->right().node()),
g.UseRegister(mleft.left().node()));
return;
}
}
// Select Logical(x, ~y) for Logical(x, Xor(y, -1)).
if ((m->right().IsWord32Xor() || m->right().IsWord64Xor()) &&
right_can_cover) {
Matcher mright(m->right().node());
if (mright.right().Is(-1)) {
// TODO(all): support shifted operand on right.
selector->Emit(inv_opcode, g.DefineAsRegister(node),
g.UseRegister(m->left().node()),
g.UseRegister(mright.left().node()));
return;
}
}
VisitBinop<Matcher>(selector, node, opcode, imm_mode);
}
static inline bool IsContiguousMask32(uint32_t value, int* mb, int* me) {
int mask_width = base::bits::CountPopulation32(value);
int mask_msb = base::bits::CountLeadingZeros32(value);
int mask_lsb = base::bits::CountTrailingZeros32(value);
if ((mask_width == 0) || (mask_msb + mask_width + mask_lsb != 32))
return false;
*mb = mask_lsb + mask_width - 1;
*me = mask_lsb;
return true;
}
#if V8_TARGET_ARCH_PPC64
static inline bool IsContiguousMask64(uint64_t value, int* mb, int* me) {
int mask_width = base::bits::CountPopulation64(value);
int mask_msb = base::bits::CountLeadingZeros64(value);
int mask_lsb = base::bits::CountTrailingZeros64(value);
if ((mask_width == 0) || (mask_msb + mask_width + mask_lsb != 64))
return false;
*mb = mask_lsb + mask_width - 1;
*me = mask_lsb;
return true;
}
#endif
// TODO(mbrandy): Absorb rotate-right into rlwinm?
void InstructionSelector::VisitWord32And(Node* node) {
PPCOperandGenerator g(this);
Int32BinopMatcher m(node);
int mb = 0;
int me = 0;
if (m.right().HasValue() && IsContiguousMask32(m.right().Value(), &mb, &me)) {
int sh = 0;
Node* left = m.left().node();
if ((m.left().IsWord32Shr() || m.left().IsWord32Shl()) &&
CanCover(node, left)) {
// Try to absorb left/right shift into rlwinm
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().IsInRange(0, 31)) {
left = mleft.left().node();
sh = mleft.right().Value();
if (m.left().IsWord32Shr()) {
// Adjust the mask such that it doesn't include any rotated bits.
if (mb > 31 - sh) mb = 31 - sh;
sh = (32 - sh) & 0x1f;
} else {
// Adjust the mask such that it doesn't include any rotated bits.
if (me < sh) me = sh;
}
}
}
if (mb >= me) {
Emit(kPPC_RotLeftAndMask32, g.DefineAsRegister(node), g.UseRegister(left),
g.TempImmediate(sh), g.TempImmediate(mb), g.TempImmediate(me));
return;
}
}
VisitLogical<Int32BinopMatcher>(
this, node, &m, kPPC_And, CanCover(node, m.left().node()),
CanCover(node, m.right().node()), kInt16Imm_Unsigned);
}
#if V8_TARGET_ARCH_PPC64
// TODO(mbrandy): Absorb rotate-right into rldic?
void InstructionSelector::VisitWord64And(Node* node) {
PPCOperandGenerator g(this);
Int64BinopMatcher m(node);
int mb = 0;
int me = 0;
if (m.right().HasValue() && IsContiguousMask64(m.right().Value(), &mb, &me)) {
int sh = 0;
Node* left = m.left().node();
if ((m.left().IsWord64Shr() || m.left().IsWord64Shl()) &&
CanCover(node, left)) {
// Try to absorb left/right shift into rldic
Int64BinopMatcher mleft(m.left().node());
if (mleft.right().IsInRange(0, 63)) {
left = mleft.left().node();
sh = mleft.right().Value();
if (m.left().IsWord64Shr()) {
// Adjust the mask such that it doesn't include any rotated bits.
if (mb > 63 - sh) mb = 63 - sh;
sh = (64 - sh) & 0x3f;
} else {
// Adjust the mask such that it doesn't include any rotated bits.
if (me < sh) me = sh;
}
}
}
if (mb >= me) {
bool match = false;
ArchOpcode opcode;
int mask;
if (me == 0) {
match = true;
opcode = kPPC_RotLeftAndClearLeft64;
mask = mb;
} else if (mb == 63) {
match = true;
opcode = kPPC_RotLeftAndClearRight64;
mask = me;
} else if (sh && me <= sh && m.left().IsWord64Shl()) {
match = true;
opcode = kPPC_RotLeftAndClear64;
mask = mb;
}
if (match) {
Emit(opcode, g.DefineAsRegister(node), g.UseRegister(left),
g.TempImmediate(sh), g.TempImmediate(mask));
return;
}
}
}
VisitLogical<Int64BinopMatcher>(
this, node, &m, kPPC_And, CanCover(node, m.left().node()),
CanCover(node, m.right().node()), kInt16Imm_Unsigned);
}
#endif
void InstructionSelector::VisitWord32Or(Node* node) {
Int32BinopMatcher m(node);
VisitLogical<Int32BinopMatcher>(
this, node, &m, kPPC_Or, CanCover(node, m.left().node()),
CanCover(node, m.right().node()), kInt16Imm_Unsigned);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Or(Node* node) {
Int64BinopMatcher m(node);
VisitLogical<Int64BinopMatcher>(
this, node, &m, kPPC_Or, CanCover(node, m.left().node()),
CanCover(node, m.right().node()), kInt16Imm_Unsigned);
}
#endif
void InstructionSelector::VisitWord32Xor(Node* node) {
PPCOperandGenerator g(this);
Int32BinopMatcher m(node);
if (m.right().Is(-1)) {
Emit(kPPC_Not, g.DefineAsRegister(node), g.UseRegister(m.left().node()));
} else {
VisitBinop<Int32BinopMatcher>(this, node, kPPC_Xor, kInt16Imm_Unsigned);
}
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Xor(Node* node) {
PPCOperandGenerator g(this);
Int64BinopMatcher m(node);
if (m.right().Is(-1)) {
Emit(kPPC_Not, g.DefineAsRegister(node), g.UseRegister(m.left().node()));
} else {
VisitBinop<Int64BinopMatcher>(this, node, kPPC_Xor, kInt16Imm_Unsigned);
}
}
#endif
void InstructionSelector::VisitWord32Shl(Node* node) {
PPCOperandGenerator g(this);
Int32BinopMatcher m(node);
if (m.left().IsWord32And() && m.right().IsInRange(0, 31)) {
// Try to absorb logical-and into rlwinm
Int32BinopMatcher mleft(m.left().node());
int sh = m.right().Value();
int mb;
int me;
if (mleft.right().HasValue() &&
IsContiguousMask32(mleft.right().Value() << sh, &mb, &me)) {
// Adjust the mask such that it doesn't include any rotated bits.
if (me < sh) me = sh;
if (mb >= me) {
Emit(kPPC_RotLeftAndMask32, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(sh),
g.TempImmediate(mb), g.TempImmediate(me));
return;
}
}
}
VisitRRO(this, kPPC_ShiftLeft32, node, kShift32Imm);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Shl(Node* node) {
PPCOperandGenerator g(this);
Int64BinopMatcher m(node);
// TODO(mbrandy): eliminate left sign extension if right >= 32
if (m.left().IsWord64And() && m.right().IsInRange(0, 63)) {
// Try to absorb logical-and into rldic
Int64BinopMatcher mleft(m.left().node());
int sh = m.right().Value();
int mb;
int me;
if (mleft.right().HasValue() &&
IsContiguousMask64(mleft.right().Value() << sh, &mb, &me)) {
// Adjust the mask such that it doesn't include any rotated bits.
if (me < sh) me = sh;
if (mb >= me) {
bool match = false;
ArchOpcode opcode;
int mask;
if (me == 0) {
match = true;
opcode = kPPC_RotLeftAndClearLeft64;
mask = mb;
} else if (mb == 63) {
match = true;
opcode = kPPC_RotLeftAndClearRight64;
mask = me;
} else if (sh && me <= sh) {
match = true;
opcode = kPPC_RotLeftAndClear64;
mask = mb;
}
if (match) {
Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(sh),
g.TempImmediate(mask));
return;
}
}
}
}
VisitRRO(this, kPPC_ShiftLeft64, node, kShift64Imm);
}
#endif
void InstructionSelector::VisitWord32Shr(Node* node) {
PPCOperandGenerator g(this);
Int32BinopMatcher m(node);
if (m.left().IsWord32And() && m.right().IsInRange(0, 31)) {
// Try to absorb logical-and into rlwinm
Int32BinopMatcher mleft(m.left().node());
int sh = m.right().Value();
int mb;
int me;
if (mleft.right().HasValue() &&
IsContiguousMask32((uint32_t)(mleft.right().Value()) >> sh, &mb, &me)) {
// Adjust the mask such that it doesn't include any rotated bits.
if (mb > 31 - sh) mb = 31 - sh;
sh = (32 - sh) & 0x1f;
if (mb >= me) {
Emit(kPPC_RotLeftAndMask32, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(sh),
g.TempImmediate(mb), g.TempImmediate(me));
return;
}
}
}
VisitRRO(this, kPPC_ShiftRight32, node, kShift32Imm);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Shr(Node* node) {
PPCOperandGenerator g(this);
Int64BinopMatcher m(node);
if (m.left().IsWord64And() && m.right().IsInRange(0, 63)) {
// Try to absorb logical-and into rldic
Int64BinopMatcher mleft(m.left().node());
int sh = m.right().Value();
int mb;
int me;
if (mleft.right().HasValue() &&
IsContiguousMask64((uint64_t)(mleft.right().Value()) >> sh, &mb, &me)) {
// Adjust the mask such that it doesn't include any rotated bits.
if (mb > 63 - sh) mb = 63 - sh;
sh = (64 - sh) & 0x3f;
if (mb >= me) {
bool match = false;
ArchOpcode opcode;
int mask;
if (me == 0) {
match = true;
opcode = kPPC_RotLeftAndClearLeft64;
mask = mb;
} else if (mb == 63) {
match = true;
opcode = kPPC_RotLeftAndClearRight64;
mask = me;
}
if (match) {
Emit(opcode, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()), g.TempImmediate(sh),
g.TempImmediate(mask));
return;
}
}
}
}
VisitRRO(this, kPPC_ShiftRight64, node, kShift64Imm);
}
#endif
void InstructionSelector::VisitWord32Sar(Node* node) {
PPCOperandGenerator g(this);
Int32BinopMatcher m(node);
// Replace with sign extension for (x << K) >> K where K is 16 or 24.
if (CanCover(node, m.left().node()) && m.left().IsWord32Shl()) {
Int32BinopMatcher mleft(m.left().node());
if (mleft.right().Is(16) && m.right().Is(16)) {
Emit(kPPC_ExtendSignWord16, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()));
return;
} else if (mleft.right().Is(24) && m.right().Is(24)) {
Emit(kPPC_ExtendSignWord8, g.DefineAsRegister(node),
g.UseRegister(mleft.left().node()));
return;
}
}
VisitRRO(this, kPPC_ShiftRightAlg32, node, kShift32Imm);
}
#if !V8_TARGET_ARCH_PPC64
void VisitPairBinop(InstructionSelector* selector, InstructionCode opcode,
InstructionCode opcode2, Node* node) {
PPCOperandGenerator g(selector);
Node* projection1 = NodeProperties::FindProjection(node, 1);
if (projection1) {
// We use UseUniqueRegister here to avoid register sharing with the output
// registers.
InstructionOperand inputs[] = {
g.UseRegister(node->InputAt(0)), g.UseUniqueRegister(node->InputAt(1)),
g.UseRegister(node->InputAt(2)), g.UseUniqueRegister(node->InputAt(3))};
InstructionOperand outputs[] = {
g.DefineAsRegister(node),
g.DefineAsRegister(NodeProperties::FindProjection(node, 1))};
selector->Emit(opcode, 2, outputs, 4, inputs);
} else {
// The high word of the result is not used, so we emit the standard 32 bit
// instruction.
selector->Emit(opcode2, g.DefineSameAsFirst(node),
g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(2)));
}
}
void InstructionSelector::VisitInt32PairAdd(Node* node) {
VisitPairBinop(this, kPPC_AddPair, kPPC_Add, node);
}
void InstructionSelector::VisitInt32PairSub(Node* node) {
VisitPairBinop(this, kPPC_SubPair, kPPC_Sub, node);
}
void InstructionSelector::VisitInt32PairMul(Node* node) {
PPCOperandGenerator g(this);
Node* projection1 = NodeProperties::FindProjection(node, 1);
if (projection1) {
InstructionOperand inputs[] = {g.UseUniqueRegister(node->InputAt(0)),
g.UseUniqueRegister(node->InputAt(1)),
g.UseUniqueRegister(node->InputAt(2)),
g.UseUniqueRegister(node->InputAt(3))};
InstructionOperand outputs[] = {
g.DefineAsRegister(node),
g.DefineAsRegister(NodeProperties::FindProjection(node, 1))};
InstructionOperand temps[] = {g.TempRegister(), g.TempRegister()};
Emit(kPPC_MulPair, 2, outputs, 4, inputs, 2, temps);
} else {
// The high word of the result is not used, so we emit the standard 32 bit
// instruction.
Emit(kPPC_Mul32, g.DefineSameAsFirst(node), g.UseRegister(node->InputAt(0)),
g.UseRegister(node->InputAt(2)));
}
}
namespace {
// Shared routine for multiple shift operations.
void VisitPairShift(InstructionSelector* selector, InstructionCode opcode,
Node* node) {
PPCOperandGenerator g(selector);
// We use g.UseUniqueRegister here to guarantee that there is
// no register aliasing of input registers with output registers.
Int32Matcher m(node->InputAt(2));
InstructionOperand shift_operand;
if (m.HasValue()) {
shift_operand = g.UseImmediate(m.node());
} else {
shift_operand = g.UseUniqueRegister(m.node());
}
InstructionOperand inputs[] = {g.UseUniqueRegister(node->InputAt(0)),
g.UseUniqueRegister(node->InputAt(1)),
shift_operand};
Node* projection1 = NodeProperties::FindProjection(node, 1);
InstructionOperand outputs[2];
InstructionOperand temps[1];
int32_t output_count = 0;
int32_t temp_count = 0;
outputs[output_count++] = g.DefineAsRegister(node);
if (projection1) {
outputs[output_count++] = g.DefineAsRegister(projection1);
} else {
temps[temp_count++] = g.TempRegister();
}
selector->Emit(opcode, output_count, outputs, 3, inputs, temp_count, temps);
}
} // namespace
void InstructionSelector::VisitWord32PairShl(Node* node) {
VisitPairShift(this, kPPC_ShiftLeftPair, node);
}
void InstructionSelector::VisitWord32PairShr(Node* node) {
VisitPairShift(this, kPPC_ShiftRightPair, node);
}
void InstructionSelector::VisitWord32PairSar(Node* node) {
VisitPairShift(this, kPPC_ShiftRightAlgPair, node);
}
#endif
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Sar(Node* node) {
PPCOperandGenerator g(this);
Int64BinopMatcher m(node);
if (CanCover(m.node(), m.left().node()) && m.left().IsLoad() &&
m.right().Is(32)) {
// Just load and sign-extend the interesting 4 bytes instead. This happens,
// for example, when we're loading and untagging SMIs.
BaseWithIndexAndDisplacement64Matcher mleft(m.left().node(),
AddressOption::kAllowAll);
if (mleft.matches() && mleft.index() == nullptr) {
int64_t offset = 0;
Node* displacement = mleft.displacement();
if (displacement != nullptr) {
Int64Matcher mdisplacement(displacement);
DCHECK(mdisplacement.HasValue());
offset = mdisplacement.Value();
}
offset = SmiWordOffset(offset);
if (g.CanBeImmediate(offset, kInt16Imm_4ByteAligned)) {
Emit(kPPC_LoadWordS32 | AddressingModeField::encode(kMode_MRI),
g.DefineAsRegister(node), g.UseRegister(mleft.base()),
g.TempImmediate(offset));
return;
}
}
}
VisitRRO(this, kPPC_ShiftRightAlg64, node, kShift64Imm);
}
#endif
// TODO(mbrandy): Absorb logical-and into rlwinm?
void InstructionSelector::VisitWord32Ror(Node* node) {
VisitRRO(this, kPPC_RotRight32, node, kShift32Imm);
}
#if V8_TARGET_ARCH_PPC64
// TODO(mbrandy): Absorb logical-and into rldic?
void InstructionSelector::VisitWord64Ror(Node* node) {
VisitRRO(this, kPPC_RotRight64, node, kShift64Imm);
}
#endif
void InstructionSelector::VisitWord32Clz(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_Cntlz32, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Clz(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_Cntlz64, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}
#endif
void InstructionSelector::VisitWord32Popcnt(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_Popcnt32, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Popcnt(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_Popcnt64, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
#endif
void InstructionSelector::VisitWord32Ctz(Node* node) { UNREACHABLE(); }
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Ctz(Node* node) { UNREACHABLE(); }
#endif
void InstructionSelector::VisitWord32ReverseBits(Node* node) { UNREACHABLE(); }
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64ReverseBits(Node* node) { UNREACHABLE(); }
#endif
void InstructionSelector::VisitWord64ReverseBytes(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitWord32ReverseBytes(Node* node) { UNREACHABLE(); }
void InstructionSelector::VisitInt32Add(Node* node) {
VisitBinop<Int32BinopMatcher>(this, node, kPPC_Add, kInt16Imm);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitInt64Add(Node* node) {
VisitBinop<Int64BinopMatcher>(this, node, kPPC_Add, kInt16Imm);
}
#endif
void InstructionSelector::VisitInt32Sub(Node* node) {
PPCOperandGenerator g(this);
Int32BinopMatcher m(node);
if (m.left().Is(0)) {
Emit(kPPC_Neg, g.DefineAsRegister(node), g.UseRegister(m.right().node()));
} else {
VisitBinop<Int32BinopMatcher>(this, node, kPPC_Sub, kInt16Imm_Negate);
}
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitInt64Sub(Node* node) {
PPCOperandGenerator g(this);
Int64BinopMatcher m(node);
if (m.left().Is(0)) {
Emit(kPPC_Neg, g.DefineAsRegister(node), g.UseRegister(m.right().node()));
} else {
VisitBinop<Int64BinopMatcher>(this, node, kPPC_Sub, kInt16Imm_Negate);
}
}
#endif
namespace {
void VisitCompare(InstructionSelector* selector, InstructionCode opcode,
InstructionOperand left, InstructionOperand right,
FlagsContinuation* cont);
void EmitInt32MulWithOverflow(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
PPCOperandGenerator g(selector);
Int32BinopMatcher m(node);
InstructionOperand result_operand = g.DefineAsRegister(node);
InstructionOperand high32_operand = g.TempRegister();
InstructionOperand temp_operand = g.TempRegister();
{
InstructionOperand outputs[] = {result_operand, high32_operand};
InstructionOperand inputs[] = {g.UseRegister(m.left().node()),
g.UseRegister(m.right().node())};
selector->Emit(kPPC_Mul32WithHigh32, 2, outputs, 2, inputs);
}
{
InstructionOperand shift_31 = g.UseImmediate(31);
InstructionOperand outputs[] = {temp_operand};
InstructionOperand inputs[] = {result_operand, shift_31};
selector->Emit(kPPC_ShiftRightAlg32, 1, outputs, 2, inputs);
}
VisitCompare(selector, kPPC_Cmp32, high32_operand, temp_operand, cont);
}
} // namespace
void InstructionSelector::VisitInt32Mul(Node* node) {
VisitRRR(this, kPPC_Mul32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitInt64Mul(Node* node) {
VisitRRR(this, kPPC_Mul64, node);
}
#endif
void InstructionSelector::VisitInt32MulHigh(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_MulHigh32, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)));
}
void InstructionSelector::VisitUint32MulHigh(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_MulHighU32, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)));
}
void InstructionSelector::VisitInt32Div(Node* node) {
VisitRRR(this, kPPC_Div32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitInt64Div(Node* node) {
VisitRRR(this, kPPC_Div64, node);
}
#endif
void InstructionSelector::VisitUint32Div(Node* node) {
VisitRRR(this, kPPC_DivU32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitUint64Div(Node* node) {
VisitRRR(this, kPPC_DivU64, node);
}
#endif
void InstructionSelector::VisitInt32Mod(Node* node) {
VisitRRR(this, kPPC_Mod32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitInt64Mod(Node* node) {
VisitRRR(this, kPPC_Mod64, node);
}
#endif
void InstructionSelector::VisitUint32Mod(Node* node) {
VisitRRR(this, kPPC_ModU32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitUint64Mod(Node* node) {
VisitRRR(this, kPPC_ModU64, node);
}
#endif
void InstructionSelector::VisitChangeFloat32ToFloat64(Node* node) {
VisitRR(this, kPPC_Float32ToDouble, node);
}
void InstructionSelector::VisitRoundInt32ToFloat32(Node* node) {
VisitRR(this, kPPC_Int32ToFloat32, node);
}
void InstructionSelector::VisitRoundUint32ToFloat32(Node* node) {
VisitRR(this, kPPC_Uint32ToFloat32, node);
}
void InstructionSelector::VisitChangeInt32ToFloat64(Node* node) {
VisitRR(this, kPPC_Int32ToDouble, node);
}
void InstructionSelector::VisitChangeUint32ToFloat64(Node* node) {
VisitRR(this, kPPC_Uint32ToDouble, node);
}
void InstructionSelector::VisitChangeFloat64ToInt32(Node* node) {
VisitRR(this, kPPC_DoubleToInt32, node);
}
void InstructionSelector::VisitChangeFloat64ToUint32(Node* node) {
VisitRR(this, kPPC_DoubleToUint32, node);
}
void InstructionSelector::VisitTruncateFloat64ToUint32(Node* node) {
VisitRR(this, kPPC_DoubleToUint32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitTryTruncateFloat32ToInt64(Node* node) {
VisitTryTruncateDouble(this, kPPC_DoubleToInt64, node);
}
void InstructionSelector::VisitTryTruncateFloat64ToInt64(Node* node) {
VisitTryTruncateDouble(this, kPPC_DoubleToInt64, node);
}
void InstructionSelector::VisitTryTruncateFloat32ToUint64(Node* node) {
VisitTryTruncateDouble(this, kPPC_DoubleToUint64, node);
}
void InstructionSelector::VisitTryTruncateFloat64ToUint64(Node* node) {
VisitTryTruncateDouble(this, kPPC_DoubleToUint64, node);
}
void InstructionSelector::VisitChangeInt32ToInt64(Node* node) {
// TODO(mbrandy): inspect input to see if nop is appropriate.
VisitRR(this, kPPC_ExtendSignWord32, node);
}
void InstructionSelector::VisitChangeUint32ToUint64(Node* node) {
// TODO(mbrandy): inspect input to see if nop is appropriate.
VisitRR(this, kPPC_Uint32ToUint64, node);
}
#endif
void InstructionSelector::VisitTruncateFloat64ToFloat32(Node* node) {
VisitRR(this, kPPC_DoubleToFloat32, node);
}
void InstructionSelector::VisitTruncateFloat64ToWord32(Node* node) {
VisitRR(this, kArchTruncateDoubleToI, node);
}
void InstructionSelector::VisitRoundFloat64ToInt32(Node* node) {
VisitRR(this, kPPC_DoubleToInt32, node);
}
void InstructionSelector::VisitTruncateFloat32ToInt32(Node* node) {
VisitRR(this, kPPC_DoubleToInt32, node);
}
void InstructionSelector::VisitTruncateFloat32ToUint32(Node* node) {
VisitRR(this, kPPC_DoubleToUint32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitTruncateInt64ToInt32(Node* node) {
// TODO(mbrandy): inspect input to see if nop is appropriate.
VisitRR(this, kPPC_Int64ToInt32, node);
}
void InstructionSelector::VisitRoundInt64ToFloat32(Node* node) {
VisitRR(this, kPPC_Int64ToFloat32, node);
}
void InstructionSelector::VisitRoundInt64ToFloat64(Node* node) {
VisitRR(this, kPPC_Int64ToDouble, node);
}
void InstructionSelector::VisitRoundUint64ToFloat32(Node* node) {
VisitRR(this, kPPC_Uint64ToFloat32, node);
}
void InstructionSelector::VisitRoundUint64ToFloat64(Node* node) {
VisitRR(this, kPPC_Uint64ToDouble, node);
}
#endif
void InstructionSelector::VisitBitcastFloat32ToInt32(Node* node) {
VisitRR(this, kPPC_BitcastFloat32ToInt32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitBitcastFloat64ToInt64(Node* node) {
VisitRR(this, kPPC_BitcastDoubleToInt64, node);
}
#endif
void InstructionSelector::VisitBitcastInt32ToFloat32(Node* node) {
VisitRR(this, kPPC_BitcastInt32ToFloat32, node);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitBitcastInt64ToFloat64(Node* node) {
VisitRR(this, kPPC_BitcastInt64ToDouble, node);
}
#endif
void InstructionSelector::VisitFloat32Add(Node* node) {
VisitRRR(this, kPPC_AddDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Add(Node* node) {
// TODO(mbrandy): detect multiply-add
VisitRRR(this, kPPC_AddDouble, node);
}
void InstructionSelector::VisitFloat32Sub(Node* node) {
VisitRRR(this, kPPC_SubDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Sub(Node* node) {
// TODO(mbrandy): detect multiply-subtract
VisitRRR(this, kPPC_SubDouble, node);
}
void InstructionSelector::VisitFloat32Mul(Node* node) {
VisitRRR(this, kPPC_MulDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Mul(Node* node) {
// TODO(mbrandy): detect negate
VisitRRR(this, kPPC_MulDouble, node);
}
void InstructionSelector::VisitFloat32Div(Node* node) {
VisitRRR(this, kPPC_DivDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Div(Node* node) {
VisitRRR(this, kPPC_DivDouble, node);
}
void InstructionSelector::VisitFloat64Mod(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_ModDouble, g.DefineAsFixed(node, d1),
g.UseFixed(node->InputAt(0), d1),
g.UseFixed(node->InputAt(1), d2))->MarkAsCall();
}
void InstructionSelector::VisitFloat32Max(Node* node) {
VisitRRR(this, kPPC_MaxDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Max(Node* node) {
VisitRRR(this, kPPC_MaxDouble, node);
}
void InstructionSelector::VisitFloat64SilenceNaN(Node* node) {
VisitRR(this, kPPC_Float64SilenceNaN, node);
}
void InstructionSelector::VisitFloat32Min(Node* node) {
VisitRRR(this, kPPC_MinDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Min(Node* node) {
VisitRRR(this, kPPC_MinDouble, node);
}
void InstructionSelector::VisitFloat32Abs(Node* node) {
VisitRR(this, kPPC_AbsDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Abs(Node* node) {
VisitRR(this, kPPC_AbsDouble, node);
}
void InstructionSelector::VisitFloat32Sqrt(Node* node) {
VisitRR(this, kPPC_SqrtDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64Ieee754Unop(Node* node,
InstructionCode opcode) {
PPCOperandGenerator g(this);
Emit(opcode, g.DefineAsFixed(node, d1), g.UseFixed(node->InputAt(0), d1))
->MarkAsCall();
}
void InstructionSelector::VisitFloat64Ieee754Binop(Node* node,
InstructionCode opcode) {
PPCOperandGenerator g(this);
Emit(opcode, g.DefineAsFixed(node, d1),
g.UseFixed(node->InputAt(0), d1),
g.UseFixed(node->InputAt(1), d2))->MarkAsCall();
}
void InstructionSelector::VisitFloat64Sqrt(Node* node) {
VisitRR(this, kPPC_SqrtDouble, node);
}
void InstructionSelector::VisitFloat32RoundDown(Node* node) {
VisitRR(this, kPPC_FloorDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64RoundDown(Node* node) {
VisitRR(this, kPPC_FloorDouble, node);
}
void InstructionSelector::VisitFloat32RoundUp(Node* node) {
VisitRR(this, kPPC_CeilDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64RoundUp(Node* node) {
VisitRR(this, kPPC_CeilDouble, node);
}
void InstructionSelector::VisitFloat32RoundTruncate(Node* node) {
VisitRR(this, kPPC_TruncateDouble | MiscField::encode(1), node);
}
void InstructionSelector::VisitFloat64RoundTruncate(Node* node) {
VisitRR(this, kPPC_TruncateDouble, node);
}
void InstructionSelector::VisitFloat64RoundTiesAway(Node* node) {
VisitRR(this, kPPC_RoundDouble, node);
}
void InstructionSelector::VisitFloat32RoundTiesEven(Node* node) {
UNREACHABLE();
}
void InstructionSelector::VisitFloat64RoundTiesEven(Node* node) {
UNREACHABLE();
}
void InstructionSelector::VisitFloat32Neg(Node* node) {
VisitRR(this, kPPC_NegDouble, node);
}
void InstructionSelector::VisitFloat64Neg(Node* node) {
VisitRR(this, kPPC_NegDouble, node);
}
void InstructionSelector::VisitInt32AddWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop<Int32BinopMatcher>(this, node, kPPC_AddWithOverflow32,
kInt16Imm, &cont);
}
FlagsContinuation cont;
VisitBinop<Int32BinopMatcher>(this, node, kPPC_AddWithOverflow32, kInt16Imm,
&cont);
}
void InstructionSelector::VisitInt32SubWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop<Int32BinopMatcher>(this, node, kPPC_SubWithOverflow32,
kInt16Imm_Negate, &cont);
}
FlagsContinuation cont;
VisitBinop<Int32BinopMatcher>(this, node, kPPC_SubWithOverflow32,
kInt16Imm_Negate, &cont);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitInt64AddWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop<Int64BinopMatcher>(this, node, kPPC_Add, kInt16Imm,
&cont);
}
FlagsContinuation cont;
VisitBinop<Int64BinopMatcher>(this, node, kPPC_Add, kInt16Imm, &cont);
}
void InstructionSelector::VisitInt64SubWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf);
return VisitBinop<Int64BinopMatcher>(this, node, kPPC_Sub, kInt16Imm_Negate,
&cont);
}
FlagsContinuation cont;
VisitBinop<Int64BinopMatcher>(this, node, kPPC_Sub, kInt16Imm_Negate, &cont);
}
#endif
static bool CompareLogical(FlagsContinuation* cont) {
switch (cont->condition()) {
case kUnsignedLessThan:
case kUnsignedGreaterThanOrEqual:
case kUnsignedLessThanOrEqual:
case kUnsignedGreaterThan:
return true;
default:
return false;
}
UNREACHABLE();
return false;
}
namespace {
// Shared routine for multiple compare operations.
void VisitCompare(InstructionSelector* selector, InstructionCode opcode,
InstructionOperand left, InstructionOperand right,
FlagsContinuation* cont) {
PPCOperandGenerator g(selector);
opcode = cont->Encode(opcode);
if (cont->IsBranch()) {
selector->Emit(opcode, g.NoOutput(), left, right,
g.Label(cont->true_block()), g.Label(cont->false_block()));
} else if (cont->IsDeoptimize()) {
selector->EmitDeoptimize(opcode, g.NoOutput(), left, right, cont->reason(),
cont->frame_state());
} else {
DCHECK(cont->IsSet());
selector->Emit(opcode, g.DefineAsRegister(cont->result()), left, right);
}
}
// Shared routine for multiple word compare operations.
void VisitWordCompare(InstructionSelector* selector, Node* node,
InstructionCode opcode, FlagsContinuation* cont,
bool commutative, ImmediateMode immediate_mode) {
PPCOperandGenerator g(selector);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
// Match immediates on left or right side of comparison.
if (g.CanBeImmediate(right, immediate_mode)) {
VisitCompare(selector, opcode, g.UseRegister(left), g.UseImmediate(right),
cont);
} else if (g.CanBeImmediate(left, immediate_mode)) {
if (!commutative) cont->Commute();
VisitCompare(selector, opcode, g.UseRegister(right), g.UseImmediate(left),
cont);
} else {
VisitCompare(selector, opcode, g.UseRegister(left), g.UseRegister(right),
cont);
}
}
void VisitWord32Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
ImmediateMode mode = (CompareLogical(cont) ? kInt16Imm_Unsigned : kInt16Imm);
VisitWordCompare(selector, node, kPPC_Cmp32, cont, false, mode);
}
#if V8_TARGET_ARCH_PPC64
void VisitWord64Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
ImmediateMode mode = (CompareLogical(cont) ? kInt16Imm_Unsigned : kInt16Imm);
VisitWordCompare(selector, node, kPPC_Cmp64, cont, false, mode);
}
#endif
// Shared routine for multiple float32 compare operations.
void VisitFloat32Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
PPCOperandGenerator g(selector);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
VisitCompare(selector, kPPC_CmpDouble, g.UseRegister(left),
g.UseRegister(right), cont);
}
// Shared routine for multiple float64 compare operations.
void VisitFloat64Compare(InstructionSelector* selector, Node* node,
FlagsContinuation* cont) {
PPCOperandGenerator g(selector);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
VisitCompare(selector, kPPC_CmpDouble, g.UseRegister(left),
g.UseRegister(right), cont);
}
// Shared routine for word comparisons against zero.
void VisitWordCompareZero(InstructionSelector* selector, Node* user,
Node* value, InstructionCode opcode,
FlagsContinuation* cont) {
while (selector->CanCover(user, value)) {
switch (value->opcode()) {
case IrOpcode::kWord32Equal: {
// Combine with comparisons against 0 by simply inverting the
// continuation.
Int32BinopMatcher m(value);
if (m.right().Is(0)) {
user = value;
value = m.left().node();
cont->Negate();
continue;
}
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitWord32Compare(selector, value, cont);
}
case IrOpcode::kInt32LessThan:
cont->OverwriteAndNegateIfEqual(kSignedLessThan);
return VisitWord32Compare(selector, value, cont);
case IrOpcode::kInt32LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual);
return VisitWord32Compare(selector, value, cont);
case IrOpcode::kUint32LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitWord32Compare(selector, value, cont);
case IrOpcode::kUint32LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitWord32Compare(selector, value, cont);
#if V8_TARGET_ARCH_PPC64
case IrOpcode::kWord64Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitWord64Compare(selector, value, cont);
case IrOpcode::kInt64LessThan:
cont->OverwriteAndNegateIfEqual(kSignedLessThan);
return VisitWord64Compare(selector, value, cont);
case IrOpcode::kInt64LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual);
return VisitWord64Compare(selector, value, cont);
case IrOpcode::kUint64LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitWord64Compare(selector, value, cont);
case IrOpcode::kUint64LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitWord64Compare(selector, value, cont);
#endif
case IrOpcode::kFloat32Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitFloat32Compare(selector, value, cont);
case IrOpcode::kFloat32LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitFloat32Compare(selector, value, cont);
case IrOpcode::kFloat32LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitFloat32Compare(selector, value, cont);
case IrOpcode::kFloat64Equal:
cont->OverwriteAndNegateIfEqual(kEqual);
return VisitFloat64Compare(selector, value, cont);
case IrOpcode::kFloat64LessThan:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThan);
return VisitFloat64Compare(selector, value, cont);
case IrOpcode::kFloat64LessThanOrEqual:
cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
return VisitFloat64Compare(selector, value, cont);
case IrOpcode::kProjection:
// Check if this is the overflow output projection of an
// <Operation>WithOverflow node.
if (ProjectionIndexOf(value->op()) == 1u) {
// We cannot combine the <Operation>WithOverflow with this branch
// unless the 0th projection (the use of the actual value of the
// <Operation> is either nullptr, which means there's no use of the
// actual value, or was already defined, which means it is scheduled
// *AFTER* this branch).
Node* const node = value->InputAt(0);
Node* const result = NodeProperties::FindProjection(node, 0);
if (result == nullptr || selector->IsDefined(result)) {
switch (node->opcode()) {
case IrOpcode::kInt32AddWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop<Int32BinopMatcher>(
selector, node, kPPC_AddWithOverflow32, kInt16Imm, cont);
case IrOpcode::kInt32SubWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop<Int32BinopMatcher>(selector, node,
kPPC_SubWithOverflow32,
kInt16Imm_Negate, cont);
case IrOpcode::kInt32MulWithOverflow:
cont->OverwriteAndNegateIfEqual(kNotEqual);
return EmitInt32MulWithOverflow(selector, node, cont);
#if V8_TARGET_ARCH_PPC64
case IrOpcode::kInt64AddWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop<Int64BinopMatcher>(selector, node, kPPC_Add,
kInt16Imm, cont);
case IrOpcode::kInt64SubWithOverflow:
cont->OverwriteAndNegateIfEqual(kOverflow);
return VisitBinop<Int64BinopMatcher>(selector, node, kPPC_Sub,
kInt16Imm_Negate, cont);
#endif
default:
break;
}
}
}
break;
case IrOpcode::kInt32Sub:
return VisitWord32Compare(selector, value, cont);
case IrOpcode::kWord32And:
// TODO(mbandy): opportunity for rlwinm?
return VisitWordCompare(selector, value, kPPC_Tst32, cont, true,
kInt16Imm_Unsigned);
// TODO(mbrandy): Handle?
// case IrOpcode::kInt32Add:
// case IrOpcode::kWord32Or:
// case IrOpcode::kWord32Xor:
// case IrOpcode::kWord32Sar:
// case IrOpcode::kWord32Shl:
// case IrOpcode::kWord32Shr:
// case IrOpcode::kWord32Ror:
#if V8_TARGET_ARCH_PPC64
case IrOpcode::kInt64Sub:
return VisitWord64Compare(selector, value, cont);
case IrOpcode::kWord64And:
// TODO(mbandy): opportunity for rldic?
return VisitWordCompare(selector, value, kPPC_Tst64, cont, true,
kInt16Imm_Unsigned);
// TODO(mbrandy): Handle?
// case IrOpcode::kInt64Add:
// case IrOpcode::kWord64Or:
// case IrOpcode::kWord64Xor:
// case IrOpcode::kWord64Sar:
// case IrOpcode::kWord64Shl:
// case IrOpcode::kWord64Shr:
// case IrOpcode::kWord64Ror:
#endif
default:
break;
}
break;
}
// Branch could not be combined with a compare, emit compare against 0.
PPCOperandGenerator g(selector);
VisitCompare(selector, opcode, g.UseRegister(value), g.TempImmediate(0),
cont);
}
void VisitWord32CompareZero(InstructionSelector* selector, Node* user,
Node* value, FlagsContinuation* cont) {
VisitWordCompareZero(selector, user, value, kPPC_Cmp32, cont);
}
#if V8_TARGET_ARCH_PPC64
void VisitWord64CompareZero(InstructionSelector* selector, Node* user,
Node* value, FlagsContinuation* cont) {
VisitWordCompareZero(selector, user, value, kPPC_Cmp64, cont);
}
#endif
} // namespace
void InstructionSelector::VisitBranch(Node* branch, BasicBlock* tbranch,
BasicBlock* fbranch) {
FlagsContinuation cont(kNotEqual, tbranch, fbranch);
VisitWord32CompareZero(this, branch, branch->InputAt(0), &cont);
}
void InstructionSelector::VisitDeoptimizeIf(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForDeoptimize(
kNotEqual, DeoptimizeReasonOf(node->op()), node->InputAt(1));
VisitWord32CompareZero(this, node, node->InputAt(0), &cont);
}
void InstructionSelector::VisitDeoptimizeUnless(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForDeoptimize(
kEqual, DeoptimizeReasonOf(node->op()), node->InputAt(1));
VisitWord32CompareZero(this, node, node->InputAt(0), &cont);
}
void InstructionSelector::VisitSwitch(Node* node, const SwitchInfo& sw) {
PPCOperandGenerator g(this);
InstructionOperand value_operand = g.UseRegister(node->InputAt(0));
// Emit either ArchTableSwitch or ArchLookupSwitch.
size_t table_space_cost = 4 + sw.value_range;
size_t table_time_cost = 3;
size_t lookup_space_cost = 3 + 2 * sw.case_count;
size_t lookup_time_cost = sw.case_count;
if (sw.case_count > 0 &&
table_space_cost + 3 * table_time_cost <=
lookup_space_cost + 3 * lookup_time_cost &&
sw.min_value > std::numeric_limits<int32_t>::min()) {
InstructionOperand index_operand = value_operand;
if (sw.min_value) {
index_operand = g.TempRegister();
Emit(kPPC_Sub, index_operand, value_operand,
g.TempImmediate(sw.min_value));
}
// Generate a table lookup.
return EmitTableSwitch(sw, index_operand);
}
// Generate a sequence of conditional jumps.
return EmitLookupSwitch(sw, value_operand);
}
void InstructionSelector::VisitWord32Equal(Node* const node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
Int32BinopMatcher m(node);
if (m.right().Is(0)) {
return VisitWord32CompareZero(this, m.node(), m.left().node(), &cont);
}
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitInt32LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitInt32LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kSignedLessThanOrEqual, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitUint32LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitWord32Compare(this, node, &cont);
}
void InstructionSelector::VisitUint32LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitWord32Compare(this, node, &cont);
}
#if V8_TARGET_ARCH_PPC64
void InstructionSelector::VisitWord64Equal(Node* const node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
Int64BinopMatcher m(node);
if (m.right().Is(0)) {
return VisitWord64CompareZero(this, m.node(), m.left().node(), &cont);
}
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitInt64LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitInt64LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kSignedLessThanOrEqual, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitUint64LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitWord64Compare(this, node, &cont);
}
void InstructionSelector::VisitUint64LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitWord64Compare(this, node, &cont);
}
#endif
void InstructionSelector::VisitInt32MulWithOverflow(Node* node) {
if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
FlagsContinuation cont = FlagsContinuation::ForSet(kNotEqual, ovf);
return EmitInt32MulWithOverflow(this, node, &cont);
}
FlagsContinuation cont;
EmitInt32MulWithOverflow(this, node, &cont);
}
void InstructionSelector::VisitFloat32Equal(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
VisitFloat32Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat32LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitFloat32Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat32LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitFloat32Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64Equal(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node);
VisitFloat64Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64LessThan(Node* node) {
FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node);
VisitFloat64Compare(this, node, &cont);
}
void InstructionSelector::VisitFloat64LessThanOrEqual(Node* node) {
FlagsContinuation cont =
FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node);
VisitFloat64Compare(this, node, &cont);
}
void InstructionSelector::EmitPrepareArguments(
ZoneVector<PushParameter>* arguments, const CallDescriptor* descriptor,
Node* node) {
PPCOperandGenerator g(this);
// Prepare for C function call.
if (descriptor->IsCFunctionCall()) {
Emit(kArchPrepareCallCFunction |
MiscField::encode(static_cast<int>(descriptor->ParameterCount())),
0, nullptr, 0, nullptr);
// Poke any stack arguments.
int slot = kStackFrameExtraParamSlot;
for (PushParameter input : (*arguments)) {
Emit(kPPC_StoreToStackSlot, g.NoOutput(), g.UseRegister(input.node()),
g.TempImmediate(slot));
++slot;
}
} else {
// Push any stack arguments.
int num_slots = static_cast<int>(descriptor->StackParameterCount());
int slot = 0;
for (PushParameter input : (*arguments)) {
if (slot == 0) {
DCHECK(input.node());
Emit(kPPC_PushFrame, g.NoOutput(), g.UseRegister(input.node()),
g.TempImmediate(num_slots));
} else {
// Skip any alignment holes in pushed nodes.
if (input.node()) {
Emit(kPPC_StoreToStackSlot, g.NoOutput(), g.UseRegister(input.node()),
g.TempImmediate(slot));
}
}
++slot;
}
}
}
bool InstructionSelector::IsTailCallAddressImmediate() { return false; }
int InstructionSelector::GetTempsCountForTailCallFromJSFunction() { return 3; }
void InstructionSelector::VisitFloat64ExtractLowWord32(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_DoubleExtractLowWord32, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitFloat64ExtractHighWord32(Node* node) {
PPCOperandGenerator g(this);
Emit(kPPC_DoubleExtractHighWord32, g.DefineAsRegister(node),
g.UseRegister(node->InputAt(0)));
}
void InstructionSelector::VisitFloat64InsertLowWord32(Node* node) {
PPCOperandGenerator g(this);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
if (left->opcode() == IrOpcode::kFloat64InsertHighWord32 &&
CanCover(node, left)) {
left = left->InputAt(1);
Emit(kPPC_DoubleConstruct, g.DefineAsRegister(node), g.UseRegister(left),
g.UseRegister(right));
return;
}
Emit(kPPC_DoubleInsertLowWord32, g.DefineSameAsFirst(node),
g.UseRegister(left), g.UseRegister(right));
}
void InstructionSelector::VisitFloat64InsertHighWord32(Node* node) {
PPCOperandGenerator g(this);
Node* left = node->InputAt(0);
Node* right = node->InputAt(1);
if (left->opcode() == IrOpcode::kFloat64InsertLowWord32 &&
CanCover(node, left)) {
left = left->InputAt(1);
Emit(kPPC_DoubleConstruct, g.DefineAsRegister(node), g.UseRegister(right),
g.UseRegister(left));
return;
}
Emit(kPPC_DoubleInsertHighWord32, g.DefineSameAsFirst(node),
g.UseRegister(left), g.UseRegister(right));
}
void InstructionSelector::VisitAtomicLoad(Node* node) {
LoadRepresentation load_rep = LoadRepresentationOf(node->op());
PPCOperandGenerator g(this);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
ArchOpcode opcode = kArchNop;
switch (load_rep.representation()) {
case MachineRepresentation::kWord8:
opcode = load_rep.IsSigned() ? kAtomicLoadInt8 : kAtomicLoadUint8;
break;
case MachineRepresentation::kWord16:
opcode = load_rep.IsSigned() ? kAtomicLoadInt16 : kAtomicLoadUint16;
break;
case MachineRepresentation::kWord32:
opcode = kAtomicLoadWord32;
break;
default:
UNREACHABLE();
return;
}
Emit(opcode | AddressingModeField::encode(kMode_MRR),
g.DefineAsRegister(node), g.UseRegister(base), g.UseRegister(index));
}
void InstructionSelector::VisitAtomicStore(Node* node) {
MachineRepresentation rep = AtomicStoreRepresentationOf(node->op());
PPCOperandGenerator g(this);
Node* base = node->InputAt(0);
Node* index = node->InputAt(1);
Node* value = node->InputAt(2);
ArchOpcode opcode = kArchNop;
switch (rep) {
case MachineRepresentation::kWord8:
opcode = kAtomicStoreWord8;
break;
case MachineRepresentation::kWord16:
opcode = kAtomicStoreWord16;
break;
case MachineRepresentation::kWord32:
opcode = kAtomicStoreWord32;
break;
default:
UNREACHABLE();
return;
}
InstructionOperand inputs[4];
size_t input_count = 0;
inputs[input_count++] = g.UseUniqueRegister(base);
inputs[input_count++] = g.UseUniqueRegister(index);
inputs[input_count++] = g.UseUniqueRegister(value);
Emit(opcode | AddressingModeField::encode(kMode_MRR),
0, nullptr, input_count, inputs);
}
// static
MachineOperatorBuilder::Flags
InstructionSelector::SupportedMachineOperatorFlags() {
return MachineOperatorBuilder::kFloat32RoundDown |
MachineOperatorBuilder::kFloat64RoundDown |
MachineOperatorBuilder::kFloat32RoundUp |
MachineOperatorBuilder::kFloat64RoundUp |
MachineOperatorBuilder::kFloat32RoundTruncate |
MachineOperatorBuilder::kFloat64RoundTruncate |
MachineOperatorBuilder::kFloat64RoundTiesAway |
MachineOperatorBuilder::kWord32Popcnt |
MachineOperatorBuilder::kWord64Popcnt;
// We omit kWord32ShiftIsSafe as s[rl]w use 0x3f as a mask rather than 0x1f.
}
// static
MachineOperatorBuilder::AlignmentRequirements
InstructionSelector::AlignmentRequirements() {
return MachineOperatorBuilder::AlignmentRequirements::
FullUnalignedAccessSupport();
}
} // namespace compiler
} // namespace internal
} // namespace v8
|
#pragma once
#include "src/Screen.hpp"
#include <SDL_events.h>
#include <memory>
namespace osc {
// META: this is a valid screen with `CookiecutterScreen` as a replaceable
// string that users can "Find+Replace" to make their own screen impl
class CookiecutterScreen final : public Screen {
public:
struct Impl;
private:
std::unique_ptr<Impl> m_Impl;
public:
CookiecutterScreen();
~CookiecutterScreen() noexcept override;
void onMount() override;
void onUnmount() override;
void onEvent(SDL_Event const&) override;
void tick(float) override;
void draw() override;
};
}
|
#ifndef STICPP_TAB_STOPS_HPP
#define STICPP_TAB_STOPS_HPP
namespace stiX {
inline const size_t tabSize = 4;
inline size_t next_tab_stop(size_t position) {
const auto currentTab = (position / tabSize);
const auto nextTab = currentTab + 1;
const auto nextStop = nextTab * tabSize;
return nextStop;
}
inline size_t distance_to_next_tab_stop(size_t position) {
return next_tab_stop(position) - position;
}
inline bool is_tab_stop(size_t position) {
return (position % tabSize) == 0;
}
}
#endif //STICPP_TAB_STOPS_HPP
|
#include "Path.h"
#include "Logging.h"
#include "utils/Constants.h"
#include "utils/AdjacentCellIterator.h"
using namespace std;
namespace map_solver {
void Path::checkInBounds(index_t idx) const {
if (idx > m_cells.size())
throw OutOfBoundsException("index is larger than the current cell size");
if (idx/m_width > m_height)
throw OutOfBoundsException("y is larger than the current height");
if (m_width == kInvalidWeight || m_height == kInvalidWeight)
throw OutOfBoundsException("m_width or m_height == -1");
}
index_t Path::cell(index_t idx) const {
checkInBounds(idx);
return m_cells[idx];
}
index_t Path::cell(index_t x, index_t y) const {
index_t idx = cartesianToIndex(x, y);
checkInBounds(idx);
return m_cells[idx];
}
void Path::markCell(index_t idx) {
checkInBounds(idx);
m_cells[idx] = 1;
};
index_t Path::cartesianToIndex(index_t x, index_t y) const {
// TODO: make a test
if (m_width == kInvalidWeight)
throw OutOfBoundsException("m_w is incorrect");
return x + y * m_width;
}
CartesianPoint Path::indexToCartesian(index_t i) const {
index_t x = i%m_width;
index_t y = i/m_width;
if ( y > m_height )
throw OutOfBoundsException("y > m_h");
return CartesianPoint{ x, y };
}
weight_t Path::calculateFromDistances(const std::vector<index_t> dist,
index_t start_idx,
index_t end_idx) {
checkInBounds(start_idx);
checkInBounds(end_idx);
m_cells[end_idx] = 1;
index_t current_idx = end_idx;
weight_t total_weight = 0;
LOG_TRACE << "Total distance: " << dist[end_idx];
total_weight = dist[end_idx];
if (total_weight >= kWallWeight)
throw DestinationUnreachableException("can't reach from start to end");
while (true) {
if (current_idx == start_idx)
break;
AdjacentCells<index_t> cells(m_width, m_height, current_idx);
auto min = min_element(cells.begin(), cells.end(), [&](auto&& lhs, auto&& rhs) {
return dist[lhs] < dist[rhs];
});
index_t min_idx = *min;
m_cells[min_idx] = 1;
current_idx = min_idx;
}
for (index_t i = 0; i < m_width; ++ i)
for (index_t j = 0; j < m_height; ++ j) {
LOG_TRACE << "Element " << i << ", " << j <<": " << m_cells[cartesianToIndex(i, j)];
}
return total_weight;
}
}
|
//******************************************************************************
//
// File: ShimDllInterface.hxx
//
// Activation parameters to be passed from the version-independent hosting shim
// exe to the version-specific hosting DLL.
//
// History:
//
// 2005-05-19: [....] - Created
// 2007/09/20: [....] Ported Windows->DevDiv. See SourcesHistory.txt.
//
// Copyright (C) by Microsoft Corporation. All rights reserved.
//
//******************************************************************************
#ifndef SHIMDLLINTERFACE_HXX
#define SHIMDLLINTERFACE_HXX
struct ActivateParameters
{
// The size of this structure. For version control. The sizes MUST be unique across versions.
DWORD dwSize;
// The URI of the application to be deployed or the document to be opened.
LPCWSTR pswzUri;
// The ApplicationIdentity of the application to be deployed. May not refer
// to an application that has actually been deployed yet.
LPCWSTR pswzApplicationIdentity;
// The RM manifest to use (documents only)
LPCWSTR pswzDocumentRmManifest;
MimeType mime;
IStream* pHistoryStream;
IStream* pDocumentStream;
HANDLE hDownloadCompletedEvent;
BOOL isDebug;
LPWSTR pswzDebugSecurityZoneURL;
IPersistHistory* pPersistHistory;
HANDLE hNoHostTimer;
// The outer object for COM aggregation purposes
// This will be a CHostShim instance; COleDocument will use it for AddRef and Release calls.
LPUNKNOWN pOuterObject;
// -->
// Added for v3.5 SP1 servicing (including for Windows 7) and v4.
// Note that a version of PresentationHostDll will normally never be invoked with this extra parameter
// if it doesn't support it, because the shim invokes the latest PHDLL, and initially they are updated
// together (for the above releases).
// ...Oops, except it turned out we had to deal with the abnormal case of PH v4 finding only an older
// PHDLL v3 that doesn't support the new feature. See fallback in CHostShim::Execute().
// Set when the shim encountered an error and wants the DLL to display it (instead of running the app).
// We have to fully activate the DocObject to be able to show the error page...
LPCWSTR pswzErrorMessageToDisplay;
};
#endif // SHIMDLLINTERFACE_HXX
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2020 Ryo Suzuki
// Copyright (c) 2016-2020 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include "CRenderer2D_GL4.hpp"
# include <Siv3D/Error.hpp>
# include <Siv3D/EngineLog.hpp>
# include <Siv3D/ScopeGuard.hpp>
# include <Siv3D/Array.hpp>
# include <Siv3D/BinaryReader.hpp>
# include <Siv3D/PointVector.hpp>
# include <Siv3D/Vertex2D.hpp>
# include <Siv3D/Mat3x2.hpp>
# include <Siv3D/Resource.hpp>
# include <Siv3D/TextReader.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
# include <Siv3D/Renderer/IRenderer.hpp>
namespace s3d
{
namespace detail
{
static GLuint LoadShaders(const FilePath& vsFilePath, const FilePath& psFilePath)
{
const std::string vsSource = TextReader(vsFilePath).readAll().toUTF8();
const std::string psSource = TextReader(psFilePath).readAll().toUTF8();
if (vsSource.empty() || psSource.empty())
{
return 0;
}
GLuint vertexShader = ::glCreateShader(GL_VERTEX_SHADER);
{
const char* vsSourcePtr = vsSource.c_str();
::glShaderSource(vertexShader, 1, &vsSourcePtr, nullptr);
::glCompileShader(vertexShader);
GLint status = GL_FALSE, infoLogLength = 0;
::glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
::glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0)
{
std::string logText(infoLogLength + 1, '\0');
::glGetShaderInfoLog(vertexShader, infoLogLength, nullptr, logText.data());
LOG_FAIL(U"VS: {0}"_fmt(Unicode::Widen(logText)));
}
}
GLuint pixelShader = ::glCreateShader(GL_FRAGMENT_SHADER);
{
const char* psSourcePtr = psSource.c_str();
::glShaderSource(pixelShader, 1, &psSourcePtr, nullptr);
::glCompileShader(pixelShader);
GLint status = GL_FALSE, infoLogLength = 0;
::glGetShaderiv(pixelShader, GL_COMPILE_STATUS, &status);
::glGetShaderiv(pixelShader, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0)
{
std::string logText(infoLogLength + 1, '\0');
::glGetShaderInfoLog(pixelShader, infoLogLength, nullptr, logText.data());
LOG_FAIL(U"PS: {0}"_fmt(Unicode::Widen(logText)));
}
}
GLuint program = ::glCreateProgram();
{
::glAttachShader(program, vertexShader);
::glAttachShader(program, pixelShader);
::glLinkProgram(program);
GLint status = GL_FALSE, infoLogLength = 0;
::glGetProgramiv(program, GL_LINK_STATUS, &status);
::glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
if (infoLogLength > 0)
{
std::string logText(infoLogLength + 1, '\0');
::glGetProgramInfoLog(pixelShader, infoLogLength, nullptr, logText.data());
LOG_FAIL(U"LINK: {0}"_fmt(Unicode::Widen(logText)));
}
}
::glDetachShader(program, vertexShader);
::glDetachShader(program, pixelShader);
::glDeleteShader(vertexShader);
::glDeleteShader(pixelShader);
return program;
}
}
CRenderer2D_GL4::CRenderer2D_GL4() = default;
CRenderer2D_GL4::~CRenderer2D_GL4()
{
LOG_SCOPED_TRACE(U"CRenderer2D_GL4::~CRenderer2D_GL4()");
//////////////////////////////////////////////////
//
// full screen triangle
//
//////////////////////////////////////////////////
if (m_sampler)
{
::glDeleteSamplers(1, &m_sampler);
m_sampler = 0;
}
if (m_vertexArray)
{
::glDeleteVertexArrays(1, &m_vertexArray);
m_vertexArray = 0;
}
if (m_copyProgram)
{
::glDeleteProgram(m_copyProgram);
m_copyProgram = 0;
}
if (m_uniformBuffer)
{
::glDeleteBuffers(1, &m_uniformBuffer);
m_uniformBuffer = 0;
}
if (m_pipeline)
{
::glDeleteProgramPipelines(1, &m_pipeline);
m_pipeline = 0;
}
if (m_psProgram)
{
::glDeleteProgram(m_psProgram);
m_psProgram = 0;
}
if (m_vsProgram)
{
::glDeleteProgram(m_vsProgram);
m_vsProgram = 0;
}
CheckOpenGLError();
}
void CRenderer2D_GL4::init()
{
LOG_SCOPED_TRACE(U"CRenderer2D_GL4::init()");
pRenderer = dynamic_cast<CRenderer_GL4*>(SIV3D_ENGINE(Renderer));
{
BinaryReader shader(Resource(U"engine/shader/glsl/test.vert"));
if (!shader)
{
throw EngineError();
}
Array<char> source(shader.size() + 1);
shader.read(source.data(), shader.size());
const char* pSource = source.data();
m_vsProgram = ::glCreateShaderProgramv(GL_VERTEX_SHADER, 1, &pSource);
GLint status = GL_FALSE;
::glGetProgramiv(m_vsProgram, GL_LINK_STATUS, &status);
GLint logLen = 0;
::glGetProgramiv(m_vsProgram, GL_INFO_LOG_LENGTH, &logLen);
if (logLen > 4)
{
std::string log(logLen + 1, '\0');
::glGetProgramInfoLog(m_vsProgram, logLen, &logLen, &log[0]);
LOG_FAIL(U"❌ Vertex shader compilation failed: {0}"_fmt(Unicode::Widen(log)));
throw EngineError();
}
if (status == GL_FALSE) // もしリンクに失敗していたら
{
::glDeleteProgram(m_vsProgram);
m_vsProgram = 0;
throw EngineError();
}
}
{
BinaryReader shader(Resource(U"engine/shader/glsl/test.frag"));
if (!shader)
{
throw EngineError();
}
Array<char> source(shader.size() + 1);
shader.read(source.data(), shader.size());
const char* pSource = source.data();
m_psProgram = ::glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &pSource);
GLint status = GL_FALSE;
::glGetProgramiv(m_psProgram, GL_LINK_STATUS, &status);
GLint logLen = 0;
::glGetProgramiv(m_psProgram, GL_INFO_LOG_LENGTH, &logLen);
// ログメッセージ
if (logLen > 4)
{
std::string log(logLen + 1, '\0');
::glGetProgramInfoLog(m_psProgram, logLen, &logLen, &log[0]);
LOG_FAIL(U"❌ Pixel shader compilation failed: {0}"_fmt(Unicode::Widen(log)));
throw EngineError();
}
if (status == GL_FALSE) // もしリンクに失敗していたら
{
::glDeleteProgram(m_psProgram);
m_psProgram = 0;
throw EngineError();
}
}
::glGenProgramPipelines(1, &m_pipeline);
::glGenBuffers(1, &m_uniformBuffer);
// Batch 管理を初期化
if (!m_batches.init())
{
throw EngineError(U"GL4Vertex2DBatch::init() failed");
}
// full screen triangle
{
m_copyProgram = detail::LoadShaders(Resource(U"engine/shader/glsl/fullscreen_triangle.vert"), Resource(U"engine/shader/glsl/fullscreen_triangle.frag"));
if (!m_copyProgram)
{
throw EngineError();
}
m_locationTexture = ::glGetUniformLocation(m_copyProgram, "Texture0");
::glGenVertexArrays(1, &m_vertexArray);
::glBindVertexArray(m_vertexArray);
::glGenSamplers(1, &m_sampler);
::glSamplerParameteri(m_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
::glSamplerParameteri(m_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
::glSamplerParameteri(m_sampler, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
CheckOpenGLError();
}
void CRenderer2D_GL4::flush()
{
ScopeGuard cleanUp = [this]()
{
m_batches.reset();
m_draw_indexCount = 0;
};
if (m_draw_indexCount == 0)
{
return;
}
::glUseProgramStages(m_pipeline, GL_VERTEX_SHADER_BIT, m_vsProgram);
::glUseProgramStages(m_pipeline, GL_FRAGMENT_SHADER_BIT, m_psProgram);
::glUseProgram(0);
::glBindProgramPipeline(m_pipeline);
const Size currentRenderTargetSize = SIV3D_ENGINE(Renderer)->getSceneBufferSize();
::glViewport(0, 0, currentRenderTargetSize.x, currentRenderTargetSize.y);
Mat3x2 transform = Mat3x2::Identity();
Mat3x2 screenMat = Mat3x2::Screen(currentRenderTargetSize);
const Mat3x2 matrix = (transform * screenMat);
Float4 cb[3];
cb[0] = Float4(matrix._11, -matrix._12, matrix._31, -matrix._32);
cb[1] = Float4(matrix._21, -matrix._22, 0.0f, 1.0f);
cb[2] = Float4(1, 1, 1, 1);
{
::glBindBuffer(GL_UNIFORM_BUFFER, m_uniformBuffer);
::glBufferData(GL_UNIFORM_BUFFER, sizeof(Float4) * 3, cb, GL_STATIC_DRAW);
::glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
{
const uint32 vsUniformBlockBinding = 0;
::glBindBufferBase(GL_UNIFORM_BUFFER, vsUniformBlockBinding, m_uniformBuffer);
}
auto batchInfo = m_batches.updateBuffers(0);
const uint32 indexCount = m_draw_indexCount;
const uint32 startIndexLocation = batchInfo.startIndexLocation;
const uint32 baseVertexLocation = batchInfo.baseVertexLocation;
const Vertex2D::IndexType* pBase = 0;
::glDrawElementsBaseVertex(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (pBase + startIndexLocation), baseVertexLocation);
batchInfo.startIndexLocation += indexCount;
::glBindVertexArray(0);
CheckOpenGLError();
}
void CRenderer2D_GL4::test_renderRectangle(const RectF& rect, const ColorF& _color)
{
constexpr Vertex2D::IndexType vertexSize = 4, indexSize = 6;
auto [pVertex, pIndex, indexOffset] = m_batches.requestBuffer(vertexSize, indexSize, m_command);
if (!pVertex)
{
return;
}
const Float4 color = _color.toFloat4();
const float left = float(rect.x);
const float right = float(rect.x + rect.w);
const float top = float(rect.y);
const float bottom = float(rect.y + rect.h);
pVertex[0].set(left, top, color);
pVertex[1].set(right, top, color);
pVertex[2].set(left, bottom, color);
pVertex[3].set(right, bottom, color);
static constexpr Vertex2D::IndexType RectIndexTable[6] = { 0, 1, 2, 2, 1, 3 };
for (Vertex2D::IndexType i = 0; i < indexSize; ++i)
{
*pIndex++ = (indexOffset + RectIndexTable[i]);
}
m_draw_indexCount += 6;
}
void CRenderer2D_GL4::drawFullScreenTriangle(const TextureFilter textureFilter)
{
// view port
{
::glBindFramebuffer(GL_FRAMEBUFFER, 0);
auto [s, viewRect] = pRenderer->getLetterboxComposition();
::glViewport(
static_cast<int32>(viewRect.left),
static_cast<int32>(viewRect.top),
static_cast<int32>(viewRect.right),
static_cast<int32>(viewRect.bottom));
}
// render states
{
const bool linearFilter = (textureFilter == TextureFilter::Linear);
::glBindSampler(0, m_sampler);
::glSamplerParameteri(m_sampler, GL_TEXTURE_MIN_FILTER, linearFilter ? GL_LINEAR : GL_NEAREST);
::glSamplerParameteri(m_sampler, GL_TEXTURE_MAG_FILTER, linearFilter ? GL_LINEAR : GL_NEAREST);
}
::glUseProgram(m_copyProgram);
{
::glUniform1i(m_locationTexture, 0);
::glBindVertexArray(m_vertexArray);
{
::glBindBuffer(GL_ARRAY_BUFFER, 0);
::glDrawArrays(GL_TRIANGLES, 0, 3);
}
::glBindVertexArray(0);
}
::glUseProgram(0);
CheckOpenGLError();
}
}
|
//
// Created by npchitman on 6/1/21.
//
#include <Aphrodite/Input/Input.h>
#include <GLFW/glfw3.h>
#include "Aphrodite/Core/Application.h"
#include "pch.h"
namespace Aph {
bool Input::IsKeyPressed(const KeyCode keycode) {
auto window = static_cast<GLFWwindow *>(Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetKey(window, static_cast<int32_t>(keycode));
return state == GLFW_PRESS || state == GLFW_REPEAT;
}
bool Input::IsMouseButtonPressed(const MouseCode button) {
auto window = static_cast<GLFWwindow *>(
Application::Get().GetWindow().GetNativeWindow());
auto state = glfwGetMouseButton(window, static_cast<int32_t>(button));
return state == GLFW_PRESS;
}
glm::vec2 Input::GetMousePosition() {
auto *window = static_cast<GLFWwindow *>(
Application::Get().GetWindow().GetNativeWindow());
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
return {static_cast<float>(xPos), static_cast<float>(yPos)};
}
float Input::GetMouseX() {
return GetMousePosition().x;
}
float Input::GetMouseY() {
return GetMousePosition().y;
}
}// namespace Aph
|
// Copyright 2019 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef ROS2_IGN_BRIDGE__BUILTIN_INTERFACES_FACTORIES_HPP_
#define ROS2_IGN_BRIDGE__BUILTIN_INTERFACES_FACTORIES_HPP_
// include ROS 2 messages
#include <std_msgs/msg/string.hpp>
// include Ignition Transport messages
#include <ignition/msgs.hh>
#include <ros2_ign_bridge/factory.hpp>
#include <memory>
#include <string>
namespace ros2_ign_bridge
{
std::shared_ptr<FactoryInterface>
get_factory_builtin_interfaces(
const std::string & ros2_type_name,
const std::string & ign_type_name);
std::shared_ptr<FactoryInterface>
get_factory(
const std::string & ros2_type_name,
const std::string & ign_type_name);
// conversion functions for available interfaces
// std_msgs
template<>
void
Factory<
std_msgs::msg::String,
ignition::msgs::StringMsg
>::convert_ros2_to_ign(
const std_msgs::msg::String & ros2_msg,
ignition::msgs::StringMsg & ign_msg);
template<>
void
Factory<
std_msgs::msg::String,
ignition::msgs::StringMsg
>::convert_ign_to_ros2(
const ignition::msgs::StringMsg & ign_msg,
std_msgs::msg::String & ros2_msg);
} // namespace ros2_ign_bridge
#endif // ROS2_IGN_BRIDGE__BUILTIN_INTERFACES_FACTORIES_HPP_
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/gaap/v20180529/model/CloseSecurityPolicyRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Gaap::V20180529::Model;
using namespace rapidjson;
using namespace std;
CloseSecurityPolicyRequest::CloseSecurityPolicyRequest() :
m_proxyIdHasBeenSet(false),
m_policyIdHasBeenSet(false)
{
}
string CloseSecurityPolicyRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_proxyIdHasBeenSet)
{
Value iKey(kStringType);
string key = "ProxyId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_proxyId.c_str(), allocator).Move(), allocator);
}
if (m_policyIdHasBeenSet)
{
Value iKey(kStringType);
string key = "PolicyId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_policyId.c_str(), allocator).Move(), allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CloseSecurityPolicyRequest::GetProxyId() const
{
return m_proxyId;
}
void CloseSecurityPolicyRequest::SetProxyId(const string& _proxyId)
{
m_proxyId = _proxyId;
m_proxyIdHasBeenSet = true;
}
bool CloseSecurityPolicyRequest::ProxyIdHasBeenSet() const
{
return m_proxyIdHasBeenSet;
}
string CloseSecurityPolicyRequest::GetPolicyId() const
{
return m_policyId;
}
void CloseSecurityPolicyRequest::SetPolicyId(const string& _policyId)
{
m_policyId = _policyId;
m_policyIdHasBeenSet = true;
}
bool CloseSecurityPolicyRequest::PolicyIdHasBeenSet() const
{
return m_policyIdHasBeenSet;
}
|
/**
* @author : archit
* @GitHub : archit-1997
* @Email : architsingh456@gmail.com
* @file : middleOfTheLinkedList.cpp
* @created : Saturday Aug 07, 2021 07:07:01 IST
*/
#include <bits/stdc++.h>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* slow=head,*fast=head;
while(slow && fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
};
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: SITLGps.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "SITLGps.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 sensor_msgs {
namespace msgs {
namespace {
const ::google::protobuf::Descriptor* SITLGps_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
SITLGps_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_SITLGps_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_SITLGps_2eproto() {
protobuf_AddDesc_SITLGps_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"SITLGps.proto");
GOOGLE_CHECK(file != NULL);
SITLGps_descriptor_ = file->message_type(0);
static const int SITLGps_offsets_[10] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, time_usec_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, latitude_deg_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, longitude_deg_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, altitude_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, eph_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, epv_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, velocity_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, velocity_east_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, velocity_north_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, velocity_up_),
};
SITLGps_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
SITLGps_descriptor_,
SITLGps::default_instance_,
SITLGps_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, _has_bits_[0]),
-1,
-1,
sizeof(SITLGps),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SITLGps, _internal_metadata_),
-1);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_SITLGps_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
SITLGps_descriptor_, &SITLGps::default_instance());
}
} // namespace
void protobuf_ShutdownFile_SITLGps_2eproto() {
delete SITLGps::default_instance_;
delete SITLGps_reflection_;
}
void protobuf_AddDesc_SITLGps_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AddDesc_SITLGps_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\rSITLGps.proto\022\020sensor_msgs.msgs\"\313\001\n\007SI"
"TLGps\022\021\n\ttime_usec\030\001 \002(\003\022\024\n\014latitude_deg"
"\030\002 \002(\001\022\025\n\rlongitude_deg\030\003 \002(\001\022\020\n\010altitud"
"e\030\004 \002(\001\022\013\n\003eph\030\005 \001(\001\022\013\n\003epv\030\006 \001(\001\022\020\n\010vel"
"ocity\030\007 \001(\001\022\025\n\rvelocity_east\030\010 \001(\001\022\026\n\016ve"
"locity_north\030\t \001(\001\022\023\n\013velocity_up\030\n \001(\001", 239);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"SITLGps.proto", &protobuf_RegisterTypes);
SITLGps::default_instance_ = new SITLGps();
SITLGps::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_SITLGps_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_SITLGps_2eproto {
StaticDescriptorInitializer_SITLGps_2eproto() {
protobuf_AddDesc_SITLGps_2eproto();
}
} static_descriptor_initializer_SITLGps_2eproto_;
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int SITLGps::kTimeUsecFieldNumber;
const int SITLGps::kLatitudeDegFieldNumber;
const int SITLGps::kLongitudeDegFieldNumber;
const int SITLGps::kAltitudeFieldNumber;
const int SITLGps::kEphFieldNumber;
const int SITLGps::kEpvFieldNumber;
const int SITLGps::kVelocityFieldNumber;
const int SITLGps::kVelocityEastFieldNumber;
const int SITLGps::kVelocityNorthFieldNumber;
const int SITLGps::kVelocityUpFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
SITLGps::SITLGps()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:sensor_msgs.msgs.SITLGps)
}
void SITLGps::InitAsDefaultInstance() {
}
SITLGps::SITLGps(const SITLGps& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:sensor_msgs.msgs.SITLGps)
}
void SITLGps::SharedCtor() {
_cached_size_ = 0;
time_usec_ = GOOGLE_LONGLONG(0);
latitude_deg_ = 0;
longitude_deg_ = 0;
altitude_ = 0;
eph_ = 0;
epv_ = 0;
velocity_ = 0;
velocity_east_ = 0;
velocity_north_ = 0;
velocity_up_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
SITLGps::~SITLGps() {
// @@protoc_insertion_point(destructor:sensor_msgs.msgs.SITLGps)
SharedDtor();
}
void SITLGps::SharedDtor() {
if (this != default_instance_) {
}
}
void SITLGps::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* SITLGps::descriptor() {
protobuf_AssignDescriptorsOnce();
return SITLGps_descriptor_;
}
const SITLGps& SITLGps::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_SITLGps_2eproto();
return *default_instance_;
}
SITLGps* SITLGps::default_instance_ = NULL;
SITLGps* SITLGps::New(::google::protobuf::Arena* arena) const {
SITLGps* n = new SITLGps;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void SITLGps::Clear() {
// @@protoc_insertion_point(message_clear_start:sensor_msgs.msgs.SITLGps)
#if defined(__clang__)
#define ZR_HELPER_(f) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(SITLGps, f) \
_Pragma("clang diagnostic pop")
#else
#define ZR_HELPER_(f) reinterpret_cast<char*>(\
&reinterpret_cast<SITLGps*>(16)->f)
#endif
#define ZR_(first, last) do {\
::memset(&first, 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
if (_has_bits_[0 / 32] & 255u) {
ZR_(time_usec_, velocity_east_);
}
ZR_(velocity_north_, velocity_up_);
#undef ZR_HELPER_
#undef ZR_
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool SITLGps::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:sensor_msgs.msgs.SITLGps)
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)) {
// required int64 time_usec = 1;
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &time_usec_)));
set_has_time_usec();
} else {
goto handle_unusual;
}
if (input->ExpectTag(17)) goto parse_latitude_deg;
break;
}
// required double latitude_deg = 2;
case 2: {
if (tag == 17) {
parse_latitude_deg:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &latitude_deg_)));
set_has_latitude_deg();
} else {
goto handle_unusual;
}
if (input->ExpectTag(25)) goto parse_longitude_deg;
break;
}
// required double longitude_deg = 3;
case 3: {
if (tag == 25) {
parse_longitude_deg:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &longitude_deg_)));
set_has_longitude_deg();
} else {
goto handle_unusual;
}
if (input->ExpectTag(33)) goto parse_altitude;
break;
}
// required double altitude = 4;
case 4: {
if (tag == 33) {
parse_altitude:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &altitude_)));
set_has_altitude();
} else {
goto handle_unusual;
}
if (input->ExpectTag(41)) goto parse_eph;
break;
}
// optional double eph = 5;
case 5: {
if (tag == 41) {
parse_eph:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &eph_)));
set_has_eph();
} else {
goto handle_unusual;
}
if (input->ExpectTag(49)) goto parse_epv;
break;
}
// optional double epv = 6;
case 6: {
if (tag == 49) {
parse_epv:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &epv_)));
set_has_epv();
} else {
goto handle_unusual;
}
if (input->ExpectTag(57)) goto parse_velocity;
break;
}
// optional double velocity = 7;
case 7: {
if (tag == 57) {
parse_velocity:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &velocity_)));
set_has_velocity();
} else {
goto handle_unusual;
}
if (input->ExpectTag(65)) goto parse_velocity_east;
break;
}
// optional double velocity_east = 8;
case 8: {
if (tag == 65) {
parse_velocity_east:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &velocity_east_)));
set_has_velocity_east();
} else {
goto handle_unusual;
}
if (input->ExpectTag(73)) goto parse_velocity_north;
break;
}
// optional double velocity_north = 9;
case 9: {
if (tag == 73) {
parse_velocity_north:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &velocity_north_)));
set_has_velocity_north();
} else {
goto handle_unusual;
}
if (input->ExpectTag(81)) goto parse_velocity_up;
break;
}
// optional double velocity_up = 10;
case 10: {
if (tag == 81) {
parse_velocity_up:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
input, &velocity_up_)));
set_has_velocity_up();
} 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::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:sensor_msgs.msgs.SITLGps)
return true;
failure:
// @@protoc_insertion_point(parse_failure:sensor_msgs.msgs.SITLGps)
return false;
#undef DO_
}
void SITLGps::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:sensor_msgs.msgs.SITLGps)
// required int64 time_usec = 1;
if (has_time_usec()) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->time_usec(), output);
}
// required double latitude_deg = 2;
if (has_latitude_deg()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->latitude_deg(), output);
}
// required double longitude_deg = 3;
if (has_longitude_deg()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->longitude_deg(), output);
}
// required double altitude = 4;
if (has_altitude()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(4, this->altitude(), output);
}
// optional double eph = 5;
if (has_eph()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->eph(), output);
}
// optional double epv = 6;
if (has_epv()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->epv(), output);
}
// optional double velocity = 7;
if (has_velocity()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->velocity(), output);
}
// optional double velocity_east = 8;
if (has_velocity_east()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(8, this->velocity_east(), output);
}
// optional double velocity_north = 9;
if (has_velocity_north()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(9, this->velocity_north(), output);
}
// optional double velocity_up = 10;
if (has_velocity_up()) {
::google::protobuf::internal::WireFormatLite::WriteDouble(10, this->velocity_up(), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:sensor_msgs.msgs.SITLGps)
}
::google::protobuf::uint8* SITLGps::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:sensor_msgs.msgs.SITLGps)
// required int64 time_usec = 1;
if (has_time_usec()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->time_usec(), target);
}
// required double latitude_deg = 2;
if (has_latitude_deg()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->latitude_deg(), target);
}
// required double longitude_deg = 3;
if (has_longitude_deg()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->longitude_deg(), target);
}
// required double altitude = 4;
if (has_altitude()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(4, this->altitude(), target);
}
// optional double eph = 5;
if (has_eph()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->eph(), target);
}
// optional double epv = 6;
if (has_epv()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->epv(), target);
}
// optional double velocity = 7;
if (has_velocity()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->velocity(), target);
}
// optional double velocity_east = 8;
if (has_velocity_east()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(8, this->velocity_east(), target);
}
// optional double velocity_north = 9;
if (has_velocity_north()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(9, this->velocity_north(), target);
}
// optional double velocity_up = 10;
if (has_velocity_up()) {
target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(10, this->velocity_up(), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:sensor_msgs.msgs.SITLGps)
return target;
}
int SITLGps::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:sensor_msgs.msgs.SITLGps)
int total_size = 0;
if (has_time_usec()) {
// required int64 time_usec = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->time_usec());
}
if (has_latitude_deg()) {
// required double latitude_deg = 2;
total_size += 1 + 8;
}
if (has_longitude_deg()) {
// required double longitude_deg = 3;
total_size += 1 + 8;
}
if (has_altitude()) {
// required double altitude = 4;
total_size += 1 + 8;
}
return total_size;
}
int SITLGps::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:sensor_msgs.msgs.SITLGps)
int total_size = 0;
if (((_has_bits_[0] & 0x0000000f) ^ 0x0000000f) == 0) { // All required fields are present.
// required int64 time_usec = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->time_usec());
// required double latitude_deg = 2;
total_size += 1 + 8;
// required double longitude_deg = 3;
total_size += 1 + 8;
// required double altitude = 4;
total_size += 1 + 8;
} else {
total_size += RequiredFieldsByteSizeFallback();
}
if (_has_bits_[4 / 32] & 240u) {
// optional double eph = 5;
if (has_eph()) {
total_size += 1 + 8;
}
// optional double epv = 6;
if (has_epv()) {
total_size += 1 + 8;
}
// optional double velocity = 7;
if (has_velocity()) {
total_size += 1 + 8;
}
// optional double velocity_east = 8;
if (has_velocity_east()) {
total_size += 1 + 8;
}
}
if (_has_bits_[8 / 32] & 768u) {
// optional double velocity_north = 9;
if (has_velocity_north()) {
total_size += 1 + 8;
}
// optional double velocity_up = 10;
if (has_velocity_up()) {
total_size += 1 + 8;
}
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void SITLGps::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:sensor_msgs.msgs.SITLGps)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const SITLGps* source =
::google::protobuf::internal::DynamicCastToGenerated<const SITLGps>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:sensor_msgs.msgs.SITLGps)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:sensor_msgs.msgs.SITLGps)
MergeFrom(*source);
}
}
void SITLGps::MergeFrom(const SITLGps& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:sensor_msgs.msgs.SITLGps)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_time_usec()) {
set_time_usec(from.time_usec());
}
if (from.has_latitude_deg()) {
set_latitude_deg(from.latitude_deg());
}
if (from.has_longitude_deg()) {
set_longitude_deg(from.longitude_deg());
}
if (from.has_altitude()) {
set_altitude(from.altitude());
}
if (from.has_eph()) {
set_eph(from.eph());
}
if (from.has_epv()) {
set_epv(from.epv());
}
if (from.has_velocity()) {
set_velocity(from.velocity());
}
if (from.has_velocity_east()) {
set_velocity_east(from.velocity_east());
}
}
if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) {
if (from.has_velocity_north()) {
set_velocity_north(from.velocity_north());
}
if (from.has_velocity_up()) {
set_velocity_up(from.velocity_up());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void SITLGps::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:sensor_msgs.msgs.SITLGps)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void SITLGps::CopyFrom(const SITLGps& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:sensor_msgs.msgs.SITLGps)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool SITLGps::IsInitialized() const {
if ((_has_bits_[0] & 0x0000000f) != 0x0000000f) return false;
return true;
}
void SITLGps::Swap(SITLGps* other) {
if (other == this) return;
InternalSwap(other);
}
void SITLGps::InternalSwap(SITLGps* other) {
std::swap(time_usec_, other->time_usec_);
std::swap(latitude_deg_, other->latitude_deg_);
std::swap(longitude_deg_, other->longitude_deg_);
std::swap(altitude_, other->altitude_);
std::swap(eph_, other->eph_);
std::swap(epv_, other->epv_);
std::swap(velocity_, other->velocity_);
std::swap(velocity_east_, other->velocity_east_);
std::swap(velocity_north_, other->velocity_north_);
std::swap(velocity_up_, other->velocity_up_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata SITLGps::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = SITLGps_descriptor_;
metadata.reflection = SITLGps_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// SITLGps
// required int64 time_usec = 1;
bool SITLGps::has_time_usec() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void SITLGps::set_has_time_usec() {
_has_bits_[0] |= 0x00000001u;
}
void SITLGps::clear_has_time_usec() {
_has_bits_[0] &= ~0x00000001u;
}
void SITLGps::clear_time_usec() {
time_usec_ = GOOGLE_LONGLONG(0);
clear_has_time_usec();
}
::google::protobuf::int64 SITLGps::time_usec() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.time_usec)
return time_usec_;
}
void SITLGps::set_time_usec(::google::protobuf::int64 value) {
set_has_time_usec();
time_usec_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.time_usec)
}
// required double latitude_deg = 2;
bool SITLGps::has_latitude_deg() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
void SITLGps::set_has_latitude_deg() {
_has_bits_[0] |= 0x00000002u;
}
void SITLGps::clear_has_latitude_deg() {
_has_bits_[0] &= ~0x00000002u;
}
void SITLGps::clear_latitude_deg() {
latitude_deg_ = 0;
clear_has_latitude_deg();
}
double SITLGps::latitude_deg() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.latitude_deg)
return latitude_deg_;
}
void SITLGps::set_latitude_deg(double value) {
set_has_latitude_deg();
latitude_deg_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.latitude_deg)
}
// required double longitude_deg = 3;
bool SITLGps::has_longitude_deg() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
void SITLGps::set_has_longitude_deg() {
_has_bits_[0] |= 0x00000004u;
}
void SITLGps::clear_has_longitude_deg() {
_has_bits_[0] &= ~0x00000004u;
}
void SITLGps::clear_longitude_deg() {
longitude_deg_ = 0;
clear_has_longitude_deg();
}
double SITLGps::longitude_deg() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.longitude_deg)
return longitude_deg_;
}
void SITLGps::set_longitude_deg(double value) {
set_has_longitude_deg();
longitude_deg_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.longitude_deg)
}
// required double altitude = 4;
bool SITLGps::has_altitude() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
void SITLGps::set_has_altitude() {
_has_bits_[0] |= 0x00000008u;
}
void SITLGps::clear_has_altitude() {
_has_bits_[0] &= ~0x00000008u;
}
void SITLGps::clear_altitude() {
altitude_ = 0;
clear_has_altitude();
}
double SITLGps::altitude() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.altitude)
return altitude_;
}
void SITLGps::set_altitude(double value) {
set_has_altitude();
altitude_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.altitude)
}
// optional double eph = 5;
bool SITLGps::has_eph() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
void SITLGps::set_has_eph() {
_has_bits_[0] |= 0x00000010u;
}
void SITLGps::clear_has_eph() {
_has_bits_[0] &= ~0x00000010u;
}
void SITLGps::clear_eph() {
eph_ = 0;
clear_has_eph();
}
double SITLGps::eph() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.eph)
return eph_;
}
void SITLGps::set_eph(double value) {
set_has_eph();
eph_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.eph)
}
// optional double epv = 6;
bool SITLGps::has_epv() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
void SITLGps::set_has_epv() {
_has_bits_[0] |= 0x00000020u;
}
void SITLGps::clear_has_epv() {
_has_bits_[0] &= ~0x00000020u;
}
void SITLGps::clear_epv() {
epv_ = 0;
clear_has_epv();
}
double SITLGps::epv() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.epv)
return epv_;
}
void SITLGps::set_epv(double value) {
set_has_epv();
epv_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.epv)
}
// optional double velocity = 7;
bool SITLGps::has_velocity() const {
return (_has_bits_[0] & 0x00000040u) != 0;
}
void SITLGps::set_has_velocity() {
_has_bits_[0] |= 0x00000040u;
}
void SITLGps::clear_has_velocity() {
_has_bits_[0] &= ~0x00000040u;
}
void SITLGps::clear_velocity() {
velocity_ = 0;
clear_has_velocity();
}
double SITLGps::velocity() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.velocity)
return velocity_;
}
void SITLGps::set_velocity(double value) {
set_has_velocity();
velocity_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.velocity)
}
// optional double velocity_east = 8;
bool SITLGps::has_velocity_east() const {
return (_has_bits_[0] & 0x00000080u) != 0;
}
void SITLGps::set_has_velocity_east() {
_has_bits_[0] |= 0x00000080u;
}
void SITLGps::clear_has_velocity_east() {
_has_bits_[0] &= ~0x00000080u;
}
void SITLGps::clear_velocity_east() {
velocity_east_ = 0;
clear_has_velocity_east();
}
double SITLGps::velocity_east() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.velocity_east)
return velocity_east_;
}
void SITLGps::set_velocity_east(double value) {
set_has_velocity_east();
velocity_east_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.velocity_east)
}
// optional double velocity_north = 9;
bool SITLGps::has_velocity_north() const {
return (_has_bits_[0] & 0x00000100u) != 0;
}
void SITLGps::set_has_velocity_north() {
_has_bits_[0] |= 0x00000100u;
}
void SITLGps::clear_has_velocity_north() {
_has_bits_[0] &= ~0x00000100u;
}
void SITLGps::clear_velocity_north() {
velocity_north_ = 0;
clear_has_velocity_north();
}
double SITLGps::velocity_north() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.velocity_north)
return velocity_north_;
}
void SITLGps::set_velocity_north(double value) {
set_has_velocity_north();
velocity_north_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.velocity_north)
}
// optional double velocity_up = 10;
bool SITLGps::has_velocity_up() const {
return (_has_bits_[0] & 0x00000200u) != 0;
}
void SITLGps::set_has_velocity_up() {
_has_bits_[0] |= 0x00000200u;
}
void SITLGps::clear_has_velocity_up() {
_has_bits_[0] &= ~0x00000200u;
}
void SITLGps::clear_velocity_up() {
velocity_up_ = 0;
clear_has_velocity_up();
}
double SITLGps::velocity_up() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.SITLGps.velocity_up)
return velocity_up_;
}
void SITLGps::set_velocity_up(double value) {
set_has_velocity_up();
velocity_up_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.SITLGps.velocity_up)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace msgs
} // namespace sensor_msgs
// @@protoc_insertion_point(global_scope)
|
/// @file
/// @version 4.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
#ifndef __ANDROID__
#ifndef _UWP
#define RESOURCE_PATH "../../demos/media/"
#else
#define RESOURCE_PATH "media/"
#endif
#elif defined(__APPLE__)
#define RESOURCE_PATH "media/"
#else
#define RESOURCE_PATH "./"
#endif
#include <stdlib.h>
#ifdef __APPLE__
#include <unistd.h>
#import <Foundation/Foundation.h>
#import <CoreFoundation/CoreFoundation.h>
#endif
#include <hltypes/hdir.h>
#include <april/april.h>
#include <april/Cursor.h>
#include <april/main.h>
#include <april/MouseDelegate.h>
#include <april/Platform.h>
#include <april/RenderSystem.h>
#include <april/SystemDelegate.h>
#include <april/UpdateDelegate.h>
#include <april/Window.h>
#include <gtypes/Rectangle.h>
#include <gtypes/Vector2.h>
#include <hltypes/hlog.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hstring.h>
#define LOG_TAG "demo_simple"
#define _ENGINE_RENDER_TEST
april::Cursor* cursor = NULL;
april::Texture* texture = NULL;
april::Texture* nearestTexture = NULL;
april::Texture* manualTexture = NULL;
april::TexturedVertex dv[4];
april::PlainVertex pv[4];
april::TexturedVertex tv[4];
april::ColoredVertex cv[3];
april::ColoredTexturedVertex ctv[3];
#if !defined(__ANDROID__) && !defined(_IOS) && !defined(_WINP8)
grectf drawRect(0.0f, 0.0f, 800.0f, 600.0f);
#else
grectf drawRect(0.0f, 0.0f, 480.0f, 320.0f);
#endif
gvec2f offset = drawRect.getSize() * 0.5f;
grectf textureRect;
grectf src(0.0f, 0.0f, 1.0f, 1.0f);
bool mousePressed = false;
class UpdateDelegate : public april::UpdateDelegate
{
bool onUpdate(float timeDelta) override
{
april::rendersys->clear();
april::rendersys->setOrthoProjection(drawRect);
april::rendersys->drawFilledRect(drawRect, april::Color(96, 96, 96));
// some general rendering testing
manualTexture->fillRect(hrand(manualTexture->getWidth()), hrand(manualTexture->getHeight()), hrand(1, 9), hrand(1, 9), april::Color(hrand(255), hrand(255), hrand(255)));
april::rendersys->setTexture(manualTexture);
april::rendersys->render(april::RenderOperation::TriangleStrip, dv, 4);
april::rendersys->setTexture(texture);
april::rendersys->drawTexturedRect(textureRect + offset, src);
april::rendersys->drawFilledRect(grectf(0.0f, drawRect.h - 75.0f, 40.0f, 75.0f), april::Color::Yellow);
april::rendersys->drawFilledRect(grectf(10.0f, drawRect.h - 65.0f, 80.0f, 55.0f), april::Color::Red);
#ifdef _ENGINE_RENDER_TEST
// testing all general render methods
april::rendersys->drawFilledRect(grectf(drawRect.w - 110.0f, drawRect.h - 310.0f, 110.0f, 310.0f), april::Color::Black);
april::rendersys->render(april::RenderOperation::TriangleList, pv, 3);
april::rendersys->render(april::RenderOperation::TriangleList, &pv[1], 3, april::Color::Yellow);
april::rendersys->render(april::RenderOperation::TriangleList, tv, 3);
april::rendersys->render(april::RenderOperation::TriangleList, &tv[1], 3, april::Color::Green);
april::rendersys->render(april::RenderOperation::TriangleList, cv, 3);
april::rendersys->render(april::RenderOperation::TriangleList, ctv, 3);
// texture filtering
april::rendersys->setTexture(nearestTexture);
april::rendersys->drawTexturedRect(grectf(drawRect.w - 50.0f, 0.0f, 50.0f, 100.0f), grectf(0.4375f, 0.25f, 0.03125f, 0.03125f));
april::rendersys->setTexture(texture);
april::rendersys->drawTexturedRect(grectf(drawRect.w - 100.0f, 0.0f, 50.0f, 100.0f), grectf(0.4375f, 0.25f, 0.03125f, 0.03125f));
#endif
return true;
}
};
class SystemDelegate : public april::SystemDelegate
{
public:
SystemDelegate() : april::SystemDelegate()
{
}
void onWindowSizeChanged(int width, int height, bool fullScreen) override
{
hlog::writef(LOG_TAG, "window size changed: %dx%d", width, height);
april::rendersys->setViewport(drawRect);
}
};
class MouseDelegate : public april::MouseDelegate
{
void onMouseDown(april::Key key) override
{
offset = april::window->getCursorPosition();
hlog::writef(LOG_TAG, "- DOWN x: %4.0f y: %4.0f button: %d", offset.x, offset.y, key.value);
mousePressed = true;
}
void onMouseUp(april::Key key) override
{
gvec2f position = april::window->getCursorPosition();
hlog::writef(LOG_TAG, "- UP x: %4.0f y: %4.0f button: %d", position.x, position.y, key.value);
mousePressed = false;
}
void onMouseMove() override
{
gvec2f position = april::window->getCursorPosition();
hlog::writef(LOG_TAG, "- MOVE x: %4.0f y: %4.0f", position.x, position.y);
if (mousePressed)
{
offset = position;
}
}
void onMouseCancel(april::Key key) override
{
hlog::writef(LOG_TAG, "- CANCEL button: %d", key.value);
}
};
static UpdateDelegate* updateDelegate = NULL;
static SystemDelegate* systemDelegate = NULL;
static MouseDelegate* mouseDelegate = NULL;
// TODOx - should be moved into april
#ifdef __APPLE__
void ObjCUtil_setCWD(const char* override_default_dir)
{
static bool set = 0;
if (!set || override_default_dir != NULL)
{
if (override_default_dir == NULL)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
const char* dir = [[[NSBundle mainBundle] resourcePath] UTF8String];
hdir::chdir(dir);
[pool release];
}
else
{
hdir::chdir(override_default_dir);
}
set = 1;
}
}
#endif
void __aprilApplicationInit()
{
#ifdef __APPLE__
// On MacOSX, the current working directory is not set by
// the Finder, since you are expected to use Core Foundation
// or ObjC APIs to find files.
ObjCUtil_setCWD(NULL);
#endif
srand((unsigned int)htime());
updateDelegate = new UpdateDelegate();
systemDelegate = new SystemDelegate();
mouseDelegate = new MouseDelegate();
#if defined(__ANDROID__) || defined(_IOS)
drawRect.setSize(april::getSystemInfo().displayResolution);
#endif
// init
april::init(april::RenderSystemType::Default, april::WindowType::Default);
april::createRenderSystem();
april::createWindow((int)drawRect.w, (int)drawRect.h, false, "APRIL: Simple Demo");
// background
dv[0].x = 0.0f; dv[0].y = 0.0f; dv[0].z = 0.0f; dv[0].u = 0.0f; dv[0].v = 0.0f;
dv[1].x = drawRect.w; dv[1].y = 0.0f; dv[1].z = 0.0f; dv[1].u = 1.0f; dv[1].v = 0.0f;
dv[2].x = 0.0f; dv[2].y = drawRect.h; dv[2].z = 0.0f; dv[2].u = 0.0f; dv[2].v = 1.0f;
dv[3].x = drawRect.w; dv[3].y = drawRect.h; dv[3].z = 0.0f; dv[3].u = 1.0f; dv[3].v = 1.0f;
// plain
pv[0].x = drawRect.w - 100.0f; pv[0].y = drawRect.h - 300.0f; pv[0].z = 0.0f;
pv[1].x = drawRect.w; pv[1].y = drawRect.h - 300.0f; pv[1].z = 0.0f;
pv[2].x = drawRect.w - 100.0f; pv[2].y = drawRect.h - 200.0f; pv[2].z = 0.0f;
pv[3].x = drawRect.w; pv[3].y = drawRect.h - 200.0f; pv[3].z = 0.0f;
// textured
tv[0].x = drawRect.w - 100.0f; tv[0].y = drawRect.h - 200.0f; tv[0].z = 0.0f; tv[0].u = 0.0f; tv[0].v = 0.0f;
tv[1].x = drawRect.w; tv[1].y = drawRect.h - 200.0f; tv[1].z = 0.0f; tv[1].u = 1.0f; tv[1].v = 0.0f;
tv[2].x = drawRect.w - 100.0f; tv[2].y = drawRect.h - 100.0f; tv[2].z = 0.0f; tv[2].u = 0.0f; tv[2].v = 1.0f;
tv[3].x = drawRect.w; tv[3].y = drawRect.h - 100.0f; tv[3].z = 0.0f; tv[3].u = 1.0f; tv[3].v = 1.0f;
// colored
cv[0].x = drawRect.w - 100.0f; cv[0].y = drawRect.h - 100.0f; cv[0].z = 0.0f; cv[0].color = april::rendersys->getNativeColorUInt(april::Color::Yellow);
cv[1].x = drawRect.w; cv[1].y = drawRect.h - 100.0f; cv[1].z = 0.0f; cv[1].color = april::rendersys->getNativeColorUInt(april::Color::Red);
cv[2].x = drawRect.w - 100.0f; cv[2].y = drawRect.h - 0.0f; cv[2].z = 0.0f; cv[2].color = april::rendersys->getNativeColorUInt(april::Color::Green);
// colored-textured
ctv[0].x = drawRect.w; ctv[0].y = drawRect.h - 100.0f; ctv[0].z = 0.0f; ctv[0].u = 1.0f; ctv[0].v = 0.0f; ctv[0].color = april::rendersys->getNativeColorUInt(april::Color::Red);
ctv[1].x = drawRect.w - 100.0f; ctv[1].y = drawRect.h - 0.0f; ctv[1].z = 0.0f; ctv[1].u = 0.0f; ctv[1].v = 1.0f; ctv[1].color = april::rendersys->getNativeColorUInt(april::Color::Green);
ctv[2].x = drawRect.w; ctv[2].y = drawRect.h - 0.0f; ctv[2].z = 0.0f; ctv[2].u = 1.0f; ctv[2].v = 1.0f; ctv[2].color = april::rendersys->getNativeColorUInt(april::Color::White);
#ifdef _UWP
april::window->setParam("cursor_mappings", "101 " RESOURCE_PATH "cursor\n102 " RESOURCE_PATH "simple");
#endif
april::window->setUpdateDelegate(updateDelegate);
april::window->setSystemDelegate(systemDelegate);
april::window->setMouseDelegate(mouseDelegate);
cursor = april::window->createCursorFromResource(RESOURCE_PATH "cursor");
april::window->setCursor(cursor);
texture = april::rendersys->createTextureFromResource(RESOURCE_PATH "logo", april::Texture::Type::Managed);
nearestTexture = april::rendersys->createTextureFromResource(RESOURCE_PATH "logo", april::Texture::Type::Managed);
nearestTexture->setFilter(april::Texture::Filter::Nearest);
textureRect.setSize(texture->getWidth() * 0.5f, texture->getHeight() * 0.5f);
textureRect.x = -textureRect.w * 0.5f;
textureRect.y = -textureRect.h * 0.5f;
// demonstrating some of the image manipulation methods
manualTexture = april::rendersys->createTexture((int)drawRect.w, (int)drawRect.h, april::Color::Clear, april::Image::Format::RGBA);
manualTexture->write(0, 0, texture->getWidth(), texture->getHeight(), 0, 0, texture);
manualTexture->invert(0, 0, 512, 128);
manualTexture->saturate(0, 128, 256, 128, 0.0f);
manualTexture->rotateHue(256, 0, 256, 256, 180.0f);
manualTexture->blit(0, 0, texture->getWidth(), texture->getHeight(), 256, 128, texture, 96);
manualTexture->blitStretch(texture->getWidth() / 2, 0, texture->getWidth() / 2, texture->getHeight(), 128, 256, 700, 200, texture, 208);
manualTexture->blitRect(320, 0, 48, 192, april::Color(april::Color::Green, 128));
}
void __aprilApplicationDestroy()
{
april::window->setCursor(NULL);
april::window->destroyCursor(cursor);
cursor = NULL;
april::rendersys->destroyTexture(texture);
texture = NULL;
april::rendersys->destroyTexture(nearestTexture);
nearestTexture = NULL;
april::rendersys->destroyTexture(manualTexture);
manualTexture = NULL;
april::destroy();
delete updateDelegate;
updateDelegate = NULL;
delete systemDelegate;
systemDelegate = NULL;
delete mouseDelegate;
mouseDelegate = NULL;
}
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* 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.
*/
#pragma once
#include <unistd.h>
#include <algorithm>
#include <random>
#include <vector>
namespace HugeCTR {
struct FileOffset {
char* offset;
long long samples;
};
class RawOffsetList {
private:
const long long num_samples_;
const long long stride_;
const long long batchsize_;
const bool use_shuffle_;
std::vector<FileOffset> offsets_;
std::atomic<long long> counter_{0};
const int num_workers_;
std::string file_name_;
public:
// stride: samle size in byte
RawOffsetList(std::string file_name, long long num_samples, long long stride, long long batchsize,
bool use_shuffle, int num_workers)
: num_samples_(num_samples),
stride_(stride),
batchsize_(batchsize),
use_shuffle_(use_shuffle),
num_workers_(num_workers),
file_name_(file_name) {
try {
auto offset_gen = [stride](long long idx, long long samples) -> FileOffset {
char* offset = (char*)(idx * stride);
return {offset, samples};
};
for (long long sample_idx = 0; sample_idx < num_samples; sample_idx += batchsize) {
if (sample_idx + batchsize <= num_samples) {
offsets_.emplace_back(offset_gen(sample_idx, batchsize));
} else {
offsets_.emplace_back(offset_gen(sample_idx, num_samples - sample_idx));
}
}
// shuffle
if (use_shuffle) {
std::random_device rd;
unsigned int seed = rd();
#ifdef ENABLE_MPI
CK_MPI_THROW_(MPI_Bcast(&seed, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD));
#endif
auto rng = std::default_random_engine{seed};
std::shuffle(std::begin(offsets_), std::end(offsets_), rng);
}
} catch (const std::runtime_error& rt_err) {
std::cerr << rt_err.what() << std::endl;
throw;
}
}
~RawOffsetList() {}
FileOffset get_offset(long long round, int worker_id) {
size_t counter = (round * num_workers_ + worker_id) % offsets_.size();
// int partition = (int)offsets_.size() / num_workers_;
// counter = partition * worker_id + (round % partition);
if (worker_id >= num_workers_) {
CK_THROW_(Error_t::WrongInput, "worker_id >= num_workers_");
}
if (counter == offsets_.size() - 1) {
// CK_THROW_(Error_t::OutOfBound, "End of File");
std::cout << "End of File, worker: " << worker_id << std::endl;
}
return offsets_[counter];
}
std::string get_file_name() { return file_name_; }
long long get_stride() { return stride_; }
long long get_batch_size() { return batchsize_; }
};
} // namespace HugeCTR
|
/*
* Tyler Hunt
* Advanved C++
* OCCC Fall 2017
* Due: 10/7/17
* Details: Tower of Hanoi
*/
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
int[] getInputs(int argc, char * argv[]);
int main(int argc, char * argv[]){
cout << "\n~~~~~~~~~~~~ Tower of Hanoi Homework - Advanced C++ Week 4 ~~~~~~~~~~~~" << endl;
int[] inputs = getInputs(int argc, char * argv[]);
return 0;
}
int[] getInputs(int argc, char * argv[]){
int[] inputs = new int[3];
if(argc == 4){
for(int i = 1; i < argc; i++){
inputs[i-1] = (int)argv[i]-48;
}
}else{
cout << "Please, enter a number of disks: ";
cin >> inputs[0];
int spindle1;
cout << "Please, enter a start spindle: ";
cin >> inputs[1];;
int spindle2;
cout << "Please, enter a end spindle: ";
cin >> inputs[2];
}
return inputs;
}
|
// Copyright (c) 2005-2009 Jaroslav Gresula
//
// Distributed under the MIT license (See accompanying file
// LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
//
#include "precompiled.h"
#include <core/jstd/message_sink_console.h>
#include <cstdio>
namespace jag { namespace jstd
{
//////////////////////////////////////////////////////////////////////////
void MessageSinkConsole::message(
jag::UInt /*code*/
, MessageSeverity sev
, jag::Char const* /*msg*/)
{
switch(sev)
{
case MSG_INFO:
//fprintf(stdout, "I%d: %s\n", code, msg);
break;
case MSG_WARNING:
//fprintf(stdout, "W%d: %s\n", code, msg);
break;
case MSG_ERROR:
//fprintf(stderr, "E%d: %s\n", code, msg);
break;
}
}
}} //namespace jag::jstd
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkHyperTreeGridAxisCut.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkHyperTreeGridAxisCut.h"
#include "vtkBitArray.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkDataSetAttributes.h"
#include "vtkHyperTreeGrid.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
vtkStandardNewMacro(vtkHyperTreeGridAxisCut);
//-----------------------------------------------------------------------------
vtkHyperTreeGridAxisCut::vtkHyperTreeGridAxisCut()
{
this->PlaneNormalAxis = 0;
this->PlanePosition = 0.;
this->Input = 0;
this->Output = 0;
this->InData = 0;
this->OutData = 0;
this->Points = 0;
this->Cells = 0;
}
//-----------------------------------------------------------------------------
vtkHyperTreeGridAxisCut::~vtkHyperTreeGridAxisCut()
{
}
//----------------------------------------------------------------------------
void vtkHyperTreeGridAxisCut::PrintSelf( ostream& os, vtkIndent indent )
{
this->Superclass::PrintSelf( os, indent );
if( this->Input )
{
os << indent << "Input:\n";
this->Input->PrintSelf( os, indent.GetNextIndent() );
}
else
{
os << indent << "Input: ( none )\n";
}
if( this->Output )
{
os << indent << "Output:\n";
this->Output->PrintSelf( os, indent.GetNextIndent() );
}
else
{
os << indent << "Output: ( none )\n";
}
os << indent << "Plane Normal Axis : " << this->PlaneNormalAxis << endl;
os << indent << "Plane Position : " << this->PlanePosition << endl;
}
//-----------------------------------------------------------------------------
int vtkHyperTreeGridAxisCut::FillInputPortInformation( int, vtkInformation *info )
{
info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkHyperTreeGrid" );
return 1;
}
//----------------------------------------------------------------------------
int vtkHyperTreeGridAxisCut::RequestData( vtkInformation*,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector )
{
// Get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject( 0 );
vtkInformation *outInfo = outputVector->GetInformationObject( 0 );
// Retrieve input and output
this->Input =
vtkHyperTreeGrid::SafeDownCast( inInfo->Get( vtkDataObject::DATA_OBJECT() ) );
this->Output =
vtkPolyData::SafeDownCast( outInfo->Get( vtkDataObject::DATA_OBJECT() ) );
// This filter is only for 2D slices of 3D grids
if ( this->Input->GetDimension() != 3 )
{
vtkErrorMacro( "Axis cut only works with 3D trees." );
return 0;
}
// Initialize output cell data
this->InData =
static_cast<vtkDataSetAttributes*>( this->Input->GetPointData() );
this->OutData =
static_cast<vtkDataSetAttributes*>( this->Output->GetCellData() );
this->OutData->CopyAllocate( this->InData );
// Cut through hyper tree grid
this->ProcessTrees();
// Clean up
this->Input = 0;
this->Output = 0;
this->InData = 0;
this->OutData = 0;
this->UpdateProgress ( 1. );
return 1;
}
//-----------------------------------------------------------------------------
void vtkHyperTreeGridAxisCut::ProcessTrees()
{
// TODO: MTime on generation of this table.
this->Input->GenerateSuperCursorTraversalTable();
// Primal corner points
this->Points = vtkPoints::New();
this->Cells = vtkCellArray::New();
// Iterate over all hyper trees
vtkIdType index;
vtkHyperTreeGrid::vtkHyperTreeIterator it;
this->Input->InitializeTreeIterator( it );
while ( it.GetNextTree( index ) )
{
// Storage for super cursors
vtkHyperTreeGrid::vtkHyperTreeGridSuperCursor superCursor;
// Initialize center cursor
this->Input->InitializeSuperCursor( &superCursor, index );
// Traverse and populate dual recursively
this->RecursiveProcessTree( &superCursor );
} // it
// Set output geometry and topology
this->Output->SetPoints( this->Points );
this->Output->SetPolys( this->Cells );
this->Points->UnRegister( this );
this->Points = 0;
this->Cells->UnRegister( this );
this->Cells = 0;
}
//----------------------------------------------------------------------------
void vtkHyperTreeGridAxisCut::AddFace( vtkIdType inId, double* origin,
double* size, double offset0,
int axis0, int axis1, int axis2 )
{
// Generate 4 points
double pt[3];
memcpy( pt, origin, 3 * sizeof(double) );
pt[axis0] += size[axis0] * offset0;
// Storage for cell IDs
vtkIdType ids[4];
ids[0] = this->Points->InsertNextPoint( pt );
pt[axis1] += size[axis1];
ids[1] = this->Points->InsertNextPoint( pt );
pt[axis2] += size[axis2];
ids[2] = this->Points->InsertNextPoint( pt );
pt[axis1] = origin[axis1];
ids[3] = this->Points->InsertNextPoint( pt );
vtkIdType outId = this->Cells->InsertNextCell( 4, ids );
this->OutData->CopyData( this->InData, inId, outId );
}
//----------------------------------------------------------------------------
void vtkHyperTreeGridAxisCut::RecursiveProcessTree( void* sc )
{
vtkHyperTreeGrid::vtkHyperTreeGridSuperCursor* superCursor =
static_cast<vtkHyperTreeGrid::vtkHyperTreeGridSuperCursor*>( sc );
// Get cursor at super cursor center
vtkHyperTreeGrid::vtkHyperTreeSimpleCursor* cursor0 = superCursor->GetCursor( 0 );
if ( cursor0->IsLeaf() )
{
// Cursor is a leaf
ProcessLeaf3D( sc );
}
else
{
// If cursor is not at leaf, recurse to all children
int numChildren = this->Input->GetNumberOfChildren();
for ( int child = 0; child < numChildren; ++ child )
{
vtkHyperTreeGrid::vtkHyperTreeGridSuperCursor newSuperCursor;
this->Input->InitializeSuperCursorChild( superCursor,&newSuperCursor, child );
this->RecursiveProcessTree( &newSuperCursor );
}
}
}
//----------------------------------------------------------------------------
void vtkHyperTreeGridAxisCut::ProcessLeaf3D( void* sc )
{
// Get cursor at super cursor center
vtkHyperTreeGrid::vtkHyperTreeGridSuperCursor* superCursor =
static_cast<vtkHyperTreeGrid::vtkHyperTreeGridSuperCursor*>( sc );
vtkHyperTreeGrid::vtkHyperTreeSimpleCursor* cursor0 = superCursor->GetCursor( 0 );
// Cursor is a leaf, retrieve its global index
vtkIdType inId = cursor0->GetGlobalNodeIndex();
// If leaf is masked, skip it
if ( this->Input->GetMaterialMask()->GetValue( inId ) )
{
return;
}
// Terminate if the node does not touch the plane.
if ( superCursor->Origin[this->PlaneNormalAxis] > this->PlanePosition ||
( superCursor->Origin[this->PlaneNormalAxis] +
superCursor->Size[this->PlaneNormalAxis] < this->PlanePosition ) )
{
return;
}
// Create rectangles at plane/grid intersection
double k = ( this->PlanePosition - superCursor->Origin[this->PlaneNormalAxis] ) /
superCursor->Size[this->PlaneNormalAxis];
int axis1, axis2;
switch ( this->PlaneNormalAxis )
{
case 0:
axis1 = 1;
axis2 = 2;
break;
case 1:
axis1 = 0;
axis2 = 2;
break;
case 2:
axis1 = 0;
axis2 = 1;
break;
default:
vtkErrorMacro( "Bad Axis." );
return;
}
this->AddFace( inId, superCursor->Origin, superCursor->Size, k,
this->PlaneNormalAxis, axis1, axis2 );
}
|
#include "T3BTuner.h"
#include "Gpio.h"
#include "SystemAdapt.h"
#include <string.h>
static const uint16_t TunerSerialBaudrate = 57600U;
static const uint8_t HeaderSizeIndex = 5U;
static const uint8_t ResponseAck = 0x00;
static const uint8_t ResponseAckNack = 0x02;
static const uint8_t UnusedPin = 255;
T3BTuner::T3BTuner(ISerialStream& stream, uint8_t const resetPin, uint8_t const mutePin) :
T3BTuner(stream, resetPin, mutePin, UnusedPin)
{
}
T3BTuner::T3BTuner(ISerialStream& stream, uint8_t const resetPin, uint8_t const mutePin,
uint8_t const spiCsPin) :
stream(stream),
pinReset(resetPin),
pinMute(mutePin),
pinSpiCs(spiCsPin)
{
}
void T3BTuner::init()
{
if (pinMute != UnusedPin)
{
gpioModeSet(pinMute, GpioMode::Output);
gpioWrite(pinMute, GpioState::High);
}
if (pinSpiCs != UnusedPin)
{
gpioModeSet(pinSpiCs, GpioMode::Output);
gpioWrite(pinSpiCs, GpioState::Low);
}
stream.begin(TunerSerialBaudrate);
stream.setTimeout(50U);
gpioModeSet(pinReset, GpioMode::Output);
gpioWrite(pinReset, GpioState::Low);
systemDelay(100U);
gpioWrite(pinReset, GpioState::High);
systemDelay(1000U);
while (!ready())
{
systemDelay(500U);
}
}
// *************************
// ***** SYSTEM ************
// *************************
/*
* Test for DAB module is ready for communication
*/
bool T3BTuner::ready()
{
Command command = commandBuilder.createSystem(CmdSystemId::Ready).build();
return commandSend(command);
}
/*
* Reset module.
* FullReset => Reset module database & module.
*/
bool T3BTuner::reset(bool const fullReset)
{
Command command =
commandBuilder.createSystem(CmdSystemId::Reset).append(static_cast<uint8_t>(fullReset)).build();
if (commandSend(command))
{
init();
return true;
}
return false;
}
/*
* Set audio output channels (SPDIF, CINCH /I2S DAC/)
* CINCH for analog output, SPDIF for optical digital output
*/
bool T3BTuner::audioOutput(bool const spdif, bool const cinch)
{
uint8_t param = static_cast<uint8_t>(spdif) | (static_cast<uint8_t>(cinch << 0x1));
Command command = commandBuilder.createSystem(CmdSystemId::AudioOutput).append(param).build();
return commandSend(command);
}
// *************************
// ***** STREAM ************
// *************************
/*
* Play DAB program
* programIndex = 1..9999999 (see programs index)
*/
bool T3BTuner::playDab(uint32_t const stationId)
{
Command command = commandBuilder.createStream(CmdStreamId::Play)
.append(static_cast<uint8_t>(TunerMode::Dab))
.append(stationId)
.build();
return commandSend(command);
}
/*
* Play FM program
* frequency = 87500..108000 (MHz)
*/
bool T3BTuner::playFm(uint32_t const frequency)
{
Command command = commandBuilder.createStream(CmdStreamId::Play)
.append(static_cast<uint8_t>(TunerMode::Fm))
.append(frequency)
.build();
return commandSend(command);
}
/*
* Play Beep.
*/
bool T3BTuner::playBeep()
{
Command command = commandBuilder.createStream(CmdStreamId::Play)
.append(static_cast<uint8_t>(TunerMode::Beep))
.append(static_cast<uint32_t>(0x00))
.build();
return commandSend(command);
}
/*
* Stop.
*/
bool T3BTuner::stop()
{
Command command = commandBuilder.createStream(CmdStreamId::Stop).build();
return commandSend(command);
}
/*
* Seek FM program.
*/
bool T3BTuner::fmSearch(bool const searchForward)
{
Command command = commandBuilder.createStream(CmdStreamId::SearchFm)
.append(static_cast<uint8_t>(searchForward))
.build();
return commandSend(command);
}
/*
* Search DAB bands for programs.
*/
bool T3BTuner::dabSearch(DabBand const band)
{
commandBuilder.createStream(CmdStreamId::SearchDab);
switch (band)
{
case DabBand::BandIII:
commandBuilder.append(static_cast<uint8_t>(0U));
commandBuilder.append(static_cast<uint8_t>(40U));
break;
case DabBand::ChinaBand:
commandBuilder.append(static_cast<uint8_t>(41U));
commandBuilder.append(static_cast<uint8_t>(71U));
break;
case DabBand::LBand:
commandBuilder.append(static_cast<uint8_t>(72U));
commandBuilder.append(static_cast<uint8_t>(94U));
break;
}
Command command = commandBuilder.build();
return commandSend(command);
}
/*
* Radio module play status.
*/
bool T3BTuner::state(TunerState* const status)
{
Command command = commandBuilder.createStream(CmdStreamId::Status).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(status)));
}
/*
* Radio module play mode.
*/
bool T3BTuner::mode(TunerMode* const mode)
{
Command command = commandBuilder.createStream(CmdStreamId::Mode).build();
return (commandSend(command) && responseUint8(0, reinterpret_cast<uint8_t*>(mode)));
}
/*
* Get DAB stationId, get FM frequency.
*/
bool T3BTuner::nowPlaying(uint32_t* const programId)
{
Command command = commandBuilder.createStream(CmdStreamId::NowPlaying).build();
return (commandSend(command) && responseUint32(0U, programId));
}
/*
* Get signal strength
* DAB: signalStrength=0..18, bitErrorRate=
* FM: signalStrength=0..100
*/
bool T3BTuner::signalStrength(uint8_t* const signalStrength, uint16_t* const bitErrorRate)
{
Command command = commandBuilder.createStream(CmdStreamId::SignalStrength).build();
return (commandSend(command) && responseUint8(0U, signalStrength) && responseUint16(1U, bitErrorRate));
}
/*
* Set stereo mode.
*/
bool T3BTuner::stereoModeSet(StereoMode const stereoMode)
{
Command command = commandBuilder.createStream(CmdStreamId::StereoModeSet)
.append(static_cast<uint8_t>(stereoMode))
.build();
return commandSend(command);
}
/*
* Get stereo mode.
*/
bool T3BTuner::stereoModeGet(StereoMode* const stereoMode)
{
Command command = commandBuilder.createStream(CmdStreamId::StereoModeGet).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(stereoMode)));
}
/*
* Get stereo type
*/
bool T3BTuner::stereoTypeGet(StereoType* const stereotype)
{
Command command = commandBuilder.createStream(CmdStreamId::StereoType).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(stereotype)));
}
/*
* Set volume.
* volumeLevel = 0..16
*/
bool T3BTuner::volumeSet(uint8_t const volume)
{
uint8_t volumeValue = (volume > 16U) ? 16U : volume;
Command command = commandBuilder.createStream(CmdStreamId::VolumeSet).append(volumeValue).build();
return commandSend(command);
}
/*
* Get volume.
* return set volumeLevel: 0..16
*/
bool T3BTuner::volumeGet(uint8_t* const volume)
{
Command command = commandBuilder.createStream(CmdStreamId::VolumeGet).build();
return (commandSend(command) && responseUint8(0U, volume));
}
/*
* Get program type.
*/
bool T3BTuner::stationTypeGet(StationType* const programType)
{
Command command = commandBuilder.createStream(CmdStreamId::StationType).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(programType)));
}
/*
* Get DAB station name.
*/
bool T3BTuner::dabStationName(uint32_t const stationId, char* const buffer, uint16_t const size,
bool const longName)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationName)
.append(stationId)
.append(static_cast<uint8_t>(longName))
.build();
return (commandSend(command) && responseText(buffer, size));
}
/*
* Get DAB text event
* return: 1=new text, 2=text is same, 3=no text
* dabText: text
*/
bool T3BTuner::dabStationText(char* const buffer, uint16_t const size)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationText).build();
if (commandSend(command))
{
if (responseSize == 1)
{
// No text received
// Response[0] value => 0 = No text available, 1 = Station text is empty.
return false;
}
responseText(buffer, size);
bool changed = (strncmp(buffer, stationText, sizeof(stationText)) != 0);
strncpy(stationText, buffer, sizeof(stationText));
return changed;
}
return false;
}
/*
* Get sampling rate (DAB/FM).
*/
bool T3BTuner::sampleRateGet(SampleRate* const sampleRate)
{
Command command = commandBuilder.createStream(CmdStreamId::SampleRate).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(sampleRate)));
}
/*
* Get data rate (DAB)
* return data: data rate in kbps
*/
bool T3BTuner::dabDataRate(uint16_t* const dataRate)
{
Command command = commandBuilder.createStream(CmdStreamId::DabDataRate).build();
return (commandSend(command) && responseUint16(0U, dataRate));
}
/*
* Get DAB signal quality
* return: 0..100
* 0..19 = playback stop
* 20..30 = the noise (short break) appears
* 100 = the bit error rate is 0
*/
bool T3BTuner::dabSignalQuality(uint8_t* const signalQuality)
{
Command command = commandBuilder.createStream(CmdStreamId::DabSignalQuality).build();
return (commandSend(command) && responseUint8(0U, signalQuality));
}
/*
* Get DAB frequency for program index
* return: frequency index
* 0=174.928MHz, 1=176.64, 2=178.352,...
*
* // TODO: add conversion table for index2freqency
*/
bool T3BTuner::dabStationFrequency(uint32_t const stationId, uint8_t* const frequency)
{
Command command = commandBuilder.createStream(CmdStreamId::DabFrequency).append(stationId).build();
return (commandSend(command) && responseUint8(0U, frequency));
}
/*
* Get DAB program ensemble name.
*/
bool T3BTuner::dabStationEnsembleName(uint32_t const stationId, char* const buffer, uint16_t const size)
{
Command command = commandBuilder.createStream(CmdStreamId::DabEnsembleName)
.append(stationId)
.append(static_cast<uint8_t>(false))
.build();
return (commandSend(command) && responseText(buffer, size));
}
/*
* Number of DAB stations in database.
*/
bool T3BTuner::dabStationCount(uint32_t* const count)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationCount).build();
return (commandSend(command) && responseUint32(0U, count));
}
/*
* Test DAB program is active (on-air)
* return: 0=off-air, 1=on-air
*/
bool T3BTuner::dabStationOnAir(uint32_t const stationId, bool* const onAir)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationOnAir).append(stationId).build();
bool result = commandSend(command);
*onAir = static_cast<bool>(response[0U]);
return result;
}
/*
* Get DAB program service short name.
*/
bool T3BTuner::dabStationServiceName(uint32_t const stationId, char* const buffer, uint16_t const size)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationServiceName)
.append(stationId)
.append(static_cast<uint8_t>(false))
.build();
return (commandSend(command) && responseText(buffer, size));
}
/*
* Number of programs found in search process.
*/
bool T3BTuner::dabFoundStationsCount(uint8_t* const count)
{
Command command = commandBuilder.createStream(CmdStreamId::DabFoundStationsCount).build();
return (commandSend(command) && responseUint8(0U, count));
}
/*
* Get DAB program service component type (ASCTy)
*/
bool T3BTuner::dabStationType(uint32_t const stationId, DabStreamType* const type)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationType).append(stationId).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(type)));
}
/*
* Set preset
*/
bool T3BTuner::memorySet(MemoryType const mode, MemoryId const id, uint32_t const programId)
{
Command command = commandBuilder.createStream(CmdStreamId::MemorySet)
.append(static_cast<uint8_t>(mode))
.append(static_cast<uint8_t>(id))
.append(programId)
.build();
return commandSend(command);
}
/*
* Get preset
*/
bool T3BTuner::memoryGet(MemoryType const mode, MemoryId const id, uint32_t* const programId)
{
Command command = commandBuilder.createStream(CmdStreamId::MemoryGet)
.append(static_cast<uint8_t>(mode))
.append(static_cast<uint8_t>(id))
.build();
return (commandSend(command) && responseUint32(0U, programId));
}
/*
* Get station info
* return serviceId = service id of DAB program
* return ensembleId = ensemble id of DAB program
*/
bool T3BTuner::dabStationInfo(uint32_t const stationId, uint32_t* const serviceId, uint16_t* const ensembleId)
{
Command command = commandBuilder.createStream(CmdStreamId::DabStationInfo).append(stationId).build();
return (commandSend(command) && responseUint32(0U, serviceId) && responseUint16(4U, ensembleId));
}
/*
* Get DAB station sort order.
*/
bool T3BTuner::dabSortGet(DabSortOrder* const sortOrder)
{
Command command = commandBuilder.createStream(CmdStreamId::DabSortGet).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(sortOrder)));
}
/*
* Set DAB station sort order.
*/
bool T3BTuner::dabSortSet(DabSortOrder const sortOrder)
{
Command command =
commandBuilder.createStream(CmdStreamId::DabSortSet).append(static_cast<uint8_t>(sortOrder)).build();
return commandSend(command);
}
/*
* Get DAB DRC.
*/
bool T3BTuner::dabDrcGet(DabDrc* const drc)
{
Command command = commandBuilder.createStream(CmdStreamId::DabDrcGet).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(drc)));
}
/*
* Set DAB DRC.
*/
bool T3BTuner::dabDrcSet(DabDrc const drc)
{
Command command =
commandBuilder.createStream(CmdStreamId::DabDrcSet).append(static_cast<uint8_t>(drc)).build();
return commandSend(command);
}
/*
* Prune programs - delete inactive programs (!on-air)
*/
bool T3BTuner::dabRemoveOffAir(uint16_t* const removedTotal, uint16_t* const removedIndex)
{
Command command = commandBuilder.createStream(CmdStreamId::DabRemoveOffAir).build();
return (commandSend(command) && responseUint16(0U, removedTotal) && responseUint16(2U, removedIndex));
}
/*
* Get ECC
* return ECC (Extended Country Code)
* return countryId (Country identification)
*/
bool T3BTuner::dabExtendedCountryCode(uint8_t* const ecc, uint8_t* const countryId)
{
Command command = commandBuilder.createStream(CmdStreamId::DabExtendedCountryCode).build();
return (commandSend(command) && responseUint8(0U, ecc) && responseUint8(1U, countryId));
}
/*
* Get FM RDS PI code
*/
bool T3BTuner::fmRdsPiCode(uint16_t* const code)
{
Command command = commandBuilder.createStream(CmdStreamId::FmRdsPiCode).build();
return (commandSend(command) && responseUint16(0U, code));
}
/*
* Set FMstereoThdLevel
* RSSIthresholdLevel = 0..10
*/
bool T3BTuner::fmStereoThresholdLevelSet(uint8_t const level)
{
Command command =
commandBuilder.createStream(CmdStreamId::FmStereoThresholdLevelSet).append(level).build();
return commandSend(command);
}
/*
* Get FMstereoThdLevel
* data return = 0..10
*/
bool T3BTuner::fmStereoThresholdLevelGet(uint8_t* const level)
{
Command command = commandBuilder.createStream(CmdStreamId::FmStereoThresholdLevelGet).build();
return (commandSend(command) && responseUint8(0U, level));
}
/*
* Get RDS raw data
* return: 1=new RDS data, 2=no new RDS data, 3=no RDS data
*/
bool T3BTuner::fmRdsRawData(uint16_t* const blockA, uint16_t* const blockB, uint16_t* const blockC,
uint16_t* const blockD, uint16_t* const blerA, uint16_t* const blerB,
uint16_t* const blerC, uint16_t* const blerD)
{
Command command = commandBuilder.createStream(CmdStreamId::FmRdsData).build();
if (commandSend(command) && responseSize > 1U)
{
return (responseUint16(0, blockA) && responseUint16(2, blockB) && responseUint16(4U, blockC) &&
responseUint16(6U, blockD) && responseUint16(8U, blerA) && responseUint16(10U, blerB) &&
responseUint16(12U, blerC) && responseUint16(14U, blerD));
}
return false;
}
/*
* Set FMseekThreshold
* RSSIthreshold = 0..100
*/
bool T3BTuner::fmSeekThresholdSet(uint8_t const threshold)
{
Command command = commandBuilder.createStream(CmdStreamId::FmSeekThresholdSet).append(threshold).build();
return commandSend(command);
}
/*
* Get FMseekThreshold
* data return = 0..100
*/
bool T3BTuner::fmSeekThresholdGet(uint8_t* const threshold)
{
Command command = commandBuilder.createStream(CmdStreamId::FmSeekThresholdGet).build();
return (commandSend(command) && responseUint8(0U, threshold));
}
/*
* Set FMstereoThreshold
* RSSIthreshold = 0..100
*/
bool T3BTuner::fmStereoThresholdSet(uint8_t const threshold)
{
Command command =
commandBuilder.createStream(CmdStreamId::FmStereoThresholdSet).append(threshold).build();
return commandSend(command);
}
/*
* Get FMstereoThreshold
* data return = 0..100
*/
bool T3BTuner::fmStereoThresholdGet(uint8_t* const threshold)
{
Command command = commandBuilder.createStream(CmdStreamId::FmStereoThresholdGet).build();
return (commandSend(command) && responseUint8(0U, threshold));
}
/*
* Get FM Exact station.
*/
bool T3BTuner::fmExactStationGet(FmExactStation* const exact)
{
Command command = commandBuilder.createStream(CmdStreamId::FmExactStation).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(exact)));
}
// *************************
// ***** RTC ***************
// *************************
/*
* Set RTC clock
* year: 2017=17,2018=18, month: 1..12, day: 1..31, hour: 0..23, minute: 0..59, second: 0..59
*/
bool T3BTuner::clockSet(uint8_t const year, uint8_t const month, uint8_t const day, uint8_t const hour,
uint8_t const minute, uint8_t const second)
{
Command command = commandBuilder.createRtc(CmdRtcId::Set)
.append(second)
.append(minute)
.append(hour)
.append(day)
.append(static_cast<uint8_t>(0x00))
.append(month)
.append(year)
.build();
return commandSend(command);
}
/*
* Get RTC ckock
* year: 2017=17,2018=18, month: 1..12, day: 1..31, hour: 0..23, minute: 0..59, second: 0..59
*/
bool T3BTuner::clockGet(uint8_t* const year, uint8_t* const month, uint8_t* const day, uint8_t* const hour,
uint8_t* const minute, uint8_t* const second)
{
Command command = commandBuilder.createRtc(CmdRtcId::Get).build();
bool result = commandSend(command);
result &= responseUint8(0U, second) & responseUint8(1U, minute);
result &= responseUint8(2U, hour) & responseUint8(3U, day);
result &= responseUint8(5U, month) & responseUint8(6U, year);
return result;
}
/*
* Set RTC sync clock from stream enable
*/
bool T3BTuner::clockSyncSet(bool const enable)
{
Command command = commandBuilder.createRtc(CmdRtcId::Sync).append(static_cast<uint8_t>(enable)).build();
return commandSend(command);
}
/*
* Get RTC sync clock status
*/
bool T3BTuner::clockSyncGet(bool* const enabled)
{
Command command = commandBuilder.createRtc(CmdRtcId::SyncStatus).build();
bool result = commandSend(command);
*enabled = response[0U];
return result;
}
/*
* Get RTC clock status
*/
bool T3BTuner::clockStatusGet(ClockStatus* const status)
{
Command command = commandBuilder.createRtc(CmdRtcId::StatusClock).build();
return (commandSend(command) && responseUint8(0U, reinterpret_cast<uint8_t*>(status)));
}
// *************************
// ***** EVENTS ************
// *************************
/*
* Enabled / Disable event notifications.
*/
bool T3BTuner::eventEnable(bool const enable)
{
uint16_t value = (enable) ? 0x7F : 0x00;
Command command =
commandBuilder.createNotification(CmdNotificationId::Notification).append(value).build();
return commandSend(command);
}
bool T3BTuner::eventReceived()
{
return (bool)stream.available();
}
/*
* Read event
*/
bool T3BTuner::eventRead(EventType* const type)
{
bool result = (responseReceive() && ((CommandType)responseHeader[1U] == CommandType::Notification));
*type = (EventType)responseHeader[2U];
return result;
}
// *************************
// ***** PRIVATE FUNCTIONS *
// *************************
/*
* Send command to DAB module and wait for answer
*/
bool T3BTuner::commandSend(Command const& command)
{
while (stream.available())
{
stream.read();
}
stream.write(command.data, command.size);
stream.flush();
return (responseReceive() &&
!(responseHeader[1U] == ResponseAck && responseHeader[2U] == ResponseAckNack));
}
bool T3BTuner::responseReceive()
{
uint16_t index = 0U;
uint8_t data = 0U;
uint32_t endMillis = systemMillis() + 200U; // timeout for answer from module = 200ms
responseSize = 0U;
while (systemMillis() < endMillis && index < T3BTunerMaxDataSize)
{
if (stream.available())
{
data = stream.read();
if (data == CommandStartValue)
{
index = 0U;
}
if (index < T3BTunerHeaderSize)
{
responseHeader[index] = data;
if (index == HeaderSizeIndex)
{
responseSize = static_cast<uint16_t>(responseHeader[5U]);
responseSize |= static_cast<uint16_t>(responseHeader[4U]) << 8U;
}
}
else if ((index - T3BTunerHeaderSize) < responseSize)
{
response[index - T3BTunerHeaderSize] = data;
}
if (data == CommandEndValue)
{
if ((index - T3BTunerHeaderSize - responseSize) == 0U)
{
return true;
}
}
index++;
}
}
return false;
}
bool T3BTuner::responseText(char* const buffer, uint16_t const size)
{
uint16_t j = 0U;
for (uint16_t i = 0U; i < responseSize; i = i + 2U)
{
if (size <= j)
return false;
buffer[j++] = uint16ToChar(response[i], response[i + 1U]);
discardTrailingSpaces(buffer);
}
return true;
}
bool T3BTuner::responseUint8(uint8_t const index, uint8_t* const resp)
{
if (responseSize > index)
{
*resp = response[index];
return true;
}
return false;
}
bool T3BTuner::responseUint16(uint8_t const index, uint16_t* const resp)
{
if (responseSize > (index + 1U))
{
*resp = static_cast<uint16_t>(response[index + 1U]);
*resp |= static_cast<uint16_t>(response[index]) << 8U;
return true;
}
return false;
}
bool T3BTuner::responseUint32(uint8_t const index, uint32_t* const resp)
{
if (responseSize > (index + 3U))
{
*resp = static_cast<uint32_t>(response[index + 3U]);
*resp |= static_cast<uint32_t>(response[index + 2U]) << 8U;
*resp |= static_cast<uint32_t>(response[index + 1U]) << 16U;
*resp |= static_cast<uint32_t>(response[index + 0U]) << 24U;
return true;
}
return false;
}
/*
* Convert uint16_t (2 * uint8_t) from Tuner to a char.
*/
char T3BTuner::uint16ToChar(uint8_t const byte1, uint8_t const byte0)
{
if (byte1 == 0x00)
{
if (byte0 < 128U)
{
return byte0;
}
switch (byte0)
{
case 0x8A:
return 'S';
case 0x8C:
return 'S';
case 0x8D:
return 'T';
case 0x8E:
return 'Z';
case 0x8F:
return 'Z';
case 0x9A:
return 's';
case 0x9D:
return 't';
case 0x9E:
return 'z';
case 0xC0:
return 'A';
case 0xC1:
return 'A';
case 0xC2:
return 'A';
case 0xC3:
return 'A';
case 0xC4:
return 'A';
case 0xC5:
return 'A';
case 0xC7:
return 'C';
case 0xC8:
return 'E';
case 0xC9:
return 'E';
case 0xCA:
return 'E';
case 0xCB:
return 'E';
case 0xCC:
return 'I';
case 0xCD:
return 'I';
case 0xCE:
return 'I';
case 0xCF:
return 'I';
case 0xD0:
return 'D';
case 0xD1:
return 'N';
case 0xD2:
return 'O';
case 0xD3:
return 'O';
case 0xD4:
return 'O';
case 0xD5:
return 'O';
case 0xD6:
return 'O';
case 0xD8:
return 'O';
case 0xD9:
return 'U';
case 0xDA:
return 'U';
case 0xDB:
return 'U';
case 0xDC:
return 'U';
case 0xDD:
return 'Y';
case 0xE0:
return 'a';
case 0xE1:
return 'a';
case 0xE2:
return 'a';
case 0xE3:
return 'a';
case 0xE4:
return 'a';
case 0xE5:
return 'a';
case 0xE7:
return 'c';
case 0xE8:
return 'e';
case 0xE9:
return 'e';
case 0xEA:
return 'e';
case 0xEB:
return 'e';
case 0xEC:
return 'i';
case 0xED:
return 'i';
case 0xEE:
return 'i';
case 0xEF:
return 'i';
case 0xF1:
return 'n';
case 0xF2:
return 'o';
case 0xF3:
return 'o';
case 0xF4:
return 'o';
case 0xF5:
return 'o';
case 0xF6:
return 'o';
case 0xF9:
return 'u';
case 0xFA:
return 'u';
case 0xFB:
return 'u';
case 0xFC:
return 'u';
case 0xFD:
return 'y';
case 0xFF:
return 'y';
}
}
else if (byte1 == 0x01)
{
switch (byte0)
{
case 0x1B:
return 'e'; // ě
case 0x48:
return 'n'; // ň
case 0x59:
return 'r'; // ř
case 0x0D:
return 'c'; // č
case 0x7E:
return 'z'; // ž
case 0x0C:
return 'C'; // Č
}
}
return 0x00;
}
void T3BTuner::discardTrailingSpaces(char* const text)
{
int16_t index = strlen(text) - 1;
while (index >= 0U && text[index] == ' ')
{
index--;
}
text[++index] = '\0';
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int n, k;
cin >> n >> k;
vector<int> p(k);
for(int i = 0; i < p.size(); ++i) {
p[i] = i + 1;
}
reverse(p.begin() + (k * 2 - n) - 1, p.end());
for(auto i : p) {
cout << i << ' ';
}
cout << endl;
}
}
|
/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkTypes.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkPoint.h"
#include "include/core/SkSurface.h"
#include "include/gpu/GrBackendSurface.h"
#include "include/gpu/GrContext.h"
#include "src/gpu/GrBackendTextureImageGenerator.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrDrawingManager.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrRenderTargetContext.h"
#include "src/gpu/GrSemaphore.h"
#include "src/gpu/GrSurfaceProxyPriv.h"
#include "src/gpu/GrTexturePriv.h"
#include "src/gpu/GrTextureProxy.h"
#include "src/gpu/SkGpuDevice.h"
#include "src/image/SkImage_Base.h"
#include "src/image/SkSurface_Gpu.h"
#include "tests/Test.h"
static constexpr int kSize = 8;
// Test that the correct mip map states are on the GrTextures when wrapping GrBackendTextures in
// SkImages and SkSurfaces
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrWrappedMipMappedTest, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
if (!context->priv().caps()->mipMapSupport()) {
return;
}
for (auto mipMapped : {GrMipMapped::kNo, GrMipMapped::kYes}) {
for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
// createBackendTexture currently doesn't support uploading data to mip maps
// so we don't send any. However, we pretend there is data for the checks below which is
// fine since we are never actually using these textures for any work on the gpu.
GrBackendTexture backendTex = context->createBackendTexture(
kSize, kSize, kRGBA_8888_SkColorType,
SkColors::kTransparent, mipMapped, renderable, GrProtected::kNo);
sk_sp<GrTextureProxy> proxy;
sk_sp<SkImage> image;
if (GrRenderable::kYes == renderable) {
sk_sp<SkSurface> surface = SkSurface::MakeFromBackendTexture(
context,
backendTex,
kTopLeft_GrSurfaceOrigin,
0,
kRGBA_8888_SkColorType,
nullptr,
nullptr);
SkGpuDevice* device = ((SkSurface_Gpu*)surface.get())->getDevice();
proxy = device->accessRenderTargetContext()->asTextureProxyRef();
} else {
image = SkImage::MakeFromTexture(context, backendTex,
kTopLeft_GrSurfaceOrigin,
kRGBA_8888_SkColorType,
kPremul_SkAlphaType, nullptr,
nullptr, nullptr);
const GrSurfaceProxyView* view = as_IB(image)->view(context);
REPORTER_ASSERT(reporter, view);
if (!view) {
context->deleteBackendTexture(backendTex);
return;
}
proxy = view->asTextureProxyRef();
}
REPORTER_ASSERT(reporter, proxy);
if (!proxy) {
context->deleteBackendTexture(backendTex);
return;
}
REPORTER_ASSERT(reporter, proxy->isInstantiated());
GrTexture* texture = proxy->peekTexture();
REPORTER_ASSERT(reporter, texture);
if (!texture) {
context->deleteBackendTexture(backendTex);
return;
}
if (GrMipMapped::kYes == mipMapped) {
REPORTER_ASSERT(reporter, GrMipMapped::kYes == texture->texturePriv().mipMapped());
if (GrRenderable::kYes == renderable) {
REPORTER_ASSERT(reporter, texture->texturePriv().mipMapsAreDirty());
} else {
REPORTER_ASSERT(reporter, !texture->texturePriv().mipMapsAreDirty());
}
} else {
REPORTER_ASSERT(reporter, GrMipMapped::kNo == texture->texturePriv().mipMapped());
}
context->deleteBackendTexture(backendTex);
}
}
}
// Test that we correctly copy or don't copy GrBackendTextures in the GrBackendTextureImageGenerator
// based on if we will use mips in the draw and the mip status of the GrBackendTexture.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrBackendTextureImageMipMappedTest, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
if (!context->priv().caps()->mipMapSupport()) {
return;
}
for (auto betMipMapped : {GrMipMapped::kNo, GrMipMapped::kYes}) {
for (auto requestMipMapped : {GrMipMapped::kNo, GrMipMapped::kYes}) {
GrBackendTexture backendTex = context->createBackendTexture(
kSize, kSize, kRGBA_8888_SkColorType, SkColors::kTransparent, betMipMapped,
GrRenderable::kNo, GrProtected::kNo);
sk_sp<SkImage> image = SkImage::MakeFromTexture(context, backendTex,
kTopLeft_GrSurfaceOrigin,
kRGBA_8888_SkColorType,
kPremul_SkAlphaType, nullptr,
nullptr, nullptr);
GrTextureProxy* proxy = as_IB(image)->peekProxy();
REPORTER_ASSERT(reporter, proxy);
if (!proxy) {
context->deleteBackendTexture(backendTex);
return;
}
REPORTER_ASSERT(reporter, proxy->isInstantiated());
sk_sp<GrTexture> texture = sk_ref_sp(proxy->peekTexture());
REPORTER_ASSERT(reporter, texture);
if (!texture) {
context->deleteBackendTexture(backendTex);
return;
}
std::unique_ptr<SkImageGenerator> imageGen = GrBackendTextureImageGenerator::Make(
texture, kTopLeft_GrSurfaceOrigin, nullptr, kRGBA_8888_SkColorType,
kPremul_SkAlphaType, nullptr);
REPORTER_ASSERT(reporter, imageGen);
if (!imageGen) {
context->deleteBackendTexture(backendTex);
return;
}
SkIPoint origin = SkIPoint::Make(0,0);
SkImageInfo imageInfo = SkImageInfo::Make(kSize, kSize, kRGBA_8888_SkColorType,
kPremul_SkAlphaType);
GrSurfaceProxyView genView =
imageGen->generateTexture(context, imageInfo, origin, requestMipMapped);
GrSurfaceProxy* genProxy = genView.proxy();
REPORTER_ASSERT(reporter, genProxy);
if (!genProxy) {
context->deleteBackendTexture(backendTex);
return;
}
if (genProxy->isLazy()) {
genProxy->priv().doLazyInstantiation(context->priv().resourceProvider());
} else if (!genProxy->isInstantiated()) {
genProxy->instantiate(context->priv().resourceProvider());
}
REPORTER_ASSERT(reporter, genProxy->isInstantiated());
if (!genProxy->isInstantiated()) {
context->deleteBackendTexture(backendTex);
return;
}
GrTexture* genTexture = genProxy->peekTexture();
REPORTER_ASSERT(reporter, genTexture);
if (!genTexture) {
context->deleteBackendTexture(backendTex);
return;
}
GrBackendTexture genBackendTex = genTexture->getBackendTexture();
if (GrBackendApi::kOpenGL == genBackendTex.backend()) {
GrGLTextureInfo genTexInfo;
GrGLTextureInfo origTexInfo;
if (genBackendTex.getGLTextureInfo(&genTexInfo) &&
backendTex.getGLTextureInfo(&origTexInfo)) {
if (requestMipMapped == GrMipMapped::kYes && betMipMapped == GrMipMapped::kNo) {
// We did a copy so the texture IDs should be different
REPORTER_ASSERT(reporter, origTexInfo.fID != genTexInfo.fID);
} else {
REPORTER_ASSERT(reporter, origTexInfo.fID == genTexInfo.fID);
}
} else {
ERRORF(reporter, "Failed to get GrGLTextureInfo");
}
#ifdef SK_VULKAN
} else if (GrBackendApi::kVulkan == genBackendTex.backend()) {
GrVkImageInfo genImageInfo;
GrVkImageInfo origImageInfo;
if (genBackendTex.getVkImageInfo(&genImageInfo) &&
backendTex.getVkImageInfo(&origImageInfo)) {
if (requestMipMapped == GrMipMapped::kYes && betMipMapped == GrMipMapped::kNo) {
// We did a copy so the texture IDs should be different
REPORTER_ASSERT(reporter, origImageInfo.fImage != genImageInfo.fImage);
} else {
REPORTER_ASSERT(reporter, origImageInfo.fImage == genImageInfo.fImage);
}
} else {
ERRORF(reporter, "Failed to get GrVkImageInfo");
}
#endif
#ifdef SK_METAL
} else if (GrBackendApi::kMetal == genBackendTex.backend()) {
GrMtlTextureInfo genImageInfo;
GrMtlTextureInfo origImageInfo;
if (genBackendTex.getMtlTextureInfo(&genImageInfo) &&
backendTex.getMtlTextureInfo(&origImageInfo)) {
if (requestMipMapped == GrMipMapped::kYes && betMipMapped == GrMipMapped::kNo) {
// We did a copy so the texture IDs should be different
REPORTER_ASSERT(reporter, origImageInfo.fTexture != genImageInfo.fTexture);
} else {
REPORTER_ASSERT(reporter, origImageInfo.fTexture == genImageInfo.fTexture);
}
} else {
ERRORF(reporter, "Failed to get GrMtlTextureInfo");
}
#endif
} else {
REPORTER_ASSERT(reporter, false);
}
// Must make sure the uses of the backend texture have finished (we possibly have a
// queued up copy) before we delete the backend texture.
context->flush();
context->priv().getGpu()->testingOnly_flushGpuAndSync();
context->deleteBackendTexture(backendTex);
}
}
}
// Test that when we call makeImageSnapshot on an SkSurface we retains the same mip status as the
// resource we took the snapshot of.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrImageSnapshotMipMappedTest, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
if (!context->priv().caps()->mipMapSupport()) {
return;
}
auto resourceProvider = context->priv().resourceProvider();
for (auto willUseMips : {false, true}) {
for (auto isWrapped : {false, true}) {
GrMipMapped mipMapped = willUseMips ? GrMipMapped::kYes : GrMipMapped::kNo;
sk_sp<SkSurface> surface;
GrBackendTexture backendTex = context->createBackendTexture(
kSize, kSize, kRGBA_8888_SkColorType,
SkColors::kTransparent, mipMapped, GrRenderable::kYes, GrProtected::kNo);
if (isWrapped) {
surface = SkSurface::MakeFromBackendTexture(context,
backendTex,
kTopLeft_GrSurfaceOrigin,
0,
kRGBA_8888_SkColorType,
nullptr,
nullptr);
} else {
SkImageInfo info = SkImageInfo::Make(kSize, kSize, kRGBA_8888_SkColorType,
kPremul_SkAlphaType);
surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info, 0,
kTopLeft_GrSurfaceOrigin, nullptr,
willUseMips);
}
REPORTER_ASSERT(reporter, surface);
if (!surface) {
context->deleteBackendTexture(backendTex);
}
SkGpuDevice* device = ((SkSurface_Gpu*)surface.get())->getDevice();
GrTextureProxy* texProxy = device->accessRenderTargetContext()->asTextureProxy();
REPORTER_ASSERT(reporter, mipMapped == texProxy->mipMapped());
texProxy->instantiate(resourceProvider);
GrTexture* texture = texProxy->peekTexture();
REPORTER_ASSERT(reporter, mipMapped == texture->texturePriv().mipMapped());
sk_sp<SkImage> image = surface->makeImageSnapshot();
REPORTER_ASSERT(reporter, image);
if (!image) {
context->deleteBackendTexture(backendTex);
}
texProxy = as_IB(image)->peekProxy();
REPORTER_ASSERT(reporter, mipMapped == texProxy->mipMapped());
texProxy->instantiate(resourceProvider);
texture = texProxy->peekTexture();
REPORTER_ASSERT(reporter, mipMapped == texture->texturePriv().mipMapped());
// Must flush the context to make sure all the cmds (copies, etc.) from above are sent
// to the gpu before we delete the backendHandle.
context->flush();
context->priv().getGpu()->testingOnly_flushGpuAndSync();
context->deleteBackendTexture(backendTex);
}
}
}
// Test that we don't create a mip mapped texture if the size is 1x1 even if the filter mode is set
// to use mips. This test passes by not crashing or hitting asserts in code.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(Gr1x1TextureMipMappedTest, reporter, ctxInfo) {
GrContext* context = ctxInfo.grContext();
if (!context->priv().caps()->mipMapSupport()) {
return;
}
// Make surface to draw into
SkImageInfo info = SkImageInfo::MakeN32(16, 16, kPremul_SkAlphaType);
sk_sp<SkSurface> surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
// Make 1x1 raster bitmap
SkBitmap bmp;
bmp.allocN32Pixels(1, 1);
SkPMColor* pixel = reinterpret_cast<SkPMColor*>(bmp.getPixels());
*pixel = 0;
sk_sp<SkImage> bmpImage = SkImage::MakeFromBitmap(bmp);
// Make sure we scale so we don't optimize out the use of mips.
surface->getCanvas()->scale(0.5f, 0.5f);
SkPaint paint;
// This should upload the image to a non mipped GrTextureProxy.
surface->getCanvas()->drawImage(bmpImage, 0, 0, &paint);
surface->flush();
// Now set the filter quality to high so we use mip maps. We should find the non mipped texture
// in the cache for the SkImage. Since the texture is 1x1 we should just use that texture
// instead of trying to do a copy to a mipped texture.
paint.setFilterQuality(kHigh_SkFilterQuality);
surface->getCanvas()->drawImage(bmpImage, 0, 0, &paint);
surface->flush();
}
// Create a new render target and draw 'mipmapView' into it using the provided 'filter'.
static std::unique_ptr<GrRenderTargetContext> draw_mipmap_into_new_render_target(
GrRecordingContext* context, GrProxyProvider* proxyProvider, GrColorType colorType,
SkAlphaType alphaType, GrSurfaceProxyView mipmapView, GrSamplerState::Filter filter) {
sk_sp<GrSurfaceProxy> renderTarget = proxyProvider->createProxy(
mipmapView.proxy()->backendFormat(), {1, 1}, mipmapView.swizzle(), GrRenderable::kYes,
1, GrMipMapped::kNo, SkBackingFit::kApprox, SkBudgeted::kYes, GrProtected::kNo);
auto rtc = GrRenderTargetContext::Make(
context, colorType, nullptr, std::move(renderTarget), kTopLeft_GrSurfaceOrigin,
nullptr);
rtc->drawTexture(GrNoClip(), std::move(mipmapView), alphaType, filter, SkBlendMode::kSrcOver,
{1,1,1,1}, SkRect::MakeWH(4, 4), SkRect::MakeWH(1,1), GrAA::kYes,
GrQuadAAFlags::kAll, SkCanvas::kFast_SrcRectConstraint, SkMatrix::I(),
nullptr);
return rtc;
}
// Test that two opsTasks using the same mipmaps both depend on the same GrTextureResolveRenderTask.
DEF_GPUTEST(GrManyDependentsMipMappedTest, reporter, /* options */) {
using CanClearFullscreen = GrRenderTargetContext::CanClearFullscreen;
using Enable = GrContextOptions::Enable;
using Filter = GrSamplerState::Filter;
for (auto enableSortingAndReduction : {Enable::kYes, Enable::kNo}) {
GrMockOptions mockOptions;
mockOptions.fMipMapSupport = true;
GrContextOptions ctxOptions;
ctxOptions.fReduceOpsTaskSplitting = enableSortingAndReduction;
sk_sp<GrContext> context = GrContext::MakeMock(&mockOptions, ctxOptions);
if (!context) {
ERRORF(reporter, "could not create mock context with fReduceOpsTaskSplitting %s.",
(Enable::kYes == enableSortingAndReduction) ? "enabled" : "disabled");
continue;
}
SkASSERT(context->priv().caps()->mipMapSupport());
GrBackendFormat format = context->defaultBackendFormat(
kRGBA_8888_SkColorType, GrRenderable::kYes);
GrColorType colorType = GrColorType::kRGBA_8888;
SkAlphaType alphaType = kPremul_SkAlphaType;
GrProxyProvider* proxyProvider = context->priv().proxyProvider();
// Create a mipmapped render target.
GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, colorType);
sk_sp<GrTextureProxy> mipmapProxy = proxyProvider->createProxy(
format, {4, 4}, swizzle, GrRenderable::kYes, 1, GrMipMapped::kYes,
SkBackingFit::kExact, SkBudgeted::kYes, GrProtected::kNo);
// Mark the mipmaps clean to ensure things still work properly when they won't be marked
// dirty again until GrRenderTask::makeClosed().
mipmapProxy->markMipMapsClean();
auto mipmapRTC = GrRenderTargetContext::Make(
context.get(), colorType, nullptr, mipmapProxy, kTopLeft_GrSurfaceOrigin, nullptr);
mipmapRTC->clear(nullptr, {.1f,.2f,.3f,.4f}, CanClearFullscreen::kYes);
REPORTER_ASSERT(reporter, mipmapProxy->getLastRenderTask());
// mipmapProxy's last render task should now just be the opsTask containing the clear.
REPORTER_ASSERT(reporter,
mipmapRTC->testingOnly_PeekLastOpsTask() == mipmapProxy->getLastRenderTask());
// Mipmaps don't get marked dirty until makeClosed().
REPORTER_ASSERT(reporter, !mipmapProxy->mipMapsAreDirty());
GrSurfaceProxyView mipmapView(mipmapProxy, kTopLeft_GrSurfaceOrigin, swizzle);
// Draw the dirty mipmap texture into a render target.
auto rtc1 = draw_mipmap_into_new_render_target(context.get(), proxyProvider, colorType,
alphaType, mipmapView, Filter::kMipMap);
// Mipmaps should have gotten marked dirty during makeClosed, then marked clean again as
// soon as a GrTextureResolveRenderTask was inserted. The way we know they were resolved is
// if mipmapProxy->getLastRenderTask() has switched from the opsTask that drew to it, to the
// task that resolved its mips.
GrRenderTask* initialMipmapRegenTask = mipmapProxy->getLastRenderTask();
REPORTER_ASSERT(reporter, initialMipmapRegenTask);
REPORTER_ASSERT(reporter,
initialMipmapRegenTask != mipmapRTC->testingOnly_PeekLastOpsTask());
REPORTER_ASSERT(reporter, !mipmapProxy->mipMapsAreDirty());
// Draw the now-clean mipmap texture into a second target.
auto rtc2 = draw_mipmap_into_new_render_target(context.get(), proxyProvider, colorType,
alphaType, mipmapView, Filter::kMipMap);
// Make sure the mipmap texture still has the same regen task.
REPORTER_ASSERT(reporter, mipmapProxy->getLastRenderTask() == initialMipmapRegenTask);
SkASSERT(!mipmapProxy->mipMapsAreDirty());
// Reset everything so we can go again, this time with the first draw not mipmapped.
context->flush();
// Mip regen tasks don't get added as dependencies until makeClosed().
REPORTER_ASSERT(reporter,
rtc1->testingOnly_PeekLastOpsTask()->dependsOn(initialMipmapRegenTask));
REPORTER_ASSERT(reporter,
rtc2->testingOnly_PeekLastOpsTask()->dependsOn(initialMipmapRegenTask));
// Render something to dirty the mips.
mipmapRTC->clear(nullptr, {.1f,.2f,.3f,.4f}, CanClearFullscreen::kYes);
REPORTER_ASSERT(reporter, mipmapProxy->getLastRenderTask());
// mipmapProxy's last render task should now just be the opsTask containing the clear.
REPORTER_ASSERT(reporter,
mipmapRTC->testingOnly_PeekLastOpsTask() == mipmapProxy->getLastRenderTask());
// Mipmaps don't get marked dirty until makeClosed().
REPORTER_ASSERT(reporter, !mipmapProxy->mipMapsAreDirty());
// Draw the dirty mipmap texture into a render target, but don't do mipmap filtering.
rtc1 = draw_mipmap_into_new_render_target(context.get(), proxyProvider, colorType,
alphaType, mipmapView, Filter::kBilerp);
// Mipmaps should have gotten marked dirty during makeClosed() when adding the dependency.
// Since the last draw did not use mips, they will not have been regenerated and should
// therefore still be dirty.
REPORTER_ASSERT(reporter, mipmapProxy->mipMapsAreDirty());
// Since mips weren't regenerated, the last render task shouldn't have changed.
REPORTER_ASSERT(reporter,
mipmapRTC->testingOnly_PeekLastOpsTask() == mipmapProxy->getLastRenderTask());
// Draw the stil-dirty mipmap texture into a second target with mipmap filtering.
rtc2 = draw_mipmap_into_new_render_target(context.get(), proxyProvider, colorType,
alphaType, std::move(mipmapView),
Filter::kMipMap);
// Make sure the mipmap texture now has a new last render task that regenerates the mips,
// and that the mipmaps are now clean.
auto mipRegenTask2 = mipmapProxy->getLastRenderTask();
REPORTER_ASSERT(reporter, mipRegenTask2);
REPORTER_ASSERT(reporter,
mipmapRTC->testingOnly_PeekLastOpsTask() != mipRegenTask2);
SkASSERT(!mipmapProxy->mipMapsAreDirty());
// Mip regen tasks don't get added as dependencies until makeClosed().
context->flush();
REPORTER_ASSERT(reporter, rtc2->testingOnly_PeekLastOpsTask()->dependsOn(mipRegenTask2));
}
}
|
/**
* \file PolygonArea.hpp
* \brief Header for GeographicLib::PolygonAreaT class
*
* Copyright (c) Charles Karney (2010-2016) <charles@karney.com> and licensed
* under the MIT/X11 License. For more information, see
* https://geographiclib.sourceforge.io/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_POLYGONAREA_HPP)
#define GEOGRAPHICLIB_POLYGONAREA_HPP 1
#include <GeographicLib/Geodesic.hpp>
#include <GeographicLib/GeodesicExact.hpp>
#include <GeographicLib/Rhumb.hpp>
#include <GeographicLib/Accumulator.hpp>
namespace GeographicLib {
/**
* \brief Polygon areas
*
* This computes the area of a polygon whose edges are geodesics using the
* method given in Section 6 of
* - C. F. F. Karney,
* <a href="https://doi.org/10.1007/s00190-012-0578-z">
* Algorithms for geodesics</a>,
* J. Geodesy <b>87</b>, 43--55 (2013);
* DOI: <a href="https://doi.org/10.1007/s00190-012-0578-z">
* 10.1007/s00190-012-0578-z</a>;
* addenda:
* <a href="https://geographiclib.sourceforge.io/geod-addenda.html">
* geod-addenda.html</a>.
*
* This class lets you add vertices and edges one at a time to the polygon.
* The sequence must start with a vertex and thereafter vertices and edges
* can be added in any order. Any vertex after the first creates a new edge
* which is the \e shortest geodesic from the previous vertex. In some
* cases there may be two or many such shortest geodesics and the area is
* then not uniquely defined. In this case, either add an intermediate
* vertex or add the edge \e as an edge (by defining its direction and
* length).
*
* The area and perimeter are accumulated at two times the standard floating
* point precision to guard against the loss of accuracy with many-sided
* polygons. At any point you can ask for the perimeter and area so far.
* There's an option to treat the points as defining a polyline instead of a
* polygon; in that case, only the perimeter is computed.
*
* This is a templated class to allow it to be used with Geodesic,
* GeodesicExact, and Rhumb. GeographicLib::PolygonArea,
* GeographicLib::PolygonAreaExact, and GeographicLib::PolygonAreaRhumb are
* typedefs for these cases.
*
* @tparam GeodType the geodesic class to use.
*
* Example of use:
* \include example-PolygonArea.cpp
*
* <a href="Planimeter.1.html">Planimeter</a> is a command-line utility
* providing access to the functionality of PolygonAreaT.
**********************************************************************/
template <class GeodType = Geodesic>
class PolygonAreaT {
private:
typedef Math::real real;
GeodType _earth;
real _area0; // Full ellipsoid area
bool _polyline; // Assume polyline (don't close and skip area)
unsigned _mask;
unsigned _num;
int _crossings;
Accumulator<> _areasum, _perimetersum;
real _lat0, _lon0, _lat1, _lon1;
static inline int transit(real lon1, real lon2) {
// Return 1 or -1 if crossing prime meridian in east or west direction.
// Otherwise return zero.
// Compute lon12 the same way as Geodesic::Inverse.
lon1 = Math::AngNormalize(lon1);
lon2 = Math::AngNormalize(lon2);
real lon12 = Math::AngDiff(lon1, lon2);
// Treat 0 as negative in these tests. This balances +/- 180 being
// treated as positive, i.e., +180.
int cross =
lon1 <= 0 && lon2 > 0 && lon12 > 0 ? 1 :
(lon2 <= 0 && lon1 > 0 && lon12 < 0 ? -1 : 0);
return cross;
}
// an alternate version of transit to deal with longitudes in the direct
// problem.
static inline int transitdirect(real lon1, real lon2) {
// We want to compute exactly
// int(floor(lon2 / 360)) - int(floor(lon1 / 360))
// Since we only need the parity of the result we can use std::remquo;
// but this is buggy with g++ 4.8.3 (glibc version < 2.22), see
// https://sourceware.org/bugzilla/show_bug.cgi?id=17569
// and requires C++11. So instead we do
#if GEOGRAPHICLIB_CXX11_MATH && GEOGRAPHICLIB_PRECISION != 4
using std::remainder;
lon1 = remainder(lon1, real(720)); lon2 = remainder(lon2, real(720));
return ( (lon2 >= 0 && lon2 < 360 ? 0 : 1) -
(lon1 >= 0 && lon1 < 360 ? 0 : 1) );
#else
using std::fmod;
lon1 = fmod(lon1, real(720)); lon2 = fmod(lon2, real(720));
return ( ((lon2 >= 0 && lon2 < 360) || lon2 < -360 ? 0 : 1) -
((lon1 >= 0 && lon1 < 360) || lon1 < -360 ? 0 : 1) );
#endif
}
public:
/**
* Constructor for PolygonAreaT.
*
* @param[in] earth the Geodesic object to use for geodesic calculations.
* @param[in] polyline if true that treat the points as defining a polyline
* instead of a polygon (default = false).
**********************************************************************/
PolygonAreaT(const GeodType& earth, bool polyline = false)
: _earth(earth)
, _area0(_earth.EllipsoidArea())
, _polyline(polyline)
, _mask(GeodType::LATITUDE | GeodType::LONGITUDE | GeodType::DISTANCE |
(_polyline ? GeodType::NONE :
GeodType::AREA | GeodType::LONG_UNROLL))
{ Clear(); }
/**
* Clear PolygonAreaT, allowing a new polygon to be started.
**********************************************************************/
void Clear() {
_num = 0;
_crossings = 0;
_areasum = 0;
_perimetersum = 0;
_lat0 = _lon0 = _lat1 = _lon1 = Math::NaN();
}
/**
* Add a point to the polygon or polyline.
*
* @param[in] lat the latitude of the point (degrees).
* @param[in] lon the longitude of the point (degrees).
*
* \e lat should be in the range [−90°, 90°].
**********************************************************************/
void AddPoint(real lat, real lon);
/**
* Add an edge to the polygon or polyline.
*
* @param[in] azi azimuth at current point (degrees).
* @param[in] s distance from current point to next point (meters).
*
* This does nothing if no points have been added yet. Use
* PolygonAreaT::CurrentPoint to determine the position of the new vertex.
**********************************************************************/
void AddEdge(real azi, real s);
/**
* Return the results so far.
*
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the perimeter of the polygon or length of the
* polyline (meters).
* @param[out] area the area of the polygon (meters<sup>2</sup>); only set
* if \e polyline is false in the constructor.
* @return the number of points.
*
* More points can be added to the polygon after this call.
**********************************************************************/
unsigned Compute(bool reverse, bool sign,
real& perimeter, real& area) const;
/**
* Return the results assuming a tentative final test point is added;
* however, the data for the test point is not saved. This lets you report
* a running result for the perimeter and area as the user moves the mouse
* cursor. Ordinary floating point arithmetic is used to accumulate the
* data for the test point; thus the area and perimeter returned are less
* accurate than if PolygonAreaT::AddPoint and PolygonAreaT::Compute are
* used.
*
* @param[in] lat the latitude of the test point (degrees).
* @param[in] lon the longitude of the test point (degrees).
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the approximate perimeter of the polygon or length
* of the polyline (meters).
* @param[out] area the approximate area of the polygon
* (meters<sup>2</sup>); only set if polyline is false in the
* constructor.
* @return the number of points.
*
* \e lat should be in the range [−90°, 90°].
**********************************************************************/
unsigned TestPoint(real lat, real lon, bool reverse, bool sign,
real& perimeter, real& area) const;
/**
* Return the results assuming a tentative final test point is added via an
* azimuth and distance; however, the data for the test point is not saved.
* This lets you report a running result for the perimeter and area as the
* user moves the mouse cursor. Ordinary floating point arithmetic is used
* to accumulate the data for the test point; thus the area and perimeter
* returned are less accurate than if PolygonAreaT::AddEdge and
* PolygonAreaT::Compute are used.
*
* @param[in] azi azimuth at current point (degrees).
* @param[in] s distance from current point to final test point (meters).
* @param[in] reverse if true then clockwise (instead of counter-clockwise)
* traversal counts as a positive area.
* @param[in] sign if true then return a signed result for the area if
* the polygon is traversed in the "wrong" direction instead of returning
* the area for the rest of the earth.
* @param[out] perimeter the approximate perimeter of the polygon or length
* of the polyline (meters).
* @param[out] area the approximate area of the polygon
* (meters<sup>2</sup>); only set if polyline is false in the
* constructor.
* @return the number of points.
**********************************************************************/
unsigned TestEdge(real azi, real s, bool reverse, bool sign,
real& perimeter, real& area) const;
/** \name Inspector functions
**********************************************************************/
///@{
/**
* @return \e a the equatorial radius of the ellipsoid (meters). This is
* the value inherited from the Geodesic object used in the constructor.
**********************************************************************/
Math::real MajorRadius() const { return _earth.MajorRadius(); }
/**
* @return \e f the flattening of the ellipsoid. This is the value
* inherited from the Geodesic object used in the constructor.
**********************************************************************/
Math::real Flattening() const { return _earth.Flattening(); }
/**
* Report the previous vertex added to the polygon or polyline.
*
* @param[out] lat the latitude of the point (degrees).
* @param[out] lon the longitude of the point (degrees).
*
* If no points have been added, then NaNs are returned. Otherwise, \e lon
* will be in the range [−180°, 180°].
**********************************************************************/
void CurrentPoint(real& lat, real& lon) const
{ lat = _lat1; lon = _lon1; }
///@}
};
/**
* @relates PolygonAreaT
*
* Polygon areas using Geodesic. This should be used if the flattening is
* small.
**********************************************************************/
typedef PolygonAreaT<Geodesic> PolygonArea;
/**
* @relates PolygonAreaT
*
* Polygon areas using GeodesicExact. (But note that the implementation of
* areas in GeodesicExact uses a high order series and this is only accurate
* for modest flattenings.)
**********************************************************************/
typedef PolygonAreaT<GeodesicExact> PolygonAreaExact;
/**
* @relates PolygonAreaT
*
* Polygon areas using Rhumb.
**********************************************************************/
typedef PolygonAreaT<Rhumb> PolygonAreaRhumb;
} // namespace GeographicLib
#endif // GEOGRAPHICLIB_POLYGONAREA_HPP
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* 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, THE UNITED STATES GOVERNMENT, OR ANY 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 "Duct.hpp"
#include "Duct_Impl.hpp"
#include "Node.hpp"
#include "Node_Impl.hpp"
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/OS_Duct_FieldEnums.hxx>
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
Duct_Impl::Duct_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == Duct::iddObjectType());
}
Duct_Impl::Duct_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == Duct::iddObjectType());
}
Duct_Impl::Duct_Impl(const Duct_Impl& other,
Model_Impl* model,
bool keepHandle)
: StraightComponent_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& Duct_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType Duct_Impl::iddObjectType() const {
return Duct::iddObjectType();
}
unsigned Duct_Impl::inletPort()
{
return OS_DuctFields::InletNode;
}
unsigned Duct_Impl::outletPort()
{
return OS_DuctFields::OutletNode;
}
bool Duct_Impl::addToNode(Node & node)
{
if(node.airLoopHVAC()) {
return StraightComponent_Impl::addToNode(node);
}
return false;
}
} // detail
Duct::Duct(const Model& model)
: StraightComponent(Duct::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::Duct_Impl>());
bool ok = true;
// ok = setHandle();
OS_ASSERT(ok);
}
IddObjectType Duct::iddObjectType() {
return IddObjectType(IddObjectType::OS_Duct);
}
/// @cond
Duct::Duct(std::shared_ptr<detail::Duct_Impl> impl)
: StraightComponent(impl)
{}
/// @endcond
} // model
} // openstudio
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparams.h"
#include "consensus/merkle.h"
#include "pubkey.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include <assert.h>
#include "script/standard.h"
#include "chainparamsseeds.h"
#include "amount.h"
static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
CMutableTransaction txNew;
txNew.nVersion = 1;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = genesisReward;
txNew.vout[0].scriptPubKey = genesisOutputScript;
CBlock genesis;
genesis.nTime = nTime;
genesis.nBits = nBits;
genesis.nNonce = nNonce;
genesis.nVersion = nVersion;
genesis.vtx.push_back(MakeTransactionRef(std::move(txNew)));
genesis.hashPrevBlock.SetNull();
genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
return genesis;
}
/**
* Build the genesis block. Note that the output of its generation
* transaction cannot be spent since it did not originally exist in the
* database.
*
* CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
* CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
* CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
* CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
* vMerkleTree: 4a5e1e
*/
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
const CScript genesisOutputScript = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}
void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
consensus.vDeployments[d].nStartTime = nStartTime;
consensus.vDeployments[d].nTimeout = nTimeout;
}
bool CChainParams::IsDuringPremine(uint32_t nHeight) const
{
return consensus.BCXHeight > 0
&& consensus.BCXPremineAmount > 0
&& (int)nHeight == consensus.BCXHeight;
}
static CScript MakePremineMultiSigScript(const std::vector<std::string> &pubKeys)
{
static const int PREMINE_PUB_KEYS_NUM = 6;
static const int PREMINE_MIN_REQUIRE_PUB_NUM = 4;
assert(pubKeys.size() == PREMINE_PUB_KEYS_NUM);
CScript script;
script << PREMINE_MIN_REQUIRE_PUB_NUM;
for (const std::string &pubKey : pubKeys)
{
script << ParseHex(pubKey);
}
script << PREMINE_PUB_KEYS_NUM << OP_CHECKMULTISIG;
return GetScriptForDestination(CScriptID(script));
}
bool CChainParams::CheckPreminePubKeyScript(const CScript &scriptPubKey, uint32_t nHeight) const
{
if (!IsDuringPremine(nHeight))
{
return true;
}
return scriptPubKey == MakePremineMultiSigScript(vPreminePubKeys);
}
/**
* Main network
*/
/**
* What makes a good checkpoint block?
* + Is surrounded by blocks with reasonable timestamps
* (no blocks before with a timestamp after, none after with
* timestamp before)
* + Contains no strange transactions
*/
class CMainParams : public CChainParams {
public:
CMainParams() {
strNetworkID = "main";
consensus.nSubsidyHalvingInterval = 210000;
consensus.nBCXSubsidyHalvingInterval = 210000 * 5;
consensus.BIP34Height = 227931;
consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8");
consensus.BIP65Height = 388381; // 000000000000000004c2b624ed5d7756c508d90fd0da2c7c679febfa6c4735f0
consensus.BIP66Height = 363725; // 00000000000000000379eaa19dce8c9b722d46ae6a57c2f1a988119488b50931
consensus.BCXHeight = 498889;
consensus.BCXPowLimitWindow = 800;
consensus.BCXPremineAmount = 105 * 10000 * COIN * BTC_2_BCX_RATE;
consensus.BCXPremineBlocks = 420000;
consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.powLimitBCXStart = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 2 * 60;
consensus.fPowAllowMinDifficultyBlocks = false;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
// Deployment of SegWit (BIP141, BIP143, and BIP147)
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1479168000; // November 15th, 2016.
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1510704000; // November 15th, 2017.
// Deployment of contract
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].bit = 2; // i.e. (1 << 2) == VERSIONBITS_BCX_CONTRACT_BITS
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].nStartTime = 1529539200; // June 21st, 2018.
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].nTimeout = 1561075200; // June 21st, 2019.
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000723d3581fe1bd55373540a");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x0000000000000000003b9ce759c2a087d52abc4266f8f4ebd6d768b89defa50a"); //477890
/**
* The message start string is designed to be unlikely to occur in normal data.
* The characters are rarely used upper ASCII, not valid as UTF-8, and produce
* a large 32-bit integer with any alignment.
*/
pchMessageStart[0] = 0x11;
pchMessageStart[1] = 0x05;
pchMessageStart[2] = 0xbc;
pchMessageStart[3] = 0xF9;
nDefaultPort = 9003;
nPruneAfterHeight = 100000;
genesis = CreateGenesisBlock(1231006505, 2083236893, 0x1d00ffff, 1, 50 * COIN * BTC_2_BCX_RATE);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"));
assert(genesis.hashMerkleRoot == uint256S("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
// Note that of those with the service bits flag, most only support a subset of possible options
vSeeds.emplace_back("seed.bcx.org", true);
vSeeds.emplace_back("seed.bcx.info", false);
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 75);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 63);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,128);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4};
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));
fDefaultConsistencyChecks = false;
fRequireStandard = true;
fMineBlocksOnDemand = false;
checkpointData = (CCheckpointData) {
{
{ 11111, uint256S("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")},
{ 33333, uint256S("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")},
{ 74000, uint256S("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")},
{105000, uint256S("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")},
{134444, uint256S("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")},
{168000, uint256S("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")},
{193000, uint256S("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")},
{210000, uint256S("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")},
{216116, uint256S("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e")},
{225430, uint256S("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932")},
{250000, uint256S("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214")},
{279000, uint256S("0x0000000000000001ae8c72a0b0c301f67e3afca10e819efa9041e458e9bd7e40")},
{295000, uint256S("0x00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983")},
}
};
chainTxData = ChainTxData{
// Data as of block 000000000000000000d97e53664d17967bd4ee50b23abb92e54a34eb222d15ae (height 478913).
1501801925, // * UNIX timestamp of last known number of transactions
243756039, // * total number of transactions between genesis and that timestamp
// (the tx=... number in the SetBestChain debug.log lines)
3.1 // * estimated number of transactions per second after that timestamp
};
vPreminePubKeys = {
"0326363a407a9acc9ecc2fc65395c9741cf62e1f90abe0649b3262cf356d8d5ec3",
"0234b445ea3f9e51f1fc397721033d11be82be684417744ac022b1e449321f13d1",
"03ac23e2161e6d8cd58dc53f75b64930d636ed4f6e29339c373392a44059a433fd",
"0296daf0572dcb98ab97b8fba1ec97c21d1dc1f387b4727af29d0e289972ad6d37",
"033a9cab8e34867c5eda0b9e6134645e340d04181d3743c6d2b3103a8c7aed51a9",
"026674593b9712433f68efe3d7988bbf9f3bdac302b77d08a45611fcd78532ffdb",
};
}
};
/**
* Testnet (v3)
*/
class CTestNetParams : public CChainParams {
public:
CTestNetParams() {
strNetworkID = "test";
consensus.nSubsidyHalvingInterval = 210000;
consensus.nBCXSubsidyHalvingInterval = 210000 * 5;
consensus.BIP34Height = 21111;
consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8");
consensus.BIP65Height = 581885; // 00000000007f6655f22f98e72ed80d8b06dc761d5da09df0fa1dc4be4f861eb6
consensus.BIP66Height = 330776; // 000000002104c8c45e99a8853285a3b592602a3ccde2b832481da85e9e4ba182
consensus.BCXHeight = 1254701;
consensus.BCXPowLimitWindow = 800;
consensus.BCXPremineAmount = 105 * COIN * BTC_2_BCX_RATE;
consensus.BCXPremineBlocks = 336;
consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.powLimitBCXStart = uint256S("00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 2 * 60;
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = false;
consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008
// Deployment of BIP68, BIP112, and BIP113.
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017
// Deployment of SegWit (BIP141, BIP143, and BIP147)
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017
// Deployment of contract
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].bit = 2; // i.e. (1 << 2) == VERSIONBITS_BCX_CONTRACT_BITS
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].nStartTime = 1526428800; // May 16th, 2018.
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].nTimeout = 1557964800; // May 16th, 2019.
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000002830dab7f76dbb7d63");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x0000000002e9e7b00e1f6dc5123a04aad68dd0f0968d8c7aa45f6640795c37b1"); //1135275
pchMessageStart[0] = 0x19;
pchMessageStart[1] = 0x9F;
pchMessageStart[2] = 0xF3;
pchMessageStart[3] = 0x18;
nDefaultPort = 19003;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1296688602, 414098458, 0x1d00ffff, 1, 50 * COIN * BTC_2_BCX_RATE);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"));
assert(genesis.hashMerkleRoot == uint256S("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
vFixedSeeds.clear();
vSeeds.clear();
// nodes with support for servicebits filtering should be at the top
vSeeds.emplace_back("testnet-seed.bcx.org", true);
vSeeds.emplace_back("testnet-seed.bcx.info", false);
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 65);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));
fDefaultConsistencyChecks = false;
fRequireStandard = false;
fMineBlocksOnDemand = false;
checkpointData = (CCheckpointData) {
{
{546, uint256S("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")},
}
};
chainTxData = ChainTxData{
// Data as of block 00000000000001c200b9790dc637d3bb141fe77d155b966ed775b17e109f7c6c (height 1156179)
1501802953,
14706531,
0.15
};
vPreminePubKeys = {
"0326363a407a9acc9ecc2fc65395c9741cf62e1f90abe0649b3262cf356d8d5ec3",
"0234b445ea3f9e51f1fc397721033d11be82be684417744ac022b1e449321f13d1",
"03ac23e2161e6d8cd58dc53f75b64930d636ed4f6e29339c373392a44059a433fd",
"0296daf0572dcb98ab97b8fba1ec97c21d1dc1f387b4727af29d0e289972ad6d37",
"033a9cab8e34867c5eda0b9e6134645e340d04181d3743c6d2b3103a8c7aed51a9",
"026674593b9712433f68efe3d7988bbf9f3bdac302b77d08a45611fcd78532ffdb",
};
}
};
/**
* Regression test
*/
class CRegTestParams : public CChainParams {
public:
CRegTestParams() {
strNetworkID = "regtest";
consensus.nSubsidyHalvingInterval = 150;
consensus.nBCXSubsidyHalvingInterval = 150 * 5;
consensus.BIP34Height = 100000000; // BIP34 has not activated on regtest (far in the future so block v1 are not rejected in tests)
consensus.BIP34Hash = uint256();
consensus.BIP65Height = 1351; // BIP65 activated on regtest (Used in rpc activation tests)
consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in rpc activation tests)
consensus.BCXHeight = 432;
consensus.BCXPowLimitWindow = 0;
consensus.BCXPremineAmount = 0;
consensus.BCXPremineBlocks = 0;
consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.powLimitBCXStart = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks
consensus.nPowTargetSpacing = 2 * 60;
consensus.fPowAllowMinDifficultyBlocks = true;
consensus.fPowNoRetargeting = true;
consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL;
// Deployment of contract
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].bit = 2; // i.e. (1 << 2) == VERSIONBITS_BCX_CONTRACT_BITS
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].nStartTime = 0;
consensus.vDeployments[Consensus::DEPLOYMENT_CONTRACT].nTimeout = 999999999999ULL;
// The best chain should have at least this much work.
consensus.nMinimumChainWork = uint256S("0x00");
// By default assume that the signatures in ancestors of this block are valid.
consensus.defaultAssumeValid = uint256S("0x00");
pchMessageStart[0] = 0x19;
pchMessageStart[1] = 0xf9;
pchMessageStart[2] = 0xa3;
pchMessageStart[3] = 0xfa;
nDefaultPort = 9005;
nPruneAfterHeight = 1000;
genesis = CreateGenesisBlock(1296688602, 2, 0x207fffff, 1, 50 * COIN * BTC_2_BCX_RATE);
consensus.hashGenesisBlock = genesis.GetHash();
assert(consensus.hashGenesisBlock == uint256S("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"));
assert(genesis.hashMerkleRoot == uint256S("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds.
vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds.
fDefaultConsistencyChecks = true;
fRequireStandard = false;
fMineBlocksOnDemand = true;
checkpointData = (CCheckpointData) {
{
{0, uint256S("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")},
}
};
chainTxData = ChainTxData{
0,
0,
0
};
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);
base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF};
base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94};
}
};
static std::unique_ptr<CChainParams> globalChainParams;
const CChainParams &Params() {
assert(globalChainParams);
return *globalChainParams;
}
std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain)
{
if (chain == CBaseChainParams::MAIN)
return std::unique_ptr<CChainParams>(new CMainParams());
else if (chain == CBaseChainParams::TESTNET)
return std::unique_ptr<CChainParams>(new CTestNetParams());
else if (chain == CBaseChainParams::REGTEST)
return std::unique_ptr<CChainParams>(new CRegTestParams());
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}
void SelectParams(const std::string& network)
{
SelectBaseParams(network);
globalChainParams = CreateChainParams(network);
}
void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout)
{
globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout);
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/blockchain.h>
#include <amount.h>
#include <base58.h>
#include <chain.h>
#include <chainparams.h>
#include <checkpoints.h>
#include <coins.h>
#include <consensus/validation.h>
#include <validation.h>
#include <core_io.h>
#include <index/txindex.h>
#include <key_io.h>
#include <policy/feerate.h>
#include <policy/policy.h>
#include <policy/rbf.h>
#include <primitives/transaction.h>
#include <rpc/server.h>
#include <script/descriptor.h>
#include <streams.h>
#include <sync.h>
#include <txdb.h>
#include <txmempool.h>
#include <util.h>
#include <utilstrencodings.h>
#include <hash.h>
#include <validationinterface.h>
#include <versionbitsinfo.h>
#include <warnings.h>
#include <assert.h>
#include <stdint.h>
#include <univalue.h>
#include <boost/algorithm/string.hpp>
#include <boost/thread/thread.hpp> // boost::thread::interrupt
#include <memory>
#include <mutex>
#include <condition_variable>
struct CUpdatedBlock
{
uint256 hash;
int height;
};
static Mutex cs_blockchange;
static std::condition_variable cond_blockchange;
static CUpdatedBlock latestblock;
/* Calculate the difficulty for a given block index.
*/
double GetDifficulty(const CBlockIndex* blockindex)
{
if (blockindex == nullptr)
{
return 1.0;
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
AssertLockHeld(cs_main);
UniValue result(UniValue::VOBJ);
result.pushKV("hash", blockindex->GetBlockHash().GetHex());
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.pushKV("confirmations", confirmations);
result.pushKV("height", blockindex->nHeight);
result.pushKV("version", blockindex->nVersion);
result.pushKV("versionHex", strprintf("%08x", blockindex->nVersion));
result.pushKV("merkleroot", blockindex->hashMerkleRoot.GetHex());
result.pushKV("time", (int64_t)blockindex->nTime);
result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast());
result.pushKV("nonce", (uint64_t)blockindex->nNonce);
result.pushKV("bits", strprintf("%08x", blockindex->nBits));
result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex->nChainWork.GetHex());
result.pushKV("nTx", (uint64_t)blockindex->nTx);
if (blockindex->pprev)
result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex());
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails)
{
AssertLockHeld(cs_main);
UniValue result(UniValue::VOBJ);
result.pushKV("hash", blockindex->GetBlockHash().GetHex());
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.pushKV("confirmations", confirmations);
result.pushKV("strippedsize", (int)::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS));
result.pushKV("size", (int)::GetSerializeSize(block, PROTOCOL_VERSION));
result.pushKV("weight", (int)::GetBlockWeight(block));
result.pushKV("height", blockindex->nHeight);
result.pushKV("version", block.nVersion);
result.pushKV("versionHex", strprintf("%08x", block.nVersion));
result.pushKV("merkleroot", block.hashMerkleRoot.GetHex());
UniValue txs(UniValue::VARR);
for(const auto& tx : block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToUniv(*tx, uint256(), objTx, true, RPCSerializationFlags());
txs.push_back(objTx);
}
else
txs.push_back(tx->GetHash().GetHex());
}
result.pushKV("tx", txs);
result.pushKV("time", block.GetBlockTime());
result.pushKV("mediantime", (int64_t)blockindex->GetMedianTimePast());
result.pushKV("nonce", (uint64_t)block.nNonce);
result.pushKV("bits", strprintf("%08x", block.nBits));
result.pushKV("difficulty", GetDifficulty(blockindex));
result.pushKV("chainwork", blockindex->nChainWork.GetHex());
result.pushKV("nTx", (uint64_t)blockindex->nTx);
if (blockindex->pprev)
result.pushKV("previousblockhash", blockindex->pprev->GetBlockHash().GetHex());
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.pushKV("nextblockhash", pnext->GetBlockHash().GetHex());
return result;
}
static UniValue getblockcount(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the longest blockchain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n"
+ HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
);
LOCK(cs_main);
return chainActive.Height();
}
static UniValue getbestblockhash(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest blockchain.\n"
"\nResult:\n"
"\"hex\" (string) the block hash, hex-encoded\n"
"\nExamples:\n"
+ HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex)
{
if(pindex) {
std::lock_guard<std::mutex> lock(cs_blockchange);
latestblock.hash = pindex->GetBlockHash();
latestblock.height = pindex->nHeight;
}
cond_blockchange.notify_all();
}
static UniValue waitfornewblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"waitfornewblock (timeout)\n"
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitfornewblock", "1000")
+ HelpExampleRpc("waitfornewblock", "1000")
);
int timeout = 0;
if (!request.params[0].isNull())
timeout = request.params[0].get_int();
CUpdatedBlock block;
{
WAIT_LOCK(cs_blockchange, lock);
block = latestblock;
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
else
cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("hash", block.hash.GetHex());
ret.pushKV("height", block.height);
return ret;
}
static UniValue waitforblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"waitforblock <blockhash> (timeout)\n"
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. \"blockhash\" (required, string) Block hash to wait for.\n"
"2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
+ HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
);
int timeout = 0;
uint256 hash(ParseHashV(request.params[0], "blockhash"));
if (!request.params[1].isNull())
timeout = request.params[1].get_int();
CUpdatedBlock block;
{
WAIT_LOCK(cs_blockchange, lock);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("hash", block.hash.GetHex());
ret.pushKV("height", block.height);
return ret;
}
static UniValue waitforblockheight(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"waitforblockheight <height> (timeout)\n"
"\nWaits for (at least) block height and returns the height and hash\n"
"of the current tip.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. height (required, int) Block height to wait for (int)\n"
"2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitforblockheight", "\"100\", 1000")
+ HelpExampleRpc("waitforblockheight", "\"100\", 1000")
);
int timeout = 0;
int height = request.params[0].get_int();
if (!request.params[1].isNull())
timeout = request.params[1].get_int();
CUpdatedBlock block;
{
WAIT_LOCK(cs_blockchange, lock);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.pushKV("hash", block.hash.GetHex());
ret.pushKV("height", block.height);
return ret;
}
static UniValue syncwithvalidationinterfacequeue(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 0) {
throw std::runtime_error(
"syncwithvalidationinterfacequeue\n"
"\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n"
"\nExamples:\n"
+ HelpExampleCli("syncwithvalidationinterfacequeue","")
+ HelpExampleRpc("syncwithvalidationinterfacequeue","")
);
}
SyncWithValidationInterfaceQueue();
return NullUniValue;
}
static UniValue getdifficulty(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n"
+ HelpExampleCli("getdifficulty", "")
+ HelpExampleRpc("getdifficulty", "")
);
LOCK(cs_main);
return GetDifficulty(chainActive.Tip());
}
static std::string EntryDescriptionString()
{
return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + " (DEPRECATED)\n"
" \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority (DEPRECATED)\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
" \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n"
" \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) (DEPRECATED)\n"
" \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
" \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n"
" \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) (DEPRECATED)\n"
" \"wtxid\" : hash, (string) hash of serialized transaction, including witness data\n"
" \"fees\" : {\n"
" \"base\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"modified\" : n, (numeric) transaction fee with fee deltas used for mining priority in " + CURRENCY_UNIT + "\n"
" \"ancestor\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one) in " + CURRENCY_UNIT + "\n"
" \"descendant\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one) in " + CURRENCY_UNIT + "\n"
" }\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n"
" \"spentby\" : [ (array) unconfirmed transactions spending outputs from this transaction\n"
" \"transactionid\", (string) child transaction id\n"
" ... ]\n"
" \"bip125-replaceable\" : true|false, (boolean) Whether this transaction could be replaced due to BIP125 (replace-by-fee)\n";
}
static void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCKS_REQUIRED(::mempool.cs)
{
AssertLockHeld(mempool.cs);
UniValue fees(UniValue::VOBJ);
fees.pushKV("base", ValueFromAmount(e.GetFee()));
fees.pushKV("modified", ValueFromAmount(e.GetModifiedFee()));
fees.pushKV("ancestor", ValueFromAmount(e.GetModFeesWithAncestors()));
fees.pushKV("descendant", ValueFromAmount(e.GetModFeesWithDescendants()));
info.pushKV("fees", fees);
info.pushKV("size", (int)e.GetTxSize());
info.pushKV("fee", ValueFromAmount(e.GetFee()));
info.pushKV("modifiedfee", ValueFromAmount(e.GetModifiedFee()));
info.pushKV("time", e.GetTime());
info.pushKV("height", (int)e.GetHeight());
info.pushKV("descendantcount", e.GetCountWithDescendants());
info.pushKV("descendantsize", e.GetSizeWithDescendants());
info.pushKV("descendantfees", e.GetModFeesWithDescendants());
info.pushKV("ancestorcount", e.GetCountWithAncestors());
info.pushKV("ancestorsize", e.GetSizeWithAncestors());
info.pushKV("ancestorfees", e.GetModFeesWithAncestors());
info.pushKV("wtxid", mempool.vTxHashes[e.vTxHashesIdx].first.ToString());
const CTransaction& tx = e.GetTx();
std::set<std::string> setDepends;
for (const CTxIn& txin : tx.vin)
{
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
for (const std::string& dep : setDepends)
{
depends.push_back(dep);
}
info.pushKV("depends", depends);
UniValue spent(UniValue::VARR);
const CTxMemPool::txiter &it = mempool.mapTx.find(tx.GetHash());
const CTxMemPool::setEntries &setChildren = mempool.GetMemPoolChildren(it);
for (CTxMemPool::txiter childiter : setChildren) {
spent.push_back(childiter->GetTx().GetHash().ToString());
}
info.pushKV("spentby", spent);
// Add opt-in RBF status
bool rbfStatus = false;
RBFTransactionState rbfState = IsRBFOptIn(tx, mempool);
if (rbfState == RBFTransactionState::UNKNOWN) {
throw JSONRPCError(RPC_MISC_ERROR, "Transaction is not in mempool");
} else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125) {
rbfStatus = true;
}
info.pushKV("bip125-replaceable", rbfStatus);
}
UniValue mempoolToJSON(bool fVerbose)
{
if (fVerbose)
{
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
for (const CTxMemPoolEntry& e : mempool.mapTx)
{
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.pushKV(hash.ToString(), info);
}
return o;
}
else
{
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
for (const uint256& hash : vtxid)
a.push_back(hash.ToString());
return a;
}
}
static UniValue getrawmempool(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw std::runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
);
bool fVerbose = false;
if (!request.params[0].isNull())
fVerbose = request.params[0].get_bool();
return mempoolToJSON(fVerbose);
}
static UniValue getmempoolancestors(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
"getmempoolancestors txid ( verbose )\n"
"\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
"\nResult (for verbose = false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolancestors", "\"mytxid\"")
+ HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
);
}
bool fVerbose = false;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setAncestors;
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
if (!fVerbose) {
UniValue o(UniValue::VARR);
for (CTxMemPool::txiter ancestorIt : setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter ancestorIt : setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.pushKV(_hash.ToString(), info);
}
return o;
}
}
static UniValue getmempooldescendants(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw std::runtime_error(
"getmempooldescendants txid ( verbose )\n"
"\nIf txid is in the mempool, returns all in-mempool descendants.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n"
"\nResult (for verbose = false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempooldescendants", "\"mytxid\"")
+ HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
);
}
bool fVerbose = false;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setDescendants;
mempool.CalculateDescendants(it, setDescendants);
// CTxMemPool::CalculateDescendants will include the given tx
setDescendants.erase(it);
if (!fVerbose) {
UniValue o(UniValue::VARR);
for (CTxMemPool::txiter descendantIt : setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
for (CTxMemPool::txiter descendantIt : setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& _hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.pushKV(_hash.ToString(), info);
}
return o;
}
}
static UniValue getmempoolentry(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
"getmempoolentry txid\n"
"\nReturns mempool data for given transaction\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"\nResult:\n"
"{ (json object)\n"
+ EntryDescriptionString()
+ "}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolentry", "\"mytxid\"")
+ HelpExampleRpc("getmempoolentry", "\"mytxid\"")
);
}
uint256 hash = ParseHashV(request.params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
const CTxMemPoolEntry &e = *it;
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
return info;
}
static UniValue getblockhash(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"getblockhash height\n"
"\nReturns hash of block in best-block-chain at height provided.\n"
"\nArguments:\n"
"1. height (numeric, required) The height index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = request.params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
static UniValue getblockheader(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex-encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"nTx\" : n, (numeric) The number of transactions in the block.\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
uint256 hash(ParseHashV(request.params[0], "hash"));
bool fVerbose = true;
if (!request.params[1].isNull())
fVerbose = request.params[1].get_bool();
const CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
static CBlock GetBlockChecked(const CBlockIndex* pblockindex)
{
CBlock block;
if (IsBlockPruned(pblockindex)) {
throw JSONRPCError(RPC_MISC_ERROR, "Block not available (pruned data)");
}
if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) {
// Block not found on disk. This could be because we have the block
// header in our index but don't have the block (for example if a
// non-whitelisted node sends us an unrequested long chain of valid
// blocks, we add the headers to our index, but don't accept the
// block).
throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
}
return block;
}
static UniValue getblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"getblock \"blockhash\" ( verbosity ) \n"
"\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbosity is 1, returns an Object with information about block <hash>.\n"
"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) The block hash\n"
"2. verbosity (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n"
"\nResult (for verbosity = 0):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nResult (for verbosity = 1):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
" \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"nTx\" : n, (numeric) The number of transactions in the block.\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbosity = 2):\n"
"{\n"
" ..., Same output as verbosity = 1.\n"
" \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
" ,...\n"
" ],\n"
" ,... Same output as verbosity = 1.\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
int verbosity = 1;
if (!request.params[1].isNull()) {
if(request.params[1].isNum())
verbosity = request.params[1].get_int();
else
verbosity = request.params[1].get_bool() ? 1 : 0;
}
const CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
const CBlock block = GetBlockChecked(pblockindex);
if (verbosity <= 0)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex, verbosity >= 2);
}
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64_t nTransactions;
uint64_t nTransactionOutputs;
uint64_t nBogoSize;
uint256 hashSerialized;
uint64_t nDiskSize;
CAmount nTotalAmount;
CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {}
};
static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
ss << hash;
ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase ? 1u : 0u);
stats.nTransactions++;
for (const auto& output : outputs) {
ss << VARINT(output.first + 1);
ss << output.second.out.scriptPubKey;
ss << VARINT(output.second.out.nValue, VarIntMode::NONNEGATIVE_SIGNED);
stats.nTransactionOutputs++;
stats.nTotalAmount += output.second.out.nValue;
stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ +
2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */;
}
ss << VARINT(0u);
}
//! Calculate statistics about the unspent transaction output set
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
{
std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
assert(pcursor);
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
stats.nHeight = LookupBlockIndex(stats.hashBlock)->nHeight;
}
ss << stats.hashBlock;
uint256 prevkey;
std::map<uint32_t, Coin> outputs;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
COutPoint key;
Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, ss, prevkey, outputs);
outputs.clear();
}
prevkey = key.hash;
outputs[key.n] = std::move(coin);
} else {
return error("%s: unable to read value", __func__);
}
pcursor->Next();
}
if (!outputs.empty()) {
ApplyStats(stats, ss, prevkey, outputs);
}
stats.hashSerialized = ss.GetHash();
stats.nDiskSize = view->EstimateSize();
return true;
}
static UniValue pruneblockchain(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"pruneblockchain\n"
"\nArguments:\n"
"1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n"
" to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n"
"\nResult:\n"
"n (numeric) Height of the last block pruned.\n"
"\nExamples:\n"
+ HelpExampleCli("pruneblockchain", "1000")
+ HelpExampleRpc("pruneblockchain", "1000"));
if (!fPruneMode)
throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode.");
LOCK(cs_main);
int heightParam = request.params[0].get_int();
if (heightParam < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height.");
// Height value more than a billion is too high to be a block height, and
// too low to be a block time (corresponds to timestamp from Sep 2001).
if (heightParam > 1000000000) {
// Add a 2 hour buffer to include blocks which might have had old timestamps
CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW);
if (!pindex) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp.");
}
heightParam = pindex->nHeight;
}
unsigned int height = (unsigned int) heightParam;
unsigned int chainHeight = (unsigned int) chainActive.Height();
if (chainHeight < Params().PruneAfterHeight())
throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning.");
else if (height > chainHeight)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height.");
else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) {
LogPrint(BCLog::RPC, "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks.\n");
height = chainHeight - MIN_BLOCKS_TO_KEEP;
}
PruneBlockFilesManual(height);
return uint64_t(height);
}
static UniValue gettxoutsetinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n"
" \"transactions\": n, (numeric) The number of transactions with unspent outputs\n"
" \"txouts\": n, (numeric) The number of unspent transaction outputs\n"
" \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n"
" \"hash_serialized_2\": \"hash\", (string) The serialized hash\n"
" \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutsetinfo", "")
+ HelpExampleRpc("gettxoutsetinfo", "")
);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (GetUTXOStats(pcoinsdbview.get(), stats)) {
ret.pushKV("height", (int64_t)stats.nHeight);
ret.pushKV("bestblock", stats.hashBlock.GetHex());
ret.pushKV("transactions", (int64_t)stats.nTransactions);
ret.pushKV("txouts", (int64_t)stats.nTransactionOutputs);
ret.pushKV("bogosize", (int64_t)stats.nBogoSize);
ret.pushKV("hash_serialized_2", stats.hashSerialized.GetHex());
ret.pushKV("disk_size", stats.nDiskSize);
ret.pushKV("total_amount", ValueFromAmount(stats.nTotalAmount));
} else {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set");
}
return ret;
}
UniValue gettxout(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
throw std::runtime_error(
"gettxout \"txid\" n ( include_mempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"n\" (numeric, required) vout number\n"
"3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true."
" Note that an unspent output that is spent in the mempool won't appear.\n"
"\nResult:\n"
"{\n"
" \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of bitcoin addresses\n"
" \"address\" (string) bitcoin address\n"
" ,...\n"
" ]\n"
" },\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
uint256 hash(ParseHashV(request.params[0], "txid"));
int n = request.params[1].get_int();
COutPoint out(hash, n);
bool fMempool = true;
if (!request.params[2].isNull())
fMempool = request.params[2].get_bool();
Coin coin;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip.get(), mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
return NullUniValue;
}
} else {
if (!pcoinsTip->GetCoin(out, coin)) {
return NullUniValue;
}
}
const CBlockIndex* pindex = LookupBlockIndex(pcoinsTip->GetBestBlock());
ret.pushKV("bestblock", pindex->GetBlockHash().GetHex());
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.pushKV("confirmations", 0);
} else {
ret.pushKV("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1));
}
ret.pushKV("value", ValueFromAmount(coin.out.nValue));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true);
ret.pushKV("scriptPubKey", o);
ret.pushKV("coinbase", (bool)coin.fCoinBase);
return ret;
}
static UniValue verifychain(const JSONRPCRequest& request)
{
int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
"verifychain ( checklevel nblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
"2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
+ HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
);
LOCK(cs_main);
if (!request.params[0].isNull())
nCheckLevel = request.params[0].get_int();
if (!request.params[1].isNull())
nCheckDepth = request.params[1].get_int();
return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth);
}
/** Implementation of IsSuperMajority with better feedback */
static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
bool activated = false;
switch(version)
{
case 2:
activated = pindex->nHeight >= consensusParams.BIP34Height;
break;
case 3:
activated = pindex->nHeight >= consensusParams.BIP66Height;
break;
case 4:
activated = pindex->nHeight >= consensusParams.BIP65Height;
break;
}
rv.pushKV("status", activated);
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
rv.pushKV("id", name);
rv.pushKV("version", version);
rv.pushKV("reject", SoftForkMajorityDesc(version, pindex, consensusParams));
return rv;
}
static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
UniValue rv(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case ThresholdState::DEFINED: rv.pushKV("status", "defined"); break;
case ThresholdState::STARTED: rv.pushKV("status", "started"); break;
case ThresholdState::LOCKED_IN: rv.pushKV("status", "locked_in"); break;
case ThresholdState::ACTIVE: rv.pushKV("status", "active"); break;
case ThresholdState::FAILED: rv.pushKV("status", "failed"); break;
}
if (ThresholdState::STARTED == thresholdState)
{
rv.pushKV("bit", consensusParams.vDeployments[id].bit);
}
rv.pushKV("startTime", consensusParams.vDeployments[id].nStartTime);
rv.pushKV("timeout", consensusParams.vDeployments[id].nTimeout);
rv.pushKV("since", VersionBitsTipStateSinceHeight(consensusParams, id));
if (ThresholdState::STARTED == thresholdState)
{
UniValue statsUV(UniValue::VOBJ);
BIP9Stats statsStruct = VersionBitsTipStatistics(consensusParams, id);
statsUV.pushKV("period", statsStruct.period);
statsUV.pushKV("threshold", statsStruct.threshold);
statsUV.pushKV("elapsed", statsStruct.elapsed);
statsUV.pushKV("count", statsStruct.count);
statsUV.pushKV("possible", statsStruct.possible);
rv.pushKV("statistics", statsUV);
}
return rv;
}
static void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
// Deployments with timeout value of 0 are hidden.
// A timeout value of 0 guarantees a softfork will never be activated.
// This is used when softfork codes are merged without specifying the deployment schedule.
if (consensusParams.vDeployments[id].nTimeout > 0)
bip9_softforks.pushKV(VersionBitsDeploymentInfo[id].name, BIP9SoftForkDesc(consensusParams, id));
}
UniValue getblockchaininfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding blockchain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n"
" \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
" \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored (only present if pruning is enabled)\n"
" \"automatic_pruning\": xx, (boolean) whether automatic pruning is enabled (only present if pruning is enabled)\n"
" \"prune_target_size\": xxxxxx, (numeric) the target size used by pruning (only present if automatic pruning is enabled)\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"reject\": { (object) progress toward rejecting pre-softfork blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" },\n"
" }, ...\n"
" ],\n"
" \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
" \"xxxx\" : { (string) name of the softfork\n"
" \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
" \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
" \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
" \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
" \"since\": xx, (numeric) height of the first block to which the status applies\n"
" \"statistics\": { (object) numeric statistics about BIP9 signalling for a softfork (only for \"started\" status)\n"
" \"period\": xx, (numeric) the length in blocks of the BIP9 signalling period \n"
" \"threshold\": xx, (numeric) the number of blocks with the version bit set required to activate the feature \n"
" \"elapsed\": xx, (numeric) the number of blocks elapsed since the beginning of the current period \n"
" \"count\": xx, (numeric) the number of blocks with the version bit set in the current period \n"
" \"possible\": xx (boolean) returns false if there are not enough blocks left in this period to pass activation threshold \n"
" }\n"
" }\n"
" }\n"
" \"warnings\" : \"...\", (string) any network and blockchain warnings.\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.pushKV("chain", Params().NetworkIDString());
obj.pushKV("blocks", (int)chainActive.Height());
obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1);
obj.pushKV("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex());
obj.pushKV("difficulty", (double)GetDifficulty(chainActive.Tip()));
obj.pushKV("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast());
obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip()));
obj.pushKV("initialblockdownload", IsInitialBlockDownload());
obj.pushKV("chainwork", chainActive.Tip()->nChainWork.GetHex());
obj.pushKV("size_on_disk", CalculateCurrentUsage());
obj.pushKV("pruned", fPruneMode);
if (fPruneMode) {
CBlockIndex* block = chainActive.Tip();
assert(block);
while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) {
block = block->pprev;
}
obj.pushKV("pruneheight", block->nHeight);
// if 0, execution bypasses the whole if block.
bool automatic_pruning = (gArgs.GetArg("-prune", 0) != 1);
obj.pushKV("automatic_pruning", automatic_pruning);
if (automatic_pruning) {
obj.pushKV("prune_target_size", nPruneTarget);
}
}
const Consensus::Params& consensusParams = Params().GetConsensus();
CBlockIndex* tip = chainActive.Tip();
UniValue softforks(UniValue::VARR);
UniValue bip9_softforks(UniValue::VOBJ);
softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
for (int pos = Consensus::DEPLOYMENT_CSV; pos != Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++pos) {
BIP9SoftForkDescPushBack(bip9_softforks, consensusParams, static_cast<Consensus::DeploymentPos>(pos));
}
obj.pushKV("softforks", softforks);
obj.pushKV("bip9_softforks", bip9_softforks);
obj.pushKV("warnings", GetWarnings("statusbar"));
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight
{
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
static UniValue getchaintips(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getchaintips\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
);
LOCK(cs_main);
/*
* Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
* Algorithm:
* - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
* - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
* - add chainActive.Tip()
*/
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
std::set<const CBlockIndex*> setOrphans;
std::set<const CBlockIndex*> setPrevs;
for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex)
{
if (!chainActive.Contains(item.second)) {
setOrphans.insert(item.second);
setPrevs.insert(item.second->pprev);
}
}
for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
{
if (setPrevs.erase(*it) == 0) {
setTips.insert(*it);
}
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
/* Construct the output array. */
UniValue res(UniValue::VARR);
for (const CBlockIndex* block : setTips)
{
UniValue obj(UniValue::VOBJ);
obj.pushKV("height", block->nHeight);
obj.pushKV("hash", block->phashBlock->GetHex());
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
obj.pushKV("branchlen", branchLen);
std::string status;
if (chainActive.Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.pushKV("status", status);
res.push_back(obj);
}
return res;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.pushKV("size", (int64_t) mempool.size());
ret.pushKV("bytes", (int64_t) mempool.GetTotalTxSize());
ret.pushKV("usage", (int64_t) mempool.DynamicMemoryUsage());
size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.pushKV("maxmempool", (int64_t) maxmempool);
ret.pushKV("mempoolminfee", ValueFromAmount(std::max(mempool.GetMinFee(maxmempool), ::minRelayTxFee).GetFeePerK()));
ret.pushKV("minrelaytxfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()));
return ret;
}
static UniValue getmempoolinfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
" \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n"
" \"minrelaytxfee\": xxxxx (numeric) Current minimum relay fee for transactions\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
);
return mempoolInfoToJSON();
}
static UniValue preciousblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"preciousblock \"blockhash\"\n"
"\nTreats a block as if it were received before others with the same work.\n"
"\nA later preciousblock call can override the effect of an earlier one.\n"
"\nThe effects of preciousblock are not retained across restarts.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) the hash of the block to mark as precious\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("preciousblock", "\"blockhash\"")
+ HelpExampleRpc("preciousblock", "\"blockhash\"")
);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
CBlockIndex* pblockindex;
{
LOCK(cs_main);
pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
}
CValidationState state;
PreciousBlock(state, Params(), pblockindex);
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue invalidateblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"invalidateblock \"blockhash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
CValidationState state;
{
LOCK(cs_main);
CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
InvalidateBlock(state, Params(), pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state, Params());
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue reconsiderblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"reconsiderblock \"blockhash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) the hash of the block to reconsider\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("reconsiderblock", "\"blockhash\"")
+ HelpExampleRpc("reconsiderblock", "\"blockhash\"")
);
uint256 hash(ParseHashV(request.params[0], "blockhash"));
{
LOCK(cs_main);
CBlockIndex* pblockindex = LookupBlockIndex(hash);
if (!pblockindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
ResetBlockFailureFlags(pblockindex);
}
CValidationState state;
ActivateBestChain(state, Params());
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, FormatStateMessage(state));
}
return NullUniValue;
}
static UniValue getchaintxstats(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 2)
throw std::runtime_error(
"getchaintxstats ( nblocks blockhash )\n"
"\nCompute statistics about the total number and rate of transactions in the chain.\n"
"\nArguments:\n"
"1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n"
"2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n"
"\nResult:\n"
"{\n"
" \"time\": xxxxx, (numeric) The timestamp for the final block in the window in UNIX format.\n"
" \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n"
" \"window_final_block_hash\": \"...\", (string) The hash of the final block in the window.\n"
" \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n"
" \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n"
" \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n"
" \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintxstats", "")
+ HelpExampleRpc("getchaintxstats", "2016")
);
const CBlockIndex* pindex;
int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month
if (request.params[1].isNull()) {
LOCK(cs_main);
pindex = chainActive.Tip();
} else {
uint256 hash(ParseHashV(request.params[1], "blockhash"));
LOCK(cs_main);
pindex = LookupBlockIndex(hash);
if (!pindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!chainActive.Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain");
}
}
assert(pindex != nullptr);
if (request.params[0].isNull()) {
blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1));
} else {
blockcount = request.params[0].get_int();
if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1");
}
}
const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount);
int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast();
int nTxDiff = pindex->nChainTx - pindexPast->nChainTx;
UniValue ret(UniValue::VOBJ);
ret.pushKV("time", (int64_t)pindex->nTime);
ret.pushKV("txcount", (int64_t)pindex->nChainTx);
ret.pushKV("window_final_block_hash", pindex->GetBlockHash().GetHex());
ret.pushKV("window_block_count", blockcount);
if (blockcount > 0) {
ret.pushKV("window_tx_count", nTxDiff);
ret.pushKV("window_interval", nTimeDiff);
if (nTimeDiff > 0) {
ret.pushKV("txrate", ((double)nTxDiff) / nTimeDiff);
}
}
return ret;
}
template<typename T>
static T CalculateTruncatedMedian(std::vector<T>& scores)
{
size_t size = scores.size();
if (size == 0) {
return 0;
}
std::sort(scores.begin(), scores.end());
if (size % 2 == 0) {
return (scores[size / 2 - 1] + scores[size / 2]) / 2;
} else {
return scores[size / 2];
}
}
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight)
{
if (scores.empty()) {
return;
}
std::sort(scores.begin(), scores.end());
// 10th, 25th, 50th, 75th, and 90th percentile weight units.
const double weights[NUM_GETBLOCKSTATS_PERCENTILES] = {
total_weight / 10.0, total_weight / 4.0, total_weight / 2.0, (total_weight * 3.0) / 4.0, (total_weight * 9.0) / 10.0
};
int64_t next_percentile_index = 0;
int64_t cumulative_weight = 0;
for (const auto& element : scores) {
cumulative_weight += element.second;
while (next_percentile_index < NUM_GETBLOCKSTATS_PERCENTILES && cumulative_weight >= weights[next_percentile_index]) {
result[next_percentile_index] = element.first;
++next_percentile_index;
}
}
// Fill any remaining percentiles with the last value.
for (int64_t i = next_percentile_index; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
result[i] = scores.back().first;
}
}
template<typename T>
static inline bool SetHasKeys(const std::set<T>& set) {return false;}
template<typename T, typename Tk, typename... Args>
static inline bool SetHasKeys(const std::set<T>& set, const Tk& key, const Args&... args)
{
return (set.count(key) != 0) || SetHasKeys(set, args...);
}
// outpoint (needed for the utxo index) + nHeight + fCoinBase
static constexpr size_t PER_UTXO_OVERHEAD = sizeof(COutPoint) + sizeof(uint32_t) + sizeof(bool);
static UniValue getblockstats(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) {
throw std::runtime_error(
"getblockstats hash_or_height ( stats )\n"
"\nCompute per block statistics for a given window. All amounts are in satoshis.\n"
"It won't work for some heights with pruning.\n"
"It won't work without -txindex for utxo_size_inc, *fee or *feerate stats.\n"
"\nArguments:\n"
"1. \"hash_or_height\" (string or numeric, required) The block hash or height of the target block\n"
"2. \"stats\" (array, optional) Values to plot, by default all values (see result below)\n"
" [\n"
" \"height\", (string, optional) Selected statistic\n"
" \"time\", (string, optional) Selected statistic\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"{ (json object)\n"
" \"avgfee\": xxxxx, (numeric) Average fee in the block\n"
" \"avgfeerate\": xxxxx, (numeric) Average feerate (in satoshis per virtual byte)\n"
" \"avgtxsize\": xxxxx, (numeric) Average transaction size\n"
" \"blockhash\": xxxxx, (string) The block hash (to check for potential reorgs)\n"
" \"feerate_percentiles\": [ (array of numeric) Feerates at the 10th, 25th, 50th, 75th, and 90th percentile weight unit (in satoshis per virtual byte)\n"
" \"10th_percentile_feerate\", (numeric) The 10th percentile feerate\n"
" \"25th_percentile_feerate\", (numeric) The 25th percentile feerate\n"
" \"50th_percentile_feerate\", (numeric) The 50th percentile feerate\n"
" \"75th_percentile_feerate\", (numeric) The 75th percentile feerate\n"
" \"90th_percentile_feerate\", (numeric) The 90th percentile feerate\n"
" ],\n"
" \"height\": xxxxx, (numeric) The height of the block\n"
" \"ins\": xxxxx, (numeric) The number of inputs (excluding coinbase)\n"
" \"maxfee\": xxxxx, (numeric) Maximum fee in the block\n"
" \"maxfeerate\": xxxxx, (numeric) Maximum feerate (in satoshis per virtual byte)\n"
" \"maxtxsize\": xxxxx, (numeric) Maximum transaction size\n"
" \"medianfee\": xxxxx, (numeric) Truncated median fee in the block\n"
" \"mediantime\": xxxxx, (numeric) The block median time past\n"
" \"mediantxsize\": xxxxx, (numeric) Truncated median transaction size\n"
" \"minfee\": xxxxx, (numeric) Minimum fee in the block\n"
" \"minfeerate\": xxxxx, (numeric) Minimum feerate (in satoshis per virtual byte)\n"
" \"mintxsize\": xxxxx, (numeric) Minimum transaction size\n"
" \"outs\": xxxxx, (numeric) The number of outputs\n"
" \"subsidy\": xxxxx, (numeric) The block subsidy\n"
" \"swtotal_size\": xxxxx, (numeric) Total size of all segwit transactions\n"
" \"swtotal_weight\": xxxxx, (numeric) Total weight of all segwit transactions divided by segwit scale factor (4)\n"
" \"swtxs\": xxxxx, (numeric) The number of segwit transactions\n"
" \"time\": xxxxx, (numeric) The block time\n"
" \"total_out\": xxxxx, (numeric) Total amount in all outputs (excluding coinbase and thus reward [ie subsidy + totalfee])\n"
" \"total_size\": xxxxx, (numeric) Total size of all non-coinbase transactions\n"
" \"total_weight\": xxxxx, (numeric) Total weight of all non-coinbase transactions divided by segwit scale factor (4)\n"
" \"totalfee\": xxxxx, (numeric) The fee total\n"
" \"txs\": xxxxx, (numeric) The number of transactions (excluding coinbase)\n"
" \"utxo_increase\": xxxxx, (numeric) The increase/decrease in the number of unspent outputs\n"
" \"utxo_size_inc\": xxxxx, (numeric) The increase/decrease in size for the utxo index (not discounting op_return and similar)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'")
+ HelpExampleRpc("getblockstats", "1000 '[\"minfeerate\",\"avgfeerate\"]'")
);
}
LOCK(cs_main);
CBlockIndex* pindex;
if (request.params[0].isNum()) {
const int height = request.params[0].get_int();
const int current_tip = chainActive.Height();
if (height < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height));
}
if (height > current_tip) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip));
}
pindex = chainActive[height];
} else {
const uint256 hash(ParseHashV(request.params[0], "hash_or_height"));
pindex = LookupBlockIndex(hash);
if (!pindex) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
}
if (!chainActive.Contains(pindex)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString()));
}
}
assert(pindex != nullptr);
std::set<std::string> stats;
if (!request.params[1].isNull()) {
const UniValue stats_univalue = request.params[1].get_array();
for (unsigned int i = 0; i < stats_univalue.size(); i++) {
const std::string stat = stats_univalue[i].get_str();
stats.insert(stat);
}
}
const CBlock block = GetBlockChecked(pindex);
const bool do_all = stats.size() == 0; // Calculate everything if nothing selected (default)
const bool do_mediantxsize = do_all || stats.count("mediantxsize") != 0;
const bool do_medianfee = do_all || stats.count("medianfee") != 0;
const bool do_feerate_percentiles = do_all || stats.count("feerate_percentiles") != 0;
const bool loop_inputs = do_all || do_medianfee || do_feerate_percentiles ||
SetHasKeys(stats, "utxo_size_inc", "totalfee", "avgfee", "avgfeerate", "minfee", "maxfee", "minfeerate", "maxfeerate");
const bool loop_outputs = do_all || loop_inputs || stats.count("total_out");
const bool do_calculate_size = do_mediantxsize ||
SetHasKeys(stats, "total_size", "avgtxsize", "mintxsize", "maxtxsize", "swtotal_size");
const bool do_calculate_weight = do_all || SetHasKeys(stats, "total_weight", "avgfeerate", "swtotal_weight", "avgfeerate", "feerate_percentiles", "minfeerate", "maxfeerate");
const bool do_calculate_sw = do_all || SetHasKeys(stats, "swtxs", "swtotal_size", "swtotal_weight");
CAmount maxfee = 0;
CAmount maxfeerate = 0;
CAmount minfee = MAX_MONEY;
CAmount minfeerate = MAX_MONEY;
CAmount total_out = 0;
CAmount totalfee = 0;
int64_t inputs = 0;
int64_t maxtxsize = 0;
int64_t mintxsize = MAX_BLOCK_SERIALIZED_SIZE;
int64_t outputs = 0;
int64_t swtotal_size = 0;
int64_t swtotal_weight = 0;
int64_t swtxs = 0;
int64_t total_size = 0;
int64_t total_weight = 0;
int64_t utxo_size_inc = 0;
std::vector<CAmount> fee_array;
std::vector<std::pair<CAmount, int64_t>> feerate_array;
std::vector<int64_t> txsize_array;
for (const auto& tx : block.vtx) {
outputs += tx->vout.size();
CAmount tx_total_out = 0;
if (loop_outputs) {
for (const CTxOut& out : tx->vout) {
tx_total_out += out.nValue;
utxo_size_inc += GetSerializeSize(out, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
}
}
if (tx->IsCoinBase()) {
continue;
}
inputs += tx->vin.size(); // Don't count coinbase's fake input
total_out += tx_total_out; // Don't count coinbase reward
int64_t tx_size = 0;
if (do_calculate_size) {
tx_size = tx->GetTotalSize();
if (do_mediantxsize) {
txsize_array.push_back(tx_size);
}
maxtxsize = std::max(maxtxsize, tx_size);
mintxsize = std::min(mintxsize, tx_size);
total_size += tx_size;
}
int64_t weight = 0;
if (do_calculate_weight) {
weight = GetTransactionWeight(*tx);
total_weight += weight;
}
if (do_calculate_sw && tx->HasWitness()) {
++swtxs;
swtotal_size += tx_size;
swtotal_weight += weight;
}
if (loop_inputs) {
if (!g_txindex) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "One or more of the selected stats requires -txindex enabled");
}
CAmount tx_total_in = 0;
for (const CTxIn& in : tx->vin) {
CTransactionRef tx_in;
uint256 hashBlock;
if (!GetTransaction(in.prevout.hash, tx_in, Params().GetConsensus(), hashBlock, false)) {
throw JSONRPCError(RPC_INTERNAL_ERROR, std::string("Unexpected internal error (tx index seems corrupt)"));
}
CTxOut prevoutput = tx_in->vout[in.prevout.n];
tx_total_in += prevoutput.nValue;
utxo_size_inc -= GetSerializeSize(prevoutput, PROTOCOL_VERSION) + PER_UTXO_OVERHEAD;
}
CAmount txfee = tx_total_in - tx_total_out;
assert(MoneyRange(txfee));
if (do_medianfee) {
fee_array.push_back(txfee);
}
maxfee = std::max(maxfee, txfee);
minfee = std::min(minfee, txfee);
totalfee += txfee;
// New feerate uses satoshis per virtual byte instead of per serialized byte
CAmount feerate = weight ? (txfee * WITNESS_SCALE_FACTOR) / weight : 0;
if (do_feerate_percentiles) {
feerate_array.emplace_back(std::make_pair(feerate, weight));
}
maxfeerate = std::max(maxfeerate, feerate);
minfeerate = std::min(minfeerate, feerate);
}
}
CAmount feerate_percentiles[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
CalculatePercentilesByWeight(feerate_percentiles, feerate_array, total_weight);
UniValue feerates_res(UniValue::VARR);
for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
feerates_res.push_back(feerate_percentiles[i]);
}
UniValue ret_all(UniValue::VOBJ);
ret_all.pushKV("avgfee", (block.vtx.size() > 1) ? totalfee / (block.vtx.size() - 1) : 0);
ret_all.pushKV("avgfeerate", total_weight ? (totalfee * WITNESS_SCALE_FACTOR) / total_weight : 0); // Unit: sat/vbyte
ret_all.pushKV("avgtxsize", (block.vtx.size() > 1) ? total_size / (block.vtx.size() - 1) : 0);
ret_all.pushKV("blockhash", pindex->GetBlockHash().GetHex());
ret_all.pushKV("feerate_percentiles", feerates_res);
ret_all.pushKV("height", (int64_t)pindex->nHeight);
ret_all.pushKV("ins", inputs);
ret_all.pushKV("maxfee", maxfee);
ret_all.pushKV("maxfeerate", maxfeerate);
ret_all.pushKV("maxtxsize", maxtxsize);
ret_all.pushKV("medianfee", CalculateTruncatedMedian(fee_array));
ret_all.pushKV("mediantime", pindex->GetMedianTimePast());
ret_all.pushKV("mediantxsize", CalculateTruncatedMedian(txsize_array));
ret_all.pushKV("minfee", (minfee == MAX_MONEY) ? 0 : minfee);
ret_all.pushKV("minfeerate", (minfeerate == MAX_MONEY) ? 0 : minfeerate);
ret_all.pushKV("mintxsize", mintxsize == MAX_BLOCK_SERIALIZED_SIZE ? 0 : mintxsize);
ret_all.pushKV("outs", outputs);
ret_all.pushKV("subsidy", GetBlockSubsidy(pindex->nHeight, Params().GetConsensus()));
ret_all.pushKV("swtotal_size", swtotal_size);
ret_all.pushKV("swtotal_weight", swtotal_weight);
ret_all.pushKV("swtxs", swtxs);
ret_all.pushKV("time", pindex->GetBlockTime());
ret_all.pushKV("total_out", total_out);
ret_all.pushKV("total_size", total_size);
ret_all.pushKV("total_weight", total_weight);
ret_all.pushKV("totalfee", totalfee);
ret_all.pushKV("txs", (int64_t)block.vtx.size());
ret_all.pushKV("utxo_increase", outputs - inputs);
ret_all.pushKV("utxo_size_inc", utxo_size_inc);
if (do_all) {
return ret_all;
}
UniValue ret(UniValue::VOBJ);
for (const std::string& stat : stats) {
const UniValue& value = ret_all[stat];
if (value.isNull()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid selected statistic %s", stat));
}
ret.pushKV(stat, value);
}
return ret;
}
static UniValue savemempool(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0) {
throw std::runtime_error(
"savemempool\n"
"\nDumps the mempool to disk. It will fail until the previous dump is fully loaded.\n"
"\nExamples:\n"
+ HelpExampleCli("savemempool", "")
+ HelpExampleRpc("savemempool", "")
);
}
if (!g_is_mempool_loaded) {
throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet");
}
if (!DumpMempool()) {
throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk");
}
return NullUniValue;
}
//! Search for a given set of pubkey scripts
bool FindScriptPubKey(std::atomic<int>& scan_progress, const std::atomic<bool>& should_abort, int64_t& count, CCoinsViewCursor* cursor, const std::set<CScript>& needles, std::map<COutPoint, Coin>& out_results) {
scan_progress = 0;
count = 0;
while (cursor->Valid()) {
COutPoint key;
Coin coin;
if (!cursor->GetKey(key) || !cursor->GetValue(coin)) return false;
if (++count % 8192 == 0) {
boost::this_thread::interruption_point();
if (should_abort) {
// allow to abort the scan via the abort reference
return false;
}
}
if (count % 256 == 0) {
// update progress reference every 256 item
uint32_t high = 0x100 * *key.hash.begin() + *(key.hash.begin() + 1);
scan_progress = (int)(high * 100.0 / 65536.0 + 0.5);
}
if (needles.count(coin.out.scriptPubKey)) {
out_results.emplace(key, coin);
}
cursor->Next();
}
scan_progress = 100;
return true;
}
/** RAII object to prevent concurrency issue when scanning the txout set */
static std::mutex g_utxosetscan;
static std::atomic<int> g_scan_progress;
static std::atomic<bool> g_scan_in_progress;
static std::atomic<bool> g_should_abort_scan;
class CoinsViewScanReserver
{
private:
bool m_could_reserve;
public:
explicit CoinsViewScanReserver() : m_could_reserve(false) {}
bool reserve() {
assert (!m_could_reserve);
std::lock_guard<std::mutex> lock(g_utxosetscan);
if (g_scan_in_progress) {
return false;
}
g_scan_in_progress = true;
m_could_reserve = true;
return true;
}
~CoinsViewScanReserver() {
if (m_could_reserve) {
std::lock_guard<std::mutex> lock(g_utxosetscan);
g_scan_in_progress = false;
}
}
};
UniValue scantxoutset(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw std::runtime_error(
"scantxoutset <action> ( <scanobjects> )\n"
"\nEXPERIMENTAL warning: this call may be removed or changed in future releases.\n"
"\nScans the unspent transaction output set for entries that match certain output descriptors.\n"
"Examples of output descriptors are:\n"
" addr(<address>) Outputs whose scriptPubKey corresponds to the specified address (does not include P2PK)\n"
" raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n"
" combo(<pubkey>) P2PK, P2PKH, P2WPKH, and P2SH-P2WPKH outputs for the given pubkey\n"
" pkh(<pubkey>) P2PKH outputs for the given pubkey\n"
" sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
"\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
"or more path elements separated by \"/\", and optionally ending in \"/*\" (unhardened), or \"/*'\" or \"/*h\" (hardened) to specify all\n"
"unhardened or hardened child keys.\n"
"In the latter case, a range needs to be specified by below if different from 1000.\n"
"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"
"\nArguments:\n"
"1. \"action\" (string, required) The action to execute\n"
" \"start\" for starting a scan\n"
" \"abort\" for aborting the current scan (returns true when abort was successful)\n"
" \"status\" for progress report (in %) of the current scan\n"
"2. \"scanobjects\" (array, required) Array of scan objects\n"
" [ Every scan object is either a string descriptor or an object:\n"
" \"descriptor\", (string, optional) An output descriptor\n"
" { (object, optional) An object with output descriptor and metadata\n"
" \"desc\": \"descriptor\", (string, required) An output descriptor\n"
" \"range\": n, (numeric, optional) Up to what child index HD chains should be explored (default: 1000)\n"
" },\n"
" ...\n"
" ]\n"
"\nResult:\n"
"{\n"
" \"unspents\": [\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id\n"
" \"vout\": n, (numeric) the vout value\n"
" \"scriptPubKey\" : \"script\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " of the unspent output\n"
" \"height\" : n, (numeric) Height of the unspent transaction output\n"
" }\n"
" ,...], \n"
" \"total_amount\" : x.xxx, (numeric) The total amount of all found unspent outputs in " + CURRENCY_UNIT + "\n"
"]\n"
);
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR});
UniValue result(UniValue::VOBJ);
if (request.params[0].get_str() == "status") {
CoinsViewScanReserver reserver;
if (reserver.reserve()) {
// no scan in progress
return NullUniValue;
}
result.pushKV("progress", g_scan_progress);
return result;
} else if (request.params[0].get_str() == "abort") {
CoinsViewScanReserver reserver;
if (reserver.reserve()) {
// reserve was possible which means no scan was running
return false;
}
// set the abort flag
g_should_abort_scan = true;
return true;
} else if (request.params[0].get_str() == "start") {
CoinsViewScanReserver reserver;
if (!reserver.reserve()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan already in progress, use action \"abort\" or \"status\"");
}
std::set<CScript> needles;
CAmount total_in = 0;
// loop through the scan objects
for (const UniValue& scanobject : request.params[1].get_array().getValues()) {
std::string desc_str;
int range = 1000;
if (scanobject.isStr()) {
desc_str = scanobject.get_str();
} else if (scanobject.isObject()) {
UniValue desc_uni = find_value(scanobject, "desc");
if (desc_uni.isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor needs to be provided in scan object");
desc_str = desc_uni.get_str();
UniValue range_uni = find_value(scanobject, "range");
if (!range_uni.isNull()) {
range = range_uni.get_int();
if (range < 0 || range > 1000000) throw JSONRPCError(RPC_INVALID_PARAMETER, "range out of range");
}
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Scan object needs to be either a string or an object");
}
FlatSigningProvider provider;
auto desc = Parse(desc_str, provider);
if (!desc) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid descriptor '%s'", desc_str));
}
if (!desc->IsRange()) range = 0;
for (int i = 0; i <= range; ++i) {
std::vector<CScript> scripts;
if (!desc->Expand(i, provider, scripts, provider)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys: '%s'", desc_str));
}
needles.insert(scripts.begin(), scripts.end());
}
}
// Scan the unspent transaction output set for inputs
UniValue unspents(UniValue::VARR);
std::vector<CTxOut> input_txos;
std::map<COutPoint, Coin> coins;
g_should_abort_scan = false;
g_scan_progress = 0;
int64_t count = 0;
std::unique_ptr<CCoinsViewCursor> pcursor;
{
LOCK(cs_main);
FlushStateToDisk();
pcursor = std::unique_ptr<CCoinsViewCursor>(pcoinsdbview->Cursor());
assert(pcursor);
}
bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins);
result.pushKV("success", res);
result.pushKV("searched_items", count);
for (const auto& it : coins) {
const COutPoint& outpoint = it.first;
const Coin& coin = it.second;
const CTxOut& txo = coin.out;
input_txos.push_back(txo);
total_in += txo.nValue;
UniValue unspent(UniValue::VOBJ);
unspent.pushKV("txid", outpoint.hash.GetHex());
unspent.pushKV("vout", (int32_t)outpoint.n);
unspent.pushKV("scriptPubKey", HexStr(txo.scriptPubKey.begin(), txo.scriptPubKey.end()));
unspent.pushKV("amount", ValueFromAmount(txo.nValue));
unspent.pushKV("height", (int32_t)coin.nHeight);
unspents.push_back(unspent);
}
result.pushKV("unspents", unspents);
result.pushKV("total_amount", ValueFromAmount(total_in));
} else {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid command");
}
return result;
}
// clang-format off
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "blockchain", "getblockchaininfo", &getblockchaininfo, {} },
{ "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} },
{ "blockchain", "getblockstats", &getblockstats, {"hash_or_height", "stats"} },
{ "blockchain", "getbestblockhash", &getbestblockhash, {} },
{ "blockchain", "getblockcount", &getblockcount, {} },
{ "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} },
{ "blockchain", "getblockhash", &getblockhash, {"height"} },
{ "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} },
{ "blockchain", "getchaintips", &getchaintips, {} },
{ "blockchain", "getdifficulty", &getdifficulty, {} },
{ "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} },
{ "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} },
{ "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} },
{ "blockchain", "getmempoolinfo", &getmempoolinfo, {} },
{ "blockchain", "getrawmempool", &getrawmempool, {"verbose"} },
{ "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} },
{ "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} },
{ "blockchain", "pruneblockchain", &pruneblockchain, {"height"} },
{ "blockchain", "savemempool", &savemempool, {} },
{ "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} },
{ "blockchain", "preciousblock", &preciousblock, {"blockhash"} },
{ "blockchain", "scantxoutset", &scantxoutset, {"action", "scanobjects"} },
/* Not shown in help */
{ "hidden", "invalidateblock", &invalidateblock, {"blockhash"} },
{ "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} },
{ "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} },
{ "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} },
{ "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} },
{ "hidden", "syncwithvalidationinterfacequeue", &syncwithvalidationinterfacequeue, {} },
};
// clang-format on
void RegisterBlockchainRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
|
#pragma once
#ifndef HYDROSIG_CONNECTION_WRAPPER_HPP_INCLUDED
#define HYDROSIG_CONNECTION_WRAPPER_HPP_INCLUDED
/*
* MIT License
*
* Copyright (c) 2017 Peter Gyulai
*
* 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 "src/macros.h"
#include "src/wrappers/wrapper_helpers.h"
#include "src/connections/connection_0.hpp"
#include "src/connections/connection_1.hpp"
#include "src/connections/connection_2.hpp"
#include "src/connections/connection_3.hpp"
#include "src/connections/connection_4.hpp"
#include "src/connections/connection_5.hpp"
#include "src/connections/connection_6.hpp"
#include "src/connections/connection_7.hpp"
#include "src/connections/connection_8.hpp"
HYDROSIG_NAMESPACE_BEGIN
/**
* Convenience connection wrappers - portable syntax.
* --------------------------------------------------
*/
HYDROSIG_TEMPLATE_PORTABLE_WRAPPER_BASE
/**
* @brief Convenience wrapper for connections with eight arguments.
* @details Connections with less arguments are specialized types of
* this template.
*/
class connection
: public connection_8<HYDROSIG_8_ARG>
{
public:
connection(const connection_8<HYDROSIG_8_ARG> &src)
: connection_8<HYDROSIG_8_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_0_ARG
/**
* @brief Convenience wrapper for connections with zero arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_0_ARG>
: public connection_0<HYDROSIG_0_ARG>
{
public:
connection(const connection_0<HYDROSIG_0_ARG> &src)
: connection_0<HYDROSIG_0_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_1_ARG
/**
* @brief Convenience wrapper for connections with one arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_1_ARG>
: public connection_1<HYDROSIG_1_ARG>
{
public:
connection(const connection_1<HYDROSIG_1_ARG> &src)
: connection_1<HYDROSIG_1_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_2_ARG
/**
* @brief Convenience wrapper for connections with two arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_2_ARG>
: public connection_2<HYDROSIG_2_ARG>
{
public:
connection(const connection_2<HYDROSIG_2_ARG> &src)
: connection_2<HYDROSIG_2_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_3_ARG
/**
* @brief Convenience wrapper for connections with three arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_3_ARG>
: public connection_3<HYDROSIG_3_ARG>
{
public:
connection(const connection_3<HYDROSIG_3_ARG> &src)
: connection_3<HYDROSIG_3_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_4_ARG
/**
* @brief Convenience wrapper for connections with four arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_4_ARG>
: public connection_4<HYDROSIG_4_ARG>
{
public:
connection(const connection_4<HYDROSIG_4_ARG> &src)
: connection_4<HYDROSIG_4_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_5_ARG
/**
* @brief Convenience wrapper for connections with five arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_5_ARG>
: public connection_5<HYDROSIG_5_ARG>
{
public:
connection(const connection_5<HYDROSIG_5_ARG> &src)
: connection_5<HYDROSIG_5_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_6_ARG
/**
* @brief Convenience wrapper for connections with six arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_6_ARG>
: public connection_6<HYDROSIG_6_ARG>
{
public:
connection(const connection_6<HYDROSIG_6_ARG> &src)
: connection_6<HYDROSIG_6_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_7_ARG
/**
* @brief Convenience wrapper for connections with seven arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class connection<HYDROSIG_PORTABLE_WRAPPER_7_ARG>
: public connection_7<HYDROSIG_7_ARG>
{
public:
connection(const connection_7<HYDROSIG_7_ARG> &src)
: connection_7<HYDROSIG_7_ARG>(src)
{}
};
/**
* Convenience connection wrappers - elegant syntax.
* -------------------------------------------------
*/
HYDROSIG_TEMPLATE_0_ARG
/**
* @brief Convenience wrapper for connections with no arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_0_ARG>
: public connection_0<HYDROSIG_0_ARG>
{
public:
connection(const connection_0<HYDROSIG_0_ARG> &src)
: connection_0<HYDROSIG_0_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_1_ARG
/**
* @brief Convenience wrapper for connections with one arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_1_ARG>
: public connection_1<HYDROSIG_1_ARG>
{
public:
connection(const connection_1<HYDROSIG_1_ARG> &src)
: connection_1<HYDROSIG_1_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_2_ARG
/**
* @brief Convenience wrapper for connections with two arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_2_ARG>
: public connection_2<HYDROSIG_2_ARG>
{
public:
connection(const connection_2<HYDROSIG_2_ARG> &src)
: connection_2<HYDROSIG_2_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_3_ARG
/**
* @brief Convenience wrapper for connections with three arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_3_ARG>
: public connection_3<HYDROSIG_3_ARG>
{
public:
connection(const connection_3<HYDROSIG_3_ARG> &src)
: connection_3<HYDROSIG_3_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_4_ARG
/**
* @brief Convenience wrapper for connections with four arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_4_ARG>
: public connection_4<HYDROSIG_4_ARG>
{
public:
connection(const connection_4<HYDROSIG_4_ARG> &src)
: connection_4<HYDROSIG_4_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_5_ARG
/**
* @brief Convenience wrapper for connections with five arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_5_ARG>
: public connection_5<HYDROSIG_5_ARG>
{
public:
connection(const connection_5<HYDROSIG_5_ARG> &src)
: connection_5<HYDROSIG_5_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_6_ARG
/**
* @brief Convenience wrapper for connections with six arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_6_ARG>
: public connection_6<HYDROSIG_6_ARG>
{
public:
connection(const connection_6<HYDROSIG_6_ARG> &src)
: connection_6<HYDROSIG_6_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_7_ARG
/**
* @brief Convenience wrapper for connections with seven arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_7_ARG>
: public connection_7<HYDROSIG_7_ARG>
{
public:
connection(const connection_7<HYDROSIG_7_ARG> &src)
: connection_7<HYDROSIG_7_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_8_ARG
/**
* @brief Convenience wrapper for connections with eight arguments.
* @details This template version uses the elegant syntax.
*/
class connection<HYDROSIG_ELEGANT_WRAPPER_8_ARG>
: public connection_8<HYDROSIG_8_ARG>
{
public:
connection(const connection_8<HYDROSIG_8_ARG> &src)
: connection_8<HYDROSIG_8_ARG>(src)
{}
};
/**
* Convenience scoped_connection wrappers - portable syntax.
* ---------------------------------------------------------
*/
HYDROSIG_TEMPLATE_PORTABLE_WRAPPER_BASE
/**
* @brief Convenience wrapper for scoped_connections with eight arguments.
* @details Connections with less arguments are specialized types of
* this template.
*/
class scoped_connection
: public scoped_connection_8<HYDROSIG_8_ARG>
{
public:
scoped_connection(const connection_8<HYDROSIG_8_ARG> &src)
: scoped_connection_8<HYDROSIG_8_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_0_ARG
/**
* @brief Convenience wrapper for scoped_connections with zero arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_0_ARG>
: public scoped_connection_0<HYDROSIG_0_ARG>
{
public:
scoped_connection(const connection_0<HYDROSIG_0_ARG> &src)
: scoped_connection_0<HYDROSIG_0_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_1_ARG
/**
* @brief Convenience wrapper for scoped_connections with one arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_1_ARG>
: public scoped_connection_1<HYDROSIG_1_ARG>
{
public:
scoped_connection(const connection_1<HYDROSIG_1_ARG> &src)
: scoped_connection_1<HYDROSIG_1_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_2_ARG
/**
* @brief Convenience wrapper for scoped_connections with two arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_2_ARG>
: public scoped_connection_2<HYDROSIG_2_ARG>
{
public:
scoped_connection(const connection_2<HYDROSIG_2_ARG> &src)
: scoped_connection_2<HYDROSIG_2_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_3_ARG
/**
* @brief Convenience wrapper for scoped_connections with three arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_3_ARG>
: public scoped_connection_3<HYDROSIG_3_ARG>
{
public:
scoped_connection(const connection_3<HYDROSIG_3_ARG> &src)
: scoped_connection_3<HYDROSIG_3_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_4_ARG
/**
* @brief Convenience wrapper for scoped_connections with four arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_4_ARG>
: public scoped_connection_4<HYDROSIG_4_ARG>
{
public:
scoped_connection(const connection_4<HYDROSIG_4_ARG> &src)
: scoped_connection_4<HYDROSIG_4_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_5_ARG
/**
* @brief Convenience wrapper for scoped_connections with five arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_5_ARG>
: public scoped_connection_5<HYDROSIG_5_ARG>
{
public:
scoped_connection(const connection_5<HYDROSIG_5_ARG> &src)
: scoped_connection_5<HYDROSIG_5_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_6_ARG
/**
* @brief Convenience wrapper for scoped_connections with six arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_6_ARG>
: public scoped_connection_6<HYDROSIG_6_ARG>
{
public:
scoped_connection(const connection_6<HYDROSIG_6_ARG> &src)
: scoped_connection_6<HYDROSIG_6_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_7_ARG
/**
* @brief Convenience wrapper for scoped_connections with seven arguments.
* @details Specialized from the template wrapper for eight arguments.
*/
class scoped_connection<HYDROSIG_PORTABLE_WRAPPER_7_ARG>
: public scoped_connection_7<HYDROSIG_7_ARG>
{
public:
scoped_connection(const connection_7<HYDROSIG_7_ARG> &src)
: scoped_connection_7<HYDROSIG_7_ARG>(src)
{}
};
/**
* Convenience scoped_connection wrappers - elegant syntax.
* --------------------------------------------------------
*/
HYDROSIG_TEMPLATE_0_ARG
/**
* @brief Convenience wrapper for scoped_connections with no arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_0_ARG>
: public scoped_connection_0<HYDROSIG_0_ARG>
{
public:
scoped_connection(const connection_0<HYDROSIG_0_ARG> &src)
: scoped_connection_0<HYDROSIG_0_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_1_ARG
/**
* @brief Convenience wrapper for scoped_connections with one arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_1_ARG>
: public scoped_connection_1<HYDROSIG_1_ARG>
{
public:
scoped_connection(const connection_1<HYDROSIG_1_ARG> &src)
: scoped_connection_1<HYDROSIG_1_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_2_ARG
/**
* @brief Convenience wrapper for scoped_connections with two arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_2_ARG>
: public scoped_connection_2<HYDROSIG_2_ARG>
{
public:
scoped_connection(const connection_2<HYDROSIG_2_ARG> &src)
: scoped_connection_2<HYDROSIG_2_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_3_ARG
/**
* @brief Convenience wrapper for scoped_connections with three arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_3_ARG>
: public scoped_connection_3<HYDROSIG_3_ARG>
{
public:
scoped_connection(const connection_3<HYDROSIG_3_ARG> &src)
: scoped_connection_3<HYDROSIG_3_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_4_ARG
/**
* @brief Convenience wrapper for scoped_connections with four arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_4_ARG>
: public scoped_connection_4<HYDROSIG_4_ARG>
{
public:
scoped_connection(const connection_4<HYDROSIG_4_ARG> &src)
: scoped_connection_4<HYDROSIG_4_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_5_ARG
/**
* @brief Convenience wrapper for scoped_connections with five arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_5_ARG>
: public scoped_connection_5<HYDROSIG_5_ARG>
{
public:
scoped_connection(const connection_5<HYDROSIG_5_ARG> &src)
: scoped_connection_5<HYDROSIG_5_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_6_ARG
/**
* @brief Convenience wrapper for scoped_connections with six arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_6_ARG>
: public scoped_connection_6<HYDROSIG_6_ARG>
{
public:
scoped_connection(const connection_6<HYDROSIG_6_ARG> &src)
: scoped_connection_6<HYDROSIG_6_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_7_ARG
/**
* @brief Convenience wrapper for scoped_connections with seven arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_7_ARG>
: public scoped_connection_7<HYDROSIG_7_ARG>
{
public:
scoped_connection(const connection_7<HYDROSIG_7_ARG> &src)
: scoped_connection_7<HYDROSIG_7_ARG>(src)
{}
};
HYDROSIG_TEMPLATE_8_ARG
/**
* @brief Convenience wrapper for connections with eight arguments.
* @details This template version uses the elegant syntax.
*/
class scoped_connection<HYDROSIG_ELEGANT_WRAPPER_8_ARG>
: public scoped_connection_8<HYDROSIG_8_ARG>
{
public:
scoped_connection(const connection_8<HYDROSIG_8_ARG> &src)
: scoped_connection_8<HYDROSIG_8_ARG>(src)
{}
};
HYDROSIG_NAMESPACE_END
#endif // HYDROSIG_CONNECTION_WRAPPER_HPP_INCLUDED
|
#pragma once
#include <string>
#include <vector>
#include "json/json.h"
inline bool json_from_str(int& i, const Json::Value& root)
{
if (root.isNull() || root.isObject() || root.isArray())
return false;
if (root.isInt())
{
i = root.asInt();
return true;
}
else
return false;
}
inline bool json_from_str(unsigned int& ui, const Json::Value& root)
{
if (root.isNull() || root.isObject() || root.isArray())
return false;
if (root.isUInt())
{
ui = root.asUInt();
return true;
}
else
return false;
}
inline bool json_from_str(double& d, const Json::Value& root)
{
if (root.isNull() || root.isObject() || root.isArray())
return false;
if (root.isDouble())
{
d = root.asDouble();
return true;
}
else
return false;
}
inline bool json_from_str(bool& b, const Json::Value& root)
{
if (root.isNull() || root.isObject() || root.isArray())
return false;
if (root.isBool())
{
b = root.asBool();
return true;
}
else
return false;
}
inline bool json_from_str(std::string& str, const Json::Value& root)
{
if (root.isNull() || root.isObject() || root.isArray())
return false;
if (root.isString())
{
str = root.asString();
return true;
}
else
return false;
}
inline bool json_from_str(std::vector<int>& is, const Json::Value& root)
{
if (root.isNull() || root.isObject() || !root.isArray())// || 0 == root.size())
return false;
for (unsigned int i = 0; i < root.size(); ++i)
{
if (!root[i].isInt())
return false;
is.emplace_back(root[i].asInt());
}
return true;
}
inline bool json_from_str(std::vector<unsigned int>& uis, const Json::Value& root)
{
if (root.isNull() || root.isObject() || !root.isArray())// || 0 == root.size())
return false;
for (unsigned int i = 0; i < root.size(); ++i)
{
if (!root[i].isUInt())
return false;
uis.emplace_back(root[i].asUInt());
}
return true;
}
inline bool json_from_str(std::vector<double>& ds, const Json::Value& root)
{
if (root.isNull() || root.isObject() || !root.isArray())// || 0 == root.size())
return false;
for (unsigned int i = 0; i < root.size(); ++i)
{
if (!root[i].isDouble())
return false;
ds.emplace_back(root[i].asDouble());
}
return true;
}
inline bool json_from_str(std::vector<bool>& bs, const Json::Value& root)
{
if (root.isNull() || root.isObject() || !root.isArray())// || 0 == root.size())
return false;
for (unsigned int i = 0; i < root.size(); ++i)
{
if (!root[i].isBool())
return false;
bs.emplace_back(root[i].asBool());
}
return true;
}
inline bool json_from_str(std::vector<std::string>& strs, const Json::Value& root)
{
if (root.isNull() || root.isObject() || !root.isArray())// || 0 == root.size())
return false;
for (unsigned int i = 0; i < root.size(); ++i)
{
if (!root[i].isString())
return false;
strs.emplace_back(root[i].asString());
}
return true;
}
template <typename T>
inline bool json_from_str(std::vector<T>& v1, const Json::Value& root)
{
if (root.isNull() || root.isObject() || !root.isArray()) //|| 0 == root.size())
return false;
for (unsigned int i = 0; i < root.size(); ++i)
{
T t;
if (!json_from_str(t, root[i]))
return false;
v1.emplace_back(t);
}
return true;
}
inline Json::Value json_to_str_imp(int i)
{
Json::Value root = i;
return std::move(root);
}
inline Json::Value json_to_str_imp(unsigned int ui)
{
Json::Value root = ui;
return std::move(root);
}
inline Json::Value json_to_str_imp(double d)
{
Json::Value root = d;
return std::move(root);
}
inline Json::Value json_to_str_imp(bool b)
{
Json::Value root = b;
return std::move(root);
}
inline Json::Value json_to_str_imp(const std::string& str)
{
Json::Value root = str;
return std::move(root);
}
inline Json::Value json_to_str_imp(const std::vector<int>& is)
{
Json::Value root = Json::ValueType::arrayValue;
if (is.empty())
root.resize(0);
else
{
for (auto value : is)
{
root.append(value);
}
}
return std::move(root);
}
inline Json::Value json_to_str_imp(const std::vector<unsigned int>& uis)
{
Json::Value root = Json::ValueType::arrayValue;
if (uis.empty())
root.resize(0);
else
{
for (auto value : uis)
{
root.append(value);
}
}
return std::move(root);
}
inline Json::Value json_to_str_imp(const std::vector<double>& ds)
{
Json::Value root = Json::ValueType::arrayValue;
if (ds.empty())
root.resize(0);
else
{
for (auto value : ds)
{
root.append(value);
}
}
return std::move(root);
}
inline Json::Value json_to_str_imp(const std::vector<bool>& bs)
{
Json::Value root = Json::ValueType::arrayValue;
if (bs.empty())
root.resize(0);
else
{
for (auto value : bs)
{
bool b = value;
root.append(b);
}
}
return std::move(root);
}
inline Json::Value json_to_str_imp(const std::vector<std::string>& strs)
{
Json::Value root = Json::ValueType::arrayValue;
if (strs.empty())
root.resize(0);
else
{
for (auto value : strs)
{
root.append(value);
}
}
return std::move(root);
}
template <typename T>
inline Json::Value json_to_str_imp(const std::vector<T>& v1)
{
Json::Value root = Json::ValueType::arrayValue;
if (v1.empty())
root.resize(0);
else
{
for (int i = 0; i < v1.size(); ++i)
{
Json::Value value = json_to_str_imp(v1[i]);
root.append(value);
}
}
return std::move(root);
}
|
// Copyright (c) 2021-present Sparky Studios. 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 <string>
#include <vector>
#include <SparkyStudios/Audio/Amplitude/Amplitude.h>
#include <Core/EngineInternalState.h>
#include <Sound/Schedulers/RandomScheduler.h>
#include <Sound/Schedulers/SequenceScheduler.h>
#include "collection_definition_generated.h"
namespace SparkyStudios::Audio::Amplitude
{
Collection::Collection()
: _bus(nullptr)
, _worldScopeScheduler(nullptr)
, _entityScopeSchedulers()
, _source()
, _sounds()
, _soundSettings()
, _id(kAmInvalidObjectId)
, _name()
, _gain()
, _priority()
, _effect(nullptr)
, _attenuation(nullptr)
, _refCounter()
{}
Collection::~Collection()
{
delete _worldScopeScheduler;
_worldScopeScheduler = nullptr;
_entityScopeSchedulers.clear();
_effect = nullptr;
_attenuation = nullptr;
}
bool Collection::LoadCollectionDefinition(const std::string& source, EngineInternalState* state)
{
// Ensure we do not load the collection more than once
AMPLITUDE_ASSERT(_id == kAmInvalidObjectId);
_source = source;
const CollectionDefinition* def = GetCollectionDefinition();
if (!def->bus())
{
CallLogFunc("Collection %s does not specify a bus.\n", def->name()->c_str());
return false;
}
if (state)
{
_bus = FindBusInternalState(state, def->bus());
if (!_bus)
{
CallLogFunc("Collection %s specifies an unknown bus ID: %u.\n", def->name(), def->bus());
return false;
}
if (def->effect() != kAmInvalidObjectId)
{
if (const auto findIt = state->effect_map.find(def->effect()); findIt != state->effect_map.end())
{
_effect = findIt->second.get();
}
else
{
CallLogFunc("[ERROR] Sound definition is invalid: invalid effect ID \"%u\"", def->effect());
return false;
}
}
if (def->attenuation() != kAmInvalidObjectId)
{
if (auto findIt = state->attenuation_map.find(def->attenuation()); findIt != state->attenuation_map.end())
{
_attenuation = findIt->second.get();
}
if (!_attenuation)
{
CallLogFunc("Collection %s specifies an unknown attenuation ID: %u.\n", def->name(), def->attenuation());
return false;
}
}
}
_id = def->id();
_name = def->name()->str();
_gain = RtpcValue(def->gain());
_priority = RtpcValue(def->priority());
flatbuffers::uoffset_t sample_count = def->sounds() ? def->sounds()->size() : 0;
_sounds.resize(sample_count);
_soundSettings.clear();
for (flatbuffers::uoffset_t i = 0; i < sample_count; ++i)
{
const DefaultCollectionEntry* entry = def->sounds()->GetAs<DefaultCollectionEntry>(i);
AmSoundID id = entry->sound();
if (id == kAmInvalidObjectId)
{
CallLogFunc("[ERROR] Collection %s specifies an invalid sound ID: %u.", def->name()->c_str(), id);
return false;
}
if (auto findIt = state->sound_map.find(id); findIt == state->sound_map.end())
{
CallLogFunc("[ERROR] Collection %s specifies an unknown sound ID: %u", def->name()->c_str(), id);
return false;
}
else
{
SoundInstanceSettings settings;
settings.m_id = def->id();
settings.m_kind = SoundKind::Contained;
settings.m_busID = def->bus();
settings.m_effectID = def->effect();
settings.m_attenuationID = def->attenuation();
settings.m_spatialization = def->spatialization();
settings.m_priority = _priority;
settings.m_gain = RtpcValue(entry->gain());
settings.m_loop = findIt->second->_loop;
settings.m_loopCount = findIt->second->_loopCount;
_sounds[i] = id;
_soundSettings[id] = settings;
}
}
_worldScopeScheduler = CreateScheduler(def);
return true;
}
bool Collection::LoadCollectionDefinitionFromFile(AmOsString filename, EngineInternalState* state)
{
std::string source;
return Amplitude::LoadFile(filename, &source) && LoadCollectionDefinition(source, state);
}
void Collection::AcquireReferences(EngineInternalState* state)
{
AMPLITUDE_ASSERT(_id != kAmInvalidObjectId);
if (_effect)
{
_effect->GetRefCounter()->Increment();
}
if (_attenuation)
{
_attenuation->GetRefCounter()->Increment();
}
for (auto&& sound : _sounds)
{
if (auto findIt = state->sound_map.find(sound); findIt != state->sound_map.end())
{
findIt->second->GetRefCounter()->Increment();
}
}
}
void Collection::ReleaseReferences(EngineInternalState* state)
{
AMPLITUDE_ASSERT(_id != kAmInvalidObjectId);
if (_effect)
{
_effect->GetRefCounter()->Decrement();
}
if (_attenuation)
{
_attenuation->GetRefCounter()->Decrement();
}
for (auto&& sound : _sounds)
{
if (auto findIt = state->sound_map.find(sound); findIt != state->sound_map.end())
{
findIt->second->GetRefCounter()->Decrement();
}
}
}
const CollectionDefinition* Collection::GetCollectionDefinition() const
{
return Amplitude::GetCollectionDefinition(_source.c_str());
}
Sound* Collection::SelectFromWorld(const std::vector<AmSoundID>& toSkip)
{
const CollectionDefinition* sound_def = GetCollectionDefinition();
if (_worldScopeScheduler == nullptr || !_worldScopeScheduler->Valid())
{
CallLogFunc("Collection %s does not have a valid scheduler.\n", sound_def->name()->c_str());
return nullptr;
}
return _worldScopeScheduler->Select(toSkip);
}
Sound* Collection::SelectFromEntity(const Entity& entity, const std::vector<AmSoundID>& toSkip)
{
const CollectionDefinition* sound_def = GetCollectionDefinition();
if (auto findIt = _entityScopeSchedulers.find(entity.GetId()); findIt == _entityScopeSchedulers.end())
{
_entityScopeSchedulers.insert({ entity.GetId(), CreateScheduler(sound_def) });
}
return _entityScopeSchedulers[entity.GetId()]->Select(toSkip);
}
void Collection::ResetEntityScopeScheduler(const Entity& entity)
{
if (auto findIt = _entityScopeSchedulers.find(entity.GetId()); findIt != _entityScopeSchedulers.end())
{
findIt->second->Reset();
}
}
Scheduler* Collection::CreateScheduler(const CollectionDefinition* definition)
{
Scheduler* scheduler;
if (!definition->scheduler())
{
CallLogFunc(
"[Debug] Collection %s does not specify a scheduler, using the RandomScheduler by default.\n", definition->name()->c_str());
scheduler = new RandomScheduler(nullptr);
}
else
{
const SoundSchedulerSettings* schedulerSettings = definition->scheduler();
switch (schedulerSettings->mode())
{
default:
case SoundSchedulerMode_Random:
scheduler = new RandomScheduler(schedulerSettings->config_as_Random());
break;
case SoundSchedulerMode_Sequence:
scheduler = new SequenceScheduler(schedulerSettings->config_as_Sequence());
break;
}
}
scheduler->Init(definition);
return scheduler;
}
const RtpcValue& Collection::GetGain() const
{
return _gain;
}
const RtpcValue& Collection::GetPriority() const
{
return _priority;
}
AmBankID Collection::GetId() const
{
return _id;
}
const std::string& Collection::GetName() const
{
return _name;
}
BusInternalState* Collection::GetBus() const
{
return _bus;
}
RefCounter* Collection::GetRefCounter()
{
return &_refCounter;
}
const std::vector<AmSoundID>& Collection::GetAudioSamples() const
{
return _sounds;
}
const Effect* Collection::GetEffect() const
{
return _effect;
}
const Attenuation* Collection::GetAttenuation() const
{
return _attenuation;
}
} // namespace SparkyStudios::Audio::Amplitude
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/route53/model/ListTagsForResourceResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <utility>
using namespace Aws::Route53::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws;
ListTagsForResourceResult::ListTagsForResourceResult()
{
}
ListTagsForResourceResult::ListTagsForResourceResult(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
ListTagsForResourceResult& ListTagsForResourceResult::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode resultNode = xmlDocument.GetRootElement();
if(!resultNode.IsNull())
{
XmlNode resourceTagSetNode = resultNode.FirstChild("ResourceTagSet");
if(!resourceTagSetNode.IsNull())
{
m_resourceTagSet = resourceTagSetNode;
}
}
return *this;
}
|
#include <cppunit/TestSuite.h>
#include <cppunit/extensions/TestFixtureFactory.h>
#include <cppunit/extensions/TestNamer.h>
#include <cppunit/extensions/TestSuiteBuilderContext.h>
CPPUNIT_NS_BEGIN
TestSuiteBuilderContextBase::TestSuiteBuilderContextBase(
TestSuite &suite,
const TestNamer &namer,
TestFixtureFactory &factory )
: m_suite( suite )
, m_namer( namer )
, m_factory( factory )
{
}
TestSuiteBuilderContextBase::~TestSuiteBuilderContextBase()
{
}
void
TestSuiteBuilderContextBase::addTest( Test *test )
{
m_suite.addTest( test );
}
std::string
TestSuiteBuilderContextBase::getFixtureName() const
{
return m_namer.getFixtureName();
}
std::string
TestSuiteBuilderContextBase::getTestNameFor(
const std::string &testMethodName ) const
{
return m_namer.getTestNameFor( testMethodName );
}
TestFixture *
TestSuiteBuilderContextBase::makeTestFixture() const
{
return m_factory.makeFixture();
}
void
TestSuiteBuilderContextBase::addProperty( const std::string &key,
const std::string &value )
{
Properties::iterator it = m_properties.begin();
for ( ; it != m_properties.end(); ++it )
{
if ( (*it).first == key )
{
(*it).second = value;
return;
}
}
Property property( key, value );
m_properties.push_back( property );
}
const std::string
TestSuiteBuilderContextBase::getStringProperty( const std::string &key ) const
{
Properties::const_iterator it = m_properties.begin();
for ( ; it != m_properties.end(); ++it )
{
if ( (*it).first == key )
return (*it).second;
}
return "";
}
CPPUNIT_NS_END
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Mixer.h"
#include <LibCore/File.h>
#include <LibCore/LocalServer.h>
int main(int, char**)
{
if (pledge("stdio recvfd thread accept rpath wpath cpath unix fattr", nullptr) < 0) {
perror("pledge");
return 1;
}
Core::EventLoop event_loop;
AudioServer::Mixer mixer;
auto server = Core::LocalServer::construct();
bool ok = server->take_over_from_system_server();
VERIFY(ok);
server->on_ready_to_accept = [&] {
auto client_socket = server->accept();
if (!client_socket) {
dbgln("AudioServer: accept failed.");
return;
}
static int s_next_client_id = 0;
int client_id = ++s_next_client_id;
IPC::new_client_connection<AudioServer::ClientConnection>(client_socket.release_nonnull(), client_id, mixer);
};
if (pledge("stdio recvfd thread accept", nullptr) < 0) {
perror("pledge");
return 1;
}
unveil(nullptr, nullptr);
return event_loop.exec();
}
|
/*++
Copyright (c) 2017 Microsoft Corporation
Module Name:
<name>
Abstract:
<abstract>
Author:
Lev Nachmanson (levnach)
Revision History:
--*/
#include "util/lp/lp_dual_simplex_def.h"
template lp::mpq lp::lp_dual_simplex<lp::mpq, lp::mpq>::get_current_cost() const;
template void lp::lp_dual_simplex<lp::mpq, lp::mpq>::find_maximal_solution();
template double lp::lp_dual_simplex<double, double>::get_current_cost() const;
template void lp::lp_dual_simplex<double, double>::find_maximal_solution();
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: DateTime
struct DateTime;
}
// Forward declaring namespace: Oculus::Platform
namespace Oculus::Platform {
// Forward declaring type: RichPresenceExtraContext
struct RichPresenceExtraContext;
}
// Completed forward declares
// Type namespace: Oculus.Platform
namespace Oculus::Platform {
// Forward declaring type: RichPresenceOptions
class RichPresenceOptions;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Oculus::Platform::RichPresenceOptions);
DEFINE_IL2CPP_ARG_TYPE(::Oculus::Platform::RichPresenceOptions*, "Oculus.Platform", "RichPresenceOptions");
// Type namespace: Oculus.Platform
namespace Oculus::Platform {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: Oculus.Platform.RichPresenceOptions
// [TokenAttribute] Offset: FFFFFFFF
class RichPresenceOptions : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.IntPtr Handle
// Size: 0x8
// Offset: 0x10
::System::IntPtr Handle;
// Field size check
static_assert(sizeof(::System::IntPtr) == 0x8);
public:
// Creating conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept {
return Handle;
}
// Get instance field reference: private System.IntPtr Handle
::System::IntPtr& dyn_Handle();
// public System.Void SetApiName(System.String value)
// Offset: 0x2A2611C
void SetApiName(::StringW value);
// public System.Void SetCurrentCapacity(System.UInt32 value)
// Offset: 0x2A26198
void SetCurrentCapacity(uint value);
// public System.Void SetDeeplinkMessageOverride(System.String value)
// Offset: 0x2A26214
void SetDeeplinkMessageOverride(::StringW value);
// public System.Void SetEndTime(System.DateTime value)
// Offset: 0x2A26290
void SetEndTime(::System::DateTime value);
// public System.Void SetExtraContext(Oculus.Platform.RichPresenceExtraContext value)
// Offset: 0x2A2630C
void SetExtraContext(::Oculus::Platform::RichPresenceExtraContext value);
// public System.Void SetInstanceId(System.String value)
// Offset: 0x2A26388
void SetInstanceId(::StringW value);
// public System.Void SetIsIdle(System.Boolean value)
// Offset: 0x2A26404
void SetIsIdle(bool value);
// public System.Void SetIsJoinable(System.Boolean value)
// Offset: 0x2A26480
void SetIsJoinable(bool value);
// public System.Void SetMaxCapacity(System.UInt32 value)
// Offset: 0x2A264FC
void SetMaxCapacity(uint value);
// public System.Void SetStartTime(System.DateTime value)
// Offset: 0x2A26578
void SetStartTime(::System::DateTime value);
// static public System.IntPtr op_Explicit(Oculus.Platform.RichPresenceOptions options)
// Offset: 0x2A25ED8
// ABORTED: conflicts with another method. explicit operator ::System::IntPtr();
// public System.Void .ctor()
// Offset: 0x2A260A4
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RichPresenceOptions* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Oculus::Platform::RichPresenceOptions::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RichPresenceOptions*, creationType>()));
}
// protected override System.Void Finalize()
// Offset: 0x2A265F4
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
}; // Oculus.Platform.RichPresenceOptions
#pragma pack(pop)
static check_size<sizeof(RichPresenceOptions), 16 + sizeof(::System::IntPtr)> __Oculus_Platform_RichPresenceOptionsSizeCheck;
static_assert(sizeof(RichPresenceOptions) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetApiName
// Il2CppName: SetApiName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(::StringW)>(&Oculus::Platform::RichPresenceOptions::SetApiName)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetApiName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetCurrentCapacity
// Il2CppName: SetCurrentCapacity
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(uint)>(&Oculus::Platform::RichPresenceOptions::SetCurrentCapacity)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetCurrentCapacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetDeeplinkMessageOverride
// Il2CppName: SetDeeplinkMessageOverride
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(::StringW)>(&Oculus::Platform::RichPresenceOptions::SetDeeplinkMessageOverride)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetDeeplinkMessageOverride", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetEndTime
// Il2CppName: SetEndTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(::System::DateTime)>(&Oculus::Platform::RichPresenceOptions::SetEndTime)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "DateTime")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetEndTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetExtraContext
// Il2CppName: SetExtraContext
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(::Oculus::Platform::RichPresenceExtraContext)>(&Oculus::Platform::RichPresenceOptions::SetExtraContext)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("Oculus.Platform", "RichPresenceExtraContext")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetExtraContext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetInstanceId
// Il2CppName: SetInstanceId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(::StringW)>(&Oculus::Platform::RichPresenceOptions::SetInstanceId)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetInstanceId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetIsIdle
// Il2CppName: SetIsIdle
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(bool)>(&Oculus::Platform::RichPresenceOptions::SetIsIdle)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetIsIdle", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetIsJoinable
// Il2CppName: SetIsJoinable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(bool)>(&Oculus::Platform::RichPresenceOptions::SetIsJoinable)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetIsJoinable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetMaxCapacity
// Il2CppName: SetMaxCapacity
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(uint)>(&Oculus::Platform::RichPresenceOptions::SetMaxCapacity)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetMaxCapacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::SetStartTime
// Il2CppName: SetStartTime
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)(::System::DateTime)>(&Oculus::Platform::RichPresenceOptions::SetStartTime)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "DateTime")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "SetStartTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::operator ::System::IntPtr
// Il2CppName: op_Explicit
// Cannot perform method pointer template specialization from operators!
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: Oculus::Platform::RichPresenceOptions::Finalize
// Il2CppName: Finalize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Oculus::Platform::RichPresenceOptions::*)()>(&Oculus::Platform::RichPresenceOptions::Finalize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Oculus::Platform::RichPresenceOptions*), "Finalize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
|
#include SAMPCPP_PCH
#include <SAMPCpp/Core/BasicInterfaces/PlacementTracker.hpp>
namespace samp_cpp
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////
I3DNodePlacementTracker::I3DNodePlacementTracker(ActorPlacement const & initialPlacement_)
: m_lastPlacement{ initialPlacement_ }
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void I3DNodePlacementTracker::whenPlacementUpdateReceived(ActorPlacement const& newPlacement_)
{
if (this->isSignificantChange(newPlacement_))
{
this->whenPlacementChanges(m_lastPlacement, newPlacement_);
m_lastPlacement = newPlacement_;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool I3DNodePlacementTracker::isSignificantChange(ActorPlacement const& newPlacement_) const
{
return newPlacement_.world != m_lastPlacement.world ||
newPlacement_.interior != m_lastPlacement.interior ||
newPlacement_.location.distanceSquared(m_lastPlacement.location) >= default_streamer::StreamerSettings.getMaxDisplacementDistanceSquared().value;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
IGlobalObjectPlacementTracker::IGlobalObjectPlacementTracker(GlobalObjectPlacement const & initialPlacement_)
: m_lastPlacement{ initialPlacement_ }
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void IGlobalObjectPlacementTracker::whenPlacementUpdateReceived(GlobalObjectPlacement const& newPlacement_)
{
if (this->isSignificantChange(newPlacement_))
{
this->whenPlacementChanges(m_lastPlacement, newPlacement_);
m_lastPlacement = newPlacement_;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool IGlobalObjectPlacementTracker::isSignificantChange(GlobalObjectPlacement const& newPlacement_) const
{
return newPlacement_.location.distanceSquared(m_lastPlacement.location) >= default_streamer::StreamerSettings.getMaxDisplacementDistanceSquared().value;
}
}
|
// Copyright (c) 2017-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/tx_verify.h>
#include <consensus/consensus.h>
#include <primitives/transaction.h>
#include <script/interpreter.h>
#include <consensus/validation.h>
#include <kernel.h>
#include <validation.h> // GetCoinAge()
// TODO remove the following dependencies
#include <chain.h>
#include <coins.h>
#include <util/moneystr.h>
bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
{
if (tx.nLockTime == 0)
return true;
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
for (const auto& txin : tx.vin) {
if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL))
return false;
}
return true;
}
std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
{
assert(prevHeights->size() == tx.vin.size());
// Will be set to the equivalent height- and time-based nLockTime
// values that would be necessary to satisfy all relative lock-
// time constraints given our view of block chain history.
// The semantics of nLockTime are the last invalid height/time, so
// use -1 to have the effect of any height or time being valid.
int nMinHeight = -1;
int64_t nMinTime = -1;
// tx.nVersion is signed integer so requires cast to unsigned otherwise
// we would be doing a signed comparison and half the range of nVersion
// wouldn't support BIP 68.
bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
&& flags & LOCKTIME_VERIFY_SEQUENCE;
// Do not enforce sequence numbers as a relative lock time
// unless we have been instructed to
if (!fEnforceBIP68) {
return std::make_pair(nMinHeight, nMinTime);
}
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
const CTxIn& txin = tx.vin[txinIndex];
// Sequence numbers with the most significant bit set are not
// treated as relative lock-times, nor are they given any
// consensus-enforced meaning at this point.
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
// The height of this input is not relevant for sequence locks
(*prevHeights)[txinIndex] = 0;
continue;
}
int nCoinHeight = (*prevHeights)[txinIndex];
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
// NOTE: Subtract 1 to maintain nLockTime semantics
// BIP 68 relative lock times have the semantics of calculating
// the first block or time at which the transaction would be
// valid. When calculating the effective block time or height
// for the entire transaction, we switch to using the
// semantics of nLockTime which is the last invalid block
// time or height. Thus we subtract 1 from the calculated
// time or height.
// Time-based relative lock-times are measured from the
// smallest allowed timestamp of the block containing the
// txout being spent, which is the median time past of the
// block prior.
nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
} else {
nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
}
}
return std::make_pair(nMinHeight, nMinTime);
}
bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
{
assert(block.pprev);
int64_t nBlockTime = block.pprev->GetMedianTimePast();
if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
return false;
return true;
}
bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
{
return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
for (const auto& txin : tx.vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
for (const auto& txout : tx.vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
{
if (tx.IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
assert(!coin.IsSpent());
const CTxOut &prevout = coin.out;
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags)
{
int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR;
if (tx.IsCoinBase())
return nSigOps;
if (flags & SCRIPT_VERIFY_P2SH) {
nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR;
}
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout);
assert(!coin.IsSpent());
const CTxOut &prevout = coin.out;
nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags);
}
return nSigOps;
}
bool Consensus::CheckTxInputs(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee, const Consensus::Params& params, uint64_t nMoneySupply)
{
// are the actual inputs available?
if (!inputs.HaveInputs(tx)) {
return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent",
strprintf("%s: inputs missing/spent", __func__));
}
CAmount nValueIn = 0;
for (unsigned int i = 0; i < tx.vin.size(); ++i) {
const COutPoint &prevout = tx.vin[i].prevout;
const Coin& coin = inputs.AccessCoin(prevout);
assert(!coin.IsSpent());
// If prev is coinbase, check that it's matured
if ((coin.IsCoinBase() || coin.IsCoinStake()) && nSpendHeight - coin.nHeight < params.nCoinbaseMaturity) {
return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "bad-txns-premature-spend-of-coinbase/coinstake",
strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight));
}
// peercoin: check transaction timestamp
if (coin.nTime > tx.nTime)
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-spent-too-early", strprintf("%s : transaction timestamp earlier than input transaction", __func__));
// Check for negative or overflow input values
nValueIn += coin.out.nValue;
if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputvalues-outofrange");
}
}
if (tx.IsCoinStake())
{
// peercoin: coin stake tx earns reward instead of paying fee
uint64_t nCoinAge;
if (!GetCoinAge(tx, inputs, nCoinAge))
return state.Invalid(TxValidationResult::TX_CONSENSUS, "unable to get coin age for coinstake");
CAmount nStakeReward = tx.GetValueOut() - nValueIn;
CAmount nCoinstakeCost = (GetMinFee(tx) < PERKB_TX_FEE) ? 0 : (GetMinFee(tx) - PERKB_TX_FEE);
if (nMoneySupply && nStakeReward > GetProofOfStakeReward(nCoinAge, tx.nTime, nMoneySupply) - nCoinstakeCost)
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-coinstake-too-large");
}
else
{
const CAmount value_out = tx.GetValueOut();
if (nValueIn < value_out) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout",
strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out)));
}
// Tally transaction fees
const CAmount txfee_aux = nValueIn - value_out;
if (!MoneyRange(txfee_aux)) {
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-outofrange");
}
// peercoin: enforce transaction fees for every block
if (txfee_aux < GetMinFee(tx))
return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-not-enough");
txfee = txfee_aux;
}
return true;
}
CAmount GetMinFee(const CTransaction& tx)
{
size_t nBytes = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
return GetMinFee(nBytes, tx.nTime);
}
CAmount GetMinFee(size_t nBytes, uint32_t nTime)
{
CAmount nMinFee;
if (IsProtocolV07(nTime)) // RFC-0007
nMinFee = (nBytes < 100) ? MIN_TX_FEE : (CAmount)(nBytes * (PERKB_TX_FEE / 1000));
else
nMinFee = (1 + (CAmount)nBytes / 1000) * PERKB_TX_FEE;
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
|
#include <hxcpp.h>
#ifndef INCLUDED_lime_graphics_opengl_ext_APPLE_sync
#include <lime/graphics/opengl/ext/APPLE_sync.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_7969c112b28ce208_4_new,"lime.graphics.opengl.ext.APPLE_sync","new",0xc89c95d4,"lime.graphics.opengl.ext.APPLE_sync.new","lime/graphics/opengl/ext/APPLE_sync.hx",4,0x38845a3a)
namespace lime{
namespace graphics{
namespace opengl{
namespace ext{
void APPLE_sync_obj::__construct(){
HX_STACKFRAME(&_hx_pos_7969c112b28ce208_4_new)
HXLINE( 21) this->TIMEOUT_IGNORED_APPLE = -1;
HXLINE( 20) this->SYNC_FLUSH_COMMANDS_BIT_APPLE = 1;
HXLINE( 19) this->WAIT_FAILED_APPLE = 37149;
HXLINE( 18) this->CONDITION_SATISFIED_APPLE = 37148;
HXLINE( 17) this->TIMEOUT_EXPIRED_APPLE = 37147;
HXLINE( 16) this->ALREADY_SIGNALED_APPLE = 37146;
HXLINE( 15) this->SIGNALED_APPLE = 37145;
HXLINE( 14) this->UNSIGNALED_APPLE = 37144;
HXLINE( 13) this->SYNC_GPU_COMMANDS_COMPLETE_APPLE = 37143;
HXLINE( 12) this->SYNC_FENCE_APPLE = 37142;
HXLINE( 11) this->SYNC_FLAGS_APPLE = 37141;
HXLINE( 10) this->SYNC_STATUS_APPLE = 37140;
HXLINE( 9) this->SYNC_CONDITION_APPLE = 37139;
HXLINE( 8) this->OBJECT_TYPE_APPLE = 37138;
HXLINE( 7) this->MAX_SERVER_WAIT_TIMEOUT_APPLE = 37137;
HXLINE( 6) this->SYNC_OBJECT_APPLE = 35411;
}
Dynamic APPLE_sync_obj::__CreateEmpty() { return new APPLE_sync_obj; }
void *APPLE_sync_obj::_hx_vtable = 0;
Dynamic APPLE_sync_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< APPLE_sync_obj > _hx_result = new APPLE_sync_obj();
_hx_result->__construct();
return _hx_result;
}
bool APPLE_sync_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x4865fa4e;
}
APPLE_sync_obj::APPLE_sync_obj()
{
}
::hx::Val APPLE_sync_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 14:
if (HX_FIELD_EQ(inName,"SIGNALED_APPLE") ) { return ::hx::Val( SIGNALED_APPLE ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"SYNC_FLAGS_APPLE") ) { return ::hx::Val( SYNC_FLAGS_APPLE ); }
if (HX_FIELD_EQ(inName,"SYNC_FENCE_APPLE") ) { return ::hx::Val( SYNC_FENCE_APPLE ); }
if (HX_FIELD_EQ(inName,"UNSIGNALED_APPLE") ) { return ::hx::Val( UNSIGNALED_APPLE ); }
break;
case 17:
if (HX_FIELD_EQ(inName,"SYNC_OBJECT_APPLE") ) { return ::hx::Val( SYNC_OBJECT_APPLE ); }
if (HX_FIELD_EQ(inName,"OBJECT_TYPE_APPLE") ) { return ::hx::Val( OBJECT_TYPE_APPLE ); }
if (HX_FIELD_EQ(inName,"SYNC_STATUS_APPLE") ) { return ::hx::Val( SYNC_STATUS_APPLE ); }
if (HX_FIELD_EQ(inName,"WAIT_FAILED_APPLE") ) { return ::hx::Val( WAIT_FAILED_APPLE ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"SYNC_CONDITION_APPLE") ) { return ::hx::Val( SYNC_CONDITION_APPLE ); }
break;
case 21:
if (HX_FIELD_EQ(inName,"TIMEOUT_EXPIRED_APPLE") ) { return ::hx::Val( TIMEOUT_EXPIRED_APPLE ); }
if (HX_FIELD_EQ(inName,"TIMEOUT_IGNORED_APPLE") ) { return ::hx::Val( TIMEOUT_IGNORED_APPLE ); }
break;
case 22:
if (HX_FIELD_EQ(inName,"ALREADY_SIGNALED_APPLE") ) { return ::hx::Val( ALREADY_SIGNALED_APPLE ); }
break;
case 25:
if (HX_FIELD_EQ(inName,"CONDITION_SATISFIED_APPLE") ) { return ::hx::Val( CONDITION_SATISFIED_APPLE ); }
break;
case 29:
if (HX_FIELD_EQ(inName,"MAX_SERVER_WAIT_TIMEOUT_APPLE") ) { return ::hx::Val( MAX_SERVER_WAIT_TIMEOUT_APPLE ); }
if (HX_FIELD_EQ(inName,"SYNC_FLUSH_COMMANDS_BIT_APPLE") ) { return ::hx::Val( SYNC_FLUSH_COMMANDS_BIT_APPLE ); }
break;
case 32:
if (HX_FIELD_EQ(inName,"SYNC_GPU_COMMANDS_COMPLETE_APPLE") ) { return ::hx::Val( SYNC_GPU_COMMANDS_COMPLETE_APPLE ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val APPLE_sync_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 14:
if (HX_FIELD_EQ(inName,"SIGNALED_APPLE") ) { SIGNALED_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"SYNC_FLAGS_APPLE") ) { SYNC_FLAGS_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"SYNC_FENCE_APPLE") ) { SYNC_FENCE_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"UNSIGNALED_APPLE") ) { UNSIGNALED_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 17:
if (HX_FIELD_EQ(inName,"SYNC_OBJECT_APPLE") ) { SYNC_OBJECT_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"OBJECT_TYPE_APPLE") ) { OBJECT_TYPE_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"SYNC_STATUS_APPLE") ) { SYNC_STATUS_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"WAIT_FAILED_APPLE") ) { WAIT_FAILED_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 20:
if (HX_FIELD_EQ(inName,"SYNC_CONDITION_APPLE") ) { SYNC_CONDITION_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 21:
if (HX_FIELD_EQ(inName,"TIMEOUT_EXPIRED_APPLE") ) { TIMEOUT_EXPIRED_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"TIMEOUT_IGNORED_APPLE") ) { TIMEOUT_IGNORED_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 22:
if (HX_FIELD_EQ(inName,"ALREADY_SIGNALED_APPLE") ) { ALREADY_SIGNALED_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 25:
if (HX_FIELD_EQ(inName,"CONDITION_SATISFIED_APPLE") ) { CONDITION_SATISFIED_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 29:
if (HX_FIELD_EQ(inName,"MAX_SERVER_WAIT_TIMEOUT_APPLE") ) { MAX_SERVER_WAIT_TIMEOUT_APPLE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"SYNC_FLUSH_COMMANDS_BIT_APPLE") ) { SYNC_FLUSH_COMMANDS_BIT_APPLE=inValue.Cast< int >(); return inValue; }
break;
case 32:
if (HX_FIELD_EQ(inName,"SYNC_GPU_COMMANDS_COMPLETE_APPLE") ) { SYNC_GPU_COMMANDS_COMPLETE_APPLE=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void APPLE_sync_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("SYNC_OBJECT_APPLE",1e,bc,93,1e));
outFields->push(HX_("MAX_SERVER_WAIT_TIMEOUT_APPLE",b3,1b,89,8b));
outFields->push(HX_("OBJECT_TYPE_APPLE",75,33,51,15));
outFields->push(HX_("SYNC_CONDITION_APPLE",12,97,05,77));
outFields->push(HX_("SYNC_STATUS_APPLE",d1,7c,b2,aa));
outFields->push(HX_("SYNC_FLAGS_APPLE",be,8b,0e,31));
outFields->push(HX_("SYNC_FENCE_APPLE",a8,52,51,7a));
outFields->push(HX_("SYNC_GPU_COMMANDS_COMPLETE_APPLE",34,e9,d2,71));
outFields->push(HX_("UNSIGNALED_APPLE",9b,28,8b,90));
outFields->push(HX_("SIGNALED_APPLE",82,d4,e2,08));
outFields->push(HX_("ALREADY_SIGNALED_APPLE",a9,58,ab,45));
outFields->push(HX_("TIMEOUT_EXPIRED_APPLE",42,08,0b,cd));
outFields->push(HX_("CONDITION_SATISFIED_APPLE",c9,b9,97,5f));
outFields->push(HX_("WAIT_FAILED_APPLE",42,2d,3b,8f));
outFields->push(HX_("SYNC_FLUSH_COMMANDS_BIT_APPLE",10,19,72,41));
outFields->push(HX_("TIMEOUT_IGNORED_APPLE",6f,af,58,06));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo APPLE_sync_obj_sMemberStorageInfo[] = {
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_OBJECT_APPLE),HX_("SYNC_OBJECT_APPLE",1e,bc,93,1e)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,MAX_SERVER_WAIT_TIMEOUT_APPLE),HX_("MAX_SERVER_WAIT_TIMEOUT_APPLE",b3,1b,89,8b)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,OBJECT_TYPE_APPLE),HX_("OBJECT_TYPE_APPLE",75,33,51,15)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_CONDITION_APPLE),HX_("SYNC_CONDITION_APPLE",12,97,05,77)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_STATUS_APPLE),HX_("SYNC_STATUS_APPLE",d1,7c,b2,aa)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_FLAGS_APPLE),HX_("SYNC_FLAGS_APPLE",be,8b,0e,31)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_FENCE_APPLE),HX_("SYNC_FENCE_APPLE",a8,52,51,7a)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_GPU_COMMANDS_COMPLETE_APPLE),HX_("SYNC_GPU_COMMANDS_COMPLETE_APPLE",34,e9,d2,71)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,UNSIGNALED_APPLE),HX_("UNSIGNALED_APPLE",9b,28,8b,90)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SIGNALED_APPLE),HX_("SIGNALED_APPLE",82,d4,e2,08)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,ALREADY_SIGNALED_APPLE),HX_("ALREADY_SIGNALED_APPLE",a9,58,ab,45)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,TIMEOUT_EXPIRED_APPLE),HX_("TIMEOUT_EXPIRED_APPLE",42,08,0b,cd)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,CONDITION_SATISFIED_APPLE),HX_("CONDITION_SATISFIED_APPLE",c9,b9,97,5f)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,WAIT_FAILED_APPLE),HX_("WAIT_FAILED_APPLE",42,2d,3b,8f)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,SYNC_FLUSH_COMMANDS_BIT_APPLE),HX_("SYNC_FLUSH_COMMANDS_BIT_APPLE",10,19,72,41)},
{::hx::fsInt,(int)offsetof(APPLE_sync_obj,TIMEOUT_IGNORED_APPLE),HX_("TIMEOUT_IGNORED_APPLE",6f,af,58,06)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *APPLE_sync_obj_sStaticStorageInfo = 0;
#endif
static ::String APPLE_sync_obj_sMemberFields[] = {
HX_("SYNC_OBJECT_APPLE",1e,bc,93,1e),
HX_("MAX_SERVER_WAIT_TIMEOUT_APPLE",b3,1b,89,8b),
HX_("OBJECT_TYPE_APPLE",75,33,51,15),
HX_("SYNC_CONDITION_APPLE",12,97,05,77),
HX_("SYNC_STATUS_APPLE",d1,7c,b2,aa),
HX_("SYNC_FLAGS_APPLE",be,8b,0e,31),
HX_("SYNC_FENCE_APPLE",a8,52,51,7a),
HX_("SYNC_GPU_COMMANDS_COMPLETE_APPLE",34,e9,d2,71),
HX_("UNSIGNALED_APPLE",9b,28,8b,90),
HX_("SIGNALED_APPLE",82,d4,e2,08),
HX_("ALREADY_SIGNALED_APPLE",a9,58,ab,45),
HX_("TIMEOUT_EXPIRED_APPLE",42,08,0b,cd),
HX_("CONDITION_SATISFIED_APPLE",c9,b9,97,5f),
HX_("WAIT_FAILED_APPLE",42,2d,3b,8f),
HX_("SYNC_FLUSH_COMMANDS_BIT_APPLE",10,19,72,41),
HX_("TIMEOUT_IGNORED_APPLE",6f,af,58,06),
::String(null()) };
::hx::Class APPLE_sync_obj::__mClass;
void APPLE_sync_obj::__register()
{
APPLE_sync_obj _hx_dummy;
APPLE_sync_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime.graphics.opengl.ext.APPLE_sync",e2,5b,88,2e);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(APPLE_sync_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< APPLE_sync_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = APPLE_sync_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = APPLE_sync_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace graphics
} // end namespace opengl
} // end namespace ext
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/customization_document.h"
#include "base/at_exit.h"
#include "base/message_loop/message_loop.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/external_provider_impl.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/prefs/pref_service_mock_factory.h"
#include "chrome/browser/prefs/pref_service_syncable.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/system/mock_statistics_provider.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_status.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::Exactly;
using ::testing::Invoke;
using ::testing::Mock;
using ::testing::_;
namespace {
const char kGoodStartupManifest[] =
"{"
" \"version\": \"1.0\","
" \"initial_locale\" : \"en-US\","
" \"initial_timezone\" : \"US/Pacific\","
" \"keyboard_layout\" : \"xkb:us::eng\","
" \"setup_content\" : {"
" \"en-US\" : {"
" \"eula_page\" : \"file:///opt/oem/eula/en-US/eula.html\","
" },"
" \"ru-RU\" : {"
" \"eula_page\" : \"file:///opt/oem/eula/ru-RU/eula.html\","
" },"
" \"default\" : {"
" \"eula_page\" : \"file:///opt/oem/eula/en/eula.html\","
" },"
" },"
" \"hwid_map\" : ["
" {"
" \"hwid_mask\": \"ZGA*34\","
" \"initial_locale\" : \"ja\","
" \"initial_timezone\" : \"Asia/Tokyo\","
" \"keyboard_layout\" : \"mozc-jp\","
" },"
" {"
" \"hwid_mask\": \"Mario 1?3*\","
" \"initial_locale\" : \"ru-RU\","
" \"initial_timezone\" : \"Europe/Moscow\","
" \"keyboard_layout\" : \"xkb:ru::rus\","
" },"
" ],"
"}";
const char kBadManifest[] = "{\"version\": \"1\"}";
const char kGoodServicesManifest[] =
"{"
" \"version\": \"1.0\","
" \"default_wallpaper\": \"http://somedomain.com/image.png\",\n"
" \"default_apps\": [\n"
" \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
" \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
" ]\n"
"}";
const char kDummyCustomizationID[] = "test-dummy";
} // anonymous namespace
namespace chromeos {
using ::testing::_;
using ::testing::DoAll;
using ::testing::NotNull;
using ::testing::Return;
using ::testing::SetArgumentPointee;
TEST(StartupCustomizationDocumentTest, Basic) {
system::MockStatisticsProvider mock_statistics_provider;
EXPECT_CALL(mock_statistics_provider, GetMachineStatistic(_, NotNull()))
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_statistics_provider,
GetMachineStatistic(std::string("hardware_class"), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<1>(std::string("Mario 12345")),
Return(true)));
StartupCustomizationDocument customization(&mock_statistics_provider,
kGoodStartupManifest);
EXPECT_EQ("ru-RU", customization.initial_locale());
EXPECT_EQ("Europe/Moscow", customization.initial_timezone());
EXPECT_EQ("xkb:ru::rus", customization.keyboard_layout());
EXPECT_EQ("file:///opt/oem/eula/en-US/eula.html",
customization.GetEULAPage("en-US"));
EXPECT_EQ("file:///opt/oem/eula/ru-RU/eula.html",
customization.GetEULAPage("ru-RU"));
EXPECT_EQ("file:///opt/oem/eula/en/eula.html",
customization.GetEULAPage("ja"));
}
TEST(StartupCustomizationDocumentTest, VPD) {
system::MockStatisticsProvider mock_statistics_provider;
EXPECT_CALL(mock_statistics_provider,
GetMachineStatistic(std::string("hardware_class"), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<1>(std::string("Mario 12345")),
Return(true)));
EXPECT_CALL(mock_statistics_provider,
GetMachineStatistic(std::string("initial_locale"), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<1>(std::string("ja")),
Return(true)));
EXPECT_CALL(mock_statistics_provider,
GetMachineStatistic(std::string("initial_timezone"), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<1>(std::string("Asia/Tokyo")),
Return(true)));
EXPECT_CALL(mock_statistics_provider,
GetMachineStatistic(std::string("keyboard_layout"), NotNull()))
.WillOnce(DoAll(SetArgumentPointee<1>(std::string("mozc-jp")),
Return(true)));
StartupCustomizationDocument customization(&mock_statistics_provider,
kGoodStartupManifest);
EXPECT_TRUE(customization.IsReady());
EXPECT_EQ("ja", customization.initial_locale());
EXPECT_EQ("Asia/Tokyo", customization.initial_timezone());
EXPECT_EQ("mozc-jp", customization.keyboard_layout());
}
TEST(StartupCustomizationDocumentTest, BadManifest) {
system::MockStatisticsProvider mock_statistics_provider;
StartupCustomizationDocument customization(&mock_statistics_provider,
kBadManifest);
EXPECT_FALSE(customization.IsReady());
}
class TestURLFetcherCallback {
public:
scoped_ptr<net::FakeURLFetcher> CreateURLFetcher(
const GURL& url,
net::URLFetcherDelegate* d,
const std::string& response_data,
net::HttpStatusCode response_code,
net::URLRequestStatus::Status status) {
scoped_ptr<net::FakeURLFetcher> fetcher(
new net::FakeURLFetcher(url, d, response_data, response_code, status));
OnRequestCreate(url, fetcher.get());
return fetcher.Pass();
}
MOCK_METHOD2(OnRequestCreate,
void(const GURL&, net::FakeURLFetcher*));
};
void AddMimeHeader(const GURL& url, net::FakeURLFetcher* fetcher) {
scoped_refptr<net::HttpResponseHeaders> download_headers =
new net::HttpResponseHeaders("");
download_headers->AddHeader("Content-Type: application/json");
fetcher->set_response_headers(download_headers);
}
class MockExternalProviderVisitor
: public extensions::ExternalProviderInterface::VisitorInterface {
public:
MockExternalProviderVisitor() {}
MOCK_METHOD6(OnExternalExtensionFileFound,
bool(const std::string&,
const base::Version*,
const base::FilePath&,
extensions::Manifest::Location,
int,
bool));
MOCK_METHOD5(OnExternalExtensionUpdateUrlFound,
bool(const std::string&,
const GURL&,
extensions::Manifest::Location,
int,
bool));
MOCK_METHOD1(OnExternalProviderReady,
void(const extensions::ExternalProviderInterface* provider));
};
class ServicesCustomizationDocumentTest : public testing::Test {
protected:
ServicesCustomizationDocumentTest()
: factory_(NULL,
base::Bind(&TestURLFetcherCallback::CreateURLFetcher,
base::Unretained(&url_callback_))) {
}
// testing::Test:
virtual void SetUp() OVERRIDE {
EXPECT_CALL(mock_statistics_provider_, GetMachineStatistic(_, NotNull()))
.WillRepeatedly(Return(false));
chromeos::system::StatisticsProvider::SetTestProvider(
&mock_statistics_provider_);
TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_);
ServicesCustomizationDocument::RegisterPrefs(local_state_.registry());
}
virtual void TearDown() OVERRIDE {
TestingBrowserProcess::GetGlobal()->SetLocalState(NULL);
chromeos::system::StatisticsProvider::SetTestProvider(NULL);
}
void RunUntilIdle() {
base::RunLoop().RunUntilIdle();
}
void AddCustomizationIdToVp(const std::string& id) {
EXPECT_CALL(mock_statistics_provider_,
GetMachineStatistic(system::kCustomizationIdKey, NotNull()))
.WillOnce(DoAll(SetArgumentPointee<1>(id),
Return(true)));
}
void AddExpectedManifest(const std::string& id,
const std::string& manifest) {
GURL url(base::StringPrintf(ServicesCustomizationDocument::kManifestUrl,
id.c_str()));
factory_.SetFakeResponse(url,
manifest,
net::HTTP_OK,
net::URLRequestStatus::SUCCESS);
EXPECT_CALL(url_callback_, OnRequestCreate(url, _))
.Times(Exactly(1))
.WillRepeatedly(Invoke(AddMimeHeader));
}
scoped_ptr<TestingProfile> CreateProfile() {
TestingProfile::Builder profile_builder;
PrefServiceMockFactory factory;
scoped_refptr<user_prefs::PrefRegistrySyncable> registry(
new user_prefs::PrefRegistrySyncable);
scoped_ptr<PrefServiceSyncable> prefs(
factory.CreateSyncable(registry.get()));
chrome::RegisterUserProfilePrefs(registry.get());
profile_builder.SetPrefService(prefs.Pass());
return profile_builder.Build();
}
private:
system::MockStatisticsProvider mock_statistics_provider_;
content::TestBrowserThreadBundle thread_bundle_;
TestingPrefServiceSimple local_state_;
TestURLFetcherCallback url_callback_;
net::FakeURLFetcherFactory factory_;
base::ShadowingAtExitManager at_exit_manager_;
};
TEST_F(ServicesCustomizationDocumentTest, Basic) {
AddCustomizationIdToVp(kDummyCustomizationID);
AddExpectedManifest(kDummyCustomizationID, kGoodServicesManifest);
ServicesCustomizationDocument* doc =
ServicesCustomizationDocument::GetInstance();
EXPECT_FALSE(doc->IsReady());
doc->StartFetching();
RunUntilIdle();
EXPECT_TRUE(doc->IsReady());
EXPECT_EQ(doc->GetDefaultWallpaperUrl().spec(),
"http://somedomain.com/image.png");
std::vector<std::string> default_apps;
EXPECT_TRUE(doc->GetDefaultApps(&default_apps));
ASSERT_EQ(default_apps.size(), 2u);
EXPECT_EQ(default_apps[0], "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
EXPECT_EQ(default_apps[1], "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
}
TEST_F(ServicesCustomizationDocumentTest, EmptyCustomization) {
ServicesCustomizationDocument* doc =
ServicesCustomizationDocument::GetInstance();
EXPECT_FALSE(doc->IsReady());
scoped_ptr<TestingProfile> profile = CreateProfile();
extensions::ExternalLoader* loader = doc->CreateExternalLoader(profile.get());
EXPECT_TRUE(loader);
MockExternalProviderVisitor visitor;
scoped_ptr<extensions::ExternalProviderImpl> provider(
new extensions::ExternalProviderImpl(
&visitor,
loader,
profile.get(),
extensions::Manifest::EXTERNAL_PREF,
extensions::Manifest::EXTERNAL_PREF_DOWNLOAD,
extensions::Extension::FROM_WEBSTORE |
extensions::Extension::WAS_INSTALLED_BY_DEFAULT));
EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
.Times(0);
EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _))
.Times(0);
EXPECT_CALL(visitor, OnExternalProviderReady(_))
.Times(1);
// Manually request a load.
loader->StartLoading();
Mock::VerifyAndClearExpectations(&visitor);
RunUntilIdle();
EXPECT_FALSE(doc->IsReady());
}
TEST_F(ServicesCustomizationDocumentTest, DefaultApps) {
AddCustomizationIdToVp(kDummyCustomizationID);
AddExpectedManifest(kDummyCustomizationID, kGoodServicesManifest);
ServicesCustomizationDocument* doc =
ServicesCustomizationDocument::GetInstance();
EXPECT_FALSE(doc->IsReady());
scoped_ptr<TestingProfile> profile = CreateProfile();
extensions::ExternalLoader* loader = doc->CreateExternalLoader(profile.get());
EXPECT_TRUE(loader);
MockExternalProviderVisitor visitor;
scoped_ptr<extensions::ExternalProviderImpl> provider(
new extensions::ExternalProviderImpl(
&visitor,
loader,
profile.get(),
extensions::Manifest::EXTERNAL_PREF,
extensions::Manifest::EXTERNAL_PREF_DOWNLOAD,
extensions::Extension::FROM_WEBSTORE |
extensions::Extension::WAS_INSTALLED_BY_DEFAULT));
EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
.Times(0);
EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _))
.Times(0);
EXPECT_CALL(visitor, OnExternalProviderReady(_))
.Times(1);
// Manually request a load.
loader->StartLoading();
Mock::VerifyAndClearExpectations(&visitor);
EXPECT_CALL(visitor, OnExternalExtensionFileFound(_, _, _, _, _, _))
.Times(0);
EXPECT_CALL(visitor, OnExternalExtensionUpdateUrlFound(_, _, _, _, _))
.Times(2);
EXPECT_CALL(visitor, OnExternalProviderReady(_))
.Times(1);
RunUntilIdle();
EXPECT_TRUE(doc->IsReady());
}
} // namespace chromeos
|
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include <functional>
#include <type_traits>
#include "caf/catch_all.hpp"
namespace caf {
struct others_t {
constexpr others_t() {
// nop
}
template <class F>
catch_all<F> operator>>(F fun) const {
return {fun};
}
};
constexpr others_t others = others_t{};
} // namespace caf
|
// Source : https://leetcode.com/problems/happy-number/
// Author : lizhenghn@gmail.com
// Date : 2015-05-11
/**********************************************************************************
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer,
replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
**********************************************************************************/
#include <iostream>
using namespace std;
long getSum(long n)
{
long sum = 0;
while (n)
{
int x = n % 10;
sum += x * x;
n = n / 10;
}
return sum;
}
bool isHappy(int n)
{
long s = getSum(n);
if (s == 1)
return true;
else if (s < 10)
return false;
else
return isHappy(s);
}
int main()
{
cout << isHappy(7) << "\n"; // true 7 -- > 49 -->
cout << isHappy(19) << "\n";
cout << isHappy(10) << "\n";
cout << isHappy(12) << "\n";
cout << isHappy(78) << "\n";
cout << isHappy(7867) << "\n";
system("pause");
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Security.Cryptography.RandomNumberGenerator
#include "System/Security/Cryptography/RandomNumberGenerator.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: System.Security.Cryptography
namespace System::Security::Cryptography {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.Security.Cryptography.RNGCryptoServiceProvider
// [TokenAttribute] Offset: FFFFFFFF
class RNGCryptoServiceProvider : public System::Security::Cryptography::RandomNumberGenerator {
public:
// private System.IntPtr _handle
// Size: 0x8
// Offset: 0x10
System::IntPtr handle;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// Creating value type constructor for type: RNGCryptoServiceProvider
RNGCryptoServiceProvider(System::IntPtr handle_ = {}) noexcept : handle{handle_} {}
// Creating conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept {
return handle;
}
// Get static field: static private System.Object _lock
static ::Il2CppObject* _get__lock();
// Set static field: static private System.Object _lock
static void _set__lock(::Il2CppObject* value);
// Get instance field: private System.IntPtr _handle
System::IntPtr _get__handle();
// Set instance field: private System.IntPtr _handle
void _set__handle(System::IntPtr value);
// static private System.Void .cctor()
// Offset: 0x175B898
static void _cctor();
// private System.Void Check()
// Offset: 0x175B998
void Check();
// static private System.Boolean RngOpen()
// Offset: 0x175B90C
static bool RngOpen();
// static private System.IntPtr RngInitialize(System.Byte[] seed)
// Offset: 0x175B994
static System::IntPtr RngInitialize(::Array<uint8_t>* seed);
// static private System.IntPtr RngGetBytes(System.IntPtr handle, System.Byte[] data)
// Offset: 0x175BA3C
static System::IntPtr RngGetBytes(System::IntPtr handle, ::Array<uint8_t>* data);
// static private System.Void RngClose(System.IntPtr handle)
// Offset: 0x175BA40
static void RngClose(System::IntPtr handle);
// public System.Void .ctor()
// Offset: 0x175B910
// Implemented from: System.Security.Cryptography.RandomNumberGenerator
// Base method: System.Void RandomNumberGenerator::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static RNGCryptoServiceProvider* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("System::Security::Cryptography::RNGCryptoServiceProvider::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<RNGCryptoServiceProvider*, creationType>()));
}
// public override System.Void GetBytes(System.Byte[] data)
// Offset: 0x175BA44
// Implemented from: System.Security.Cryptography.RandomNumberGenerator
// Base method: System.Void RandomNumberGenerator::GetBytes(System.Byte[] data)
void GetBytes(::Array<uint8_t>* data);
// protected override System.Void Finalize()
// Offset: 0x175BBE8
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
// protected override System.Void Dispose(System.Boolean disposing)
// Offset: 0x175BCB8
// Implemented from: System.Security.Cryptography.RandomNumberGenerator
// Base method: System.Void RandomNumberGenerator::Dispose(System.Boolean disposing)
void Dispose(bool disposing);
}; // System.Security.Cryptography.RNGCryptoServiceProvider
#pragma pack(pop)
static check_size<sizeof(RNGCryptoServiceProvider), 16 + sizeof(System::IntPtr)> __System_Security_Cryptography_RNGCryptoServiceProviderSizeCheck;
static_assert(sizeof(RNGCryptoServiceProvider) == 0x18);
}
DEFINE_IL2CPP_ARG_TYPE(System::Security::Cryptography::RNGCryptoServiceProvider*, "System.Security.Cryptography", "RNGCryptoServiceProvider");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Security::Cryptography::RNGCryptoServiceProvider::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::Check
// Il2CppName: Check
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::RNGCryptoServiceProvider::*)()>(&System::Security::Cryptography::RNGCryptoServiceProvider::Check)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "Check", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::RngOpen
// Il2CppName: RngOpen
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&System::Security::Cryptography::RNGCryptoServiceProvider::RngOpen)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "RngOpen", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::RngInitialize
// Il2CppName: RngInitialize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (*)(::Array<uint8_t>*)>(&System::Security::Cryptography::RNGCryptoServiceProvider::RngInitialize)> {
static const MethodInfo* get() {
static auto* seed = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "RngInitialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{seed});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::RngGetBytes
// Il2CppName: RngGetBytes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (*)(System::IntPtr, ::Array<uint8_t>*)>(&System::Security::Cryptography::RNGCryptoServiceProvider::RngGetBytes)> {
static const MethodInfo* get() {
static auto* handle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
static auto* data = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "RngGetBytes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{handle, data});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::RngClose
// Il2CppName: RngClose
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(System::IntPtr)>(&System::Security::Cryptography::RNGCryptoServiceProvider::RngClose)> {
static const MethodInfo* get() {
static auto* handle = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "RngClose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{handle});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::GetBytes
// Il2CppName: GetBytes
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::RNGCryptoServiceProvider::*)(::Array<uint8_t>*)>(&System::Security::Cryptography::RNGCryptoServiceProvider::GetBytes)> {
static const MethodInfo* get() {
static auto* data = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "GetBytes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{data});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::Finalize
// Il2CppName: Finalize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::RNGCryptoServiceProvider::*)()>(&System::Security::Cryptography::RNGCryptoServiceProvider::Finalize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "Finalize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Security::Cryptography::RNGCryptoServiceProvider::Dispose
// Il2CppName: Dispose
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Security::Cryptography::RNGCryptoServiceProvider::*)(bool)>(&System::Security::Cryptography::RNGCryptoServiceProvider::Dispose)> {
static const MethodInfo* get() {
static auto* disposing = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::RNGCryptoServiceProvider*), "Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{disposing});
}
};
|
// atcoder/abc150/A/main.cpp
// author: @___Johniel
// github: https://github.com/johniel/
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; }
template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int k, x;
while (cin >> k >> x) {
cout << (x <= 500 * k ? "Yes" : "No") << endl;
}
return 0;
}
|
// txt2html - written by Steve Plimpton, May 2004
// table formatting by Anna Reese, Jul 2004
// Sandia National Labs, www.cs.sandia.gov/~sjplimp
//
// txt2html converts a text file with simple formatting & markup into HTML
// formatting & markup specification is given in README
//
// Syntax: txt2html options file read one file, write to stdout
// txt2html optoins file1 file2 ... read files, write files.html
//
// options:
// -b = add a page-break comment to end of each HTML file
// useful when set of HTML files will be converted to PDF
// -x file = skip a file even if it appears in file list
// specify full file name of input file
// input files are first opened as-is
// if that fails a .txt suffix is added
// output files have an .html suffix added or replaced
// (unless written to stdout)
#include <string>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define MAXLINE 1024
// function prototypes
static int next_paragraph(FILE *fp, string ¶graph);
static int index_of_first_char_of_last_word(string ¶graph);
static void process_commands(int flag, string &s, string &pre, string &post);
static void substitute(string &s);
static string td_tag(int currentc);
static long find_n(string &s, int nend, int &n1);
static void file_open(int npair, string &infile, FILE **in, FILE **out);
// global variables for links, tables, lists, all command
vector<string> alias1;
vector<string> alias2;
int nlink;
int tableflag; // makes a table if tb command specified
int rowquit; // number of cols per row if c=N specified (default = 0)
string dwidth; // width for all of the columns
string tabledelim; // speciallized separator
string tablealign; // alignment for the table as an image
string dataalign; // alignment for data in table
string rowvalign; // vertical alignment for table
int ncnum; // # of columns with specified width
vector<int> cnum; // column IDs
vector<string> cwidth; // column widths
int ncalign; // # of columns with specified alignment
vector<int> acolnum; // column IDs
vector<string> colalign ; // column alignment
int ncvalign; // # of columns with specified vertical alignment
vector<int> vacolnum; // column IDs
vector<string> colvalign ; // column vertical alignment
string listflag;
string allflag;
// main program
int main(int narg, char **arg)
{
int npair;
size_t n;
string *infile;
FILE *in,*out;
int style,ifirst,ilast;
string raw,pre,post,body,commands,final;
// parse command-line options and args
// setup list of files to process
// npair = # of files to process
// infile = input file names
if (narg == 1) {
fprintf(stderr,"Syntax: txt2html options file\n");
fprintf(stderr," txt2html options file1 file2 ...\n");
exit(1);
}
int breakflag = 0;
int nskip = 0;
char **skipfiles = NULL;
int iarg = 1;
while (arg[iarg][0] == '-') {
if (strcmp(arg[iarg],"-b") == 0) breakflag = 1;
else if (strcmp(arg[iarg],"-x") == 0) {
skipfiles = (char **) realloc(skipfiles,(nskip+1)*sizeof(char *));
n = strlen(arg[iarg+1]) + 1;
skipfiles[nskip] = new char[n];
strcpy(skipfiles[nskip],arg[iarg+1]);
nskip++;
iarg++;
} else {
fprintf(stderr,"Syntax: txt2html options file\n");
fprintf(stderr," txt2html options file1 file2 ...\n");
exit(1);
}
iarg++;
}
if (narg-iarg == 1) {
npair = 1;
infile = new string[npair];
infile[0] = arg[narg-1];
} else {
npair = narg-iarg;
infile = new string[npair];
for (int i = 0; i < npair; i++) infile[i] = arg[i+iarg];
}
// loop over files
for (int ipair = 0; ipair < npair; ipair++) {
// skip file if matches -x switch
int flag = 0;
for (int i = 0; i < nskip; i++)
if (strcmp(infile[ipair].c_str(),skipfiles[i]) == 0) flag = 1;
if (flag) continue;
// clear global variables before processing file
alias1.clear();
alias2.clear();
nlink = 0;
tableflag = 0;
listflag = "";
allflag = "";
// open files & message to screen
file_open(0,infile[ipair],&in,&out);
fprintf(stderr,"Converting %s ...\n",infile[ipair].c_str());
// scan file for link definitions
// read file one paragraph at a time
// process commands, looking only for link definitions
while ((style = next_paragraph(in,raw))) {
if (style == 2) {
int n = index_of_first_char_of_last_word(raw);
commands = raw.substr(n+1);
process_commands(0,commands,pre,post);
}
raw.erase();
}
// close & reopen files
fclose(in);
file_open(npair,infile[ipair],&in,&out);
// write leading <HTML>
fprintf(out,"<HTML>\n");
// process entire file
// read file one paragraph at a time
// delete newlines when line-continuation char at end-of-line
// process commands for each paragraph
// substitute text for each paragraph
// write HTML to output file
int rstflag = 0;
while ((style = next_paragraph(in,raw))) {
if (rstflag && raw.find("END_RST -->") != string::npos) {
rstflag = 0;
raw.erase();
continue;
} else if (rstflag == 0 && raw.find("<!-- RST") != string::npos) {
rstflag = 1;
raw.erase();
continue;
} else if (rstflag) {
raw.erase();
continue;
}
n = raw.find("\\\n");
while (n < string::npos) {
raw.erase(n,2);
n = raw.find("\\\n");
}
ifirst = raw.find_first_not_of(" \t\n");
ilast = raw.find_last_not_of(" \t\n");
pre.erase();
post.erase();
if (raw[ifirst] == '<' && raw[ilast] == '>') {
body = raw;
} else if (style == 1) {
body = raw;
commands = "p\n";
process_commands(1,commands,pre,post);
substitute(body);
} else {
int n = index_of_first_char_of_last_word(raw);
body = raw.substr(0,n) + "\n";
commands = raw.substr(n+1);
process_commands(1,commands,pre,post);
substitute(body);
}
final = pre + body + post;
fprintf(out,"%s\n",final.c_str());
raw.erase();
}
// write trailing </HTML>
if (breakflag) fprintf(out,"<!-- PAGE BREAK -->\n");
fprintf(out,"</HTML>\n");
// close files
fclose(in);
if (out != stdout) fclose(out);
}
// clean up memory
for (int i = 0; i < nskip; i++) delete [] skipfiles[i];
if (skipfiles) free(skipfiles);
delete [] infile;
}
// return next paragraph as string
// discard leading blank lines
// paragraph is terminated by:
// EOF or blank line or line ending with command that starts with ":"
// return 0 if EOF and no paragraph
// return 1 if no trailing command
// return 2 if trailing command
int next_paragraph(FILE *fp, string ¶graph)
{
char *ptr;
char str[MAXLINE];
int first = 1;
int len = 0;
while (1) {
ptr = fgets(str,MAXLINE,fp);
if (ptr == NULL && first) return 0;
if (ptr == NULL) return 1;
len = strlen(str);
if (len == MAXLINE-1) {
fprintf(stderr,"ERROR: File has too-long a string - increase MAXLINE\n");
exit(1);
}
// check for valid 7-bit ascii characters
bool nonascii = false;
for (int i=0; i < len; ++i) {
char c = str[i];
if (c != '\n' && c != '\t' && (c < ' ' || c > '~'))
nonascii = true;
}
if (nonascii)
fprintf(stderr,"WARNING: Non-portable characters in line: %s",ptr);
if (strspn(str," \t\n") == strlen(str) && first) continue;
if (strspn(str," \t\n") == strlen(str)) return 1;
first = 0;
paragraph += str;
if (paragraph[index_of_first_char_of_last_word(paragraph)] == ':')
return 2;
}
}
// return index of first char in last word of paragraph string
int index_of_first_char_of_last_word(string ¶graph)
{
size_t n = paragraph.find_last_not_of(" \t\n");
size_t m = paragraph.find_last_of(" \t\n",n);
if (m == string::npos) return 0;
else return m+1;
}
// apply commands one after the other to the paragraph
void process_commands(int flag, string &s, string &pre, string &post)
{
size_t start,stop,last;
int narg;
string command;
vector<string> arg;
start = 0;
last = s.find_last_not_of(" \t\n");
if (last == string::npos) return;
while (start <= last) {
// grab a single command with optional arguments
// command = name of command
// narg = # of args
// arg = list of argument strings
stop = s.find_first_of(",( \t\n",start);
if (s[stop] == '(') {
command = s.substr(start,stop-start);
start = stop+1;
narg = 0;
while (1) {
stop = s.find_first_of(",)",start);
if (stop == string::npos) {
fprintf(stderr,"ERROR: No trailing parenthesis in %s\n",s.c_str());
exit(1);
}
arg.resize(narg+1);
arg[narg] = s.substr(start,stop-start);
narg++;
start = stop+1;
if (s[stop] == ')') {
start++;
break;
}
}
} else {
command = s.substr(start,stop-start);
start = stop+1;
narg = 0;
}
// if only in scan mode, just operate on link command
if (flag == 0) {
if (command == "link" && narg == 2) {
// s.erase(s.length()-1,1);
for (int i = 0; i < nlink; i++)
if (alias1[i] == arg[0]) {
fprintf(stderr,"ERROR: Link %s appears more than once\n",
arg[0].c_str());
exit(1);
}
alias1.resize(nlink+1);
alias2.resize(nlink+1);
alias1[nlink] = arg[0];
alias2[nlink] = arg[1];
nlink++;
} else continue;
}
// process the command
if (command == "line") {
pre.append("<HR>");
} else if (command == "p") {
pre.append("<P>");
post.insert(0,"</P>");
} else if (command == "pre") {
pre.append("<PRE>");
post.insert(0,"</PRE>");
} else if (command == "c") {
pre.append("<CENTER>");
post.insert(0,"</CENTER>");
} else if (command == "h1") {
pre.append("<H1>");
post.insert(0,"</H1>");
} else if (command == "h2") {
pre.append("<H2>");
post.insert(0,"</H2>");
} else if (command == "h3") {
pre.append("<H3>");
post.insert(0,"</H3>");
} else if (command == "h4") {
pre.append("<H4>");
post.insert(0,"</H4>");
} else if (command == "h5") {
pre.append("<H5>");
post.insert(0,"</H5>");
} else if (command == "h6") {
pre.append("<H6>");
post.insert(0,"</H6>");
} else if (command == "b") {
post.insert(0,"<BR>");
} else if (command == "ulb") {
pre.append("<UL>");
} else if (command == "ule") {
post.insert(0,"</UL>");
} else if (command == "olb") {
pre.append("<OL>");
} else if (command == "ole") {
post.insert(0,"</OL>");
} else if (command == "dlb") {
pre.append("<DL>");
} else if (command == "dle") {
post.insert(0,"</DL>");
} else if (command == "l") {
pre.append("<LI>");
} else if (command == "dt") {
pre.append("<DT>");
} else if (command == "dd") {
pre.append("<DD>");
} else if (command == "ul") {
listflag = command;
pre.append("<UL>");
post.insert(0,"</UL>");
} else if (command == "ol") {
listflag = command;
pre.append("<OL>");
post.insert(0,"</OL>");
} else if (command == "dl") {
listflag = command;
pre.append("<DL>");
post.insert(0,"</DL>");
} else if (command == "link") {
if (narg == 1) {
string aname = "<A NAME = \"" + arg[0] + "\"></A>";
pre.append(aname);
}
} else if (command == "image") {
if (narg == 1) {
string img = "<IMG SRC = \"" + arg[0] + "\">";
pre.append(img);
} else if (narg == 2) {
string img = "<A HREF = \"" + arg[1] + "\">" +
"<IMG SRC = \"" + arg[0] + "\">" + "</A>";
pre.append(img);
}
} else if (command == "tb") { // read the table command and set settings
tableflag = 1;
string tableborder = "1"; // these are the table defaults
rowquit = 0;
tablealign = "c";
dataalign = "0";
rowvalign = "0";
ncnum = 0;
ncalign = 0;
ncvalign = 0;
cnum.clear();
acolnum.clear();
vacolnum.clear();
cwidth.clear();
colalign.clear();
colvalign.clear();
tabledelim = ",";
string tw = "";
dwidth = "0";
for (int i = 0; i < narg; i++) { // loop through each tb() arg
int tbstop;
string tbcommand;
tbstop = 0;
tbstop = arg[i].find("=");
tbcommand = arg[i].substr(0,tbstop);
int n = arg[i].length();
if (tbstop == -1) {
continue;
} else if (tbcommand == "c") {
string collumn= arg[i].substr (tbstop+1,n-(tbstop+1));
rowquit = atoi(collumn.c_str());
} else if (tbcommand == "s") {
tabledelim= arg[i].substr (tbstop+1,n-(tbstop+1));
} else if (tbcommand == "b") {
tableborder= arg[i].substr (tbstop+1,n-(tbstop+1));
} else if (tbcommand == "w") {
string width = "0";
if (arg[i].substr (n-1,1) == "%") {
string width = arg[i].substr (tbstop+1,n-(tbstop+1));
tw = " WIDTH=\"" + width + "\"";
} else
dwidth = arg[i].substr (tbstop+1,n-(tbstop+1));
} else if (tbcommand == "ea") {
dataalign= arg[i].substr (tbstop+1,n-(tbstop+1));
} else if (tbcommand == "eva") {
rowvalign= arg[i].substr (tbstop+1,n-(tbstop+1));
} else if (tbcommand == "a") {
tablealign= arg[i].substr (tbstop+1,n-(tbstop+1));
} else if (tbcommand.substr(0,2) == "cw") {
string cwnum= tbcommand.substr(2,tbstop-1);
cnum.resize(ncnum+1);
cnum[ncnum] = atoi(cwnum.c_str());
cwidth.resize(ncnum+1);
cwidth[ncnum]= arg[i].substr(tbstop+1,n-(tbstop+1));
ncnum++;
} else if (tbcommand.substr(0,2) == "ca") {
string canum= tbcommand.substr(2,tbstop-1);
acolnum.resize(ncalign+1);
acolnum[ncalign] = atoi(canum.c_str());
colalign.resize(ncalign+1);
colalign[ncalign]= arg[i].substr(tbstop+1,n-(tbstop+1));
ncalign++;
} else if (tbcommand.substr(0,3) == "cva") {
string cvanum= tbcommand.substr(2,tbstop-1);
vacolnum.resize(ncvalign+1);
vacolnum[ncvalign] = atoi(cvanum.c_str());
colvalign.resize(ncvalign+1);
colvalign[ncvalign]= arg[i].substr(tbstop+1,n-(tbstop+1));
ncvalign++;
} else {
fprintf(stderr,
"ERROR: Unrecognized table command %s\n",tbcommand.c_str());
exit(1);
}
tbstop = s.find("=");
}
string align;
if (tablealign=="c") align="center";
else if (tablealign=="r") align="right ";
else if (tablealign=="l") align="left ";
else align="center";
string tablea = "<DIV ALIGN=" + align + ">" ;
pre.append(tablea);
pre.append("<TABLE ");
pre.append(tw);
string border=" BORDER=" + tableborder + " >\n";
pre.append(border);
post.insert(0,"</TD></TR></TABLE></DIV>\n");
} else if (command == "all") {
if (narg == 1) allflag = arg[0];
} else {
fprintf(stderr,"ERROR: Unrecognized command %s\n",command.c_str());
exit(1);
}
}
}
// perform substitutions within text of paragraph
void substitute(string &s)
{
size_t n,m,p;
char c;
string text,link,href;
string punctuation = ".,?!;:()";
// substitute for bold & italic markers
// if preceded by \ char, then leave markers in text
n = s.find_first_of("[]{}");
while (n != string::npos) {
c = s[n];
if (n > 0 && s[n-1] == '\\') s.erase(n-1,1);
else {
s.erase(n,1);
if (c == '[') s.insert(n,"<B>");
else if (c == ']') s.insert(n,"</B>");
else if (c == '{') s.insert(n,"<I>");
else if (c == '}') s.insert(n,"</I>");
}
n = s.find_first_of("[]{}",n);
}
// substitute for links
n = s.find("\"_");
while (n != string::npos) {
m = s.rfind("\"",n-1);
if (m == string::npos) {
fprintf(stderr,"ERROR: Could not find matching \" for \"_ in %s\n",
s.c_str());
exit(1);
}
p = s.find_first_of(" \t\n",n) - 1;
if (p == string::npos) {
fprintf(stderr,"ERROR: Could not find end-of-link in %s\n",s.c_str());
exit(1);
}
while (s.find_first_of(".,?!;:()",p) == p) p--;
text = s.substr(m+1,n-m-1);
link = s.substr(n+2,p-n-1);
for (int i = 0; i < nlink; i++)
if (alias1[i] == link) {
link = alias2[i];
break;
}
s.erase(m,p-m+1);
href = "<A HREF = \"" + link + "\">" + text + "</A>";
s.insert(m,href);
n = s.find("\"_");
}
// format the paragraph as a table
if (tableflag) {
tableflag = 0;
string DT;
// set up <TR> tag
// alignment for data in rows
string tbalign;
if (dataalign != "0"){
string align;
if (dataalign=="c") align="\"center\"";
else if (dataalign=="r") align="\"right\"";
else if (dataalign=="l") align="\"left\"";
else {
fprintf(stderr,
"ERROR: Unrecognized table alignment argument %s for ea=X\n",
dataalign.c_str());
exit(1);
}
tbalign = " ALIGN=" + align;
} else tbalign="";
// set up vertical alignment for particular columns
string va;
if (rowvalign != "0"){
string valign;
if (rowvalign == "t") valign= "top";
else if (rowvalign == "m") valign= "middle";
else if (rowvalign == "ba") valign= "baseline";
else if (rowvalign == "bo") valign= "bottom";
else {
fprintf(stderr,
"ERROR: Unrecognized table alignment argument %s for eva=X\n",
rowvalign.c_str());
exit(1);
}
va = " VALIGN =\"" + valign + "\"";
} else va="";
//tr_tag is keyword for data in rows
string tr_tag= "<TR" + tbalign + va + ">";
//declare integers to help with counting and finding position
int currentc=0; // current column
int nend = 0;
int n1=0;
long n = find_n(s,nend,n1);
// if there are no separators, go to the end of the string
if (n < 0) n = s.length();
// while n exists:
while (n != static_cast<long>(string::npos)) {
// ignore = 0 when pass by \n because looking for delimiters only
// when ignore==0 do not put in a <tr>
int ignore=1;
// For each loop starts nend at n
nend=n;
// current column is 0, (very first loop), insert first <TR>
if (currentc == 0){
currentc++;
DT=td_tag(currentc);
s.insert(0,tr_tag);
s.insert(tr_tag.length(),DT);
nend=nend+tr_tag.length()+DT.length();
n = find_n(s,nend,n1);
if (n==n1) currentc++;
else {
// currentc will remain one if rowquit==0
if (rowquit>0){
s.erase(n,1);
n = find_n(s,nend,n1);
currentc++;
}
}
} else {
// if n is separator
if (n == n1){
s.erase(n,tabledelim.length());
if(currentc==(rowquit+1)&& rowquit!=0){
s.insert(nend,"</TD></TR>\n");
nend=nend+11;
// set current column back to one to start new line
currentc=1;
}else{
DT= td_tag(currentc);
s.insert (nend,"</TD>");
nend=nend+5;
s.insert (nend,DT);
nend=nend+DT.length();
// add one so current column is updated
currentc++;
n = find_n(s,nend,n1);
}
}
//if n is newline character
else{
s.erase(n,1);
// if columns == 0 means ARE searching for newlines
// else erase and ignore insert <tr> later and
// search for next separator
if (rowquit==0){
s.insert(nend,"</TD></TR>\n");
nend=nend+11;
// set current column back to one to start new line
currentc=1;
}else{
ignore=0;
n = find_n(s,nend,n1);
}
}
// if we are at the beginning of the row then insert <TR>
if (currentc==1&&ignore) {
DT = td_tag(currentc); // find DT for currentc=1
s.insert(nend,tr_tag);
nend=nend+tr_tag.length();
s.insert(nend,DT);
n = find_n(s,nend,n1); // search for next separator
currentc++;
}
} // end to else statement
} // end to while loop
} // end to if tableflag
// if listflag is set, put list marker at beginning of every line
if (listflag != "") {
string marker;
int toggle = 0;
n = s.find('\n');
while (n != string::npos) {
m = s.rfind('\n',n-1);
if (listflag == "dl" && toggle == 0) marker = "<DT>";
else if (listflag == "dl" && toggle == 1) marker = "<DD>";
else marker = "<LI>";
if (m == string::npos) s.insert(0,marker);
else s.insert(m+1,marker);
n = s.find('\n',m+1);
n = s.find('\n',n+1);
if (toggle) toggle = 0;
else toggle = 1;
}
listflag = "";
}
// if allflag is set, add markers to every line
if (allflag != "") {
string marker1,marker2;
if (allflag == "p") {
marker1 = "<P>";
marker2 = "</P>";
} else if (allflag == "c") {
marker1 = "<CENTER>";
marker2 = "</CENTER>";
} else if (allflag == "b") {
marker1 = "";
marker2 = "<BR>";
} else if (allflag == "l") {
marker1 = "<LI>";
marker2 = "";
} else marker1 = marker2 = "";
n = s.find('\n');
while (n != string::npos) {
m = s.rfind('\n',n-1);
if (m == string::npos) s.insert(0,marker1);
else s.insert(m+1,marker1);
n = s.find('\n',m+1);
s.insert(n,marker2);
n = s.find('\n',n);
n = s.find('\n',n+1);
}
allflag = "";
}
}
// open input file as-is or as file.txt
// if npair = 0, don't open output file (is just initial pass thru input)
// if npair = 1, open output file as stdout
// if npair > 1, open output file with .html suffix
// either replace .txt in input file, or append .html
void file_open(int npair, string &infile, FILE **in, FILE **out)
{
*in = fopen(infile.c_str(),"r");
if (*in == NULL) {
string root = infile;
infile = infile + ".txt";
*in = fopen(infile.c_str(),"r");
if (*in == NULL) {
fprintf(stderr,"ERROR: Could not open %s or %s\n",
root.c_str(),infile.c_str());
exit(1);
}
}
if (npair == 0) return;
else if (npair == 1) *out = stdout;
else {
string outfile;
size_t pos = infile.rfind(".txt");
if (pos == infile.length()-4) outfile = infile.substr(0,pos) + ".html";
else outfile = infile + ".html";
*out = fopen(outfile.c_str(),"w");
if (*out == NULL) {
fprintf(stderr,"ERROR: Could not open %s\n",outfile.c_str());
exit(1);
}
}
}
// for tables:
// build <TD> string (DT) based on current column
string td_tag(int currentc) {
// eacolumn gives the alignment printout of a specific column
string eacolumn;
// va gives vertical alignment to a specific column
string va;
// DT is the complete <td> tag, with width and align
string DT;
// dw is the width for tables. It is also the <dt> tag beginning
string dw;
// set up alignment for particular columns
for (int counter=0; counter < ncalign; counter++){
if (ncalign != 0 && acolnum[counter] == currentc){
string align;
if (colalign[counter] == "l") align= "left";
else if (colalign[counter] == "r") align= "right";
else if (colalign[counter] == "c") align= "center";
else {
fprintf(stderr,
"ERROR: Unrecognized table alignment argument %s for caM=X\n",
colalign[counter].c_str());
exit(1);
}
eacolumn= " ALIGN =\"" + align +"\"";
}else eacolumn= "";
}
// set up vertical alignment for particular columns
for (int counter=0; counter < ncvalign; counter++){
if (ncvalign != 0 && vacolnum[counter] == currentc){
string valign;
if (colvalign[counter] == "t") valign= "top";
else if (colvalign[counter] == "m") valign= "middle";
else if (colvalign[counter] == "ba") valign= "baseline";
else if (colvalign[counter] == "bo") valign= "bottom";
else {
fprintf(stderr,
"ERROR: Unrecognized table alignment argument %s for cvaM=X\n",
colvalign[counter].c_str());
exit(1);
}
va = " VALIGN =\"" + valign + "\"";
} else va = " ";
}
// put in special width if specified
// new code
// if dwidth has not been set, dw is blank
// if dwidth has been set, dw has that... unless
if (dwidth=="0") dw = " ";
else dw =" WIDTH=\""+ dwidth + "\"";
for (int counter = 0; counter < ncnum; counter++){
// if it is the right column, dw = cwidth property
if (cnum[counter] == currentc) dw= " WIDTH=\"" + cwidth[counter] + "\"";
}
// DT is set for all of this particular separator : reset next separator
DT = "<TD" + dw + eacolumn + va + ">";
return DT;
}
// for tables:
// find the next separator starting at nend(the end of the last .insert)
// if there is either a delim or newline
// decide which is first
// set n = to that position
// nsep is position of the next separator. changes in here.
long find_n(string &s, int nend, int &nsep)
// nsep is position of the next separator. changes in here.
{
long n;
nsep = s.find(tabledelim,nend);
long n2 = s.find('\n',nend);
long m = s.length() - 1;
if (nsep >= 0 && n2 >= 0) {
if (nsep <= n2) n = nsep;
else n = n2;
} else {
if (nsep >= 0) n = nsep;
else{
if (n2 < m) n = n2;
else n = string::npos;
}
}
return n;
}
|
#include <glm/gtc/matrix_transform.hpp>
#include <OBJ_Loader.h>
#include <unordered_map>
#include <algorithm>
#include <cstdint>
#include "Model.h"
#include "Log.h"
#include "Utility.h"
namespace fly
{
inline static glm::vec3 to_vec3(const objl::Vector3& v)
{
return {v.X, v.Y, v.Z};
}
Model::Model(const std::string& model_path)
: m_monotoneColor(false)
{
m_vao.bind();
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glGenBuffers(1, &m_elementBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementBuffer);
if (m_shaderProgram.loadShaderFile("shaders/model.vert", Shader::Vertex))
{
LOG(Info) << "Loaded Vertex shader" << std::endl;
}
if (m_shaderProgram.loadShaderFile("shaders/model.frag", Shader::Fragment))
{
LOG(Info) << "Loaded Fragment shader" << std::endl;
}
objl::Loader loader;
if (loader.LoadFile(model_path))
{
glBufferData(GL_ARRAY_BUFFER, loader.LoadedVertices.size() * sizeof(objl::Vertex),
loader.LoadedVertices.data(), GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, loader.LoadedIndices.size() * sizeof(unsigned int),
loader.LoadedIndices.data(), GL_STATIC_DRAW);
m_shaderProgram.setAttributeFloat("position", 3, sizeof(objl::Vertex),
offsetof(objl::Vertex, Position));
m_shaderProgram.setAttributeFloat("normal", 3, sizeof(objl::Vertex),
offsetof(objl::Vertex, Normal));
// m_shaderProgram.setAttributeFloat("texcoords", 2, sizeof(objl::Vertex),
// offsetof(objl::Vertex, TextureCoordinate));
// TODO Remove texcoords (since I'm not using it, instead of wasting precious GPU memory)
// Calculate bounding box
glm::vec3 min {to_vec3(loader.LoadedVertices.front().Position)};
glm::vec3 max {min};
for (const auto& vertex : loader.LoadedVertices)
{
auto vec = to_vec3(vertex.Position);
min = component_wise_apply(min, vec, std::min);
max = component_wise_apply(max, vec, std::max);
}
m_localBounds.dimensions = max - min;
m_localBounds.position = (max + min) / 2.f;
LOG(Info) << "Model size: " << m_localBounds.dimensions << std::endl;
LOG(Info) << "Model center: " << m_localBounds.position << std::endl;
std::unordered_map<std::string, std::size_t> materials_map;
for (const auto& m : loader.LoadedMaterials)
{
materials_map[m.name] = m_materials.size();
m_materials.push_back({
{m.Ka.X, m.Ka.Y, m.Ka.Z},
{m.Kd.X, m.Kd.Y, m.Kd.Z},
{m.Ks.X, m.Ks.Y, m.Ks.Z},
m.Ns
});
}
uint offset = 0;
for (const auto& mesh : loader.LoadedMeshes)
{
m_meshes.push_back({mesh.MeshName, offset, static_cast<uint>(mesh.Indices.size()),
m_materials.at(materials_map[mesh.MeshMaterial.name])});
offset += mesh.Indices.size();
}
m_totalElements = loader.LoadedIndices.size();
assert(offset == m_totalElements);
LOG(Info) << "Loaded model: " << model_path << std::endl;
}
else
LOG(Error) << "Error in opening model file: " << model_path << std::endl;
m_vao.unbind();
ASSERT_GL_ERRORS();
}
Model::~Model()
{
glDeleteBuffers(1, &m_vertexBuffer);
glDeleteBuffers(1, &m_elementBuffer);
}
void Model::draw()
{
if (m_monotoneColor)
{
m_shaderProgram.setUniform("flash", true);
rawDraw();
// m_shaderProgram.setUniform("flash", false);
// m_flash = false;
}
else
{
m_shaderProgram.use();
m_vao.bind();
for (auto& mesh : m_meshes)
{
m_shaderProgram.setUniform("ambient_color", mesh.material.ambient_color);
m_shaderProgram.setUniform("diffuse_color", mesh.material.diffuse_color);
m_shaderProgram.setUniform("specular_exponent", mesh.material.specular_exponent);
m_shaderProgram.setUniform("specular_color", mesh.material.specular_color);
glDrawElements(GL_TRIANGLES, mesh.elements_size, GL_UNSIGNED_INT,
reinterpret_cast<void*>(mesh.elements_offset * sizeof(unsigned int)));
}
m_vao.unbind();
}
}
void Model::rawDraw()
{
m_vao.bind();
glDrawElements(GL_TRIANGLES, m_totalElements, GL_UNSIGNED_INT, 0);
m_vao.unbind();
}
}
|
//----------------------------------*-C++-*----------------------------------//
/*!
* \file parser/test/tstExpression.cc
* \author Kent Budge
* \date Wed Jul 26 08:15:18 2006
* \brief Test the Expression class and expression parsing.
* \note Copyright (C) 2016-2019 Triad National Security, LLC.
* All rights reserved. */
//---------------------------------------------------------------------------//
#include "ds++/DracoMath.hh"
#include "ds++/Release.hh"
#include "ds++/ScalarUnitTest.hh"
#include "parser/Expression.hh"
#include "parser/String_Token_Stream.hh"
using namespace std;
using namespace rtt_dsxx;
using namespace rtt_parser;
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
void tstExpression(UnitTest &ut) {
// Create an expression as a String_Token_Stream.
string const expression_text =
"(((+1 && 1.3)||!(y<-m))/5+(2>1)*(r/m)*(2.7-1.1*(z/m))^2)*(t/s)";
String_Token_Stream tokens(expression_text);
typedef pair<unsigned, Unit> vd;
map<string, vd> variable_map;
variable_map["r"] = vd(0, m);
variable_map["y"] = vd(1, m);
variable_map["z"] = vd(2, m);
variable_map["t"] = vd(3, s);
vector<string> vars(4);
vars[0] = "r";
vars[1] = "y";
vars[2] = "z";
vars[3] = "t";
std::shared_ptr<Expression const> expression =
Expression::parse(4, variable_map, tokens);
if (tokens.error_count() == 0 && tokens.lookahead().type() == EXIT) {
PASSMSG("expression successfully parsed");
} else {
FAILMSG("expression NOT successfully parsed");
cerr << tokens.messages() << endl;
}
ostringstream expression_text_copy;
expression->write(vars, expression_text_copy);
char const *expression_text_raw =
"((1&&1.3||!(y<-m))/5+(2>1)*r/m*pow(2.7-1.1*z/m,2))*t/s";
// changes slightly due to stripping of extraneous whitespace, parentheses,
// and positive prefix
if (expression_text_copy.str() == expression_text_raw) {
PASSMSG("expression successfully rendered as text");
} else {
FAILMSG("expression NOT successfully rendered as text");
cerr << expression_text_raw << endl;
cerr << expression_text_copy.str() << endl;
}
#if 0
// Test calculus
std::shared_ptr<Expression const> deriv = expression->pd(3);
ostringstream deriv_text;
deriv->write(vars, deriv_text);
expression_text_raw =
"((1&&1.3||!(y<-m))/5+(2>1)*r/m*pow(2.7-1.1*z/m,2))*t/s";
if (deriv_text.str()==expression_text_raw)
{
PASSMSG("expression successfully derived");
}
else
{
FAILMSG("expression NOT successfully derived");
cerr << expression_text_raw << endl;
cerr << deriv_text.str() << endl;
}
#endif
vector<double> xs;
double x = 1.2;
double r = x;
double y = 3.1;
double z = 0.0;
double t = 2.8;
xs.resize(4);
xs[0] = r;
xs[1] = y;
xs[2] = z;
xs[3] = t;
#if defined(MSVC)
#pragma warning(push)
// warning C4804: '/' : unsafe use of type 'bool' in operation
#pragma warning(disable : 4804)
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wliteral-conversion"
#endif
if (soft_equiv((*expression)(xs), (((1 && 1.3) || !(y < -1)) / 5. +
(2 > 1) * r * square(2.7 - 1.1 * z)) *
t)) {
PASSMSG("expression successfully evaluated");
} else {
FAILMSG("expression NOT successfully evaluated");
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#if defined(MSVC)
#pragma warning(pop)
#endif
tokens = string("20*(r>=1.1*m && z<=1.5*m || r>=2.0*m && r<=7.0*m)");
expression = Expression::parse(4, variable_map, tokens);
if (expression != std::shared_ptr<Expression>())
PASSMSG("expression successfully parsed");
else
FAILMSG("expression NOT successfully parsed");
if (soft_equiv((*expression)(xs),
20.0 *
((r >= 1.1) && ((z <= 1.5) || (r >= 2.0 && r <= 7.0))))) {
PASSMSG("expression successfully evaluated");
} else {
FAILMSG("expression NOT successfully evaluated");
}
{
ostringstream lexpression_text_copy;
expression->write(vars, lexpression_text_copy);
char const *lexpression_text_raw =
"20*(r>=1.1*m&&z<=1.5*m||r>=2*m&&r<=7*m)";
// changes slightly due to stripping of extraneous whitespace, parentheses,
// and positive prefix
if (lexpression_text_copy.str() == lexpression_text_raw) {
PASSMSG("expression successfully rendered as text");
} else {
FAILMSG("expression NOT successfully rendered as text");
cerr << lexpression_text_raw << endl;
cerr << lexpression_text_copy.str() << endl;
}
}
tokens = String_Token_Stream("(1 && (4>=6 || 4>6 || 6<4 || 6<=4 || !0))"
"* ( (r/m)^(t/s) + -3 - z/m)");
expression = Expression::parse(4, variable_map, tokens);
if (tokens.error_count() == 0 && tokens.lookahead().type() == EXIT) {
PASSMSG("expression successfully parsed");
} else {
FAILMSG("expression NOT successfully parsed");
cerr << tokens.messages() << endl;
}
if (soft_equiv((*expression)(xs), pow(r, t) + -3 - z))
PASSMSG("expression successfully evaluated");
else
FAILMSG("expression NOT successfully evaluated");
if (!expression->is_constant() && !expression->is_constant(0) &&
expression->is_constant(1))
PASSMSG("is_constant good");
else
FAILMSG("is_constant NOT good");
tokens = String_Token_Stream("exp(-0.5*r/m)*(3*cos(2*y/m) + 5*sin(3*y/m))");
expression = Expression::parse(4, variable_map, tokens);
if (expression != std::shared_ptr<Expression>())
PASSMSG("expression successfully parsed");
else
FAILMSG("expression NOT successfully parsed");
if (soft_equiv((*expression)(xs),
exp(-0.5 * r) * (3 * cos(2 * y) + 5 * sin(3 * y)))) {
PASSMSG("expression successfully evaluated");
} else {
FAILMSG("expression NOT successfully evaluated");
}
{
ostringstream lexpression_text_copy;
expression->write(vars, lexpression_text_copy);
char const *lexpression_text_raw =
"exp(-0.5*r/m)*(3*cos(2*y/m)+5*sin(3*y/m))";
// changes slightly due to stripping of extraneous whitespace, parentheses,
// and positive prefix
if (lexpression_text_copy.str() == lexpression_text_raw) {
PASSMSG("expression successfully rendered as text");
} else {
FAILMSG("expression NOT successfully rendered as text");
cerr << lexpression_text_raw << endl;
cerr << lexpression_text_copy.str() << endl;
}
}
tokens = String_Token_Stream("log(1.0)");
expression = Expression::parse(4, variable_map, tokens);
if (expression != std::shared_ptr<Expression>())
PASSMSG("expression successfully parsed");
else
FAILMSG("expression NOT successfully parsed");
if (soft_equiv((*expression)(xs), 0.0))
PASSMSG("expression successfully evaluated");
else
FAILMSG("expression NOT successfully evaluated");
{
ostringstream lexpression_text_copy;
expression->write(vars, lexpression_text_copy);
char const *lexpression_text_raw = "log(1)";
// changes slightly due to stripping of extraneous whitespace, parentheses,
// and positive prefix
if (lexpression_text_copy.str() == lexpression_text_raw) {
PASSMSG("expression successfully rendered as text");
} else {
FAILMSG("expression NOT successfully rendered as text");
cerr << lexpression_text_raw << endl;
cerr << lexpression_text_copy.str() << endl;
}
}
{
tokens = String_Token_Stream("log(1.0) + cos(2.0) + exp(3.0) + sin(4.0)");
std::shared_ptr<Expression> lexpression =
Expression::parse(4, variable_map, tokens);
if (lexpression->is_constant(0))
PASSMSG("expression successfully const tested");
else
FAILMSG("expression NOT successfully const tested");
lexpression->set_units(J);
if (is_compatible(J, lexpression->units()))
PASSMSG("units correctly set");
else
FAILMSG("units NOT correctly set");
}
{
tokens = String_Token_Stream(
"(log(1.0) + cos(2.0) + exp(3.0) + sin(4.0))/(m*s)");
std::shared_ptr<Expression> lexpression =
Expression::parse(4, variable_map, tokens);
if (lexpression->is_constant(0))
PASSMSG("expression successfully const tested");
else
FAILMSG("expression NOT successfully const tested");
ostringstream lexpression_text_copy;
lexpression->write(vars, lexpression_text_copy);
cout << lexpression_text_copy.str() << endl;
char const *lexpression_text_raw = "(log(1)+cos(2)+exp(3)+sin(4))/(m*s)";
// changes slightly due to stripping of extraneous whitespace, parentheses,
// and positive prefix
if (lexpression_text_copy.str() == lexpression_text_raw) {
PASSMSG("expression successfully rendered as text");
} else {
FAILMSG("expression NOT successfully rendered as text");
cerr << lexpression_text_raw << endl;
cerr << lexpression_text_copy.str() << endl;
}
lexpression->set_units(J);
if (is_compatible(J, lexpression->units()))
PASSMSG("units correctly set");
else
FAILMSG("units NOT correctly set");
}
}
//---------------------------------------------------------------------------//
int main(int argc, char *argv[]) {
ScalarUnitTest ut(argc, argv, release);
try {
tstExpression(ut);
}
UT_EPILOG(ut);
}
//---------------------------------------------------------------------------//
// end of tstExpression.cc
//---------------------------------------------------------------------------//
|
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "modules/webgl/WebGLLoseContext.h"
#include "modules/webgl/WebGLRenderingContextBase.h"
namespace blink {
WebGLLoseContext::WebGLLoseContext(WebGLRenderingContextBase* context)
: WebGLExtension(context) {}
WebGLLoseContext::~WebGLLoseContext() {}
void WebGLLoseContext::lose(bool force) {
if (force)
WebGLExtension::lose(true);
}
WebGLExtensionName WebGLLoseContext::name() const {
return WebGLLoseContextName;
}
WebGLLoseContext* WebGLLoseContext::create(WebGLRenderingContextBase* context) {
return new WebGLLoseContext(context);
}
void WebGLLoseContext::loseContext() {
WebGLExtensionScopedContext scoped(this);
if (!scoped.isLost()) {
scoped.context()->forceLostContext(
WebGLRenderingContextBase::WebGLLoseContextLostContext,
WebGLRenderingContextBase::Manual);
}
}
void WebGLLoseContext::restoreContext() {
WebGLExtensionScopedContext scoped(this);
if (!scoped.isLost())
scoped.context()->forceRestoreContext();
}
bool WebGLLoseContext::supported(WebGLRenderingContextBase*) {
return true;
}
const char* WebGLLoseContext::extensionName() {
return "WEBGL_lose_context";
}
} // namespace blink
|
#include "Vertex.h"
#include <df3d/lib/Utils.h>
#include <df3d/engine/EngineController.h>
namespace df3d {
static uint16_t GetAttributeSize(VertexFormat::VertexAttribute attrib)
{
switch (attrib)
{
case VertexFormat::POSITION:
return 3 * sizeof(float);
case VertexFormat::TX:
return 2 * sizeof(float);
case VertexFormat::COLOR:
return 4 * sizeof(float);
case VertexFormat::NORMAL:
return 3 * sizeof(float);
case VertexFormat::TANGENT:
return 3 * sizeof(float);
case VertexFormat::BITANGENT:
return 3 * sizeof(float);
default:
DF3D_ASSERT_MESS(false, "no such attribute in vertex format");
}
return 0;
}
static uint16_t GetAttributeCompCount(VertexFormat::VertexAttribute attrib)
{
switch (attrib)
{
case VertexFormat::TX:
return 2;
case VertexFormat::POSITION:
case VertexFormat::NORMAL:
case VertexFormat::TANGENT:
case VertexFormat::BITANGENT:
return 3;
case VertexFormat::COLOR:
return 4;
default:
DF3D_ASSERT_MESS(false, "Unknown vertex attribute");
}
return 0;
}
uint16_t VertexFormat::getHash() const
{
uint16_t res = 0;
for (uint16_t i = 0; i < COUNT; i++)
{
if (hasAttribute((VertexAttribute)i))
res |= (uint16_t)1 << i;
}
return res;
}
VertexFormat::VertexFormat()
: m_size(0)
{
memset(&m_attribs, 0xFFFF, sizeof(m_attribs));
}
VertexFormat::VertexFormat(std::initializer_list<VertexAttribute> attribs)
: VertexFormat()
{
uint16_t totalOffset = 0;
for (auto attrib : attribs)
{
uint16_t attribSize = GetAttributeSize(attrib);
uint16_t attribCompCount = GetAttributeCompCount(attrib);
DF3D_ASSERT(attribCompCount >= 1 && attribCompCount <= 4);
m_attribs[attrib] = (totalOffset << 8) | attribCompCount;
m_size += attribSize;
totalOffset = m_size;
DF3D_ASSERT(totalOffset <= (2 << 8));
}
}
VertexData::VertexData(const VertexFormat &format)
: m_data(MemoryManager::allocDefault()),
m_format(format)
{
}
void VertexData::addVertices(size_t verticesCount)
{
DF3D_ASSERT(verticesCount > 0);
m_data.resize(m_format.getVertexSize() * verticesCount + m_data.size());
}
void VertexData::addVertex()
{
m_data.resize(m_data.size() + m_format.getVertexSize());
}
void* VertexData::getVertex(size_t idx)
{
DF3D_ASSERT(idx < getVerticesCount());
return m_data.data() + m_format.getVertexSize() * idx;
}
void* VertexData::getVertexAttribute(size_t idx, VertexFormat::VertexAttribute attrib)
{
DF3D_ASSERT(m_format.hasAttribute(attrib));
auto vertex = (uint8_t*)getVertex(idx);
return vertex + m_format.getOffsetTo(attrib);
}
size_t VertexData::getVerticesCount() const
{
return m_data.size() / m_format.getVertexSize();
}
const VertexFormat& Vertex_p_tx_c::getFormat()
{
static VertexFormat format = { VertexFormat::POSITION, VertexFormat::TX, VertexFormat::COLOR };
return format;
}
const VertexFormat& Vertex_p_n_tx_tan_bitan::getFormat()
{
static VertexFormat format = { VertexFormat::POSITION, VertexFormat::NORMAL,
VertexFormat::TX, VertexFormat::TANGENT, VertexFormat::BITANGENT };
return format;
}
}
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include <psapi.h>
using namespace std;
using namespace FederationTest;
using namespace Federation;
using namespace Common;
int const RandomFederationTestSession::DefaultPingIntervalInSeconds = 3;
RandomFederationTestSession::RingContext::RingContext(RandomFederationTestSession & session, wstring const & ringName, vector<LargeInteger> const & allNodes, int baseLeaseAgentPort)
: session_(session),
ringName_(ringName),
allNodes_(allNodes),
baseLeaseAgentPort_(baseLeaseAgentPort),
belowQuorumStartTime_(StopwatchTime::Zero),
lastArbitrationTime_(StopwatchTime::Zero)
{
RandomFederationTestConfig const & config = session_.config_;
seedCount_ = static_cast<size_t>(config.SeedNodeCount);
quorum_ = (seedCount_ / 2) + 1;
for (int i = 0; i < sizeof(storeValues_) / sizeof(int64); i++)
{
storeValues_[i] = 0;
}
}
wstring RandomFederationTestSession::RingContext::GetSeedNodes()
{
wstring result;
StringWriter w(result);
for (size_t i = 0; i < seedCount_; i++)
{
w.Write(" {0}", allNodes_[i]);
if (session_.ringCount_ > 1)
{
w.Write("@{0}", ringName_);
}
liveNodes_.push_back(allNodes_[i]);
liveSeedNodes_.insert(make_pair(allNodes_[i], Stopwatch::Now()));
}
sort(liveNodes_.begin(), liveNodes_.end());
return result;
}
void RandomFederationTestSession::RingContext::AddSeedNodes()
{
for (size_t i = 0; i < seedCount_; i++)
{
session_.AddInput(FederationTestDispatcher::AddCommand + allNodes_[i].ToString() + wformatString(" {0}", GetLeaseAgentPort(allNodes_[i])));
}
}
bool RandomFederationTestSession::RingContext::ContainsNode(std::vector<Common::LargeInteger> const& nodes, Common::LargeInteger const& node)
{
vector<LargeInteger>::const_iterator result = find(nodes.begin(), nodes.end(), node);
bool res = result != nodes.end();
return res;
}
bool RandomFederationTestSession::RingContext::IsSeedNode(LargeInteger const& node)
{
for (size_t i = 0; i < seedCount_; i++)
{
if (allNodes_[i] == node)
{
return true;
}
}
return false;
}
int RandomFederationTestSession::RingContext::GetLeaseAgentPort(LargeInteger const node) const
{
for (size_t i = 0; i < allNodes_.size(); i++)
{
if (allNodes_[i] == node)
{
return baseLeaseAgentPort_ + static_cast<int>(i);
}
}
Assert::CodingError("Node {0} not found", node);
}
int RandomFederationTestSession::RingContext::GetArbitratorCount()
{
FederationConfig const & config = FederationConfig::GetConfig();
StopwatchTime startTime = Stopwatch::Now() - (config.MaxLeaseDuration + config.ArbitrationTimeout + TimeSpan::FromSeconds(5));
int count = 0;
for (auto it = liveSeedNodes_.begin(); it != liveSeedNodes_.end(); ++it)
{
if (it->second < startTime)
{
count++;
}
}
return count;
}
void RandomFederationTestSession::RingContext::InitializeFederationStage()
{
nodeHistory_.clear();
}
LargeInteger RandomFederationTestSession::RingContext::SelectLiveNode()
{
size_t r = static_cast<size_t>(session_.random_.Next()) % liveNodes_.size();
return liveNodes_[r];
}
void RandomFederationTestSession::RingContext::AddNode(bool seedNodeOnly)
{
LargeInteger node;
size_t index = 0;
do
{
size_t range = (seedNodeOnly ? seedCount_ : allNodes_.size());
index = session_.random_.Next() % range;
node = allNodes_[index];
} while (ContainsNode(nodeHistory_, node) || ContainsNode(liveNodes_, node));
liveNodes_.push_back(node);
sort(liveNodes_.begin(), liveNodes_.end());
if (IsSeedNode(node))
{
liveSeedNodes_.insert(make_pair(node, Stopwatch::Now()));
}
session_.AddInput(FederationTestDispatcher::AddCommand + node.ToString() + wformatString(" {0}", GetLeaseAgentPort(node)));
nodeHistory_.push_back(node);
}
void RandomFederationTestSession::RingContext::RemoveNode(bool seedNodeOnly)
{
size_t r = static_cast<size_t>(session_.random_.Next());
bool done = false;
while (!done)
{
r %= liveNodes_.size();
LargeInteger id = liveNodes_[r];
if (!ContainsNode(nodeHistory_, id) && (!seedNodeOnly || r < seedCount_))
{
int arbitratorCount = GetArbitratorCount();
if (IsSeedNode(id))
{
if (seedNodeOnly || arbitratorCount > quorum_)
{
auto it = liveSeedNodes_.find(id);
liveSeedNodes_.erase(it);
arbitratorCount = GetArbitratorCount();
}
else
{
r++;
continue;
}
}
liveNodes_.erase(liveNodes_.begin() + r);
int randomSample = session_.random_.Next(100);
if (randomSample < session_.config_.AbortRatio)
{
if ((randomSample % 3) > 0 && arbitratorCount >= quorum_ && !seedNodeOnly)
{
if ((randomSample % 3) > 1)
{
int leaseAgentPort = GetLeaseAgentPort(id);
session_.AddInput(wformatString("!expect,Node {0} Failed", id));
session_.AddUnreliableTransportBehavior(wformatString("{0} * ArbitrateKeepAlive", id), true);
session_.AddUnreliableTransportBehavior(wformatString("{0} * ArbitrateRequest", id), true);
session_.AddInput(wformatString("addleasebehavior {0} * indirect", leaseAgentPort));
session_.AddInput(wformatString("blockleaseagent {0}", leaseAgentPort));
}
else
{
session_.AddInput(wformatString("blockleaseagent {0}", GetLeaseAgentPort(id)));
session_.AddInput(FederationTestDispatcher::AbortCommand + L" " + id.ToString());
}
lastArbitrationTime_ = Stopwatch::Now();
}
else
{
session_.AddInput(FederationTestDispatcher::AbortCommand + L" " + id.ToString());
}
}
else
{
session_.AddInput(FederationTestDispatcher::RemoveCommand + id.ToString());
}
nodeHistory_.push_back(id);
done = true;
}
r++;
}
}
void RandomFederationTestSession::RingContext::AddOrRemoveNode()
{
if (liveSeedNodes_.size() < quorum_ && Stopwatch::Now() > belowQuorumStartTime_ + TimeSpan::FromSeconds(30))
{
session_.AddInput(wformatString("#Seed node count {0} below quorum, restoring quorum", liveSeedNodes_.size()));
while (liveSeedNodes_.size() < quorum_)
{
AddNode(true);
}
return;
}
int ratio = 100 * (static_cast<int>(liveNodes_.size()) - session_.config_.MinNodes) / (session_.config_.MaxNodes - session_.config_.MinNodes);
int r = session_.random_.Next() % 100;
if ((r >= ratio || ratio == 0) && ratio != 100)
{
AddNode(false);
}
else
{
FederationConfig const & config = FederationConfig::GetConfig();
StopwatchTime now = Stopwatch::Now();
if (liveSeedNodes_.size() == quorum_ &&
now > belowQuorumStartTime_ + TimeSpan::FromTicks(config.GlobalTicketLeaseDuration.Ticks * 4) &&
now > lastArbitrationTime_ + config.MaxLeaseDuration + config.ArbitrationTimeout &&
session_.random_.Next() % 3 == 0)
{
int remove = session_.random_.Next() % (quorum_ - 1) + 1;
session_.AddInput(wformatString("#Closing {0} seed nodes", remove));
for (int i = 0; i < remove; i++)
{
RemoveNode(true);
}
belowQuorumStartTime_ = now;
}
else
{
RemoveNode(false);
}
}
}
void RandomFederationTestSession::RingContext::ExecuteArbitrationStage()
{
FederationConfig const & config = FederationConfig::GetConfig();
int arbitratorCount = GetArbitratorCount();
if (arbitratorCount < quorum_ || liveNodes_.size() < config.NeighborhoodSize * 2 + 1)
{
return;
}
vector<LargeInteger> nodes = liveNodes_;
sort(nodes.begin(), nodes.end());
set<LargeInteger> blocked;
set<LargeInteger> blockedSeeds;
int nodeCount = static_cast<int>(nodes.size());
int count = session_.random_.Next(session_.config_.MaxBlockedLeaseAgent);
if (count > nodeCount - liveSeedNodes_.size())
{
count = nodeCount - static_cast<int>(liveSeedNodes_.size());
}
if (count == 0)
{
return;
}
session_.AddInput(wformatString("#Blocking {0} nodes, arbitrator={1}", count, arbitratorCount));
session_.AddInput(wformatString("addbehavior blockkeepalive * * ArbitrateKeepAlive {0}", session_.random_.NextDouble()));
session_.AddInput(wformatString("addleasebehavior * * indirect blockindirect"));
for (int i = 0; i < count && arbitratorCount >= quorum_; i++)
{
int j = session_.random_.Next(nodeCount);
LargeInteger id = nodes[j];
while ((blocked.find(id) != blocked.end()) ||
(IsSeedNode(id) && arbitratorCount == quorum_ && blockedSeeds.find(id) == blockedSeeds.end()))
{
j = (j + 1) % nodeCount;
id = nodes[j];
}
session_.AddInput(wformatString("#Blocking {0} port {1}", id, GetLeaseAgentPort(id)));
blocked.insert(id);
if (IsSeedNode(id))
{
if (blockedSeeds.find(id) == blockedSeeds.end())
{
arbitratorCount--;
blockedSeeds.insert(id);
}
}
vector<LargeInteger> neighbors;
int k = (j + nodeCount - config.NeighborhoodSize) % nodeCount;
for (int n = 0; n < config.NeighborhoodSize * 2 + 1; n++)
{
LargeInteger neighbor = nodes[(k + n) % nodeCount];
if (blocked.find(neighbor) == blocked.end())
{
neighbors.push_back(neighbor);
}
}
random_shuffle(neighbors.begin(), neighbors.end());
int blockCount = session_.random_.Next(static_cast<int>(neighbors.size()));
for (k = 0; k < blockCount; k++)
{
if (IsSeedNode(neighbors[k]) && blockedSeeds.find(neighbors[k]) == blockedSeeds.end())
{
if (arbitratorCount == quorum_)
{
continue;
}
blockedSeeds.insert(neighbors[k]);
arbitratorCount--;
}
session_.AddInput(wformatString("{0} add {1} {2}", FederationTestDispatcher::ArbitrationVerifierCommand, id, neighbors[k]));
session_.AddInput(wformatString("{0} {1} {2} *~", FederationTestDispatcher::AddLeaseBehaviorCommand, GetLeaseAgentPort(id), GetLeaseAgentPort(neighbors[k])));
}
}
session_.AddInput(wformatString("!pause,{0}", (config.LeaseDuration + config.ArbitrationTimeout).TotalSeconds()));
session_.AddInput(L"removebehavior blockkeepalive");
session_.AddCommand(L"removeleasebehavior");
session_.AddInput(L"!pause,10");
session_.AddInput(wformatString("{0} verify", FederationTestDispatcher::ArbitrationVerifierCommand));
session_.AddInput(L"verify");
}
void RandomFederationTestSession::RingContext::TestRouting()
{
LargeInteger from = SelectLiveNode();
LargeInteger target = LargeInteger::RandomLargeInteger_();
wstring toRing;
if (session_.ringCount_ > 1)
{
int r = session_.random_.Next(session_.ringCount_);
if (session_.rings_[r]->GetRingName() != ringName_)
{
toRing = L"@" + session_.rings_[r]->GetRingName();
}
}
session_.AddInput(FederationTestDispatcher::RouteRequestCommand + L" " + from.ToString() + L" " + target.ToString() + toRing);
}
void RandomFederationTestSession::RingContext::TestBroadcast()
{
LargeInteger from = SelectLiveNode();
int r = session_.random_.Next(4);
if (r < 2)
{
wstring destination;
if (r == 1 && session_.ringCount_ > 1)
{
destination = L" *";
}
session_.AddInput(FederationTestDispatcher::BroadcastOneWayReliableCommand + L" " + from.ToString() + destination);
}
else if (r == 2)
{
session_.AddInput(FederationTestDispatcher::BroadcastRequestCommand + L" " + from.ToString());
}
else
{
set<NodeId> targets;
double ratio = session_.random_.NextDouble();
for (size_t j = 0; j < liveNodes_.size(); j++)
{
if (session_.random_.NextDouble() > ratio)
{
targets.insert(liveNodes_[j]);
}
}
if (targets.size() == 0)
{
for (size_t j = 0; j < liveNodes_.size(); j++)
{
targets.insert(liveNodes_[j]);
}
}
while (session_.random_.Next(2) == 0)
{
NodeId extraId = NodeId(LargeInteger::RandomLargeInteger_());
targets.insert(extraId);
}
wstring temp;
for (auto it = targets.begin(); it != targets.end(); ++it)
{
if (temp.size() > 0)
{
temp = temp + L",";
}
temp = temp + it->ToString();
}
session_.AddInput(FederationTestDispatcher::MulticastCommand + L" " + from.ToString() + L" " + temp);
}
}
void RandomFederationTestSession::RingContext::TestVoterStore()
{
map<int, int> entries;
for (int i = 0; i < session_.random_.Next(1, session_.config_.MaxStoreWrites); i++)
{
int index = session_.random_.Next(sizeof(storeValues_) / sizeof(int64));
if (entries.find(index) == entries.end())
{
entries[index] = 1;
}
else
{
entries[index]++;
}
}
for (auto it = entries.begin(); it != entries.end(); ++it)
{
int index = it->first;
wstring key = wformatString("key{0}", index);
int64 oldValue = storeValues_[index];
for (int i = 0; i < it->second; i++)
{
LargeInteger from = SelectLiveNode();
bool checked = (it->second == 1 || session_.random_.Next(2) == 0);
int64 value = (checked ? ++storeValues_[index] : oldValue + it->second);
wstring command = wformatString("{0} {1} {2} {3}",
FederationTestDispatcher::WriteVoterStoreCommand,
from,
key,
value);
if (checked)
{
command = command + L" auto";
if (it->second > 1)
{
command = command + L" allowConflict";
}
}
session_.AddInput(command);
}
storeValues_[index] = oldValue + it->second;
}
session_.AddInput(FederationTestDispatcher::VerifyCommand + L" " + session_.waitTime_);
for (int i = 0; i < session_.random_.Next(1, session_.config_.MaxStoreWrites); i++)
{
int index = session_.random_.Next(sizeof(storeValues_) / sizeof(int64));
wstring key = wformatString("key{0}", index);
LargeInteger from = SelectLiveNode();
wstring command = wformatString("{0} {1} {2} auto auto",
FederationTestDispatcher::ReadVoterStoreCommand,
from,
key);
session_.AddInput(command);
}
}
void RandomFederationTestSession::RingContext::UpdateNodes(set<NodeId> const & nodes)
{
for (auto it = liveNodes_.begin(); it != liveNodes_.end();)
{
if (nodes.find(NodeId(*it)) == nodes.end())
{
liveSeedNodes_.erase(*it);
it = liveNodes_.erase(it);
}
else
{
++it;
}
}
}
void RandomFederationTestSession::CreateSingleton(int iterations, int timeout, wstring const& label, bool autoMode, int ringCount)
{
shared_ptr<RandomFederationTestSession> randomFederationTestSession = shared_ptr<RandomFederationTestSession>(new RandomFederationTestSession(iterations, timeout, label, autoMode, ringCount));
singleton_ = new shared_ptr<FederationTestSession>(static_pointer_cast<FederationTestSession>(randomFederationTestSession));
}
RandomFederationTestSession::RandomFederationTestSession(int iterations, int timeout, std::wstring const& label, bool autoMode, int ringCount)
: FederationTestSession(label, autoMode),
config_(RandomFederationTestConfig::GetConfig()),
testStage_(0),
initalizeStage_(0),
iterations_(iterations),
timeout_(timeout <= 0 ? TimeSpan::MaxValue : TimeSpan::FromSeconds(timeout)),
random_(),
highMemoryStartTime_(StopwatchTime::Zero),
ringCount_(ringCount),
currentRing_(0)
{
vector<LargeInteger> allNodes;
for (int i = 0; i < max(config_.TotalNodes, config_.SeedNodeCount); i++)
{
LargeInteger id = LargeInteger::RandomLargeInteger_();
if (find(allNodes.begin(), allNodes.end(), id) == allNodes.end())
{
allNodes.push_back(id);
}
}
int baseLeaseAgentPort = 17000;
for (int i = 0; i < ringCount_; i++)
{
wstring ringName = (ringCount_ > 1 ? wformatString("r{0}", i) : L"");
rings_.push_back(make_unique<RingContext>(*this, ringName, allNodes, baseLeaseAgentPort));
baseLeaseAgentPort += 100;
}
}
wstring RandomFederationTestSession::GetInput()
{
if (initalizeStage_ == 0)
{
//ClearTicket
AddInput(FederationTestDispatcher::ClearTicketCommand);
AddInput(FederationTestDispatcher::RemoveLeaseBehaviorCommand);
//Set OpenTimeout
int64 openTimeoutInSeconds = config_.OpenTimeout.TotalSeconds();
wstring openTimeout = wformatString(openTimeoutInSeconds);
AddInput(FederationTestDispatcher::SetPropertyCommand + L" " +
FederationTestConfig::GetConfig().OpenTimeoutEntry.Key + L" " +
openTimeout);
//Set RetryOpen
AddInput(FederationTestDispatcher::SetPropertyCommand + L" " +
FederationTestDispatcher::TestNodeRetryOpenPropertyName + L" true");
//Set Route Retry Timeout
AddInput(FederationTestDispatcher::SetPropertyCommand + L" " +
FederationTestConfig::GetConfig().RouteRetryTimeoutEntry.Key + L" 2");
//Set Route Timeout
int64 routeTimeoutInSeconds = config_.RouteTimeout.TotalSeconds();
wstring routeTimeout = wformatString(routeTimeoutInSeconds);
AddInput(FederationTestDispatcher::SetPropertyCommand + L" " +
FederationTestConfig::GetConfig().RouteTimeoutEntry.Key + L" " +
routeTimeout);
waitTime_ = wformatString(config_.WaitTime.TotalSeconds());
AddInput(L"!updatecfg Federation.VoterStoreBootstrapWaitInterval=30");
//AddInput(L"!updatecfg Federation.ArbitrationTimeout=15");
//AddInput(L"!updatecfg Federation.LeaseDuration=15");
initalizeStage_ = 1;
watch_.Start();
}
if(!CheckMemory())
{
AddInput(L"#Memory check failed. Aborting...");
AddInput(TestSession::AbortCommand);
return wstring();
}
else
{
if (timeout_.IsExpired)
{
AddInput(L"#Time limit reached. Exiting...");
AddInput(TestSession::QuitCommand);
return wstring();
}
switch(testStage_)
{
case 0:
{
wstring text;
StringWriter w(text);
w.Write("Iterations left: {0}, time elapsed: {1}", iterations_, TimeSpan::FromTicks(watch_.ElapsedTicks));
TraceConsoleSink::Write(0x0b, text);
}
ExecuteFederationStage();
AddInput(FederationTestDispatcher::VerifyCommand + L" " + waitTime_);
ClearUnreliableTransportBehavior();
AddInput(FederationTestDispatcher::ListCommand);
testStage_++;
break;
case 1:
if (config_.MaxBlockedLeaseAgent > 0)
{
ExecuteArbitrationStage();
AddInput(FederationTestDispatcher::ListCommand);
}
testStage_++;
break;
case 2:
for (auto it = rings_.begin(); it != rings_.end(); ++it)
{
set<NodeId> nodes;
TestFederation* federation = FederationDispatcher.GetTestFederation((*it)->GetRingName());
ASSERT_IF(federation == nullptr, "Ring {0} not found", (*it)->GetRingName());
federation->GetNodeList(nodes);
(*it)->UpdateNodes(nodes);
}
if(config_.MaxRoutes > 0)
{
ExecuteRoutingStage();
AddInput(TestSession::WaitCommand + L"," + waitTime_);
}
testStage_++;
break;
case 3:
if(config_.MaxBroadcasts > 0)
{
ExecuteBroadcastStage();
AddInput(TestSession::WaitCommand + L"," + waitTime_);
}
testStage_++;
break;
case 4:
if (config_.MaxStoreWrites > 0)
{
ExecuteVoterStoreStage();
AddInput(TestSession::WaitCommand + L"," + waitTime_);
}
testStage_++;
break;
default:
iterations_--;
if(iterations_ == 0)
{
watch_.Stop();
AddInput(L"-*");
AddInput(TestSession::QuitCommand);
return wstring();
}
else
{
testStage_ = 0;
}
break;
}
if(testStage_ == 0)
{
return GetInput();
}
return wstring();
}
}
bool RandomFederationTestSession::CheckMemory()
{
//todo, memory check should be consistent with Transport/Throttle.cpp
//on Linux, ProcessInfo::DataSize() is checked for throttling
//on Windows, PagefileUsage is checked for throttling
size_t MaxAllowedPrivateBytes = static_cast<size_t>(config_.MaxAllowedMemoryInMB) * 1024 * 1024;
#ifdef PLATFORM_UNIX
auto pmi = ProcessInfo::GetSingleton();
string summary;
auto rss = pmi->GetRssAndSummary(summary);
if(MaxAllowedPrivateBytes != 0 /*Memory check disabled if 0*/ && rss > MaxAllowedPrivateBytes)
{
TestSession::WriteError(
"FederationTest.Memory",
"Federation session: workingSet/rss exceeds limit {0}, {1}",
MaxAllowedPrivateBytes,
summary);
if (highMemoryStartTime_ == StopwatchTime::Zero)
{
highMemoryStartTime_ = Stopwatch::Now();
}
bool result = highMemoryStartTime_ + config_.MaxAllowedMemoryTimeout > Stopwatch::Now();
ASSERT_IF(!result && config_.AssertOnMemoryCheckFailure, "Memory check failed");
return result;
}
TestSession::WriteInfo("FederationTest.Memory", "Federation session: {0}", summary);
highMemoryStartTime_ = StopwatchTime::Zero;
return true;
#else
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
hProcess = OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
GetCurrentProcessId());
TestSession::FailTestIf(NULL == hProcess, "OpenProcess failed");
TestSession::FailTestIf(FALSE == GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc)), "GetProcessMemoryInfo failed");
CloseHandle( hProcess );
if(MaxAllowedPrivateBytes != 0 /*Memory check disabled if 0*/ && pmc.WorkingSetSize > MaxAllowedPrivateBytes)
{
TestSession::WriteError(
"FederationTest.Memory",
"Federation session WorkingSet {0} more than {1}. PeakWorkingSetSize {2} MB, PageFileUsage {3} MB, PeakPagefileUsage {4} MB",
pmc.WorkingSetSize / (1024 * 1024),
config_.MaxAllowedMemoryInMB,
pmc.PeakWorkingSetSize / (1024 * 1024),
pmc.PagefileUsage / (1024 * 1024),
pmc.PeakPagefileUsage / (1024 * 1024));
if (highMemoryStartTime_ == StopwatchTime::Zero)
{
highMemoryStartTime_ = Stopwatch::Now();
}
bool result = highMemoryStartTime_ + config_.MaxAllowedMemoryTimeout > Stopwatch::Now();
ASSERT_IF(!result && config_.AssertOnMemoryCheckFailure, "Memory check failed");
return result;
}
else
{
TestSession::WriteInfo(
"FederationTest.Memory",
"Federation session current memory = {0} MB. PeakWorkingSetSize {1} MB, PageFileUsage {2} MB, PeakPagefileUsage {3} MB",
pmc.WorkingSetSize / (1024 * 1024),
pmc.PeakWorkingSetSize / (1024 * 1024),
pmc.PagefileUsage / (1024 * 1024),
pmc.PeakPagefileUsage / (1024 * 1024));
highMemoryStartTime_ = StopwatchTime::Zero;
return true;
}
#endif
}
void RandomFederationTestSession::ChangeRing(size_t index)
{
if (index != currentRing_)
{
currentRing_ = index;
AddInput(wformatString("{0} {1}", FederationTestDispatcher::ChangeRingCommand, rings_[index]->GetRingName()));
}
}
void RandomFederationTestSession::SelectRing()
{
if (ringCount_ > 1)
{
int index = random_.Next(0, ringCount_);
ChangeRing(index);
}
}
void RandomFederationTestSession::InitializeSeedNodes()
{
wstring voteCommand = L"votes";
for (size_t i = 0; i < rings_.size(); i++)
{
voteCommand = voteCommand + rings_[i]->GetSeedNodes();
}
AddInput(voteCommand);
AddInput(FederationTestDispatcher::ClearTicketCommand);
for (size_t i = 0; i < rings_.size(); i++)
{
ChangeRing(i);
rings_[i]->AddSeedNodes();
}
}
void RandomFederationTestSession::ExecuteFederationStage()
{
if (initalizeStage_ == 1)
{
InitializeSeedNodes();
initalizeStage_ = 2;
}
for (auto it = rings_.begin(); it != rings_.end(); ++it)
{
(*it)->InitializeFederationStage();
}
int dynamism = random_.Next(1, config_.MaxDynamism + 1);
for (int i = 0; i < dynamism; i++)
{
SelectRing();
rings_[currentRing_]->AddOrRemoveNode();
}
}
void RandomFederationTestSession::ExecuteArbitrationStage()
{
rings_[currentRing_]->ExecuteArbitrationStage();
}
void RandomFederationTestSession::ExecuteRoutingStage()
{
int routes = random_.Next(1, config_.MaxRoutes);
for (int i = 0; i < routes; i++)
{
SelectRing();
rings_[currentRing_]->TestRouting();
}
}
void RandomFederationTestSession::ExecuteBroadcastStage()
{
int broadcasts = random_.Next(1, config_.MaxBroadcasts);
for (int i = 0; i < broadcasts; i++)
{
SelectRing();
rings_[currentRing_]->TestBroadcast();
}
}
void RandomFederationTestSession::ExecuteVoterStoreStage()
{
SelectRing();
rings_[currentRing_]->TestVoterStore();
}
void RandomFederationTestSession::AddUnreliableTransportBehavior(wstring const & command, bool userMode)
{
wstring alias;
if (userMode)
{
alias = wformatString("b{0}", unreliableTransportCommands_.size());
AddInput(wformatString("addbehavior {0} {1}", alias, command));
}
else
{
alias = wformatString("k{0}", unreliableTransportCommands_.size());
AddInput(wformatString("addleasebehavior {0} {1}", command, alias));
}
unreliableTransportCommands_.push_back(move(alias));
}
void RandomFederationTestSession::ClearUnreliableTransportBehavior()
{
bool clearKernelTransportBehavior = false;
for (wstring const & alias : unreliableTransportCommands_)
{
if (alias[0] == L'b')
{
AddInput(wformatString("removebehavior {0}", alias));
}
else
{
clearKernelTransportBehavior = true;
}
}
if (clearKernelTransportBehavior)
{
AddInput(FederationTestDispatcher::RemoveLeaseBehaviorCommand);
}
unreliableTransportCommands_.clear();
}
|
//----------------------------------------------------------------------------
/// @file sort_basic.hpp
/// @brief Spin Sort algorithm
///
/// @author Copyright (c) 2016 Francisco José Tapia (fjtapia@gmail.com )\n
/// Distributed under the Boost Software License, Version 1.0.\n
/// ( See accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt )
/// @version 0.1
///
/// @remarks
//-----------------------------------------------------------------------------
#ifndef __BOOST_SORT_COMMON_SORT_BASIC_HPP
#define __BOOST_SORT_COMMON_SORT_BASIC_HPP
//#include <boost/sort/spinsort/util/indirect.hpp>
#include <boost/sort/insert_sort/insert_sort.hpp>
#include <boost/sort/common/util/traits.hpp>
#include <boost/sort/common/range.hpp>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <memory>
#include <type_traits>
#include <vector>
#include <cstddef>
namespace boost
{
namespace sort
{
namespace common
{
//----------------------------------------------------------------------------
// USING SENTENCES
//----------------------------------------------------------------------------
using boost::sort::insert_sort;
//-----------------------------------------------------------------------------
// function : is_stable_sorted_forward
/// @brief examine the elements in the range first, last if they are stable
/// sorted, and return an iterator to the first element not sorted
/// @param first : iterator to the first element in the range
/// @param last : ierator after the last element of the range
/// @param comp : object for to compare two elements
/// @return iterator to the first element not stable sorted. The number of
/// elements sorted is the iterator returned minus first
//-----------------------------------------------------------------------------
template<class Iter_t, class Compare = std::less<value_iter<Iter_t> > >
inline Iter_t is_stable_sorted_forward (Iter_t first, Iter_t last,
Compare comp = Compare())
{
#ifdef __BS_DEBUG
assert ( (last- first) >= 0);
#endif
if ((last - first) < 2) return first;
Iter_t it2 = first + 1;
for (Iter_t it1 = first; it2 != last and not comp(*it2, *it1); it1 = it2++);
return it2;
}
//-----------------------------------------------------------------------------
// function : is_reverse_stable_sorted_forward
/// @brief examine the elements in the range first, last if they are reverse
/// stable sorted, and return an iterator to the first element not
/// reverse stable sorted
/// @param first : iterator to the first element in the range
/// @param last : ierator after the last element of the range
/// @param comp : object for to compare two elements
/// @return iterator to the first element not reverse stable sorted. The number
/// of elements sorted is the iterator returned minus first
//-----------------------------------------------------------------------------
template<class Iter_t, class Compare = std::less<value_iter<Iter_t> > >
inline Iter_t is_reverse_stable_sorted_forward(Iter_t first, Iter_t last,
Compare comp = Compare())
{
#ifdef __BS_DEBUG
assert ( (last- first) >= 0);
#endif
if ((last - first) < 2) return first;
Iter_t it2 = first + 1;
for (Iter_t it1 = first; it2 != last and comp(*it2, *it1); it1 = it2++);
return it2;
};
//-----------------------------------------------------------------------------
// function : number_stable_sorted_forward
/// @brief examine the elements in the range first, last if they are stable
/// sorted, and return the number of elements sorted
/// @param first : iterator to the first element in the range
/// @param last : ierator after the last element of the range
/// @param comp : object for to compare two elements
/// @param min_process : minimal number of elements to be consideer
/// @return number of element sorted. I f the number is lower than min_process
/// return 0
//-----------------------------------------------------------------------------
template<class Iter_t, class Compare = std::less<value_iter<Iter_t> > >
size_t number_stable_sorted_forward (Iter_t first, Iter_t last,
size_t min_process,
Compare comp = Compare())
{
#ifdef __BS_DEBUG
assert ( (last- first) >= 0);
#endif
if ((last - first) < 2) return 0;
// sorted elements
Iter_t it2 = first + 1;
for (Iter_t it1 = first; it2 != last and not comp(*it2, *it1); it1 = it2++);
size_t nsorted = size_t ( it2 - first);
if ( nsorted != 1)
return (nsorted >= min_process) ? nsorted: 0;
// reverse sorted elements
it2 = first + 1;
for (Iter_t it1 = first; it2 != last and comp(*it2, *it1); it1 = it2++);
nsorted = size_t ( it2 - first);
if ( nsorted < min_process) return 0 ;
util::reverse ( first , it2);
return nsorted;
};
//-----------------------------------------------------------------------------
// function : is_stable_sorted_backward
/// @brief examine the elements in the range first, last beginning at end, and
/// if they are stablesorted, and return an iterator to the last element
/// sorted
/// @param first : iterator to the first element in the range
/// @param last : ierator after the last element of the range
/// @param comp : object for to compare two elements
/// @return iterator to the last element stable sorted. The number of
/// elements sorted is the last minus the iterator returned
//-----------------------------------------------------------------------------
template<class Iter_t, class Compare = std::less<value_iter<Iter_t> > >
inline Iter_t is_stable_sorted_backward(Iter_t first, Iter_t last,
Compare comp = Compare())
{
#ifdef __BS_DEBUG
assert ( (last- first) >= 0);
#endif
if ((last - first) < 2) return first;
Iter_t itaux = last - 1;
while (itaux != first and not comp(*itaux, *(itaux - 1))) {--itaux; };
return itaux;
}
//-----------------------------------------------------------------------------
// function : is_reverse_stable_sorted_backward
/// @brief examine the elements in the range first, last beginning at end, and
/// if they are stablesorted, and return an iterator to the last element
/// sorted
/// @param first : iterator to the first element in the range
/// @param last : ierator after the last element of the range
/// @param comp : object for to compare two elements
/// @return iterator to the last element stable sorted. The number of
/// elements sorted is the last minus the iterator returned
//-----------------------------------------------------------------------------
template<class Iter_t, class Compare = std::less<value_iter<Iter_t> > >
inline Iter_t is_reverse_stable_sorted_backward (Iter_t first, Iter_t last,
Compare comp = Compare())
{
#ifdef __BS_DEBUG
assert ( (last- first) >= 0);
#endif
if ((last - first) < 2) return first;
Iter_t itaux = last - 1;
for (; itaux != first and comp(*itaux, *(itaux - 1)); --itaux);
return itaux;
}
//-----------------------------------------------------------------------------
// function : number_stable_sorted_backward
/// @brief examine the elements in the range first, last if they are stable
/// sorted, and return the number of elements sorted
/// @param first : iterator to the first element in the range
/// @param last : ierator after the last element of the range
/// @param comp : object for to compare two elements
/// @param min_process : minimal number of elements to be consideer
/// @return number of element sorted. I f the number is lower than min_process
/// return 0
//-----------------------------------------------------------------------------
template<class Iter_t, class Compare = std::less<value_iter<Iter_t> > >
size_t number_stable_sorted_backward (Iter_t first, Iter_t last,
size_t min_process,
Compare comp = Compare())
{
#ifdef __BS_DEBUG
assert ( (last- first) >= 0);
#endif
if ((last - first) < 2) return 0;
Iter_t itaux = last - 1;
while (itaux != first and not comp(*itaux, *(itaux - 1))) {--itaux; };
size_t nsorted = size_t ( last - itaux);
if ( nsorted != 1)
return ( nsorted >= min_process)?nsorted: 0 ;
itaux = last - 1;
for (; itaux != first and comp(*itaux, *(itaux - 1)); --itaux);
nsorted = size_t ( last - itaux);
if ( nsorted < min_process) return 0 ;
util::reverse ( itaux, last );
return nsorted;
}
//-----------------------------------------------------------------------------
// function : internal_sort
/// @brief this function divide r_input in two parts, sort it,and merge moving
/// the elements to range_buf
/// @param range_input : range with the elements to sort
/// @param range_buffer : range with the elements sorted
/// @param comp : object for to compare two elements
/// @param level : when is 1, sort with the insertionsort algorithm
/// if not make a recursive call splitting the ranges
//
//-----------------------------------------------------------------------------
template <class Iter1_t, class Iter2_t, class Compare>
inline void internal_sort (const range<Iter1_t> &rng1,
const range<Iter2_t> &rng2,
Compare comp, uint32_t level, bool even = true)
{
//-----------------------------------------------------------------------
// metaprogram
//-----------------------------------------------------------------------
typedef value_iter<Iter1_t> value_t;
typedef value_iter<Iter2_t> value2_t;
static_assert (std::is_same< value_t, value2_t>::value,
"Incompatible iterators\n");
//-----------------------------------------------------------------------
// program
//-----------------------------------------------------------------------
#ifdef __BS_DEBUG
assert (rng1.size ( ) == rng2.size ( ) );
#endif
size_t nelem = (rng1.size() + 1) >> 1;
range<Iter1_t> rng1_left(rng1.first, rng1.first + nelem),
rng1_right(rng1.first + nelem, rng1.last);
range<Iter2_t> rng2_left(rng2.first, rng2.first + nelem),
rng2_right(rng2.first + nelem, rng2.last);
if (nelem <= 32 and (level & 1) == even)
{
insert_sort(rng1_left.first, rng1_left.last, comp);
insert_sort(rng1_right.first, rng1_right.last, comp);
}
else
{
internal_sort(rng2_left, rng1_left, comp, level + 1, even);
internal_sort(rng2_right, rng1_right, comp, level + 1, even);
};
merge(rng2, rng1_left, rng1_right, comp);
};
//-----------------------------------------------------------------------------
// function : range_sort_data
/// @brief this sort elements using the range_sort function and receiving a
/// buffer of initialized memory
/// @param rng_data : range with the elements to sort
/// @param rng_aux : range of at least the same memory than rng_data used as
/// auxiliary memory in the sorting
/// @param comp : object for to compare two elements
//-----------------------------------------------------------------------------
template<class Iter1_t, class Iter2_t, class Compare>
static void range_sort_data (const range<Iter1_t> & rng_data,
const range<Iter2_t> & rng_aux, Compare comp)
{
//-----------------------------------------------------------------------
// metaprogram
//-----------------------------------------------------------------------
typedef value_iter<Iter1_t> value_t;
typedef value_iter<Iter2_t> value2_t;
static_assert (std::is_same< value_t, value2_t>::value,
"Incompatible iterators\n");
//------------------------------------------------------------------------
// program
//------------------------------------------------------------------------
#ifdef __BS_DEBUG
assert ( rng_data.size() == rng_aux.size());
#endif
// minimal number of element before to jump to insertionsort
const uint32_t sort_min = 32;
if (rng_data.size() <= sort_min)
{
insert_sort(rng_data.first, rng_data.last, comp);
return;
};
internal_sort(rng_aux, rng_data, comp, 0, true);
};
//-----------------------------------------------------------------------------
// function : range_sort_buffer
/// @brief this sort elements using the range_sort function and receiving a
/// buffer of initialized memory
/// @param rng_data : range with the elements to sort
/// @param rng_aux : range of at least the same memory than rng_data used as
/// auxiliary memory in the sorting
/// @param comp : object for to compare two elements
//-----------------------------------------------------------------------------
template<class Iter1_t, class Iter2_t, class Compare>
static void range_sort_buffer(const range<Iter1_t> & rng_data,
const range<Iter2_t> & rng_aux, Compare comp)
{
//-----------------------------------------------------------------------
// metaprogram
//-----------------------------------------------------------------------
typedef value_iter<Iter1_t> value_t;
typedef value_iter<Iter2_t> value2_t;
static_assert (std::is_same< value_t, value2_t>::value,
"Incompatible iterators\n");
//------------------------------------------------------------------------
// program
//------------------------------------------------------------------------
#ifdef __BS_DEBUG
assert ( rng_data.size() == rng_aux.size());
#endif
// minimal number of element before to jump to insertionsort
const uint32_t sort_min = 32;
if (rng_data.size() <= sort_min)
{
insert_sort(rng_data.first, rng_data.last, comp);
move_forward(rng_aux, rng_data);
return;
};
internal_sort(rng_data, rng_aux, comp, 0, false);
};
//****************************************************************************
};// End namespace common
};// End namespace sort
};// End namepspace boost
//****************************************************************************
//
#endif
|
#ifndef __RESPONSE__
#define __RESPONSE__
#include "../utils/include.hpp"
#include "../utils/utilities.hpp"
#include <string>
const std::string SERVER_NAME = "AP HTTP Server";
class Response {
public:
Response(int code = 200);
std::string print(int &);
void log(bool showBody = false);
void setHeader(std::string name, std::string value);
void setBody(std::string _body);
void setStatus(int code, std::string phrase);
void setStatus(int code);
int getStatusCode();
std::string getStatusPhrase();
std::string getHeader(std::string name);
void setSessionId(std::string sessionId);
static Response *redirect(std::string url);
private:
int code;
std::string phrase;
std::string body;
cimap headers;
};
#endif
|
/// @ref gtx_hash
///
/// @see core (dependence)
///
/// @defgroup gtx_hash GLM_GTX_hash
/// @ingroup gtx
///
/// @brief Add std::hash support for glm types
///
/// <glm/gtx/hash.inl> need to be included to use the features of this extension.
namespace glm {
namespace detail
{
GLM_INLINE void hash_combine(size_t &seed, size_t hash)
{
hash += 0x9e3779b9 + (seed << 6) + (seed >> 2);
seed ^= hash;
}
}}
namespace std
{
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::vec<1, T, Q>>::operator()(glm::vec<1, T, Q> const& v) const
{
hash<T> hasher;
return hasher(v.x);
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::vec<2, T, Q>>::operator()(glm::vec<2, T, Q> const& v) const
{
size_t seed = 0;
hash<T> hasher;
glm::detail::hash_combine(seed, hasher(v.x));
glm::detail::hash_combine(seed, hasher(v.y));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::vec<3, T, Q>>::operator()(glm::vec<3, T, Q> const& v) const
{
size_t seed = 0;
hash<T> hasher;
glm::detail::hash_combine(seed, hasher(v.x));
glm::detail::hash_combine(seed, hasher(v.y));
glm::detail::hash_combine(seed, hasher(v.z));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::vec<4, T, Q>>::operator()(glm::vec<4, T, Q> const& v) const
{
size_t seed = 0;
hash<T> hasher;
glm::detail::hash_combine(seed, hasher(v.x));
glm::detail::hash_combine(seed, hasher(v.y));
glm::detail::hash_combine(seed, hasher(v.z));
glm::detail::hash_combine(seed, hasher(v.w));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::qua<T, Q>>::operator()(glm::qua<T,Q> const& q) const
{
size_t seed = 0;
hash<T> hasher;
glm::detail::hash_combine(seed, hasher(q.x));
glm::detail::hash_combine(seed, hasher(q.y));
glm::detail::hash_combine(seed, hasher(q.z));
glm::detail::hash_combine(seed, hasher(q.w));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::tdualquat<T, Q>>::operator()(glm::tdualquat<T, Q> const& q) const
{
size_t seed = 0;
hash<glm::qua<T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(q.real));
glm::detail::hash_combine(seed, hasher(q.dual));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<2, 2, T, Q>>::operator()(glm::mat<2, 2, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<2, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<2, 3, T, Q>>::operator()(glm::mat<2, 3, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<3, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<2, 4, T, Q>>::operator()(glm::mat<2, 4, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<4, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<3, 2, T, Q>>::operator()(glm::mat<3, 2, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<2, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
glm::detail::hash_combine(seed, hasher(m[2]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<3, 3, T, Q>>::operator()(glm::mat<3, 3, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<3, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
glm::detail::hash_combine(seed, hasher(m[2]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<3, 4, T, Q>>::operator()(glm::mat<3, 4, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<4, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
glm::detail::hash_combine(seed, hasher(m[2]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<4, 2, T,Q>>::operator()(glm::mat<4, 2, T,Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<2, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
glm::detail::hash_combine(seed, hasher(m[2]));
glm::detail::hash_combine(seed, hasher(m[3]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<4, 3, T,Q>>::operator()(glm::mat<4, 3, T,Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<3, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
glm::detail::hash_combine(seed, hasher(m[2]));
glm::detail::hash_combine(seed, hasher(m[3]));
return seed;
}
template<typename T, glm::qualifier Q>
GLM_FUNC_QUALIFIER size_t hash<glm::mat<4, 4, T,Q>>::operator()(glm::mat<4, 4, T, Q> const& m) const
{
size_t seed = 0;
hash<glm::vec<4, T, Q>> hasher;
glm::detail::hash_combine(seed, hasher(m[0]));
glm::detail::hash_combine(seed, hasher(m[1]));
glm::detail::hash_combine(seed, hasher(m[2]));
glm::detail::hash_combine(seed, hasher(m[3]));
return seed;
}
}
|
/** @File Mouse2D class definition
*/
#ifndef MOUSE2D_HH_
# define MOUSE2D_HH_
# include <set>
# include "vector-2d.hh"
# include "game-observer-2d.hh"
namespace opl
{
/// Mouse state representation from 2D programming
class Mouse2D: public GameObserver2D
{
public:
static Mouse2D*
instance ();
bool
is_down (int code) const;
///Returns if button has been pressed on the current frame
bool
is_pressed (int code) const;
///Returns if button has been released on the current frame
bool
is_released (int code) const;
r_type
x_get () const;
r_type
y_get () const;
Vector2D
position () const;
virtual void
notify_mouse_move (r_type x, r_type y) override;
virtual void
notify_mouse_down (int code) override;
virtual void
notify_mouse_up (int code) override;
virtual void
notify_update () override;
static const int LEFT;
static const int MIDDLE;
static const int RIGHT;
static const int X1;
static const int X2;
private:
r_type x_;
r_type y_;
std::set<int> next_down_;
std::set<int> next_up_;
std::set<int> bts_down_;
std::set<int> bts_pressed_;
std::set<int> bts_released_;
Mouse2D ();
Mouse2D (const Mouse2D&) = delete;
static Mouse2D* instance_;
};
}
#endif //!MOUSE_HH_
|
/// libdas: DENG asset handling management library
/// licence: Apache, see LICENCE file
/// file: GLTFParser.cpp - GLTF format parsing class implementation
/// author: Karl-Mihkel Ott
#define GLTF_PARSER_CPP
#include <GLTFParser.h>
namespace Libdas {
GLTFParser::GLTFParser(const std::string &_file_name) :
JSONParser(MODEL_FORMAT_GLTF, _file_name), m_error(MODEL_FORMAT_GLTF)
{
_InitialiseRootObjectTypeMap();
}
void GLTFParser::_InitialiseRootObjectTypeMap() {
m_root_objects["accessors"] = GLTF_OBJECT_ACCESSORS;
m_root_objects["animations"] = GLTF_OBJECT_ANIMATIONS;
m_root_objects["asset"] = GLTF_OBJECT_ASSET;
m_root_objects["buffers"] = GLTF_OBJECT_BUFFERS;
m_root_objects["bufferViews"] = GLTF_OBJECT_BUFFERVIEWS;
m_root_objects["cameras"] = GLTF_OBJECT_CAMERAS;
m_root_objects["extensions"] = GLTF_OBJECT_EXTENSIONS;
m_root_objects["extensionsUsed"] = GLTF_OBJECT_EXTENSIONS;
m_root_objects["extensionsRequired"] = GLTF_OBJECT_EXTENSIONS;
m_root_objects["extras"] = GLTF_OBJECT_EXTRAS;
m_root_objects["images"] = GLTF_OBJECT_IMAGES;
m_root_objects["materials"] = GLTF_OBJECT_MATERIALS;
m_root_objects["meshes"] = GLTF_OBJECT_MESHES;
m_root_objects["nodes"] = GLTF_OBJECT_NODES;
m_root_objects["samplers"] = GLTF_OBJECT_SAMPLERS;
m_root_objects["scene"] = GLTF_OBJECT_SCENE;
m_root_objects["scenes"] = GLTF_OBJECT_SCENES;
m_root_objects["skins"] = GLTF_OBJECT_SKINS;
m_root_objects["textures"] = GLTF_OBJECT_TEXTURES;
}
GLTFObjectType GLTFParser::_FindRootObjectType(const std::string &_obj_str, uint32_t _line) {
// object key not found
if(m_root_objects.find(_obj_str) == m_root_objects.end())
m_error.Error(LIBDAS_ERROR_INVALID_KEYWORD, _line, _obj_str);
return m_root_objects[_obj_str];
}
void GLTFParser::_VerifySourceData(JSONNode *_node, JSONType _supported_type, bool _is_array) {
// find an appropriate expected type string in case of error
std::string exp_type_str;
if(_supported_type & JSON_TYPE_STRING) {
if(!_is_array)
exp_type_str = "string";
else exp_type_str = "string array";
} else if (_supported_type & JSON_TYPE_BOOLEAN) {
if(!_is_array)
exp_type_str = "boolean";
else exp_type_str = "boolean array";
} else if (_supported_type & JSON_TYPE_INTEGER || _supported_type & JSON_TYPE_FLOAT) {
if(!_is_array)
exp_type_str = "number";
else exp_type_str = "number array";
} else if (_supported_type & JSON_TYPE_OBJECT) {
if(!_is_array)
exp_type_str = "object";
else exp_type_str = "object array";
}
// throw an error if array type is not specified, but there are
// multiple values in values vector
if(!_is_array && _node->values.size() > 1)
m_error.Error(LIBDAS_ERROR_INVALID_TYPE, _node->key_val_decl_line, _node->name, exp_type_str);
else {
// check if array elements are homogenous and supported
for(size_t i = 0; i < _node->values.size(); i++) {
if(!(_node->values[i].first & _supported_type))
m_error.Error(LIBDAS_ERROR_INVALID_TYPE, _node->key_val_decl_line, _node->name, exp_type_str);
}
}
}
void GLTFParser::_CopyJSONDataToGLTFRoot(JSONNode *_src, GLTFUniversalScopeValue &_dst) {
switch(_dst.type) {
case GLTF_TYPE_STRING:
_VerifySourceData(_src, JSON_TYPE_STRING, false);
*reinterpret_cast<JSONString*>(_dst.val_ptr) = std::any_cast<JSONString>(_src->values.back().second);
break;
case GLTF_TYPE_INTEGER: {
_VerifySourceData(_src, JSON_TYPE_INTEGER | JSON_TYPE_FLOAT, false);
*reinterpret_cast<JSONInteger*>(_dst.val_ptr) = _CastVariantNumber<JSONInteger, JSONNumber>(
std::any_cast<std::variant<JSONInteger, JSONNumber>>(_src->values.back().second));
break;
}
case GLTF_TYPE_FLOAT:
_VerifySourceData(_src, JSON_TYPE_INTEGER | JSON_TYPE_FLOAT, false);
*reinterpret_cast<JSONNumber*>(_dst.val_ptr) = _CastVariantNumber<JSONNumber, JSONInteger>(
std::any_cast<std::variant<JSONInteger, JSONNumber>>(_src->values.back().second));
break;
case GLTF_TYPE_INTEGER_ARRAY:
_VerifySourceData(_src, JSON_TYPE_INTEGER | JSON_TYPE_FLOAT, true);
*reinterpret_cast<std::vector<JSONInteger>*>(_dst.val_ptr) = _NumericalJsonValueToVectorCast<JSONInteger>(_src->values);
break;
case GLTF_TYPE_FLOAT_ARRAY:
_VerifySourceData(_src, JSON_TYPE_FLOAT | JSON_TYPE_INTEGER, true);
*reinterpret_cast<std::vector<JSONNumber>*>(_dst.val_ptr) = _NumericalJsonValueToVectorCast<JSONNumber>(_src->values);
break;
case GLTF_TYPE_STRING_ARRAY:
_VerifySourceData(_src, JSON_TYPE_STRING, true);
*reinterpret_cast<std::vector<JSONString>*>(_dst.val_ptr) = _JsonValueToVectorCast<JSONString>(_src->values);
break;
case GLTF_TYPE_ACCESSOR_SPARSE:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadAccessorSparse(_src, *reinterpret_cast<GLTFAccessorSparse*>(_dst.val_ptr));
break;
case GLTF_TYPE_ACCESSOR_SPARSE_INDICES:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadAccessorSparseIndices(_src, *reinterpret_cast<GLTFAccessorSparseIndices*>(_dst.val_ptr));
break;
case GLTF_TYPE_ACCESSOR_SPARSE_VALUES:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadAccessorSparseValues(_src, *reinterpret_cast<GLTFAccessorSparseValues*>(_dst.val_ptr));
break;
case GLTF_TYPE_ANIMATION_CHANNELS:
_VerifySourceData(_src, JSON_TYPE_OBJECT, true);
_ReadAnimationChannels(_src, *reinterpret_cast<std::vector<GLTFAnimationChannel>*>(_dst.val_ptr));
break;
case GLTF_TYPE_ANIMATION_CHANNEL_TARGET:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadAnimationChannelTarget(_src, *reinterpret_cast<GLTFAnimationChannelTarget*>(_dst.val_ptr));
break;
case GLTF_TYPE_ANIMATION_SAMPLERS:
_VerifySourceData(_src, JSON_TYPE_OBJECT, true);
_ReadAnimationSamplers(_src, *reinterpret_cast<std::vector<GLTFAnimationSampler>*>(_dst.val_ptr));
break;
case GLTF_TYPE_CAMERA_ORTHOGRAPHIC:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadCameraOrthographic(_src, *reinterpret_cast<GLTFCameraOrthographic*>(_dst.val_ptr));
break;
case GLTF_TYPE_CAMERA_PERSPECTIVE:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadCameraPerspective(_src, *reinterpret_cast<GLTFCameraPerspective*>(_dst.val_ptr));
break;
case GLTF_TYPE_MATERIAL_PBR_METALLIC_ROUGHNESS:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadMaterialPbrMetallicRoughness(_src, *reinterpret_cast<GLTFpbrMetallicRoughness*>(_dst.val_ptr));
break;
case GLTF_TYPE_MATERIAL_NORMAL_TEXTURE:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadMaterialNormalTexture(_src, *reinterpret_cast<GLTFNormalTextureInfo*>(_dst.val_ptr));
break;
case GLTF_TYPE_MATERIAL_OCCLUSION_TEXTURE:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadMaterialOcclusionTexture(_src, *reinterpret_cast<GLTFOcclusionTextureInfo*>(_dst.val_ptr));
break;
case GLTF_TYPE_MATERIAL_TEXTURE_INFO:
_VerifySourceData(_src, JSON_TYPE_OBJECT, false);
_ReadMaterialTextureInfo(_src, *reinterpret_cast<GLTFTextureInfo*>(_dst.val_ptr));
break;
case GLTF_TYPE_MESH_PRIMITIVES:
_VerifySourceData(_src, JSON_TYPE_OBJECT, true);
_ReadMeshPrimitives(_src, *reinterpret_cast<std::vector<GLTFMeshPrimitive>*>(_dst.val_ptr));
break;
default:
break;
}
}
void GLTFParser::_IterateSubNodes(JSONNode *_node, std::unordered_map<std::string, GLTFUniversalScopeValue> &_val_map) {
// iterate through all subscopes
for(auto it = _node->sub_nodes.begin(); it != _node->sub_nodes.end(); it++) {
// error no subscope name found
if(_val_map.find(it->first) == _val_map.end())
m_error.Error(LIBDAS_ERROR_INVALID_KEYWORD, it->second->key_val_decl_line, it->first);
_CopyJSONDataToGLTFRoot(it->second.get(), _val_map[it->first]);
}
}
void GLTFParser::_ReadAccessors(JSONNode *_node) {
GLTFAccessor accessor;
// map with key and pointer of the element
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("bufferView", GLTFUniversalScopeValue{ &accessor.buffer_view, GLTF_TYPE_INTEGER }),
std::make_pair("byteOffset", GLTFUniversalScopeValue{ &accessor.byte_offset, GLTF_TYPE_INTEGER }),
std::make_pair("componentType", GLTFUniversalScopeValue{ &accessor.component_type, GLTF_TYPE_INTEGER }),
std::make_pair("normalized", GLTFUniversalScopeValue{ &accessor.normalized, GLTF_TYPE_BOOLEAN }),
std::make_pair("count", GLTFUniversalScopeValue{ &accessor.count, GLTF_TYPE_INTEGER }),
std::make_pair("type", GLTFUniversalScopeValue{ &accessor.type, GLTF_TYPE_STRING }),
std::make_pair("max", GLTFUniversalScopeValue{ &accessor.max, GLTF_TYPE_FLOAT_ARRAY }),
std::make_pair("min", GLTFUniversalScopeValue{ &accessor.min, GLTF_TYPE_FLOAT_ARRAY }),
std::make_pair("name", GLTFUniversalScopeValue{ &accessor.name, GLTF_TYPE_STRING }),
std::make_pair("extensions", GLTFUniversalScopeValue{ &accessor.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS }),
std::make_pair("extras", GLTFUniversalScopeValue{ &accessor.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS }),
std::make_pair("sparse", GLTFUniversalScopeValue{ &accessor.sparse, GLTF_TYPE_ACCESSOR_SPARSE })
};
_IterateValueObjects<GLTFAccessor>(_node, values, accessor, m_root.accessors);
}
void GLTFParser::_ReadAccessorSparse(JSONNode *_node, GLTFAccessorSparse &_sparse) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("count", GLTFUniversalScopeValue { &_sparse.count, GLTF_TYPE_INTEGER } ),
std::make_pair("indices", GLTFUniversalScopeValue { &_sparse.indices, GLTF_TYPE_ACCESSOR_SPARSE_INDICES } ),
std::make_pair("values", GLTFUniversalScopeValue { &_sparse.values, GLTF_TYPE_ACCESSOR_SPARSE_VALUES } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_sparse.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_sparse.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadAccessorSparseIndices(JSONNode *_node, GLTFAccessorSparseIndices &_indices) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("bufferView", GLTFUniversalScopeValue { &_indices.buffer_view, GLTF_TYPE_INTEGER } ),
std::make_pair("byteOffset", GLTFUniversalScopeValue { &_indices.byte_offset, GLTF_TYPE_INTEGER } ),
std::make_pair("componentType", GLTFUniversalScopeValue { &_indices.component_type, GLTF_TYPE_INTEGER } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_indices.extension, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_indices.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadAccessorSparseValues(JSONNode *_node, GLTFAccessorSparseValues &_values) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("bufferView", GLTFUniversalScopeValue { &_values.buffer_view, GLTF_TYPE_INTEGER } ),
std::make_pair("byteOffset", GLTFUniversalScopeValue { &_values.byte_offset, GLTF_TYPE_INTEGER } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_values.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_values.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadAnimations(JSONNode *_node) {
GLTFAnimation animation;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("channels", GLTFUniversalScopeValue { &animation.channels, GLTF_TYPE_ANIMATION_CHANNELS } ),
std::make_pair("samplers", GLTFUniversalScopeValue { &animation.samplers, GLTF_TYPE_ANIMATION_SAMPLERS } ),
std::make_pair("name", GLTFUniversalScopeValue { &animation.name, GLTF_TYPE_STRING } ),
std::make_pair("channels", GLTFUniversalScopeValue { &animation.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("channels", GLTFUniversalScopeValue { &animation.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFAnimation>(_node, values, animation, m_root.animations);
}
void GLTFParser::_ReadAnimationChannels(JSONNode *_node, std::vector<GLTFAnimationChannel> &_root) {
GLTFAnimationChannel channel;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("sampler", GLTFUniversalScopeValue { &channel.sampler, GLTF_TYPE_INTEGER } ),
std::make_pair("target", GLTFUniversalScopeValue { &channel.target, GLTF_TYPE_ANIMATION_CHANNEL_TARGET } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &channel.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &channel.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFAnimationChannel>(_node, values, channel, _root);
}
void GLTFParser::_ReadAnimationChannelTarget(JSONNode *_node, GLTFAnimationChannelTarget &_target) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("node", GLTFUniversalScopeValue { &_target.node, GLTF_TYPE_INTEGER } ),
std::make_pair("path", GLTFUniversalScopeValue { &_target.path, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_target.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_target.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadAnimationSamplers(JSONNode *_node, std::vector<GLTFAnimationSampler> &_root) {
GLTFAnimationSampler sampler;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("input", GLTFUniversalScopeValue { &sampler.input, GLTF_TYPE_INTEGER } ),
std::make_pair("interpolation", GLTFUniversalScopeValue { &sampler.interpolation, GLTF_TYPE_STRING } ),
std::make_pair("output", GLTFUniversalScopeValue { &sampler.output, GLTF_TYPE_INTEGER } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &sampler.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &sampler.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFAnimationSampler>(_node, values, sampler, _root);
}
void GLTFParser::_ReadAsset(JSONNode *_node) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("copyright", GLTFUniversalScopeValue { &m_root.asset.copyright, GLTF_TYPE_STRING } ),
std::make_pair("generator", GLTFUniversalScopeValue { &m_root.asset.generator, GLTF_TYPE_STRING } ),
std::make_pair("version", GLTFUniversalScopeValue { &m_root.asset.version, GLTF_TYPE_STRING } ),
std::make_pair("minVersion", GLTFUniversalScopeValue { &m_root.asset.min_version, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &m_root.asset.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &m_root.asset.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadBuffers(JSONNode *_node) {
GLTFBuffer buffer;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("uri", GLTFUniversalScopeValue { &buffer.uri, GLTF_TYPE_STRING } ),
std::make_pair("byteLength", GLTFUniversalScopeValue { &buffer.byte_length, GLTF_TYPE_INTEGER } ),
std::make_pair("name", GLTFUniversalScopeValue { &buffer.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &buffer.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &buffer.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFBuffer>(_node, values, buffer, m_root.buffers);
}
void GLTFParser::_ReadBufferviews(JSONNode *_node) {
GLTFBufferView buffer_view;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("buffer", GLTFUniversalScopeValue { &buffer_view.buffer, GLTF_TYPE_INTEGER } ),
std::make_pair("byteOffset", GLTFUniversalScopeValue { &buffer_view.byte_offset, GLTF_TYPE_INTEGER } ),
std::make_pair("byteLength", GLTFUniversalScopeValue { &buffer_view.byte_length, GLTF_TYPE_INTEGER } ),
std::make_pair("byteStride", GLTFUniversalScopeValue { &buffer_view.byte_stride, GLTF_TYPE_INTEGER } ),
std::make_pair("target", GLTFUniversalScopeValue { &buffer_view.target, GLTF_TYPE_INTEGER } ),
std::make_pair("name", GLTFUniversalScopeValue { &buffer_view.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &buffer_view.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &buffer_view.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateValueObjects<GLTFBufferView>(_node, values, buffer_view, m_root.buffer_views);
}
void GLTFParser::_ReadCameras(JSONNode *_node) {
GLTFCamera camera;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("orthographic", GLTFUniversalScopeValue { &camera.orthographic, GLTF_TYPE_CAMERA_ORTHOGRAPHIC } ),
std::make_pair("perspective", GLTFUniversalScopeValue { &camera.perspective, GLTF_TYPE_CAMERA_PERSPECTIVE } ),
std::make_pair("type", GLTFUniversalScopeValue { &camera.type, GLTF_TYPE_STRING } ),
std::make_pair("name", GLTFUniversalScopeValue { &camera.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &camera.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &camera.orthographic, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFCamera>(_node, values, camera, m_root.cameras);
}
void GLTFParser::_ReadCameraOrthographic(JSONNode *_node, GLTFCameraOrthographic &_orthographic) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("xmag", GLTFUniversalScopeValue { &_orthographic.xmag, GLTF_TYPE_FLOAT } ),
std::make_pair("ymag", GLTFUniversalScopeValue { &_orthographic.ymag, GLTF_TYPE_FLOAT } ),
std::make_pair("zfar", GLTFUniversalScopeValue { &_orthographic.zfar, GLTF_TYPE_FLOAT } ),
std::make_pair("znear", GLTFUniversalScopeValue { &_orthographic.znear, GLTF_TYPE_FLOAT } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_orthographic.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_orthographic.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadCameraPerspective(JSONNode *_node, GLTFCameraPerspective &_perspective) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("aspectRatio", GLTFUniversalScopeValue { &_perspective.aspect_ratio, GLTF_TYPE_FLOAT } ),
std::make_pair("yfov", GLTFUniversalScopeValue { &_perspective.yfov, GLTF_TYPE_FLOAT } ),
std::make_pair("zfar", GLTFUniversalScopeValue { &_perspective.zfar, GLTF_TYPE_FLOAT } ),
std::make_pair("znear", GLTFUniversalScopeValue { &_perspective.znear, GLTF_TYPE_FLOAT } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_perspective.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_perspective.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadImages(JSONNode *_node) {
GLTFImage image;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("uri", GLTFUniversalScopeValue { &image.uri, GLTF_TYPE_STRING } ),
std::make_pair("mimeType", GLTFUniversalScopeValue { &image.mime_type, GLTF_TYPE_STRING } ),
std::make_pair("bufferView", GLTFUniversalScopeValue { &image.buffer_view, GLTF_TYPE_INTEGER } ),
std::make_pair("name", GLTFUniversalScopeValue { &image.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &image.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &image.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateValueObjects<GLTFImage>(_node, values, image, m_root.images);
}
void GLTFParser::_ReadMaterials(JSONNode *_node) {
GLTFMaterial material;
std::vector<JSONNumber> emissive_factor;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("name", GLTFUniversalScopeValue { &material.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &material.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &material.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("pbrMetallicRoughness", GLTFUniversalScopeValue { &material.pbr_metallic_roughness, GLTF_TYPE_MATERIAL_PBR_METALLIC_ROUGHNESS } ),
std::make_pair("normalTexture", GLTFUniversalScopeValue { &material.normal_texture, GLTF_TYPE_MATERIAL_NORMAL_TEXTURE } ),
std::make_pair("occlusionTexture", GLTFUniversalScopeValue { &material.occlusion_texture, GLTF_TYPE_MATERIAL_OCCLUSION_TEXTURE } ),
std::make_pair("emissiveTexture", GLTFUniversalScopeValue { &material.emissive_texture, GLTF_TYPE_MATERIAL_TEXTURE_INFO } ),
std::make_pair("emissiveFactor", GLTFUniversalScopeValue { &emissive_factor, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("alphaMode", GLTFUniversalScopeValue { &material.alpha_mode, GLTF_TYPE_STRING } ),
std::make_pair("alphaCutoff", GLTFUniversalScopeValue { &material.alpha_cutoff, GLTF_TYPE_FLOAT } ),
std::make_pair("doubleSided", GLTFUniversalScopeValue { &material.double_sided, GLTF_TYPE_BOOLEAN } )
};
// for each element in values
for(size_t i = 0; i < _node->values.size(); i++) {
// error: invalid element type, only JSON objects are supported
if(_node->values[i].first != JSON_TYPE_OBJECT)
m_error.Error(LIBDAS_ERROR_INVALID_TYPE, _node->key_val_decl_line, _node->name, "JSON object");
_IterateSubNodes(std::any_cast<JSONNode>(&_node->values[i].second), values);
// check if emissive factor should be considered
if(emissive_factor.size() == 3)
material.emissive_factor = *reinterpret_cast<Point3D<JSONNumber>*>(emissive_factor.data());
m_root.materials.push_back(material);
material = GLTFMaterial();
}
}
void GLTFParser::_ReadMaterialPbrMetallicRoughness(JSONNode *_node, GLTFpbrMetallicRoughness &_met_roughness) {
std::vector<JSONNumber> base_color_factor;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("baseColorFactor", GLTFUniversalScopeValue { &base_color_factor, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("baseColorTexture", GLTFUniversalScopeValue { &_met_roughness.base_color_texture, GLTF_TYPE_MATERIAL_TEXTURE_INFO } ),
std::make_pair("metallicFactor", GLTFUniversalScopeValue { &_met_roughness.metallic_factor, GLTF_TYPE_FLOAT } ),
std::make_pair("roughnessFactor", GLTFUniversalScopeValue { &_met_roughness.roughness_factor, GLTF_TYPE_FLOAT } ),
std::make_pair("metallicRoughnessTexture", GLTFUniversalScopeValue { &_met_roughness.metallic_roughness_texture, GLTF_TYPE_MATERIAL_TEXTURE_INFO } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_met_roughness.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_met_roughness.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateSubNodes(_node, values);
if(base_color_factor.size() == 4)
_met_roughness.base_color_factor = *reinterpret_cast<Point4D<float>*>(&base_color_factor);
}
void GLTFParser::_ReadMaterialNormalTexture(JSONNode *_node, GLTFNormalTextureInfo &_norm_tex) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("index", GLTFUniversalScopeValue { &_norm_tex.index, GLTF_TYPE_INTEGER } ),
std::make_pair("texCoord", GLTFUniversalScopeValue { &_norm_tex.tex_coord, GLTF_TYPE_INTEGER } ),
std::make_pair("scale", GLTFUniversalScopeValue { &_norm_tex.scale, GLTF_TYPE_FLOAT } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_norm_tex.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_norm_tex.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadMaterialOcclusionTexture(JSONNode *_node, GLTFOcclusionTextureInfo &_occlusion_tex) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("index", GLTFUniversalScopeValue { &_occlusion_tex.index, GLTF_TYPE_INTEGER } ),
std::make_pair("texCoord", GLTFUniversalScopeValue { &_occlusion_tex.tex_coord, GLTF_TYPE_INTEGER } ),
std::make_pair("strength", GLTFUniversalScopeValue { &_occlusion_tex.strength, GLTF_TYPE_FLOAT } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_occlusion_tex.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_occlusion_tex.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateSubNodes(_node, values);
}
void GLTFParser::_ReadMaterialTextureInfo(JSONNode *_node, GLTFTextureInfo &_tex_info) {
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("index", GLTFUniversalScopeValue { &_tex_info.index, GLTF_TYPE_INTEGER } ),
std::make_pair("texCoord", GLTFUniversalScopeValue { &_tex_info.tex_coord, GLTF_TYPE_INTEGER } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &_tex_info.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &_tex_info.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
}
void GLTFParser::_ReadMeshes(JSONNode *_node) {
GLTFMesh mesh;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("primitives", GLTFUniversalScopeValue { &mesh.primitives, GLTF_TYPE_MESH_PRIMITIVES } ),
std::make_pair("weights", GLTFUniversalScopeValue { &mesh.weights, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("name", GLTFUniversalScopeValue { &mesh.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &mesh.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &mesh.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFMesh>(_node, values, mesh, m_root.meshes);
}
void GLTFParser::_ReadMeshPrimitives(JSONNode *_node, std::vector<GLTFMeshPrimitive> &_primitives) {
GLTFMeshPrimitive primitive;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("attributes", GLTFUniversalScopeValue { &primitive.attributes, GLTF_TYPE_MESH_PRIMITIVE_ATTRIBUTES } ),
std::make_pair("indices", GLTFUniversalScopeValue { &primitive.indices, GLTF_TYPE_INTEGER } ),
std::make_pair("material", GLTFUniversalScopeValue { &primitive.material, GLTF_TYPE_INTEGER } ),
std::make_pair("mode", GLTFUniversalScopeValue { &primitive.mode, GLTF_TYPE_INTEGER } ),
std::make_pair("targets", GLTFUniversalScopeValue { &primitive.targets, GLTF_TYPE_MESH_PRIMITIVE_ATTRIBUTES } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &primitive.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &primitive.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFMeshPrimitive>(_node, values, primitive, _primitives);
}
void GLTFParser::_ReadMeshPrimitiveAttributes(JSONNode *_node, GLTFMeshPrimitive::AttributesType &_attrs) {
// iterate through each subnode now
for(auto it = _node->sub_nodes.begin(); it != _node->sub_nodes.end(); it++) {
_VerifySourceData(it->second.get(), JSON_TYPE_INTEGER, false);
_attrs[it->first] = std::any_cast<uint32_t>(it->second->values.back());
}
}
void GLTFParser::_ReadNodes(JSONNode *_node) {
GLTFNode node;
std::vector<float> matrix; // size must be 16 elements
std::vector<float> rotation; // size must be 4 elements
std::vector<float> scale; // size must be 3 elements
std::vector<float> translation; // size must be 3 elements
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("camera", GLTFUniversalScopeValue { &node.camera, GLTF_TYPE_INTEGER } ),
std::make_pair("children", GLTFUniversalScopeValue { &node.children, GLTF_TYPE_INTEGER_ARRAY } ),
std::make_pair("skin", GLTFUniversalScopeValue { &node.skin, GLTF_TYPE_INTEGER } ),
std::make_pair("matrix", GLTFUniversalScopeValue { &matrix, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("mesh", GLTFUniversalScopeValue { &node.mesh, GLTF_TYPE_INTEGER } ),
std::make_pair("rotation", GLTFUniversalScopeValue { &rotation, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("scale", GLTFUniversalScopeValue { &scale, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("translation", GLTFUniversalScopeValue { &translation, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("weights", GLTFUniversalScopeValue { &node.weights, GLTF_TYPE_FLOAT_ARRAY } ),
std::make_pair("name", GLTFUniversalScopeValue { &node.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &node.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &node.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
// for each node in nodes
for(size_t i = 0; i < _node->values.size(); i++) {
// error: invalid value type, expected JSON object
if(_node->values[i].first != JSON_TYPE_OBJECT)
m_error.Error(LIBDAS_ERROR_INVALID_TYPE, _node->key_val_decl_line, _node->name, "JSON object");
_IterateSubNodes(std::any_cast<JSONNode>(&_node->values[i].second), values);
// append matrix data into correct data structure if possible
if(matrix.size() == 16) {
Matrix4<float> *data = reinterpret_cast<Matrix4<float>*>(matrix.data());
node.matrix = data->Transpose(); // transpose from column major to row major matrix
}
// append rotation data into correct data structure if possible
if(rotation.size() == 4)
node.rotation = *reinterpret_cast<Vector4<float>*>(rotation.data());
// append scale data into correct data structure if possible
if(scale.size() == 3)
node.scale = *reinterpret_cast<Point3D<float>*>(scale.data());
// append translation data into correct data structure if possible
if(translation.size() == 3)
node.translation = *reinterpret_cast<Point3D<float>*>(translation.data());
// clear all tmp structures
matrix.clear();
rotation.clear();
scale.clear();
translation.clear();
m_root.nodes.push_back(node);
node = GLTFNode();
}
}
void GLTFParser::_ReadSamplers(JSONNode *_node) {
GLTFSampler sampler;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("magFilter", GLTFUniversalScopeValue { &sampler.mag_filter, GLTF_TYPE_INTEGER } ),
std::make_pair("minFilter", GLTFUniversalScopeValue { &sampler.min_filter, GLTF_TYPE_INTEGER } ),
std::make_pair("wrapS", GLTFUniversalScopeValue { &sampler.wrap_s, GLTF_TYPE_INTEGER } ),
std::make_pair("wrapT", GLTFUniversalScopeValue { &sampler.wrap_t, GLTF_TYPE_INTEGER } ),
std::make_pair("name", GLTFUniversalScopeValue { &sampler.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &sampler.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &sampler.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
};
_IterateValueObjects<GLTFSampler>(_node, values, sampler, m_root.samplers);
}
void GLTFParser::_ReadScenes(JSONNode *_node, bool is_root) {
GLTFScene scene;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("nodes", GLTFUniversalScopeValue { &scene.nodes, GLTF_TYPE_INTEGER_ARRAY } ),
std::make_pair("name", GLTFUniversalScopeValue { &scene.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &scene.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &scene.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
if(!is_root)
_IterateValueObjects<GLTFScene>(_node, values, scene, m_root.scenes);
else m_root.load_time_scene = std::any_cast<uint32_t>(_node->values.back());
}
void GLTFParser::_ReadSkins(JSONNode *_node) {
GLTFSkin skin;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("inverseBindMatrices", GLTFUniversalScopeValue { &skin.inverse_bind_matrices, GLTF_TYPE_INTEGER } ),
std::make_pair("skeleton", GLTFUniversalScopeValue { &skin.skeleton, GLTF_TYPE_INTEGER } ),
std::make_pair("joints", GLTFUniversalScopeValue { &skin.joints, GLTF_TYPE_INTEGER_ARRAY } ),
std::make_pair("name", GLTFUniversalScopeValue { &skin.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &skin.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &skin.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateValueObjects<GLTFSkin>(_node, values, skin, m_root.skins);
}
void GLTFParser::_ReadTextures(JSONNode *_node) {
GLTFTexture texture;
std::unordered_map<std::string, GLTFUniversalScopeValue> values = {
std::make_pair("sampler", GLTFUniversalScopeValue { &texture.sampler, GLTF_TYPE_INTEGER } ),
std::make_pair("source", GLTFUniversalScopeValue { &texture.source, GLTF_TYPE_INTEGER } ),
std::make_pair("name", GLTFUniversalScopeValue { &texture.name, GLTF_TYPE_STRING } ),
std::make_pair("extensions", GLTFUniversalScopeValue { &texture.extensions, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } ),
std::make_pair("extras", GLTFUniversalScopeValue { &texture.extras, GLTF_TYPE_EXTRAS_OR_EXTENSIONS } )
};
_IterateValueObjects<GLTFTexture>(_node, values, texture, m_root.textures);
}
void GLTFParser::_RootObjectParserCaller(GLTFObjectType _type, JSONNode *_node) {
switch(_type) {
case GLTF_OBJECT_ACCESSORS:
_ReadAccessors(_node);
break;
case GLTF_OBJECT_ANIMATIONS:
_ReadAnimations(_node);
break;
case GLTF_OBJECT_ASSET:
_ReadAsset(_node);
break;
case GLTF_OBJECT_BUFFERS:
_ReadBuffers(_node);
break;
case GLTF_OBJECT_BUFFERVIEWS:
_ReadBufferviews(_node);
break;
case GLTF_OBJECT_CAMERAS:
_ReadCameras(_node);
break;
case GLTF_OBJECT_EXTENSIONS:
case GLTF_OBJECT_EXTRAS:
break;
case GLTF_OBJECT_IMAGES:
_ReadImages(_node);
break;
case GLTF_OBJECT_MATERIALS:
_ReadMaterials(_node);
break;
case GLTF_OBJECT_MESHES:
_ReadMeshes(_node);
break;
case GLTF_OBJECT_NODES:
_ReadNodes(_node);
break;
case GLTF_OBJECT_SAMPLERS:
_ReadSamplers(_node);
break;
case GLTF_OBJECT_SCENE:
_ReadScenes(_node, true);
break;
case GLTF_OBJECT_SCENES:
_ReadScenes(_node, false);
break;
case GLTF_OBJECT_SKINS:
_ReadSkins(_node);
break;
case GLTF_OBJECT_TEXTURES:
_ReadTextures(_node);
break;
default:
LIBDAS_ASSERT(false);
break;
}
}
void GLTFParser::_ResolveBufferUris(const std::string &_file_name) {
std::set<std::string> duplicate_uris;
// iterate through all buffer objects
for(auto it = m_root.buffers.begin(); it != m_root.buffers.end(); it++) {
// check if the uri already exists in the map
if(m_root.resources.find(it->uri) != m_root.resources.end()) {
duplicate_uris.insert(it->uri);
continue;
}
URIResolver resolver(it->uri, String::ExtractRootPath(_file_name));
m_root.resources[it->uri] = resolver.MoveBuffer();
}
// iterate through all image objects
for(auto it = m_root.images.begin(); it != m_root.images.end(); it++) {
// check if the uri already exists in the map
if(m_root.resources.find(it->uri) != m_root.resources.end()) {
duplicate_uris.insert(it->uri);
continue;
}
URIResolver resolver(it->uri, String::ExtractRootPath(_file_name));
std::vector<char> buf = resolver.MoveBuffer();
}
for(auto it = duplicate_uris.begin(); it != duplicate_uris.end(); it++)
std::cout << "GLTF warning: Duplicate URI '" << *it << std::endl;
}
void GLTFParser::Parse(const std::string &_file_name) {
if(_file_name != "") m_file_name = _file_name;
// parse json files with JSON parser
JSONParser::Parse(m_file_name);
JSONNode &root = JSONParser::GetRootNode();
// traverse the root node for data
for(auto it = root.sub_nodes.begin(); it != root.sub_nodes.end(); it++) {
GLTFObjectType type = _FindRootObjectType(it->first, it->second->key_val_decl_line);
_RootObjectParserCaller(type, it->second.get());
}
_ResolveBufferUris(m_file_name);
}
GLTFRoot &GLTFParser::GetRootObject() {
return m_root;
}
}
|
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file DataReaderImpl.hpp
*
*/
#ifndef _FASTRTPS_DATAREADERIMPL_HPP_
#define _FASTRTPS_DATAREADERIMPL_HPP_
#ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC
#include <fastdds/dds/core/LoanableCollection.hpp>
#include <fastdds/dds/core/LoanableSequence.hpp>
#include <fastdds/dds/core/status/StatusMask.hpp>
#include <fastdds/dds/subscriber/qos/DataReaderQos.hpp>
#include <fastdds/dds/subscriber/DataReaderListener.hpp>
#include <fastdds/dds/subscriber/SampleInfo.hpp>
#include <fastdds/dds/topic/TypeSupport.hpp>
#include <fastdds/rtps/attributes/ReaderAttributes.h>
#include <fastdds/rtps/common/LocatorList.hpp>
#include <fastdds/rtps/common/Guid.h>
#include <fastdds/rtps/history/IPayloadPool.h>
#include <fastdds/rtps/reader/ReaderListener.h>
#include <fastrtps/attributes/TopicAttributes.h>
#include <fastrtps/subscriber/SubscriberHistory.h>
#include <fastrtps/qos/LivelinessChangedStatus.h>
#include <fastrtps/types/TypesBase.h>
#include <fastdds/subscriber/DataReaderImpl/DataReaderLoanManager.hpp>
#include <fastdds/subscriber/DataReaderImpl/SampleInfoPool.hpp>
#include <fastdds/subscriber/DataReaderImpl/SampleLoanManager.hpp>
#include <fastdds/subscriber/SubscriberImpl.hpp>
#include <rtps/history/ITopicPayloadPool.h>
using eprosima::fastrtps::types::ReturnCode_t;
namespace eprosima {
namespace fastrtps {
namespace rtps {
class RTPSReader;
class TimedEvent;
} // namespace rtps
} // namespace fastrtps
namespace fastdds {
namespace dds {
class Subscriber;
class SubscriberImpl;
class TopicDescription;
using SampleInfoSeq = LoanableSequence<SampleInfo>;
namespace detail {
struct ReadTakeCommand;
} // namespace detail
/**
* Class DataReader, contains the actual implementation of the behaviour of the Subscriber.
* @ingroup FASTDDS_MODULE
*/
class DataReaderImpl
{
friend struct detail::ReadTakeCommand;
protected:
using ITopicPayloadPool = eprosima::fastrtps::rtps::ITopicPayloadPool;
using IPayloadPool = eprosima::fastrtps::rtps::IPayloadPool;
friend class SubscriberImpl;
/**
* Creates a DataReader. Don't use it directly, but through Subscriber.
*/
DataReaderImpl(
SubscriberImpl* s,
const TypeSupport& type,
TopicDescription* topic,
const DataReaderQos& qos,
DataReaderListener* listener = nullptr);
public:
virtual ~DataReaderImpl();
virtual ReturnCode_t enable();
bool can_be_deleted() const;
/**
* Method to block the current thread until an unread message is available
*/
bool wait_for_unread_message(
const fastrtps::Duration_t& timeout);
/** @name Read or take data methods.
* Methods to read or take data from the History.
*/
///@{
ReturnCode_t read(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples = LENGTH_UNLIMITED,
SampleStateMask sample_states = ANY_SAMPLE_STATE,
ViewStateMask view_states = ANY_VIEW_STATE,
InstanceStateMask instance_states = ANY_INSTANCE_STATE);
ReturnCode_t read_instance(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples = LENGTH_UNLIMITED,
const InstanceHandle_t& a_handle = HANDLE_NIL,
SampleStateMask sample_states = ANY_SAMPLE_STATE,
ViewStateMask view_states = ANY_VIEW_STATE,
InstanceStateMask instance_states = ANY_INSTANCE_STATE);
ReturnCode_t read_next_instance(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples = LENGTH_UNLIMITED,
const InstanceHandle_t& previous_handle = HANDLE_NIL,
SampleStateMask sample_states = ANY_SAMPLE_STATE,
ViewStateMask view_states = ANY_VIEW_STATE,
InstanceStateMask instance_states = ANY_INSTANCE_STATE);
ReturnCode_t read_next_sample(
void* data,
SampleInfo* info);
ReturnCode_t take(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples = LENGTH_UNLIMITED,
SampleStateMask sample_states = ANY_SAMPLE_STATE,
ViewStateMask view_states = ANY_VIEW_STATE,
InstanceStateMask instance_states = ANY_INSTANCE_STATE);
ReturnCode_t take_instance(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples = LENGTH_UNLIMITED,
const InstanceHandle_t& a_handle = HANDLE_NIL,
SampleStateMask sample_states = ANY_SAMPLE_STATE,
ViewStateMask view_states = ANY_VIEW_STATE,
InstanceStateMask instance_states = ANY_INSTANCE_STATE);
ReturnCode_t take_next_instance(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples = LENGTH_UNLIMITED,
const InstanceHandle_t& previous_handle = HANDLE_NIL,
SampleStateMask sample_states = ANY_SAMPLE_STATE,
ViewStateMask view_states = ANY_VIEW_STATE,
InstanceStateMask instance_states = ANY_INSTANCE_STATE);
ReturnCode_t take_next_sample(
void* data,
SampleInfo* info);
///@}
ReturnCode_t return_loan(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos);
/**
* @brief Returns information about the first untaken sample.
* @param [out] info Pointer to a SampleInfo structure to store first untaken sample information.
* @return true if sample info was returned. false if there is no sample to take.
*/
ReturnCode_t get_first_untaken_info(
SampleInfo* info);
/**
* @return the number of samples pending to be read.
*/
uint64_t get_unread_count() const;
/**
* Get associated GUID
* @return Associated GUID
*/
const fastrtps::rtps::GUID_t& guid() const;
fastrtps::rtps::InstanceHandle_t get_instance_handle() const;
/**
* Get topic data type
* @return Topic data type
*/
TypeSupport type();
/**
* Get TopicDescription
* @return TopicDescription
*/
const TopicDescription* get_topicdescription() const;
ReturnCode_t get_requested_deadline_missed_status(
fastrtps::RequestedDeadlineMissedStatus& status);
ReturnCode_t set_qos(
const DataReaderQos& qos);
const DataReaderQos& get_qos() const;
ReturnCode_t set_listener(
DataReaderListener* listener);
const DataReaderListener* get_listener() const;
/* TODO
bool get_key_value(
void* data,
const fastrtps::rtps::InstanceHandle_t& handle);
*/
ReturnCode_t get_liveliness_changed_status(
fastrtps::LivelinessChangedStatus& status);
ReturnCode_t get_requested_incompatible_qos_status(
RequestedIncompatibleQosStatus& status);
/* TODO
bool get_sample_lost_status(
fastrtps::SampleLostStatus& status) const;
*/
/* TODO
bool get_sample_rejected_status(
fastrtps::SampleRejectedStatus& status) const;
*/
const Subscriber* get_subscriber() const;
/* TODO
bool wait_for_historical_data(
const fastrtps::Duration_t& max_wait) const;
*/
//! Remove all listeners in the hierarchy to allow a quiet destruction
virtual void disable();
/* Check whether values in the DataReaderQos are compatible among them or not
* @return True if correct.
*/
static ReturnCode_t check_qos (
const DataReaderQos& qos);
/* Check whether the DataReaderQos can be updated with the values provided. This method DOES NOT update anything.
* @param to Reference to the qos instance to be changed.
* @param from Reference to the qos instance with the new values.
* @return True if they can be updated.
*/
static bool can_qos_be_updated(
const DataReaderQos& to,
const DataReaderQos& from);
/* Update a DataReaderQos with new values
* @param to Reference to the qos instance to be changed.
* @param from Reference to the qos instance with the new values.
* @param first_time Boolean indicating whether is the first time (If not some parameters cannot be set).
*/
static void set_qos(
DataReaderQos& to,
const DataReaderQos& from,
bool first_time);
/**
* Checks whether the sample is still valid or is corrupted
* @param data Pointer to the sample data to check
* @param info Pointer to the SampleInfo related to \c data
* @return true if the sample is valid
*/
bool is_sample_valid(
const void* data,
const SampleInfo* info) const;
/**
* Get the list of locators on which this DataReader is listening.
*
* @param [out] locators LocatorList where the list of locators will be stored.
*
* @return NOT_ENABLED if the reader has not been enabled.
* @return OK if a list of locators is returned.
*/
ReturnCode_t get_listening_locators(
rtps::LocatorList& locators) const;
protected:
//!Subscriber
SubscriberImpl* subscriber_ = nullptr;
//!Pointer to associated RTPSReader
fastrtps::rtps::RTPSReader* reader_ = nullptr;
//! Pointer to the TopicDataType object.
TypeSupport type_;
TopicDescription* topic_ = nullptr;
DataReaderQos qos_;
//!History
fastrtps::SubscriberHistory history_;
//!Listener
DataReaderListener* listener_ = nullptr;
class InnerDataReaderListener : public fastrtps::rtps::ReaderListener
{
public:
InnerDataReaderListener(
DataReaderImpl* s)
: data_reader_(s)
{
}
virtual ~InnerDataReaderListener() override
{
}
void onReaderMatched(
fastrtps::rtps::RTPSReader* reader,
const SubscriptionMatchedStatus& info) override;
void onNewCacheChangeAdded(
fastrtps::rtps::RTPSReader* reader,
const fastrtps::rtps::CacheChange_t* const change) override;
void on_liveliness_changed(
fastrtps::rtps::RTPSReader* reader,
const fastrtps::LivelinessChangedStatus& status) override;
void on_requested_incompatible_qos(
fastrtps::rtps::RTPSReader* reader,
fastdds::dds::PolicyMask qos) override;
DataReaderImpl* data_reader_;
}
reader_listener_;
//! A timer used to check for deadlines
fastrtps::rtps::TimedEvent* deadline_timer_ = nullptr;
//! Deadline duration in microseconds
std::chrono::duration<double, std::ratio<1, 1000000>> deadline_duration_us_;
//! The current timer owner, i.e. the instance which started the deadline timer
fastrtps::rtps::InstanceHandle_t timer_owner_;
//! Liveliness changed status
LivelinessChangedStatus liveliness_changed_status_;
//! Requested deadline missed status
fastrtps::RequestedDeadlineMissedStatus deadline_missed_status_;
//! Requested incompatible QoS status
RequestedIncompatibleQosStatus requested_incompatible_qos_status_;
//! A timed callback to remove expired samples
fastrtps::rtps::TimedEvent* lifespan_timer_ = nullptr;
//! The lifespan duration
std::chrono::duration<double, std::ratio<1, 1000000>> lifespan_duration_us_;
DataReader* user_datareader_ = nullptr;
std::shared_ptr<ITopicPayloadPool> payload_pool_;
std::shared_ptr<detail::SampleLoanManager> sample_pool_;
detail::SampleInfoPool sample_info_pool_;
detail::DataReaderLoanManager loan_manager_;
ReturnCode_t check_collection_preconditions_and_calc_max_samples(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t& max_samples);
ReturnCode_t prepare_loan(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t& max_samples);
ReturnCode_t read_or_take(
LoanableCollection& data_values,
SampleInfoSeq& sample_infos,
int32_t max_samples,
const InstanceHandle_t& handle,
SampleStateMask sample_states,
ViewStateMask view_states,
InstanceStateMask instance_states,
bool exact_instance,
bool single_instance,
bool should_take);
ReturnCode_t read_or_take_next_sample(
void* data,
SampleInfo* info,
bool should_take);
/**
* @brief A method called when a new cache change is added
* @param change The cache change that has been added
* @return True if the change was added (due to some QoS it could have been 'rejected')
*/
bool on_new_cache_change_added(
const fastrtps::rtps::CacheChange_t* const change);
/**
* @brief Method called when an instance misses the deadline
*/
bool deadline_missed();
/**
* @brief A method to reschedule the deadline timer
*/
bool deadline_timer_reschedule();
/**
* @brief A method called when the lifespan timer expires
*/
bool lifespan_expired();
fastrtps::TopicAttributes topic_attributes() const;
void subscriber_qos_updated();
RequestedIncompatibleQosStatus& update_requested_incompatible_qos(
PolicyMask incompatible_policies);
LivelinessChangedStatus& update_liveliness_status(
const fastrtps::LivelinessChangedStatus& status);
/**
* Returns the most appropriate listener to handle the callback for the given status,
* or nullptr if there is no appropriate listener.
*/
DataReaderListener* get_listener_for(
const StatusMask& status);
std::shared_ptr<IPayloadPool> get_payload_pool();
void release_payload_pool();
ReturnCode_t check_datasharing_compatible(
const fastrtps::rtps::ReaderAttributes& reader_attributes,
bool& is_datasharing_compatible) const;
};
} /* namespace dds */
} /* namespace fastdds */
} /* namespace eprosima */
#endif // ifndef DOXYGEN_SHOULD_SKIP_THIS_PUBLIC
#endif /* _FASTRTPS_DATAREADERIMPL_HPP_*/
|
#pragma once
#include <vector>
#include "rocksdb/write_batch.h"
namespace py_rocks {
class RecordItemsHandler: public rocksdb::WriteBatch::Handler {
public:
enum Optype {PutRecord, MergeRecord, DeleteRecord};
class BatchItem {
public:
BatchItem(
const Optype& op,
uint32_t column_family_id,
const rocksdb::Slice& key,
const rocksdb::Slice& value):
op(op),
column_family_id(column_family_id),
key(key),
value(value)
{}
const Optype op;
uint32_t column_family_id;
const rocksdb::Slice key;
const rocksdb::Slice value;
};
typedef std::vector<BatchItem> BatchItems;
public:
/* Items is filled during iteration. */
RecordItemsHandler(BatchItems* items): items(items) {}
virtual rocksdb::Status PutCF(
uint32_t column_family_id, const Slice& key, const Slice& value) {
this->items->emplace_back(PutRecord, column_family_id, key, value);
return rocksdb::Status::OK();
}
virtual rocksdb::Status MergeCF(
uint32_t column_family_id, const Slice& key, const Slice& value) {
this->items->emplace_back(MergeRecord, column_family_id, key, value);
return rocksdb::Status::OK();
}
virtual rocksdb::Status DeleteCF(
uint32_t column_family_id, const Slice& key) {
this->items->emplace_back(DeleteRecord, column_family_id, key, rocksdb::Slice());
return rocksdb::Status::OK();
}
private:
BatchItems* items;
};
rocksdb::Status
get_batch_items(const rocksdb::WriteBatch* batch, RecordItemsHandler::BatchItems* items) {
RecordItemsHandler handler(items);
return batch->Iterate(&handler);
}
}
|
#include "sdk/ins_sdk.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace galaxy::ins::sdk;
void my_watch_cb(const WatchParam& param, SDKError error) {
InsSDK* sdk = static_cast<InsSDK*>(param.context);
printf("key: %s\n", param.key.c_str());
printf("value: %s\n", param.value.c_str());
printf("deleted: %s\n", param.deleted ?"true":"false");
printf("error code: %d\n", static_cast<int>(error));
if (sdk) {
printf("watch again\n");
SDKError er;
sdk->Watch(param.key, my_watch_cb, (void*)sdk, &er);
}
}
void on_session_timeout(void* context) {
(void)context;
fprintf(stderr, "in session timeout\n");
exit(1);
}
int main(int argc, char* argv[]) {
std::vector<std::string> members;
if (argc < 2) {
fprintf(stderr, "./sample [read|write]\n");
return 1;
}
if (strcmp("write", argv[1]) == 0) {
fprintf(stderr, "write test\n");
InsSDK::ParseFlagFromArgs(argc, argv, &members);
InsSDK sdk(members);
char key_buf[1024] = {'\0'};
char value_buf[1024] = {'\0'};
SDKError err;
for (int i=1; i<=100000; i++) {
snprintf(key_buf, sizeof(key_buf), "key_%d", i);
snprintf(value_buf, sizeof(value_buf), "value_%d", i);
sdk.Put(key_buf, value_buf, &err);
if (err == kClusterDown) {
i--;
printf("try put again: %s\n", key_buf);
sleep(2);
continue;
}
printf("%s\n", key_buf);
fflush(stdout);
}
} else if(strcmp("read", argv[1]) == 0) {
fprintf(stderr, "read test\n");
InsSDK::ParseFlagFromArgs(argc, argv, &members);
InsSDK sdk(members);
char key_buf[1024] = {'\0'};
char value_buf[1024] = {'\0'};
SDKError err;
for (int i=1; i<=100000; i++) {
snprintf(key_buf, sizeof(key_buf), "key_%d", i);
snprintf(value_buf, sizeof(value_buf), "value_%d", i);
std::string value;
sdk.Get(key_buf, &value, &err);
if (err == kClusterDown) {
i--;
printf("try get again: %s", key_buf);
sleep(2);
continue;
}
if (err == kOK) {
printf("%s\n", value.c_str());
} else if (err == kNoSuchKey) {
printf("NOT FOUND\n");
}
fflush(stdout);
}
} else if(strcmp("watch", argv[1]) == 0) {
fprintf(stderr, "watch test\n");
InsSDK::ParseFlagFromArgs(argc, argv, &members);
InsSDK sdk(members);
sdk.RegisterSessionTimeout(on_session_timeout, NULL);
char key_buf[1024] = {'\0'};
SDKError err;
for (int i=1; i<=1000; i++) {
snprintf(key_buf, sizeof(key_buf), "key_%d", i);
sdk.Watch(key_buf, my_watch_cb, &sdk, &err);
}
while (true) {
sleep(1);
}
}
return 0;
}
|
/*************************************************************************
* Copyright (c) 2015-2020, NVIDIA CORPORATION. All rights reserved.
*
* See LICENSE.txt for license information
************************************************************************/
#include "enqueue.h"
#include "collectives.h"
#include "devcomm.h"
ncclResult_t msccl2DAllToAll(const void *sendbuff, void *recvbuff, size_t sendcount,
ncclDataType_t datatype, ncclComm_t comm, cudaStream_t stream){
int nGpus = comm->localRanks, nNodes = comm->nNodes;
if (nGpus == 1 || nNodes == 1){
WARN("number of local GPUs (%d) or number of nodes (%d) is 1.", nGpus, nNodes);
return ncclInvalidUsage;
}
// 2D Hierarchical AlltoAll algorithm
// phase 0. per-gpu (nGpus) stride copy
CUDACHECK(strideMemcpyAsync(recvbuff, sendbuff, sendcount * ncclTypeSize(datatype), nGpus, nNodes, stream));
// phase 1. intra-node alltoall
NCCLCHECK(ncclGroupStart());
for (int g = 0; g < nGpus; g++)
{
NCCLCHECK(ncclSend(((char *)recvbuff) + g * nNodes * sendcount * ncclTypeSize(datatype), nNodes * sendcount, datatype, g + comm->node * nGpus, comm, stream));
NCCLCHECK(ncclRecv(((char *)sendbuff) + g * nNodes * sendcount * ncclTypeSize(datatype), nNodes * sendcount, datatype, g + comm->node * nGpus, comm, stream));
}
NCCLCHECK(ncclGroupEnd());
// phase 2. per-gpu (nNodes) stride copy
CUDACHECK(strideMemcpyAsync(recvbuff, sendbuff, sendcount * ncclTypeSize(datatype), nNodes, nGpus, stream));
// phase 3. inter-node alltoall
NCCLCHECK(ncclGroupStart());
for (int n = 0; n < nNodes; n++)
{
NCCLCHECK(ncclSend(((char *)recvbuff) + n * nGpus * sendcount * ncclTypeSize(datatype), nGpus * sendcount, datatype, n * nGpus + comm->cudaDev, comm, stream));
NCCLCHECK(ncclRecv(((char *)sendbuff) + n * nGpus * sendcount * ncclTypeSize(datatype), nGpus * sendcount, datatype, n * nGpus + comm->cudaDev, comm, stream));
}
NCCLCHECK(ncclGroupEnd());
CUDACHECK(cudaMemcpyAsync(recvbuff, sendbuff, comm->nRanks * sendcount * ncclTypeSize(datatype), cudaMemcpyDeviceToDevice, stream));
return ncclSuccess;
}
NCCL_API(ncclResult_t, ncclAllToAll, const void *sendbuff, void *recvbuff, size_t sendcount,
ncclDataType_t datatype, ncclComm_t comm, cudaStream_t stream);
ncclResult_t ncclAllToAll(const void *sendbuff, void *recvbuff, size_t sendcount,
ncclDataType_t datatype, ncclComm_t comm, cudaStream_t stream)
{
if (sendcount == 0) return ncclSuccess;
size_t allcount = sendcount * comm->nRanks;
size_t nbytes = allcount * ncclTypeSize(datatype);
if (comm->nMscclRegistrations > 0)
{
for (int i = 0; i < comm->nMscclRegistrations; ++i)
{
struct mscclRegistration *reg = &comm->mscclRegistrations[i];
if (reg->minBytes <= nbytes && (nbytes < reg->maxBytes || reg->maxBytes == -1))
{
struct mscclAlgorithm *mscclAlgo = &comm->mscclAlgos[reg->algoIndex];
if ((mscclAlgo->isValid) && (mscclAlgo->collectiveType == ncclFuncAllToAll) && (comm->nRanks == mscclAlgo->ngpus) && ((allcount % mscclAlgo->nchunksPerLoop) == 0))
{
// if it was the 2D algorithm, select it first.
if (!strcmp(mscclAlgo->name, "2D")) {
return msccl2DAllToAll(sendbuff, recvbuff, sendcount, datatype, comm, stream);
} else {
NVTX3_FUNC_RANGE_IN(nccl_domain);
struct ncclInfo info = {ncclFuncAllToAll, "AllToAll",
sendbuff, recvbuff, 0 /* all-to-all can only be out of place */, sendcount, datatype, ncclSum, 0, comm, stream, /* Args */
MSCCL_CHUNKSTEPS, MSCCL_SLICESTEPS};
info.mscclAlgoIndex = reg->algoIndex;
auto curProto = mscclAlgo->protocol;
mscclAlgo->protocol = reg->protocol;
auto ret = ncclEnqueueCheck(&info);
mscclAlgo->protocol = curProto;
return ret;
}
}
}
}
}
else
{
for (int mscclAlgoIndex = 0; mscclAlgoIndex < comm->numberOfMSCCLAlgorithms; mscclAlgoIndex++)
{
struct mscclAlgorithm *mscclAlgo = &comm->mscclAlgos[mscclAlgoIndex];
if ((mscclAlgo->isValid) && (mscclAlgo->collectiveType == ncclFuncAllToAll) && (comm->nRanks == mscclAlgo->ngpus) && ((allcount % comm->mscclAlgos[mscclAlgoIndex].nchunksPerLoop) == 0) && (nbytes >= mscclAlgo->minBytes) && (nbytes < mscclAlgo->maxBytes))
{
// if it was the 2D algorithm, select it first.
if (!strcmp(mscclAlgo->name, "2D")) {
return msccl2DAllToAll(sendbuff, recvbuff, sendcount, datatype, comm, stream);
} else {
NVTX3_FUNC_RANGE_IN(nccl_domain);
struct ncclInfo info = {ncclFuncAllToAll, "AllToAll",
sendbuff, recvbuff, 0 /* all-to-all can only be out of place */, sendcount, datatype, ncclSum, 0, comm, stream, /* Args */
MSCCL_CHUNKSTEPS, MSCCL_SLICESTEPS};
info.mscclAlgoIndex = mscclAlgoIndex;
return ncclEnqueueCheck(&info);
}
}
}
}
// default p2p if all failed
NCCLCHECK(ncclGroupStart());
for (int r = 0; r < comm->nRanks; r++)
{
NCCLCHECK(ncclSend(((char *)sendbuff) + r * sendcount * ncclTypeSize(datatype), sendcount, datatype, r, comm, stream));
NCCLCHECK(ncclRecv(((char *)recvbuff) + r * sendcount * ncclTypeSize(datatype), sendcount, datatype, r, comm, stream));
}
NCCLCHECK(ncclGroupEnd());
return ncclSuccess;
}
|
#ifndef BOOST_MPL_MAP_AUX_ERASE_IMPL_HPP_INCLUDED
#define BOOST_MPL_MAP_AUX_ERASE_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
// Copyright David Abrahams 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: erase_impl.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
#include <Awl/boost/mpl/erase_fwd.hpp>
#include <Awl/boost/mpl/map/aux_/erase_key_impl.hpp>
#include <Awl/boost/mpl/map/aux_/tag.hpp>
namespace boost { namespace mpl {
template<>
struct erase_impl< aux::map_tag >
{
template<
typename Map
, typename Pos
, typename unused_
>
struct apply
: erase_key_impl<aux::map_tag>
::apply<Map,typename Pos::type::first>
{
};
};
}}
#endif // BOOST_MPL_MAP_AUX_ERASE_IMPL_HPP_INCLUDED
|
#include "neste_private.h"
#include <stdexcept>
NESTED_CPPMM_API unsigned int nest__NestBE_do_something(
nest_NestBE_t * this_)
{
try {
(to_cpp(this_)) -> do_something();
return 0;
} catch (std::exception& e) {
TLG_EXCEPTION_STRING = e.what();
return -1;
}
}
|
#include "IEFile.h"
#include <cassert>
IEFile::IEFile() : relativePtrLocation(0),
fileOpened(false),
fileSize(0),
eofReached(true)
{}
IEFile::IEFile(IEFile&& mv)
: handle(mv.handle)
, relativePtrLocation(mv.relativePtrLocation)
, fileOpened(mv.fileOpened)
, fileSize(mv.fileSize)
, eofReached(mv.eofReached)
{
mv.fileOpened = false;
}
IEFile::~IEFile()
{
Close();
}
IEFile& IEFile::operator=(IEFile&& mv)
{
assert(&mv != this);
handle = mv.handle;
relativePtrLocation = mv.relativePtrLocation;
fileOpened = mv.fileOpened;
fileSize = mv.fileSize;
eofReached = mv.eofReached;
mv.fileOpened = false;
return *this;
}
bool IEFile::hasFileOpened() const
{
return fileOpened;
}
uint64_t IEFile::getFileSize() const
{
return fileSize;
}
bool IEFile::isEOFReached() const
{
return eofReached;
}
uint64_t IEFile::getRelativePtrLocation() const
{
return relativePtrLocation;
}
IEFileErrorType IEFile::ReadAll(uint8_t data[], size_t arrayLength,
const char* path,
IEFileShareType share)
{
// Open file but all the data to byte
IEFile f;
f.Open(path, IEFileActionType::ACCESS, IEFileAccessType::READ, share);
if(arrayLength < f.getFileSize())
{
return IEFileErrorType::READ_BUFFER_TOO_SMALL;
}
return f.ReadRest(data, arrayLength);
}
|
#include <boost/typeof/decltype.hpp>
|
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int a[32][32],n,m,pr[32];
int countPoint(int i, int p)
{
int l,r,mid;
sort (a[i],a[i]+n);
if(p<a[i][0]||p>a[i][n-1])return -500;
l=0;r=n-1;
while(l<=r)
{
mid=(l+r)/2;
if(p==a[i][mid]) return p;
if(p>a[i][mid])l=mid+1;
else r=mid-1;
}
if (abs(p-a[i][l])>abs(p-a[i][r]))return a[i][r];
if (abs(p-a[i][l])<abs(p-a[i][r]))return a[i][l];
return max(a[i][l],a[i][r]);
}
int main()
{
int sum=0, i,j;
cin>>m>>n;
for(i=0;i<m;i++)
{
cin>>pr[i];
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<m;i++)
{
sum+=countPoint(i,pr[i]);
}
cout<<sum<<endl;
return 0;
}
|
// ***********************************************************************
//
// Grappolo: A C++ library for graph clustering
// Mahantesh Halappanavar (hala@pnnl.gov)
// Pacific Northwest National Laboratory
//
// ***********************************************************************
//
// Copyright (2014) Battelle Memorial Institute
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// ************************************************************************
#include "defs.h"
#include "coloring.h"
#include "stdlib.h"
#include "time.h"
//Return the number of colors used (zero is a valid color)
//Algorithm: Adaptation of Luby-Jones-Plusman
//Source: http://on-demand.gputechconf.com/gtc/2012/presentations/S0332-Efficient-Graph-Matching-and-Coloring-on-GPUs.pdf
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
void generateRandomNumbers2(double* randValues, comm_type NVer)
{
for(int v = 0; v<NVer; v++)
{
randValues[v] = (double)rand();
}
}
int algoColoringMultiHashMaxMin(graph *G, int *vtxColor, int nThreads, double *totTime, int nHash, int nItrs)
{
#ifdef PRINT_DETAILED_STATS_
std::cout << "Within algoColoringMultiHashMaxMin(nHash= " << nHash << " -- nItrs= " << nItrs << ")\n";
#endif
if (nThreads < 1)
omp_set_num_threads(1); //default to one thread
else
omp_set_num_threads(nThreads);
int nT;
#pragma omp parallel
{
nT = omp_get_num_threads();
}
#ifdef PRINT_DETAILED_STATS_
printf("Actual number of threads: %d (requested: %d)\n", nT, nThreads);
#endif
assert(nItrs > 0); assert(nHash > 0);
double time1=0, time2=0, totalTime=0;
//Get the iterators for the graph:
comm_type NVer = G->numVertices;
comm_type NEdge = G->numEdges;
comm_type *verPtr = G->edgeListPtrs; //Vertex Pointer: pointers to endV
edge *verInd = G->edgeList; //Vertex Index: destination id of an edge (src -> dest)
int maxColor = (2 * nHash * nItrs); //Two colors for each hash per iteration; zero is a valid color
int totalColored = 0;
#ifdef PRINT_DETAILED_STATS_
printf("Vertices: %ld Edges: %ld Max color index: %d\n\n\n", NVer, NEdge, maxColor);
#endif
//Build a vector of random numbers:
//Note: Cheating a little bit now -- need to fix this with a hash function
/*
double *randValues = (double*) malloc (NVer * sizeof(double));
assert(randValues != 0); */
time1 = omp_get_wtime();
double **randValuesPtr = (double**) malloc(nHash * sizeof(double*));
for(int i=0; i < nHash; i++)
{
randValuesPtr[i] = (double*) malloc (NVer * sizeof(double));
generateRandomNumbers2(randValuesPtr[i], NVer);
}
time2 = omp_get_wtime();
totalTime = time2-time1;
#ifdef PRINT_DETAILED_STATS_
printf("Time to generate random numbers: %lf\n", time2-time1);
#endif
//Color all the vertices to a maximum number (means that the vertex did not get colored)
#pragma omp parallel for
for (comm_type v=0; v<NVer; v++) {
vtxColor[v] = maxColor; //Set the color to maximum
}
int iterFreq = 0;
printf("--------------------------------------------------------------\n");
printf("Itr \t This iteration \t\t Total colored\n");
printf("--------------------------------------------------------------\n");
//Loop through the iterations:
for (int itr=0; itr<nItrs; itr++) {
//Iterate for the number of hashes
time1 = omp_get_wtime();
for (int ihash=0; ihash<nHash; ihash++) {
int currentColor = (2*itr*nHash + 2*ihash); //Color to be used in current itr-hash combination
#pragma omp parallel for
for (comm_type v=0; v<NVer; v++) {
//Iterate over all the vertices:
//Check if this vertex has already been colored
if(vtxColor[v] != maxColor)
continue; //The vertex has already been colored
//Vertex v has not been colored. Check to see if it is a local max or a local min
comm_type adj1 = verPtr[v];
comm_type adj2 = verPtr[v+1];
//Browse the adjacency set of vertex v
bool isMax = true, isMin = true;
for(comm_type k = adj1; k < adj2; k++ ) {
if ( v == verInd[k].tail ) //Self-loops
continue;
//if(vtxColor[verInd[k].tail] < maxColor)
if(vtxColor[verInd[k].tail] < currentColor) //Colored in previous iterations
continue; //It has already been colored -- ignore this neighbor
if ( randValuesPtr[ihash][v] <= randValuesPtr[ihash][verInd[k].tail] ) {
isMax = false;
}
if ( randValuesPtr[ihash][v] >= randValuesPtr[ihash][verInd[k].tail] ) {
isMin = false;
}
//Corner case: if all neighbors have been colored,
//both isMax and isMin will be true, but it doesn't matter
}//End of for(k)
if (isMax == true) {
vtxColor[v] = currentColor;
//printf("Color[%d]=%d\n", v+1, (2*itr*nHash) + 2*ihash);
__sync_fetch_and_add(&iterFreq,1);
} else if (isMin == true) {
vtxColor[v] = currentColor+1;
//printf("Color[%d]=%d\n", v+1, ((2*itr*nHash) + 2*ihash + 1));
__sync_fetch_and_add(&iterFreq,1);
}
}//End of for(v)
}//End of for(ihash)
totalColored += iterFreq;
time2 = omp_get_wtime();
totalTime = time2-time1;
printf("%d \t %d (%3.2lf%%) \t\t\t %d (%3.2lf%%)\n", itr, iterFreq, (double)iterFreq/NVer*100, totalColored, (double)totalColored/NVer*100);
if(iterFreq == 0) {
if(totalColored == NVer) {
printf("All vertices got colored in a smaller number\n");
maxColor = (2*(itr-1)*nHash) + 2*nHash + 1;
break;
}
} else {
iterFreq = 0; //reset the counter
}
} //End of for(itr)
printf("--------------------------------------------------------------\n");
//Verify Results and Cleanup
comm_type myConflicts = 0;
comm_type unColored = 0;
#pragma omp parallel for
for (comm_type v=0; v < NVer; v++ ) {
comm_type adj1 = verPtr[v];
comm_type adj2 = verPtr[v+1];
if ( vtxColor[v] == maxColor ) {//Ignore uncolored vertices
__sync_fetch_and_add(&unColored, 1);
continue;
}
//Browse the adjacency set of vertex v
for(comm_type k = adj1; k < adj2; k++ ) {
if ( v == verInd[k].tail ) //Self-loops
continue;
if ( vtxColor[v] == vtxColor[verInd[k].tail] ) {
__sync_fetch_and_add(&myConflicts, 1); //increment the counter
}
}//End of inner for loop: w in adj(v)
}//End of outer for loop: for each vertex
myConflicts = myConflicts / 2; //Have counted each conflict twice
if (myConflicts > 0)
printf("Check - WARNING: Number of conflicts detected after resolution: %d \n\n", myConflicts);
else
printf("Check - SUCCESS: No conflicts exist\n\n");
#ifdef PRINT_DETAILED_STATS_
printf("***********************************************\n");
printf("Number of colors used : %d \n", maxColor);
printf("Number of uncolored vertices : %d \n", unColored);
printf("Total Time : %3.3lf sec\n", totalTime);
printf("***********************************************\n");
#endif
*totTime = totalTime;
//Cleanup:
for(int i = 0; i < nHash; i++)
{
// for(int j =0; j < NVer; j++)
// printf("%lf",randValuesPtr[i][j]);
if (randValuesPtr[i] != 0)
free(randValuesPtr[i]);
}
if (randValuesPtr != 0)
free(randValuesPtr);
return maxColor; //Return the number of colors used (maxColor is also a valid color)
}//End of algoColoringMultiHashMaxMin()
|
/****************************************************************************
**
** Copyright (C) 2019 Xiaohai <xiaohaidotpro@outlook.com>.
** Contact: http://xiaohai.pro
**
** This file is part of data-structure-and-algorithm
**
**
****************************************************************************/
#include "bits/stdc++.h"
#include "Hash_Seperate_Chain.hpp"
using namespace std;
int main(int /* argc */, char** /* argv */) {
DSAA::HashTable<int> h1;
DSAA::HashTable<int> h2;
const int NUMS = 400000;
const int GAP = 37;
int i;
cout << "Checking... (no more output means success)" << endl;
for (i = GAP; i != 0; i = (i + GAP) % NUMS) h1.insert(i);
h2 = h1;
for (i = 1; i < NUMS; i += 2) h2.remove(i);
for (i = 2; i < NUMS; i += 2)
if (!h2.contains(i))
cout << "Contains fails " << i << endl;
for (i = 1; i < NUMS; i += 2) {
if (h2.contains(i))
cout << "OOPS!!! " << i << endl;
}
return 0;
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2018 by Contributors
* \file dynamic_shape_ops.cc
*/
#include "./dynamic_shape_ops-inl.h"
#include "../tensor/elemwise_binary_op.h"
#include "../elemwise_op_common.h"
namespace mxnet {
namespace op {
inline bool DynamicReshapeType(const nnvm::NodeAttrs& attrs,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]);
TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]);
return true;
}
bool DynamicReshapeStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
CHECK_EQ(in_attrs->size(), 2);
CHECK_EQ(out_attrs->size(), 1);
for (size_t i = 0; i < in_attrs->size(); ++i) {
STORAGE_TYPE_ASSIGN_CHECK(*in_attrs, i, kDefaultStorage);
}
for (size_t i = 0; i < out_attrs->size(); ++i) {
STORAGE_TYPE_ASSIGN_CHECK(*out_attrs, i, kDefaultStorage);
}
DISPATCH_MODE_ASSIGN_CHECK(dispatch_mode, 0, DispatchMode::kFComputeEx);
return true;
}
bool DynamicReshapeBackwardStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs) {
CHECK_EQ(in_attrs->size(), 1);
CHECK_EQ(out_attrs->size(), 2);
for (size_t i = 0; i < in_attrs->size(); ++i) {
STORAGE_TYPE_ASSIGN_CHECK(*in_attrs, i, kDefaultStorage);
}
for (size_t i = 0; i < out_attrs->size(); ++i) {
STORAGE_TYPE_ASSIGN_CHECK(*out_attrs, i, kDefaultStorage);
}
DISPATCH_MODE_ASSIGN_CHECK(dispatch_mode, 0, DispatchMode::kFComputeEx);
return true;
}
NNVM_REGISTER_OP(_contrib_dynamic_reshape)
.describe(R"code(
Experimental support for reshape operator with dynamic shape.
Accepts 2 inputs - data and shape.
The output returns data in the new shape.
Some dimensions of the shape can take special values from the set {0, -1, -2, -3, -4}. The significance of each is explained below:
- ``0`` copy this dimension from the input to the output shape.
Example::
- input shape = (2,3,4), shape = (4,0,2), output shape = (4,3,2)
- input shape = (2,3,4), shape = (2,0,0), output shape = (2,3,4)
- ``-1`` infers the dimension of the output shape by using the remainder of the input dimensions
keeping the size of the new array same as that of the input array.
At most one dimension of shape can be -1.
Example::
- input shape = (2,3,4), shape = (6,1,-1), output shape = (6,1,4)
- input shape = (2,3,4), shape = (3,-1,8), output shape = (3,1,8)
- input shape = (2,3,4), shape=(-1,), output shape = (24,)
- ``-2`` copy all/remainder of the input dimensions to the output shape.
Example::
- input shape = (2,3,4), shape = (-2,), output shape = (2,3,4)
- input shape = (2,3,4), shape = (2,-2), output shape = (2,3,4)
- input shape = (2,3,4), shape = (-2,1,1), output shape = (2,3,4,1,1)
- ``-3`` use the product of two consecutive dimensions of the input shape as the output dimension.
Example::
- input shape = (2,3,4), shape = (-3,4), output shape = (6,4)
- input shape = (2,3,4,5), shape = (-3,-3), output shape = (6,20)
- input shape = (2,3,4), shape = (0,-3), output shape = (2,12)
- input shape = (2,3,4), shape = (-3,-2), output shape = (6,4)
- ``-4`` split one dimension of the input into two dimensions passed subsequent to -4 in shape (can contain -1).
Example::
- input shape = (2,3,4), shape = (-4,1,2,-2), output shape =(1,2,3,4)
- input shape = (2,3,4), shape = (2,-4,-1,3,-2), output shape = (2,1,3,4)
Example::
data = mx.nd.array(np.random.normal(0,1,(2,3,5,5)))
shape = mx.nd.array((0,-1))
out = mx.sym.contrib.dynamic_reshape(data = data, shape = shape)
// out will be of shape (2,75)
)code" ADD_FILELINE)
.set_num_inputs(2)
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
return std::vector<std::string>{"data", "shape"};
})
.set_attr<nnvm::FInferType>("FInferType", DynamicReshapeType)
.set_attr<FInferStorageType>("FInferStorageType", DynamicReshapeStorageType)
.set_attr<FComputeEx>("FComputeEx<cpu>", DynamicReshapeForward<cpu>)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseNone{"_backward_contrib_dynamic_reshape"})
.add_argument("data", "NDArray-or-Symbol", "Data")
.add_argument("shape", "NDArray-or-Symbol", "Shape");
NNVM_REGISTER_OP(_backward_contrib_dynamic_reshape)
.set_num_inputs(1)
.set_num_outputs(2)
.set_attr<nnvm::TIsBackward>("TIsBackward", true)
.set_attr<FInferStorageType>("FInferStorageType", DynamicReshapeBackwardStorageType)
.set_attr<FComputeEx>("FComputeEx<cpu>", DynamicReshapeBackward<cpu>);
} // namespace op
} // namespace mxnet
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.