hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6171bb11a6387e2320a987392a4e49dea717e619 | 2,739 | cpp | C++ | tests/gl-320-glsl-cast-fail.cpp | lostgoat/ogl-samples | 9985448efd25bbd89d94a5ad76597cdb461fb5fc | [
"MIT"
] | null | null | null | tests/gl-320-glsl-cast-fail.cpp | lostgoat/ogl-samples | 9985448efd25bbd89d94a5ad76597cdb461fb5fc | [
"MIT"
] | null | null | null | tests/gl-320-glsl-cast-fail.cpp | lostgoat/ogl-samples | 9985448efd25bbd89d94a5ad76597cdb461fb5fc | [
"MIT"
] | 1 | 2020-04-30T09:17:01.000Z | 2020-04-30T09:17:01.000Z | #include "test.hpp"
namespace
{
char const * VERT_SHADER_SOURCE("gl-320/glsl-cast-fail.vert");
char const * FRAG_SHADER_SOURCE("gl-320/glsl-cast-fail.frag");
char const * TEXTURE_DIFFUSE("kueken7_rgba8_srgb.dds");
GLsizei const VertexCount(4);
GLsizeiptr const VertexSize = VertexCount * sizeof(glf::vertex_v2fv2f);
glf::vertex_v2fv2f const VertexData[VertexCount] =
{
glf::vertex_v2fv2f(glm::vec2(-1.0f,-1.0f), glm::vec2(0.0f, 1.0f)),
glf::vertex_v2fv2f(glm::vec2( 1.0f,-1.0f), glm::vec2(1.0f, 1.0f)),
glf::vertex_v2fv2f(glm::vec2( 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)),
glf::vertex_v2fv2f(glm::vec2(-1.0f, 1.0f), glm::vec2(0.0f, 0.0f))
};
GLsizei const ElementCount(6);
GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort);
GLushort const ElementData[ElementCount] =
{
0, 1, 2,
2, 3, 0
};
namespace buffer
{
enum type
{
VERTEX,
ELEMENT,
TRANSFORM,
MAX
};
}//namespace buffer
GLuint VertexArrayName(0);
GLuint ProgramName(0);
GLuint TextureName(0);
std::vector<GLuint> BufferName(buffer::MAX);
GLint UniformTransform(0);
GLint UniformDiffuse(0);
}//namespace
class gl_320_glsl_precision : public test
{
public:
gl_320_glsl_precision(int argc, char* argv[]) :
test(argc, argv, "gl-320-glsl-cast-fail", test::CORE, 3, 2, glm::vec2(0), test::GENERATE_ERROR)
{}
private:
bool initProgram()
{
bool Validated(true);
if(Validated)
{
compiler Compiler;
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 150 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 150 --profile core");
Validated = Validated && Compiler.check();
ProgramName = glCreateProgram();
glAttachShader(ProgramName, VertShaderName);
glAttachShader(ProgramName, FragShaderName);
glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position");
glBindAttribLocation(ProgramName, semantic::attr::TEXCOORD, "Texcoord");
glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color");
glLinkProgram(ProgramName);
Validated = Validated && !Compiler.check_program(ProgramName);
glDeleteProgram(ProgramName);
glDeleteShader(VertShaderName);
glDeleteShader(FragShaderName);
}
return Validated && this->checkError("initProgram");
}
bool begin()
{
bool Validated = true;
if(Validated)
Validated = initProgram();
return Validated && this->checkError("begin");
}
bool end()
{
return this->checkError("end");
}
bool render()
{
return true;
}
};
int main(int argc, char* argv[])
{
int Error(0);
gl_320_glsl_precision Test(argc, argv);
Error += Test();
return Error;
}
| 23.612069 | 136 | 0.705002 | [
"render",
"vector",
"transform"
] |
617e29d95e7966c45021070e5ff125c20971cda5 | 1,459 | cpp | C++ | src/cpp/JNI/org_jsfml_window_VideoMode.cpp | comqdhb/JSFML | c1397d0ed1ac1c334e33a346b17b59ead2dfb862 | [
"Zlib"
] | 41 | 2015-01-10T16:39:36.000Z | 2022-02-03T12:06:12.000Z | src/cpp/JNI/org_jsfml_window_VideoMode.cpp | comqdhb/JSFML | c1397d0ed1ac1c334e33a346b17b59ead2dfb862 | [
"Zlib"
] | 22 | 2015-01-26T01:36:16.000Z | 2019-01-05T07:31:49.000Z | src/cpp/JNI/org_jsfml_window_VideoMode.cpp | comqdhb/JSFML | c1397d0ed1ac1c334e33a346b17b59ead2dfb862 | [
"Zlib"
] | 38 | 2015-03-12T00:55:51.000Z | 2021-11-08T22:38:43.000Z | #include <JSFML/JNI/org_jsfml_window_VideoMode.h>
#include <SFML/Window/VideoMode.hpp>
/*
* Class: org_jsfml_window_VideoMode
* Method: nativeGetDesktopMode
* Signature: (Ljava/nio/Buffer;)V
*/
JNIEXPORT void JNICALL Java_org_jsfml_window_VideoMode_nativeGetDesktopMode
(JNIEnv *env, jclass cls, jobject buf) {
sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
jint *vmode = (jint*)env->GetDirectBufferAddress(buf);
vmode[0] = desktop.width;
vmode[1] = desktop.height;
vmode[2] = desktop.bitsPerPixel;
}
/*
* Class: org_jsfml_window_VideoMode
* Method: nativeGetFullscreenModeCount
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_jsfml_window_VideoMode_nativeGetFullscreenModeCount
(JNIEnv *env, jclass cls) {
return (jint)sf::VideoMode::getFullscreenModes().size();
}
/*
* Class: org_jsfml_window_VideoMode
* Method: nativeGetFullscreenModes
* Signature: (Ljava/nio/Buffer;)V
*/
JNIEXPORT void JNICALL Java_org_jsfml_window_VideoMode_nativeGetFullscreenModes
(JNIEnv *env, jclass cls, jobject buf) {
const std::vector<sf::VideoMode>& modes = sf::VideoMode::getFullscreenModes();
jint *data = (jint*)env->GetDirectBufferAddress(buf);
for(int i = 0; i < modes.size(); i++) {
const sf::VideoMode& mode = modes[i];
data[3 * i] = mode.width;
data[3 * i + 1] = mode.height;
data[3 * i + 2] = mode.bitsPerPixel;
}
}
| 29.18 | 83 | 0.686772 | [
"vector"
] |
618017ae81dea3010430c74cfb3920c2fdf63ee3 | 28,409 | cpp | C++ | intern/elbeem/intern/ntl_ray.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | 2 | 2018-06-18T01:50:25.000Z | 2018-06-18T01:50:32.000Z | intern/elbeem/intern/ntl_ray.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | intern/elbeem/intern/ntl_ray.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | /** \file elbeem/intern/ntl_ray.cpp
* \ingroup elbeem
*/
/******************************************************************************
*
* El'Beem - Free Surface Fluid Simulation with the Lattice Boltzmann Method
* Copyright 2003-2006 Nils Thuerey
*
* main renderer class
*
*****************************************************************************/
#include "utilities.h"
#include "ntl_ray.h"
#include "ntl_world.h"
#include "ntl_geometryobject.h"
#include "ntl_geometryshader.h"
/* Minimum value for refl/refr to be traced */
#define RAY_THRESHOLD 0.001
#if GFX_PRECISION==1
// float values
//! Minimal contribution for rays to be traced on
#define RAY_MINCONTRIB (1e-04)
#else
// double values
//! Minimal contribution for rays to be traced on
#define RAY_MINCONTRIB (1e-05)
#endif
/******************************************************************************
* Constructor
*****************************************************************************/
ntlRay::ntlRay( void )
: mOrigin(0.0)
, mDirection(0.0)
, mvNormal(0.0)
, mDepth(0)
, mpGlob(NULL)
, mIsRefracted(0)
{
errFatal("ntlRay::ntlRay()","Don't use uninitialized rays !", SIMWORLD_GENERICERROR);
return;
}
/******************************************************************************
* Copy - Constructor
*****************************************************************************/
ntlRay::ntlRay( const ntlRay &r )
{
// copy it! initialization is not enough!
mOrigin = r.mOrigin;
mDirection = r.mDirection;
mvNormal = r.mvNormal;
mDepth = r.mDepth;
mIsRefracted = r.mIsRefracted;
mIsReflected = r.mIsReflected;
mContribution = r.mContribution;
mpGlob = r.mpGlob;
// get new ID
if(mpGlob) {
mID = mpGlob->getCounterRays()+1;
mpGlob->setCounterRays( mpGlob->getCounterRays()+1 );
} else {
mID = 0;
}
}
/******************************************************************************
* Constructor with explicit parameters and global render object
*****************************************************************************/
ntlRay::ntlRay(const ntlVec3Gfx &o, const ntlVec3Gfx &d, unsigned int i, gfxReal contrib, ntlRenderGlobals *glob)
: mOrigin( o )
, mDirection( d )
, mvNormal(0.0)
, mDepth( i )
, mContribution( contrib )
, mpGlob( glob )
, mIsRefracted( 0 )
, mIsReflected( 0 )
{
// get new ID
if(mpGlob) {
mID = mpGlob->getCounterRays()+1;
mpGlob->setCounterRays( mpGlob->getCounterRays()+1 );
} else {
mID = 0;
}
}
/******************************************************************************
* Destructor
*****************************************************************************/
ntlRay::~ntlRay()
{
/* nothing to do... */
}
/******************************************************************************
* AABB
*****************************************************************************/
/* for AABB intersect */
#define NUMDIM 3
#define RIGHT 0
#define LEFT 1
#define MIDDLE 2
//! intersect ray with AABB
#ifndef ELBEEM_PLUGIN
void ntlRay::intersectFrontAABB(ntlVec3Gfx mStart, ntlVec3Gfx mEnd, gfxReal &t, ntlVec3Gfx &retnormal,ntlVec3Gfx &retcoord) const
{
char inside = true; /* inside box? */
char hit = false; /* ray hits box? */
int whichPlane; /* intersection plane */
gfxReal candPlane[NUMDIM]; /* candidate plane */
gfxReal quadrant[NUMDIM]; /* quadrants */
gfxReal maxT[NUMDIM]; /* max intersection T for planes */
ntlVec3Gfx coord; /* intersection point */
ntlVec3Gfx dir = mDirection;
ntlVec3Gfx origin = mOrigin;
ntlVec3Gfx normal(0.0, 0.0, 0.0);
t = GFX_REAL_MAX;
/* check intersection planes for AABB */
for(int i=0;i<NUMDIM;i++) {
if(origin[i] < mStart[i]) {
quadrant[i] = LEFT;
candPlane [i] = mStart[i];
inside = false;
} else if(origin[i] > mEnd[i]) {
quadrant[i] = RIGHT;
candPlane[i] = mEnd[i];
inside = false;
} else {
quadrant[i] = MIDDLE;
}
}
/* inside AABB? */
if(!inside) {
/* get t distances to planes */
/* treat too small direction components as paralell */
for(int i=0;i<NUMDIM;i++) {
if((quadrant[i] != MIDDLE) && (fabs(dir[i]) > getVecEpsilon()) ) {
maxT[i] = (candPlane[i] - origin[i]) / dir[i];
} else {
maxT[i] = -1;
}
}
/* largest max t */
whichPlane = 0;
for(int i=1;i<NUMDIM;i++) {
if(maxT[whichPlane] < maxT[i]) whichPlane = i;
}
/* check final candidate */
hit = true;
if(maxT[whichPlane] >= 0.0) {
for(int i=0;i<NUMDIM;i++) {
if(whichPlane != i) {
coord[i] = origin[i] + maxT[whichPlane] * dir[i];
if( (coord[i] < mStart[i]-getVecEpsilon() ) ||
(coord[i] > mEnd[i] +getVecEpsilon() ) ) {
/* no hit... */
hit = false;
}
}
else {
coord[i] = candPlane[i];
}
}
/* AABB hit... */
if( hit ) {
t = maxT[whichPlane];
if(quadrant[whichPlane]==RIGHT) normal[whichPlane] = 1.0;
else normal[whichPlane] = -1.0;
}
}
} else {
/* inside AABB... */
t = 0.0;
coord = origin;
return;
}
if(t == GFX_REAL_MAX) t = -1.0;
retnormal = normal;
retcoord = coord;
}
//! intersect ray with AABB
void ntlRay::intersectBackAABB(ntlVec3Gfx mStart, ntlVec3Gfx mEnd, gfxReal &t, ntlVec3Gfx &retnormal,ntlVec3Gfx &retcoord) const
{
char hit = false; /* ray hits box? */
int whichPlane; /* intersection plane */
gfxReal candPlane[NUMDIM]; /* candidate plane */
gfxReal quadrant[NUMDIM]; /* quadrants */
gfxReal maxT[NUMDIM]; /* max intersection T for planes */
ntlVec3Gfx coord; /* intersection point */
ntlVec3Gfx dir = mDirection;
ntlVec3Gfx origin = mOrigin;
ntlVec3Gfx normal(0.0, 0.0, 0.0);
t = GFX_REAL_MAX;
for(int i=0;i<NUMDIM;i++) {
if(origin[i] < mStart[i]) {
quadrant[i] = LEFT;
candPlane [i] = mEnd[i];
} else if(origin[i] > mEnd[i]) {
quadrant[i] = RIGHT;
candPlane[i] = mStart[i];
} else {
if(dir[i] > 0) {
quadrant[i] = LEFT;
candPlane [i] = mEnd[i];
} else
if(dir[i] < 0) {
quadrant[i] = RIGHT;
candPlane[i] = mStart[i];
} else {
quadrant[i] = MIDDLE;
}
}
}
/* get t distances to planes */
/* treat too small direction components as paralell */
for(int i=0;i<NUMDIM;i++) {
if((quadrant[i] != MIDDLE) && (fabs(dir[i]) > getVecEpsilon()) ) {
maxT[i] = (candPlane[i] - origin[i]) / dir[i];
} else {
maxT[i] = GFX_REAL_MAX;
}
}
/* largest max t */
whichPlane = 0;
for(int i=1;i<NUMDIM;i++) {
if(maxT[whichPlane] > maxT[i]) whichPlane = i;
}
/* check final candidate */
hit = true;
if(maxT[whichPlane] != GFX_REAL_MAX) {
for(int i=0;i<NUMDIM;i++) {
if(whichPlane != i) {
coord[i] = origin[i] + maxT[whichPlane] * dir[i];
if( (coord[i] < mStart[i]-getVecEpsilon() ) ||
(coord[i] > mEnd[i] +getVecEpsilon() ) ) {
/* no hit... */
hit = false;
}
}
else {
coord[i] = candPlane[i];
}
}
/* AABB hit... */
if( hit ) {
t = maxT[whichPlane];
if(quadrant[whichPlane]==RIGHT) normal[whichPlane] = 1.0;
else normal[whichPlane] = -1.0;
}
}
if(t == GFX_REAL_MAX) t = -1.0;
retnormal = normal;
retcoord = coord;
}
#endif // ELBEEM_PLUGIN
//! intersect ray with AABB
void ntlRay::intersectCompleteAABB(ntlVec3Gfx mStart, ntlVec3Gfx mEnd, gfxReal &tmin, gfxReal &tmax) const
{
// char inside = true; /* inside box? */ /* UNUSED */
char hit = false; /* ray hits box? */
int whichPlane; /* intersection plane */
gfxReal candPlane[NUMDIM]; /* candidate plane */
gfxReal quadrant[NUMDIM]; /* quadrants */
gfxReal maxT[NUMDIM]; /* max intersection T for planes */
ntlVec3Gfx coord; /* intersection point */
ntlVec3Gfx dir = mDirection;
ntlVec3Gfx origin = mOrigin;
gfxReal t = GFX_REAL_MAX;
/* check intersection planes for AABB */
for(int i=0;i<NUMDIM;i++) {
if(origin[i] < mStart[i]) {
quadrant[i] = LEFT;
candPlane [i] = mStart[i];
// inside = false;
} else if(origin[i] > mEnd[i]) {
quadrant[i] = RIGHT;
candPlane[i] = mEnd[i];
// inside = false;
} else {
/* intersect with backside */
if(dir[i] > 0) {
quadrant[i] = LEFT;
candPlane [i] = mStart[i];
} else
if(dir[i] < 0) {
quadrant[i] = RIGHT;
candPlane[i] = mEnd[i];
} else {
quadrant[i] = MIDDLE;
}
}
}
/* get t distances to planes */
for(int i=0;i<NUMDIM;i++) {
if((quadrant[i] != MIDDLE) && (fabs(dir[i]) > getVecEpsilon()) ) {
maxT[i] = (candPlane[i] - origin[i]) / dir[i];
} else {
maxT[i] = GFX_REAL_MAX;
}
}
/* largest max t */
whichPlane = 0;
for(int i=1;i<NUMDIM;i++) {
if( ((maxT[whichPlane] < maxT[i])&&(maxT[i]!=GFX_REAL_MAX)) ||
(maxT[whichPlane]==GFX_REAL_MAX) )
whichPlane = i;
}
/* check final candidate */
hit = true;
if(maxT[whichPlane]<GFX_REAL_MAX) {
for(int i=0;i<NUMDIM;i++) {
if(whichPlane != i) {
coord[i] = origin[i] + maxT[whichPlane] * dir[i];
if( (coord[i] < mStart[i]-getVecEpsilon() ) ||
(coord[i] > mEnd[i] +getVecEpsilon() ) ) {
/* no hit... */
hit = false;
}
}
else { coord[i] = candPlane[i]; }
}
/* AABB hit... */
if( hit ) {
t = maxT[whichPlane];
}
}
tmin = t;
/* now the backside */
t = GFX_REAL_MAX;
for(int i=0;i<NUMDIM;i++) {
if(origin[i] < mStart[i]) {
quadrant[i] = LEFT;
candPlane [i] = mEnd[i];
} else if(origin[i] > mEnd[i]) {
quadrant[i] = RIGHT;
candPlane[i] = mStart[i];
} else {
if(dir[i] > 0) {
quadrant[i] = LEFT;
candPlane [i] = mEnd[i];
} else
if(dir[i] < 0) {
quadrant[i] = RIGHT;
candPlane[i] = mStart[i];
} else {
quadrant[i] = MIDDLE;
}
}
}
/* get t distances to planes */
for(int i=0;i<NUMDIM;i++) {
if((quadrant[i] != MIDDLE) && (fabs(dir[i]) > getVecEpsilon()) ) {
maxT[i] = (candPlane[i] - origin[i]) / dir[i];
} else {
maxT[i] = GFX_REAL_MAX;
}
}
/* smallest max t */
whichPlane = 0;
for(int i=1;i<NUMDIM;i++) {
if(maxT[whichPlane] > maxT[i]) whichPlane = i;
}
/* check final candidate */
hit = true;
if(maxT[whichPlane] != GFX_REAL_MAX) {
for(int i=0;i<NUMDIM;i++) {
if(whichPlane != i) {
coord[i] = origin[i] + maxT[whichPlane] * dir[i];
if( (coord[i] < mStart[i]-getVecEpsilon() ) ||
(coord[i] > mEnd[i] +getVecEpsilon() ) ) {
/* no hit... */
hit = false;
}
}
else {
coord[i] = candPlane[i];
}
}
/* AABB hit... */
if( hit ) {
t = maxT[whichPlane];
}
}
tmax = t;
}
/******************************************************************************
* Determine color of this ray by tracing through the scene
*****************************************************************************/
const ntlColor ntlRay::shade() //const
{
#ifndef ELBEEM_PLUGIN
ntlGeometryObject *closest = NULL;
gfxReal minT = GFX_REAL_MAX;
vector<ntlLightObject*> *lightlist = mpGlob->getLightList();
mpGlob->setCounterShades( mpGlob->getCounterShades()+1 );
bool intersectionInside = 0;
if(mpGlob->getDebugOut() > 5) errorOut(std::endl<<"New Ray: depth "<<mDepth<<", org "<<mOrigin<<", dir "<<mDirection );
/* check if this ray contributes enough */
if(mContribution <= RAY_MINCONTRIB) {
//return ntlColor(0.0);
}
/* find closes object that intersects */
ntlTriangle *tri = NULL;
ntlVec3Gfx normal;
mpGlob->getRenderScene()->intersectScene(*this, minT, normal, tri, 0);
if(minT>0) {
closest = mpGlob->getRenderScene()->getObject( tri->getObjectId() );
}
/* object hit... */
if (closest != NULL) {
ntlVec3Gfx triangleNormal = tri->getNormal();
if( equal(triangleNormal, ntlVec3Gfx(0.0)) ) errorOut("ntlRay warning: trinagle normal= 0 "); // DEBUG
/* intersection on inside faces? if yes invert normal afterwards */
gfxReal valDN; // = mDirection | normal;
valDN = dot(mDirection, triangleNormal);
if( valDN > 0.0) {
intersectionInside = 1;
normal = normal * -1.0;
triangleNormal = triangleNormal * -1.0;
}
/* ... -> do reflection */
ntlVec3Gfx intersectionPosition(mOrigin + (mDirection * (minT)) );
ntlMaterial *clossurf = closest->getMaterial();
/*if(mpGlob->getDebugOut() > 5) {
errorOut("Ray hit: at "<<intersectionPosition<<" n:"<<normal<<" dn:"<<valDN<<" ins:"<<intersectionInside<<" cl:"<<((unsigned int)closest) );
errorOut(" t1:"<<mpGlob->getRenderScene()->getVertex(tri->getPoints()[0])<<" t2:"<<mpGlob->getRenderScene()->getVertex(tri->getPoints()[1])<<" t3:"<<mpGlob->getScene()->getVertex(tri->getPoints()[2]) );
errorOut(" trin:"<<tri->getNormal() );
} // debug */
/* current transparence and reflectivity */
gfxReal currTrans = clossurf->getTransparence();
gfxReal currRefl = clossurf->getMirror();
/* correct intersectopm position */
intersectionPosition += ( triangleNormal*getVecEpsilon() );
/* reflection at normal */
ntlVec3Gfx reflectedDir = getNormalized( reflectVector(mDirection, normal) );
int badRefl = 0;
if(dot(reflectedDir, triangleNormal)<0.0 ) {
badRefl = 1;
if(mpGlob->getDebugOut() > 5) { errorOut("Ray Bad reflection...!"); }
}
/* refraction direction, depending on in/outside hit */
ntlVec3Gfx refractedDir;
int refRefl = 0;
/* refraction at normal is handled by inverting normal before */
gfxReal myRefIndex = 1.0;
if((currTrans>RAY_THRESHOLD)||(clossurf->getFresnel())) {
if(intersectionInside) {
myRefIndex = 1.0/clossurf->getRefracIndex();
} else {
myRefIndex = clossurf->getRefracIndex();
}
refractedDir = refractVector(mDirection, normal, myRefIndex , (gfxReal)(1.0) /* global ref index */, refRefl);
}
/* calculate fresnel? */
if(clossurf->getFresnel()) {
// for total reflection, just set trans to 0
if(refRefl) {
currRefl = 1.0; currTrans = 0.0;
} else {
// calculate fresnel coefficients
clossurf->calculateFresnel( mDirection, normal, myRefIndex, currRefl,currTrans );
}
}
ntlRay reflectedRay(intersectionPosition, reflectedDir, mDepth+1, mContribution*currRefl, mpGlob);
reflectedRay.setNormal( normal );
ntlColor currentColor(0.0);
ntlColor highlightColor(0.0);
/* first add reflected ambient color */
currentColor += (clossurf->getAmbientRefl() * mpGlob->getAmbientLight() );
/* calculate lighting, not on the insides of objects... */
if(!intersectionInside) {
for (vector<ntlLightObject*>::iterator iter = lightlist->begin();
iter != lightlist->end();
iter++) {
/* let light illuminate point */
currentColor += (*iter)->illuminatePoint( reflectedRay, closest, highlightColor );
} // for all lights
}
// recurse ?
if ((mDepth < mpGlob->getRayMaxDepth() )&&(currRefl>RAY_THRESHOLD)) {
if(badRefl) {
ntlVec3Gfx intersectionPosition2;
ntlGeometryObject *closest2 = NULL;
gfxReal minT2 = GFX_REAL_MAX;
ntlTriangle *tri2 = NULL;
ntlVec3Gfx normal2;
ntlVec3Gfx refractionPosition2(mOrigin + (mDirection * minT) );
refractionPosition2 -= (triangleNormal*getVecEpsilon() );
ntlRay reflectedRay2 = ntlRay(refractionPosition2, reflectedDir, mDepth+1, mContribution*currRefl, mpGlob);
mpGlob->getRenderScene()->intersectScene(reflectedRay2, minT2, normal2, tri2, 0);
if(minT2>0) {
closest2 = mpGlob->getRenderScene()->getObject( tri2->getObjectId() );
}
/* object hit... */
if (closest2 != NULL) {
ntlVec3Gfx triangleNormal2 = tri2->getNormal();
gfxReal valDN2;
valDN2 = dot(reflectedDir, triangleNormal2);
if( valDN2 > 0.0) {
triangleNormal2 = triangleNormal2 * -1.0;
intersectionPosition2 = ntlVec3Gfx(intersectionPosition + (reflectedDir * (minT2)) );
/* correct intersection position and create new reflected ray */
intersectionPosition2 += ( triangleNormal2*getVecEpsilon() );
reflectedRay = ntlRay(intersectionPosition2, reflectedDir, mDepth+1, mContribution*currRefl, mpGlob);
} else {
// ray seems to work, continue normally ?
}
}
}
// add mirror color multiplied by mirror factor of surface
if(mpGlob->getDebugOut() > 5) errorOut("Reflected ray from depth "<<mDepth<<", dir "<<reflectedDir );
ntlColor reflectedColor = reflectedRay.shade() * currRefl;
currentColor += reflectedColor;
}
/* Trace another ray on for transparent objects */
if(currTrans > RAY_THRESHOLD) {
/* position at the other side of the surface, along ray */
ntlVec3Gfx refraction_position(mOrigin + (mDirection * minT) );
refraction_position += (mDirection * getVecEpsilon());
refraction_position -= (triangleNormal*getVecEpsilon() );
ntlColor refracCol(0.0); /* refracted color */
/* trace refracted ray */
ntlRay transRay(refraction_position, refractedDir, mDepth+1, mContribution*currTrans, mpGlob);
transRay.setRefracted(1);
transRay.setNormal( normal );
if(mDepth < mpGlob->getRayMaxDepth() ) {
// full reflection should make sure refracindex&fresnel are on...
if((0)||(!refRefl)) {
if(mpGlob->getDebugOut() > 5) errorOut("Refracted ray from depth "<<mDepth<<", dir "<<refractedDir );
refracCol = transRay.shade();
} else {
//we shouldnt reach this!
if(mpGlob->getDebugOut() > 5) errorOut("Fully reflected ray from depth "<<mDepth<<", dir "<<reflectedDir );
refracCol = reflectedRay.shade();
}
}
//errMsg("REFMIR","t"<<currTrans<<" thres"<<RAY_THRESHOLD<<" mirr"<<currRefl<<" refRefl"<<refRefl<<" md"<<mDepth);
/* calculate color */
// use transadditive setting!?
/* additive transparency "light amplification" */
//? ntlColor add_col = currentColor + refracCol * currTrans;
/* mix additive and subtractive */
//? add_col += sub_col;
//? currentColor += (refracCol * currTrans);
/* subtractive transparency, more realistic */
ntlColor sub_col = (refracCol * currTrans) + ( currentColor * (1.0-currTrans) );
currentColor = sub_col;
}
/* add highlights (should not be affected by transparence as the diffuse reflections */
currentColor += highlightColor;
/* attentuate as a last step*/
/* check if we're on the inside or outside */
if(intersectionInside) {
gfxReal kr,kg,kb; /* attentuation */
/* calculate attentuation */
ntlColor attCol = clossurf->getTransAttCol();
kr = exp( attCol[0] * minT );
kg = exp( attCol[1] * minT );
kb = exp( attCol[2] * minT );
currentColor = currentColor * ntlColor(kr,kg,kb);
}
/* done... */
if(mpGlob->getDebugOut() > 5) { errorOut("Ray "<<mDepth<<" color "<<currentColor ); }
return ntlColor(currentColor);
}
#endif // ELBEEM_PLUGIN
/* no object hit -> ray goes to infinity */
return mpGlob->getBackgroundCol();
}
/******************************************************************************
******************************************************************************
******************************************************************************
* scene implementation
******************************************************************************
******************************************************************************
*****************************************************************************/
/******************************************************************************
* Constructor
*****************************************************************************/
ntlScene::ntlScene( ntlRenderGlobals *glob, bool del ) :
mpGlob( glob ), mSceneDel(del),
mpTree( NULL ),
mSceneBuilt( false ), mFirstInitDone( false )
{
}
/******************************************************************************
* Destructor
*****************************************************************************/
ntlScene::~ntlScene()
{
if(mpTree != NULL) delete mpTree;
// cleanup lists, only if this is the rendering cleanup scene
if(mSceneDel)
{
for (vector<ntlGeometryClass*>::iterator iter = mGeos.begin();
iter != mGeos.end(); iter++) {
//errMsg("ntlScene::~ntlScene","Deleting obj "<<(*iter)->getName() );
delete (*iter);
}
for (vector<ntlLightObject*>::iterator iter = mpGlob->getLightList()->begin();
iter != mpGlob->getLightList()->end(); iter++) {
delete (*iter);
}
for (vector<ntlMaterial*>::iterator iter = mpGlob->getMaterials()->begin();
iter != mpGlob->getMaterials()->end(); iter++) {
delete (*iter);
}
}
errMsg("ntlScene::~ntlScene","Deleted, ObjFree:"<<mSceneDel);
}
/******************************************************************************
* Build the scene arrays (obj, tris etc.)
*****************************************************************************/
void ntlScene::buildScene(double time,bool firstInit)
{
const bool buildInfo=true;
if(firstInit) {
mObjects.clear();
/* init geometry array, first all standard objects */
for (vector<ntlGeometryClass*>::iterator iter = mGeos.begin();
iter != mGeos.end(); iter++) {
bool geoinit = false;
int tid = (*iter)->getTypeId();
if(tid & GEOCLASSTID_OBJECT) {
ntlGeometryObject *geoobj = (ntlGeometryObject*)(*iter);
geoinit = true;
mObjects.push_back( geoobj );
if(buildInfo) debMsgStd("ntlScene::BuildScene",DM_MSG,"added GeoObj "<<geoobj->getName()<<" Id:"<<geoobj->getObjectId(), 5 );
}
//if(geoshad) {
if(tid & GEOCLASSTID_SHADER) {
ntlGeometryShader *geoshad = (ntlGeometryShader*)(*iter);
geoinit = true;
if(!mFirstInitDone) {
// only on first init
geoshad->initializeShader();
}
for (vector<ntlGeometryObject*>::iterator siter = geoshad->getObjectsBegin();
siter != geoshad->getObjectsEnd();
siter++) {
if(buildInfo) debMsgStd("ntlScene::BuildScene",DM_MSG,"added shader geometry "<<(*siter)->getName()<<" Id:"<<(*siter)->getObjectId(), 5 );
mObjects.push_back( (*siter) );
}
}
if(!geoinit) {
errFatal("ntlScene::BuildScene","Invalid geometry class!", SIMWORLD_INITERROR);
return;
}
}
}
// collect triangles
mTriangles.clear();
mVertices.clear();
mVertNormals.clear();
/* for test mode deactivate transparencies etc. */
if( mpGlob->getTestMode() ) {
debugOut("ntlScene::buildScene : Test Mode activated!", 2);
// assign random colors to dark materials
int matCounter = 0;
ntlColor stdCols[] = { ntlColor(0,0,1.0), ntlColor(0,1.0,0), ntlColor(1.0,0.7,0) , ntlColor(0.7,0,0.6) };
int stdColNum = 4;
for (vector<ntlMaterial*>::iterator iter = mpGlob->getMaterials()->begin();
iter != mpGlob->getMaterials()->end(); iter++) {
(*iter)->setTransparence(0.0);
(*iter)->setMirror(0.0);
(*iter)->setFresnel(false);
// too dark?
if( norm((*iter)->getDiffuseRefl()) <0.01) {
(*iter)->setDiffuseRefl( stdCols[matCounter] );
matCounter ++;
matCounter = matCounter%stdColNum;
}
}
// restrict output file size to 400
float downscale = 1.0;
if(mpGlob->getResX() > 400){ downscale = 400.0/(float)mpGlob->getResX(); }
if(mpGlob->getResY() > 400){
float downscale2 = 400.0/(float)mpGlob->getResY();
if(downscale2<downscale) downscale=downscale2;
}
mpGlob->setResX( (int)(mpGlob->getResX() * downscale) );
mpGlob->setResY( (int)(mpGlob->getResY() * downscale) );
}
/* collect triangles from objects */
int idCnt = 0; // give IDs to objects
bool debugTriCollect = false;
if(debugTriCollect) debMsgStd("ntlScene::buildScene",DM_MSG,"Start...",5);
for (vector<ntlGeometryObject*>::iterator iter = mObjects.begin();
iter != mObjects.end();
iter++) {
/* only add visible objects */
if(firstInit) {
if(debugTriCollect) debMsgStd("ntlScene::buildScene",DM_MSG,"Collect init of "<<(*iter)->getName()<<" idCnt:"<<idCnt, 4 );
(*iter)->initialize( mpGlob ); }
if(debugTriCollect) debMsgStd("ntlScene::buildScene",DM_MSG,"Collecting tris from "<<(*iter)->getName(), 4 );
int vstart = mVertNormals.size();
(*iter)->setObjectId(idCnt);
(*iter)->getTriangles(time, &mTriangles, &mVertices, &mVertNormals, idCnt);
(*iter)->applyTransformation(time, &mVertices, &mVertNormals, vstart, mVertices.size(), false );
if(debugTriCollect) debMsgStd("ntlScene::buildScene",DM_MSG,"Done with "<<(*iter)->getName()<<" totTris:"<<mTriangles.size()<<" totVerts:"<<mVertices.size()<<" totNorms:"<<mVertNormals.size(), 4 );
idCnt ++;
}
if(debugTriCollect) debMsgStd("ntlScene::buildScene",DM_MSG,"End",5);
/* calculate triangle normals, and initialize flags */
for (vector<ntlTriangle>::iterator iter = mTriangles.begin();
iter != mTriangles.end();
iter++) {
// calculate normal from triangle points
ntlVec3Gfx normal =
cross( (ntlVec3Gfx)( (mVertices[(*iter).getPoints()[2]] - mVertices[(*iter).getPoints()[0]]) *-1.0), // BLITZ minus sign right??
(ntlVec3Gfx)(mVertices[(*iter).getPoints()[1]] - mVertices[(*iter).getPoints()[0]]) );
normalize(normal);
(*iter).setNormal( normal );
}
// scene geometry built
mSceneBuilt = true;
// init shaders that require complete geometry
if(!mFirstInitDone) {
// only on first init
for (vector<ntlGeometryClass*>::iterator iter = mGeos.begin();
iter != mGeos.end(); iter++) {
if( (*iter)->getTypeId() & GEOCLASSTID_SHADER ) {
ntlGeometryShader *geoshad = (ntlGeometryShader*)(*iter);
if(geoshad->postGeoConstrInit( mpGlob )) {
errFatal("ntlScene::buildScene","Init failed for object '"<< (*iter)->getName() <<"' !", SIMWORLD_INITERROR );
return;
}
}
}
mFirstInitDone = true;
}
// check unused attributes (for classes and objects!)
for (vector<ntlGeometryObject*>::iterator iter = mObjects.begin(); iter != mObjects.end(); iter++) {
if((*iter)->getAttributeList()->checkUnusedParams()) {
(*iter)->getAttributeList()->print(); // DEBUG
errFatal("ntlScene::buildScene","Unused params for object '"<< (*iter)->getName() <<"' !", SIMWORLD_INITERROR );
return;
}
}
for (vector<ntlGeometryClass*>::iterator iter = mGeos.begin(); iter != mGeos.end(); iter++) {
if((*iter)->getAttributeList()->checkUnusedParams()) {
(*iter)->getAttributeList()->print(); // DEBUG
errFatal("ntlScene::buildScene","Unused params for object '"<< (*iter)->getName() <<"' !", SIMWORLD_INITERROR );
return;
}
}
}
/******************************************************************************
* Prepare the scene triangles and maps for raytracing
*****************************************************************************/
void ntlScene::prepareScene(double time)
{
/* init triangles... */
buildScene(time, false);
// what for currently not used ???
if(mpTree != NULL) delete mpTree;
mpTree = new ntlTree(
# if FSGR_STRICT_DEBUG!=1
mpGlob->getTreeMaxDepth(), mpGlob->getTreeMaxTriangles(),
# else
mpGlob->getTreeMaxDepth()/3*2, mpGlob->getTreeMaxTriangles()*2,
# endif
this, TRI_GEOMETRY );
//debMsgStd("ntlScene::prepareScene",DM_MSG,"Stats - tris:"<< (int)mTriangles.size()<<" verts:"<<mVertices.size()<<" vnorms:"<<mVertNormals.size(), 5 );
}
/******************************************************************************
* Do some memory cleaning, when frame is finished
*****************************************************************************/
void ntlScene::cleanupScene( void )
{
mTriangles.clear();
mVertices.clear();
mVertNormals.clear();
if(mpTree != NULL) delete mpTree;
mpTree = NULL;
}
/******************************************************************************
* Intersect a ray with the scene triangles
*****************************************************************************/
void ntlScene::intersectScene(const ntlRay &r, gfxReal &distance, ntlVec3Gfx &normal, ntlTriangle *&tri,int flags) const
{
distance = -1.0;
mpGlob->setCounterSceneInter( mpGlob->getCounterSceneInter()+1 );
mpTree->intersect(r, distance, normal, tri, flags, false);
}
| 31.014192 | 206 | 0.563554 | [
"geometry",
"render",
"object",
"vector"
] |
6181c20817d58c9deb0d0aa90b4dd1fe333073a5 | 10,667 | cpp | C++ | UITitlebarPlug/SearchView.cpp | lirui1111/startalk_pc | 7d625f812e784bca68b3d6f6ffe21d383b400491 | [
"MIT"
] | 1 | 2020-02-10T06:53:28.000Z | 2020-02-10T06:53:28.000Z | UITitlebarPlug/SearchView.cpp | lirui1111/startalk_pc | 7d625f812e784bca68b3d6f6ffe21d383b400491 | [
"MIT"
] | null | null | null | UITitlebarPlug/SearchView.cpp | lirui1111/startalk_pc | 7d625f812e784bca68b3d6f6ffe21d383b400491 | [
"MIT"
] | null | null | null | //
// Created by QITMAC000260 on 2019-07-08.
//
#include "SearchView.h"
#include "../Platform/Platform.h"
#include "../Platform/dbPlatform.h"
#include <QScrollBar>
#include <QMouseEvent>
using namespace QTalk::Search;
SearchView::SearchView(QWidget* parent)
: QListView(parent)
{
setObjectName("SearchView");
this->verticalScrollBar()->setVisible(false);
this->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
this->verticalScrollBar()->setSingleStep(10);
_srcModel = new QStandardItemModel(this);
this->setModel(_srcModel);
_pItemDelegate = new SearchItemDelegate(this);
this->setItemDelegate(_pItemDelegate);
this->setFrameShape(QFrame::NoFrame);
this->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
this->setEditTriggers(QAbstractItemView::NoEditTriggers);
connect(_pItemDelegate, &SearchItemDelegate::sgOpenNewSession,
this, &SearchView::onOpenNewSession, Qt::QueuedConnection);
connect(_pItemDelegate, &SearchItemDelegate::sgGetMore, this, &SearchView::sgGetMore);
connect(_pItemDelegate, &SearchItemDelegate::sgSwitchFun, this, &SearchView::sgSwitchFun);
connect(_pItemDelegate, &SearchItemDelegate::sgShowMessageRecordWnd, this, &SearchView::sgShowMessageRecordWnd);
connect(_pItemDelegate, &SearchItemDelegate::sgShowFileRecordWnd, this, &SearchView::sgShowFileRecordWnd);
}
SearchView::~SearchView() = default;
void SearchView::onOpenNewSession(int type, const QString& xmppid, const QString& name, const QString& icon)
{
StSessionInfo sessionInfo(type, xmppid, name);
sessionInfo.headPhoto = icon;
emit sgOpenNewSession(sessionInfo);
}
void SearchView::selectUp() {
auto curIndex = currentIndex();
if(curIndex.row() > 0)
setCurrentIndex(_srcModel->index(curIndex.row() - 1, 0));
}
void SearchView::selectDown()
{
auto curIndex = currentIndex();
if(curIndex.row() < _srcModel->rowCount() - 1)
setCurrentIndex(_srcModel->index(curIndex.row() + 1, 0));
}
void SearchView::selectItem() {
auto index = currentIndex();
SearchItemType itemType = (SearchItemType)index.data(EM_TYPE_TYPE).toInt();
switch (itemType)
{
case EM_ITEM_TYPE_ITEM:
{
//
int type = index.data(EM_ITEM_ROLE_ITEM_TYPE).toInt();
if(QTalk::Search::EM_ACTION_USER == type)
{
int chatType = QTalk::Enum::TwoPersonChat;
QString xmppId = index.data(EM_ITEM_ROLE_XMPPID).toString();
QString icon = index.data(EM_ITEM_ROLE_ICON).toString();
QString name = index.data(EM_ITEM_ROLE_NAME).toString();
onOpenNewSession(chatType, xmppId, name, icon);
}
else if(QTalk::Search::EM_ACTION_MUC == type ||
QTalk::Search::EM_ACTION_COMMON_MUC == type)
{
int chatType = QTalk::Enum::GroupChat;
QString xmppId = index.data(EM_ITEM_ROLE_XMPPID).toString();
QString icon = index.data(EM_ITEM_ROLE_ICON).toString();
QString name = index.data(EM_ITEM_ROLE_NAME).toString();
onOpenNewSession(chatType, xmppId, name, icon);
}
else
{
}
break;
}
case EM_ITEM_TYPE_SHOW_MORE:
{
int req = index.data(EM_TITLE_ROLE_REQ_TYPE).toInt();
emit sgGetMore(req);
break;
}
case EM_ITEM_TYPE_TITLE:
default:
break;
}
}
void SearchView::clear()
{
if(_srcModel)
_srcModel->clear();
}
void addUserItem(QStandardItemModel *model, const std::vector<StUserItem>& users)
{
for(const auto& it : users)
{
auto* pItem = new QStandardItem;
pItem->setData(EM_ITEM_TYPE_ITEM, EM_TYPE_TYPE);
pItem->setData(EM_ACTION_USER, EM_ITEM_ROLE_ITEM_TYPE);
pItem->setData(QTalk::GetHeadPathByUrl(it.icon).data(), EM_ITEM_ROLE_ICON);
pItem->setData(it.name.data(), EM_ITEM_ROLE_NAME);
pItem->setData(it.structure.data(), EM_ITEM_ROLE_SUB_MESSAGE);
pItem->setData(it.xmppId.data(), EM_ITEM_ROLE_XMPPID);
pItem->setData(it.tips.data(), Qt::ToolTipRole);
model->appendRow(pItem);
}
}
void addGroupItem(QStandardItemModel *model, const std::vector<StGroupItem>& groups)
{
for(const auto& it : groups)
{
auto* pItem = new QStandardItem;
pItem->setData(EM_ITEM_TYPE_ITEM, EM_TYPE_TYPE);
pItem->setData(it.type, EM_ITEM_ROLE_ITEM_TYPE);
pItem->setData(QTalk::GetHeadPathByUrl(it.icon).data(), EM_ITEM_ROLE_ICON);
pItem->setData(it.name.data(), EM_ITEM_ROLE_NAME);
if(!it._hits.empty())
{
QString subMessage = QObject::tr("包含: ");
for(const auto& hit : it._hits)
{
subMessage.append(QString("%1 ").arg(hit.data()));
}
pItem->setData(subMessage, EM_ITEM_ROLE_SUB_MESSAGE);
}
pItem->setData(it.xmppId.data(), EM_ITEM_ROLE_XMPPID);
pItem->setData(it.name.data(), Qt::ToolTipRole);
model->appendRow(pItem);
}
}
void addHistoryItem(QStandardItemModel *model, const std::vector<StHistory>& historys)
{
for(const auto& it : historys)
{
auto* pItem = new QStandardItem;
pItem->setData(EM_ITEM_TYPE_ITEM, EM_TYPE_TYPE);
pItem->setData(it.type, EM_ITEM_ROLE_ITEM_TYPE);
// todo 接口问题
// pItem->setData(it.name.data(), EM_ITEM_ROLE_NAME);
if(EM_ACTION_HS_SINGLE == it.type)
{
std::string selfXmppId = Platform::instance().getSelfXmppId();
std::string id = selfXmppId == it.from ? it.to : it.from;
pItem->setData(QTalk::getUserNameNoMask(id).data(), EM_ITEM_ROLE_NAME);
auto user_info = dbPlatForm::instance().getUserInfo(id);
if(user_info)
pItem->setData(QTalk::GetHeadPathByUrl(user_info->HeaderSrc).data(), EM_ITEM_ROLE_ICON);
}
else
{
pItem->setData(it.name.data(), EM_ITEM_ROLE_NAME);
pItem->setData(QTalk::GetHeadPathByUrl(it.icon).data(), EM_ITEM_ROLE_ICON);
}
pItem->setData(it.key.data(), EM_ITEM_ROLE_KEY);
pItem->setData(it.to.data(), EM_ITEM_ROLE_XMPPID);
if(it.count <= 1)
{
QString content = QFontMetricsF(pItem->font()).elidedText(it.body.data(), Qt::ElideRight, 230);
pItem->setData(it.body.data(), EM_ITEM_ROLE_SUB_MESSAGE);
}
else
{
QString content = QObject::tr("%1条与“%2”相关聊天记录").arg(it.count).arg(it.key.data());
pItem->setData(content, EM_ITEM_ROLE_SUB_MESSAGE);
}
model->appendRow(pItem);
}
}
void addHistoryFileItem(QStandardItemModel *model, const std::vector<StHistoryFile>& files)
{
for(const auto& it : files)
{
auto* pItem = new QStandardItem;
pItem->setData(it.key.data(), EM_ITEM_ROLE_KEY);
pItem->setData(EM_ITEM_TYPE_ITEM, EM_TYPE_TYPE);
pItem->setData(EM_ACTION_HS_FILE, EM_ITEM_ROLE_ITEM_TYPE);
pItem->setData(QTalk::GetHeadPathByUrl(it.icon).data(), EM_ITEM_ROLE_ICON);
pItem->setData(it.file_name.data(), EM_ITEM_ROLE_NAME);
QString content = QObject::tr("来自:%1").arg(it.source.data());
pItem->setData(content, EM_ITEM_ROLE_SUB_MESSAGE);
model->appendRow(pItem);
}
}
/**
*
* @param ret
*/
void SearchView::addSearchResult(const QTalk::Search::StSearchResult& ret, int reqType, bool isGetMore)
{
if(!isGetMore)
{
auto* titleItem = new QStandardItem;
titleItem->setData(EM_ITEM_TYPE_TITLE, EM_TYPE_TYPE);
titleItem->setData(ret.resultType, EM_TITLE_ROLE_TYPE);
titleItem->setData(ret.groupLabel.data(), EM_TITLE_ROLE_NAME);
titleItem->setData(ret.hasMore, EM_TITLE_ROLE_HAS_MORE);
titleItem->setData(reqType, EM_TITLE_ROLE_REQ_TYPE);
//
_srcModel->appendRow(titleItem);
if(_srcModel->rowCount() == 1)
setCurrentIndex(titleItem->index());
}
if(ret.resultType & EM_ACTION_USER)
{
addUserItem(_srcModel, ret._users);
}
else if((ret.resultType & EM_ACTION_MUC) ||
(ret.resultType & EM_ACTION_COMMON_MUC))
{
addGroupItem(_srcModel, ret._groups);
}
else if((ret.resultType & EM_ACTION_HS_SINGLE) ||
(ret.resultType & EM_ACTION_HS_MUC))
{
addHistoryItem(_srcModel, ret._history);
}
else if((ret.resultType & EM_ACTION_HS_FILE))
{
addHistoryFileItem(_srcModel, ret._files);
}
if(ret.hasMore && reqType != REQ_TYPE_ALL)
{
auto* moreItem = new QStandardItem;
moreItem->setData(EM_ITEM_TYPE_SHOW_MORE, EM_TYPE_TYPE);
moreItem->setData(reqType, EM_TITLE_ROLE_REQ_TYPE);
_srcModel->appendRow(moreItem);
}
}
//
void SearchView::addOpenWithIdItem(const QString& keyId) {
auto* titleItem = new QStandardItem;
titleItem->setData(EM_ITEM_TYPE_TITLE, EM_TYPE_TYPE);
// titleItem->setData(REQ_TYPE_ALL, EM_TITLEROLE_TYPE);
titleItem->setData(QString(tr("打开ID为[ %1 ]的会话")).arg(keyId), EM_TITLE_ROLE_NAME);
titleItem->setData(false, EM_TITLE_ROLE_HAS_MORE);
// titleItem->setData(REQ_TYPE_ALL, EM_TITLEROLE_REQ_TYPE);
//
_srcModel->appendRow(titleItem);
if(_srcModel->rowCount() == 1)
setCurrentIndex(titleItem->index());
//
QString id = keyId;
id = id.trimmed().toLower();
if(!id.contains("@"))
{
id += QString("@%1").arg(Platform::instance().getSelfDomain().data());
}
auto* pItem = new QStandardItem;
pItem->setData(EM_ITEM_TYPE_ITEM, EM_TYPE_TYPE);
pItem->setData(EM_ACTION_USER, EM_ITEM_ROLE_ITEM_TYPE);
pItem->setData("", EM_ITEM_ROLE_ICON);
pItem->setData(keyId, EM_ITEM_ROLE_NAME);
pItem->setData("/", EM_ITEM_ROLE_SUB_MESSAGE);
pItem->setData(id, EM_ITEM_ROLE_XMPPID);
pItem->setData(tr("打开离职员工或者跨域用户会话"), Qt::ToolTipRole);
_srcModel->appendRow(pItem);
}
/**
*
*/
void SearchView::removeMoreBar()
{
int row = _srcModel->rowCount();
while (row != 0)
{
QModelIndex index = _srcModel->index(--row, 0);
if(index.isValid())
{
int type = index.data(EM_TYPE_TYPE).toInt();
if(EM_ITEM_TYPE_SHOW_MORE == type)
{
_srcModel->removeRow(row);
break;
}
}
}
} | 34.299035 | 116 | 0.639168 | [
"vector",
"model"
] |
6181e1c32c3bae468245d6f8fe8134beb819f674 | 15,105 | cpp | C++ | src/L1/uva.cpp | Halolegend94/mgbench | cc43ebddac795c118d407bb7ed6a620e73753266 | [
"BSD-3-Clause"
] | null | null | null | src/L1/uva.cpp | Halolegend94/mgbench | cc43ebddac795c118d407bb7ed6a620e73753266 | [
"BSD-3-Clause"
] | null | null | null | src/L1/uva.cpp | Halolegend94/mgbench | cc43ebddac795c118d407bb7ed6a620e73753266 | [
"BSD-3-Clause"
] | null | null | null | #include "hip/hip_runtime.h"
// MGBench: Multi-GPU Computing Benchmark Suite
// Copyright (c) 2016, Tal Ben-Nun
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the names of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cstdio>
#include <cstdlib>
#include <chrono>
#include <map>
#include <random>
#include <gflags/gflags.h>
#include <hip/hip_runtime.h>
DEFINE_uint64(size, 100*1024*1024, "The amount of data to transfer");
DEFINE_uint64(type_size, sizeof(float), "The size of the data chunk to "
"transfer, e.g. 4 for a 4-byte float");
DEFINE_uint64(repetitions, 100, "Number of repetitions to average");
DEFINE_uint64(block_size, 32, "Copy kernel block size");
DEFINE_bool(fullduplex, false, "True for bi-directional copy");
DEFINE_bool(write, false, "Perform DMA write instead of read");
DEFINE_bool(random, false, "Use random access instead of coalesced");
DEFINE_int32(from, -1, "Only copy from a single GPU index/host (Host is "
"0, GPUs start from 1), or -1 for all");
DEFINE_int32(to, -1, "Only copy to a single GPU index/host (Host is "
"0, GPUs start from 1), or -1 for all");
static void HandleError(const char *file, int line, hipError_t err)
{
printf("ERROR in %s:%d: %s (%d)\n", file, line,
hipGetErrorString(err), err);
hipGetLastError();
}
// CUDA assertions
#define CUDA_CHECK(err) do { hipError_t errr = (err); if(errr != hipSuccess) { HandleError(__FILE__, __LINE__, errr); exit(1); } } while(0)
#define CUDA_CHECK_RET(err) do { hipError_t errr = (err); if(errr != hipSuccess) { HandleError(__FILE__, __LINE__, errr); return; } } while(0)
template<typename T>
__global__ void CopyKernel(T *dst_data, const T *src_data, int size)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= size)
return;
dst_data[idx] = src_data[idx];
}
template<typename T, bool WRITE>
__global__ void CopyKernelRandom(T *dst_data, const T *src_data, const int *indices, int size)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= size)
return;
if (WRITE)
dst_data[indices[idx]] = src_data[idx];
else
dst_data[idx] = src_data[indices[idx]];
}
inline void DispatchCopy(void *dst, const void *src, const size_t& sz, const size_t& type_size,
const dim3& grid, const dim3& block, hipStream_t stream)
{
switch (type_size)
{
case 1: // sizeof(char)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernel<char>), dim3(grid), dim3(block), 0, stream, (char *)dst, (const char *)src, sz);
return;
case 2: // sizeof(short)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernel<short>), dim3(grid), dim3(block), 0, stream, (short *)dst, (const short *)src, sz);
return;
default:
case 4: // sizeof(float)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernel<float>), dim3(grid), dim3(block), 0, stream, (float *)dst, (const float *)src, sz);
return;
case 8: // sizeof(double)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernel<double>), dim3(grid), dim3(block), 0, stream, (double *)dst, (const double *)src, sz);
return;
case 16: // sizeof(float4)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernel<float4>), dim3(grid), dim3(block), 0, stream, (float4 *)dst, (const float4 *)src, sz);
return;
}
}
template <bool WRITE>
inline void DispatchCopyRandom(void *dst, const void *src, const int *rnd,
const size_t& sz, const size_t& type_size,
const dim3& grid, const dim3& block, hipStream_t stream)
{
switch (type_size)
{
case 1: // sizeof(char)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernelRandom<char, WRITE>), dim3(grid), dim3(block), 0, stream, (char *)dst, (const char *)src, rnd, sz);
return;
case 2: // sizeof(short)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernelRandom<short, WRITE>), dim3(grid), dim3(block), 0, stream, (short *)dst, (const short *)src, rnd, sz);
return;
default:
case 4: // sizeof(float)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernelRandom<float, WRITE>), dim3(grid), dim3(block), 0, stream, (float *)dst, (const float *)src, rnd, sz);
return;
case 8: // sizeof(double)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernelRandom<double, WRITE>), dim3(grid), dim3(block), 0, stream, (double *)dst, (const double *)src, rnd, sz);
return;
case 16: // sizeof(float4)
hipLaunchKernelGGL(HIP_KERNEL_NAME(CopyKernelRandom<float4, WRITE>), dim3(grid), dim3(block), 0, stream, (float4 *)dst, (const float4 *)src, rnd, sz);
return;
}
}
void CopySegmentUVA(int a, int b)
{
void *deva_buff = nullptr, *devb_buff = nullptr;
void *deva_buff2 = nullptr, *devb_buff2 = nullptr;
int *devrnd_buff = nullptr;
hipStream_t a_stream, b_stream;
size_t sz = FLAGS_size / FLAGS_type_size, typesize = FLAGS_type_size;
// Allocate buffers
if (a > 0)
{
CUDA_CHECK_RET(hipSetDevice(a - 1));
CUDA_CHECK_RET(hipMalloc(&deva_buff, FLAGS_size));
CUDA_CHECK_RET(hipMalloc(&deva_buff2, FLAGS_size));
}
else
{
CUDA_CHECK_RET(hipHostMalloc(&deva_buff, FLAGS_size));
CUDA_CHECK_RET(hipHostMalloc(&deva_buff2, FLAGS_size));
}
CUDA_CHECK_RET(hipStreamCreateWithFlags(&a_stream, hipStreamNonBlocking));
if (b > 0)
{
CUDA_CHECK_RET(hipSetDevice(b - 1));
CUDA_CHECK_RET(hipMalloc(&devb_buff, FLAGS_size));
CUDA_CHECK_RET(hipMalloc(&devb_buff2, FLAGS_size));
}
else
{
CUDA_CHECK_RET(hipHostMalloc(&devb_buff, FLAGS_size));
CUDA_CHECK_RET(hipHostMalloc(&devb_buff2, FLAGS_size));
}
if (FLAGS_random)
{
// Create and allocate random index buffer
std::vector<int> host_rnd (sz);
// Randomize
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(0, sz - 1);
for (size_t i = 0; i < sz; ++i)
host_rnd[i] = dist(gen);
// Device->Device / Host->Device
if (b > 0)
{
CUDA_CHECK_RET(hipSetDevice(b - 1));
}
else if (a > 0) // Device->Host
{
CUDA_CHECK_RET(hipSetDevice(a - 1));
}
CUDA_CHECK_RET(hipMalloc(&devrnd_buff, sz * sizeof(int)));
CUDA_CHECK_RET(hipMemcpy(devrnd_buff, host_rnd.data(),
sz * sizeof(int), hipMemcpyHostToDevice));
}
CUDA_CHECK_RET(hipStreamCreateWithFlags(&b_stream, hipStreamNonBlocking));
// Synchronize devices before copying
if (a > 0)
{
CUDA_CHECK_RET(hipSetDevice(a - 1));
CUDA_CHECK_RET(hipDeviceSynchronize());
}
if (b > 0)
{
CUDA_CHECK_RET(hipSetDevice(b - 1));
CUDA_CHECK_RET(hipDeviceSynchronize());
}
dim3 block_dim (FLAGS_block_size),
grid_dim((sz + FLAGS_block_size - 1) / FLAGS_block_size);
// If using UVA to write, simply swap the buffers
if (FLAGS_write)
{
std::swap(deva_buff, devb_buff);
std::swap(deva_buff2, devb_buff2);
}
// Copy or Exchange using UVA
auto t1 = std::chrono::high_resolution_clock::now();
for(uint64_t i = 0; i < FLAGS_repetitions; ++i)
{
if (b > 0)
CUDA_CHECK_RET(hipSetDevice(b - 1));
else
CUDA_CHECK_RET(hipSetDevice(a - 1));
if (FLAGS_random)
{
if (FLAGS_write)
DispatchCopyRandom<true>(devb_buff, deva_buff, devrnd_buff,
sz, typesize, grid_dim, block_dim,
b_stream);
else
DispatchCopyRandom<false>(devb_buff, deva_buff, devrnd_buff,
sz, typesize, grid_dim, block_dim,
b_stream);
}
else
{
DispatchCopy(devb_buff, deva_buff, sz, typesize,
grid_dim, block_dim, b_stream);
}
if (FLAGS_fullduplex)
{
if (a > 0)
CUDA_CHECK_RET(hipSetDevice(a - 1));
DispatchCopy(deva_buff2, devb_buff2, sz, typesize,
grid_dim, block_dim, a_stream);
}
}
if (a > 0)
{
CUDA_CHECK_RET(hipSetDevice(a - 1));
CUDA_CHECK_RET(hipDeviceSynchronize());
}
if (b > 0)
{
CUDA_CHECK_RET(hipSetDevice(b - 1));
CUDA_CHECK_RET(hipDeviceSynchronize());
}
auto t2 = std::chrono::high_resolution_clock::now();
double mstime = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count() / 1000.0 / FLAGS_repetitions;
// MiB/s = [bytes / (1024^2)] / [ms / 1000]
double MBps = (FLAGS_size / 1024.0 / 1024.0) / (mstime / 1000.0);
printf("%.2lf MB/s (%lf ms)\n", MBps, mstime);
// Swap buffers back, if necessary
if (FLAGS_write)
{
std::swap(deva_buff, devb_buff);
std::swap(deva_buff2, devb_buff2);
}
// Free buffers
if (a > 0)
{
CUDA_CHECK_RET(hipSetDevice(a - 1));
CUDA_CHECK_RET(hipFree(deva_buff));
CUDA_CHECK_RET(hipFree(deva_buff2));
}
else
{
CUDA_CHECK_RET(hipHostFree(deva_buff));
CUDA_CHECK_RET(hipHostFree(deva_buff2));
}
CUDA_CHECK_RET(hipStreamDestroy(a_stream));
if (b > 0)
{
CUDA_CHECK_RET(hipSetDevice(b - 1));
CUDA_CHECK_RET(hipFree(devb_buff));
CUDA_CHECK_RET(hipFree(devb_buff2));
}
else
{
CUDA_CHECK_RET(hipHostFree(devb_buff));
CUDA_CHECK_RET(hipHostFree(devb_buff2));
}
// Free randomized buffer, if exists
if (FLAGS_random)
{
if (b > 0)
{
CUDA_CHECK_RET(hipSetDevice(b - 1));
}
else if (a > 0)
{
CUDA_CHECK_RET(hipSetDevice(a - 1));
}
CUDA_CHECK_RET(hipFree(devrnd_buff));
}
CUDA_CHECK_RET(hipStreamDestroy(b_stream));
}
int main(int argc, char **argv)
{
gflags::ParseCommandLineFlags(&argc, &argv, true);
printf("Inter-GPU DMA %s exchange test\n",
(FLAGS_fullduplex ? "bi-directional" : "uni-directional"));
int ndevs = 0;
CUDA_CHECK(hipGetDeviceCount(&ndevs));
if (FLAGS_from >= (ndevs + 1))
{
printf("Invalid --from flag. Only %d GPUs are available.\n", ndevs);
return 1;
}
if (FLAGS_to >= (ndevs + 1))
{
printf("Invalid --to flag. Only %d GPUs are available.\n", ndevs);
return 2;
}
if (FLAGS_random && FLAGS_fullduplex)
{
printf("Cannot enable both --random and --fullduplex flags\n");
return 3;
}
printf("Enabling peer-to-peer access\n");
int tmp = 0;
// Enable peer-to-peer access
std::map<std::pair<int, int>, bool> canAccessPeer;
for(int i = 0; i < ndevs; ++i)
{
CUDA_CHECK(hipSetDevice(i));
for(int j = 0; j < ndevs; ++j)
if (i != j)
{
hipDeviceEnablePeerAccess(j, 0);
hipDeviceCanAccessPeer(&tmp, i, j);
canAccessPeer[std::make_pair(i, j)] = (tmp ? true : false);
}
}
printf("GPUs: %d (+ host)\n", ndevs);
printf("Data size: %.2f MB\n", (FLAGS_size / 1024.0f / 1024.0f));
printf("Data type size: %d bytes\n", (int)FLAGS_type_size);
printf("Block size: %d\n", (int)FLAGS_block_size);
printf("Access type: %s\n", (FLAGS_random ? "Randomized" : "Coalesced"));
printf("Repetitions: %d\n", (int)FLAGS_repetitions);
printf("\n");
for(int i = 0; i < ndevs + 1; ++i)
{
// Skip source GPUs
if(FLAGS_from >= 0 && i != FLAGS_from)
continue;
int start = FLAGS_fullduplex ? i : 0;
for(int j = start; j < ndevs + 1; ++j)
{
// Skip self-copies
if(i == j)
continue;
// Skip target GPUs
if(FLAGS_to >= 0 && j != FLAGS_to)
continue;
// Skip cases where host is the target
if (j == 0)
continue;
if (FLAGS_fullduplex && i == 0)
continue;
if (FLAGS_fullduplex)
{
printf("Exchanging between GPU %d and GPU %d: ", i - 1, j - 1);
}
else
{
if (!FLAGS_write)
{
if (i == 0)
printf("Copying from host to GPU %d: ", j - 1);
else
printf("Copying from GPU %d to GPU %d: ", i - 1, j - 1);
}
else
{
if (i == 0)
printf("Copying from GPU %d to host: ", j - 1);
else
printf("Copying from GPU %d to GPU %d: ", j - 1, i - 1);
}
}
// Make sure that DMA access is possible
if (i > 0 && j > 0)
{
if (!canAccessPeer[std::make_pair(i - 1, j - 1)] ||
(FLAGS_fullduplex && !canAccessPeer[std::make_pair(j - 1, i - 1)]))
{
printf("No DMA\n");
continue;
}
}
CopySegmentUVA(i, j);
}
}
return 0;
}
| 33.197802 | 160 | 0.577623 | [
"vector"
] |
618791173807291b39f1d4cdfa224cc4601b791d | 11,113 | cpp | C++ | examples/data_distribution/histogram/histogram_14.cpp | gitplcc/matplotplusplus | c088749434154c230ee7547c6871d65e58876dc6 | [
"MIT"
] | 2,709 | 2020-08-29T01:25:40.000Z | 2022-03-31T18:35:25.000Z | examples/data_distribution/histogram/histogram_14.cpp | p-ranav/matplotplusplus | b45015e2be88e3340b400f82637b603d733d45ce | [
"MIT"
] | 124 | 2020-08-29T04:48:17.000Z | 2022-03-25T15:45:59.000Z | examples/data_distribution/histogram/histogram_14.cpp | p-ranav/matplotplusplus | b45015e2be88e3340b400f82637b603d733d45ce | [
"MIT"
] | 203 | 2020-08-29T04:16:22.000Z | 2022-03-30T02:08:36.000Z | #include <iostream>
#include <matplot/matplot.h>
#include <random>
constexpr size_t DEFAULT_BOOTSTRAP_REPLICATES = 1000000;
std::vector<double>
bootstrap(std::function<double()> statistic,
size_t replicates = DEFAULT_BOOTSTRAP_REPLICATES) {
std::vector<double> data(replicates);
std::generate(data.begin(), data.end(), statistic);
return data;
}
std::vector<double>
bootstrap(std::function<double(std::vector<double>)> statistic,
std::function<double()> data_source, size_t sample_size,
size_t replicates = DEFAULT_BOOTSTRAP_REPLICATES) {
std::vector<double> data(replicates);
return bootstrap(
[&]() {
std::vector<double> data(sample_size);
std::generate(data.begin(), data.end(), data_source);
return statistic(data);
},
replicates);
}
template <typename NUMBER> double mean(const std::vector<NUMBER> &v) {
double sum = 0.0;
for (const auto &item : v) {
sum += static_cast<double>(item);
}
return sum / static_cast<double>(v.size());
}
int main() {
// Example bootstraping from many distributions.
// Distributions:
// https://blog.cloudera.com/blog/2015/12/common-probability-distributions-the-data-scientists-crib-sheet/
using namespace matplot;
auto f = figure(true);
f->width(f->width() * 3);
f->height(f->height() * 2);
f->x_position(10);
f->y_position(10);
enum histogram::normalization norm = histogram::normalization::probability;
enum histogram::binning_algorithm alg =
histogram::binning_algorithm::automatic;
const size_t n_bins = 200;
const float hist_alpha = 0.7f;
std::default_random_engine r;
std::mt19937 generator(r());
std::cout << "Averages - Normal" << std::endl;
subplot(2, 3, 0);
title("Average - Normal / Gaussian - mean(x)= {∑ x_i}/{n} - x_i = N(0,1)");
xlim({-4, 4});
legend();
std::normal_distribution<double> d(0, 1);
std::function<double()> normal_data_source = [&]() { return d(generator); };
hist(bootstrap(mean<double>, normal_data_source, 1), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("1 sample");
f->draw();
hold(on);
hist(bootstrap(mean<double>, normal_data_source, 2), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("2 samples");
f->draw();
hist(bootstrap(mean<double>, normal_data_source, 5), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("5 samples");
f->draw();
hist(bootstrap(mean<double>, normal_data_source, 10), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("10 samples");
f->draw();
hist(bootstrap(mean<double>, normal_data_source, 30), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("30 samples");
f->draw();
xlabel("Value");
ylabel("Frequency");
std::cout << "Averages - Uniform" << std::endl;
subplot(2, 3, 1);
title("Average - Uniform - mean(x)= {∑ x_i}/{n} - x_i = U(-1;+1)");
xlim({-1, 1});
legend();
std::uniform_real_distribution<double> u(-1.0, 1.0);
std::function<double()> uniform_data_source = [&]() {
return u(generator);
};
hist(bootstrap(mean<double>, uniform_data_source, 1), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("1 sample");
f->draw();
hold(on);
hist(bootstrap(mean<double>, uniform_data_source, 2), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("2 samples");
f->draw();
hist(bootstrap(mean<double>, uniform_data_source, 5), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("5 samples");
f->draw();
hist(bootstrap(mean<double>, uniform_data_source, 10), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("10 samples");
f->draw();
hist(bootstrap(mean<double>, uniform_data_source, 30), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("30 samples");
f->draw();
xlabel("Value");
ylabel("Frequency");
std::cout << "Sum of squares - Chi-squared distribution" << std::endl;
subplot(2, 3, 2);
title("Sum of Squares - Chi-Squared - ∑ (x_i - mean(x))^2");
xlim({0, 5});
legend();
double m = 0;
auto chi2_data_source = [&]() {
return pow(normal_data_source() - m, 2.0);
};
hist(bootstrap(mean<double>, chi2_data_source, 1), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("1 sample");
f->draw();
hold(on);
hist(bootstrap(mean<double>, chi2_data_source, 2), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("2 samples");
f->draw();
hist(bootstrap(mean<double>, chi2_data_source, 5), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("5 samples");
f->draw();
hist(bootstrap(mean<double>, chi2_data_source, 10), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("10 samples");
f->draw();
hist(bootstrap(mean<double>, chi2_data_source, 30), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("30 samples");
f->draw();
// xlim({0,50});
xlabel("Value");
ylabel("Frequency");
std::cout << "Square root of sum of squares (Chi distribution)"
<< std::endl;
subplot(2, 3, 3);
title("Square Root of Sum of Squares - Chi - √{∑ (x_i - mean(x))^2}");
xlim({0, 4});
legend();
auto chi_data_source = [&]() { return sqrt(chi2_data_source()); };
hist(bootstrap(mean<double>, chi_data_source, 1), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("1 sample");
f->draw();
hold(on);
hist(bootstrap(mean<double>, chi_data_source, 2), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("2 samples");
f->draw();
hist(bootstrap(mean<double>, chi_data_source, 5), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("5 samples");
f->draw();
hist(bootstrap(mean<double>, chi_data_source, 10), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("10 samples");
f->draw();
hist(bootstrap(mean<double>, chi_data_source, 30), n_bins)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("30 samples");
f->draw();
xlabel("Value");
ylabel("Frequency");
std::cout << "Ratio of scaled sums of squares / variance (F distribution)"
<< std::endl;
subplot(2, 3, 4);
title("Variance ratio - F - σ_1 / σ_2");
legend();
m = 0.0;
auto ratio_ss = [&]() { return chi2_data_source() / chi2_data_source(); };
xlim({0, 5});
std::vector<double> edges = linspace(0, 10, n_bins);
hist(bootstrap(mean<double>, ratio_ss, 1), edges)
->bin_limits_min(0)
.bin_limits_max(5)
.normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("1 sample");
f->draw();
hold(on);
hist(bootstrap(mean<double>, ratio_ss, 2), edges)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("2 samples");
f->draw();
hist(bootstrap(mean<double>, ratio_ss, 5), edges)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("5 samples");
f->draw();
hist(bootstrap(mean<double>, ratio_ss, 10), edges)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("10 samples");
f->draw();
hist(bootstrap(mean<double>, ratio_ss, 30), edges)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("30 samples");
f->draw();
xlabel("Value");
ylabel("Frequency");
std::cout << "Averages - Bernoulli" << std::endl;
subplot(2, 3, 5);
title("Average - Bernoulli - mean(x)= {∑ x_i}/{n} - x_i = B(1/6)");
xlim({0, 1});
legend();
std::bernoulli_distribution b(1. / 6.);
std::function<double()> bernoulli_data_source = [&]() {
return static_cast<double>(b(generator));
};
hist(bootstrap(mean<double>, bernoulli_data_source, 1), 4)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("1 sample");
f->draw();
hold(on);
hist(bootstrap(mean<double>, bernoulli_data_source, 5), 6)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("5 samples");
f->draw();
hist(bootstrap(mean<double>, bernoulli_data_source, 30), 10)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("30 samples");
f->draw();
hist(bootstrap(mean<double>, bernoulli_data_source, 300, 100000), 50)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("300 samples");
f->draw();
hist(bootstrap(mean<double>, bernoulli_data_source, 3000, 10000), 50)
->normalization(norm)
.algorithm(alg)
.edge_alpha(1.0)
.face_alpha(hist_alpha)
.display_name("3000 samples");
f->draw();
xlabel("Value");
ylabel("Frequency");
// save("distributions.png");
// save("distributions.pdf");
// save("distributions.eps");
// save("distributions.gif");
// save("distributions.jpg");
show();
return 0;
} | 31.571023 | 110 | 0.5876 | [
"vector"
] |
6189aeef24803949245d54ed5c59957aeda6b33a | 15,733 | cpp | C++ | server/physics.cpp | Silvman/arkanoid_mult | 8764b483e5833a2dbef823d1fb06e4ee7ad7431a | [
"MIT"
] | 1 | 2021-09-04T19:22:20.000Z | 2021-09-04T19:22:20.000Z | server/physics.cpp | Silvman/arkanoid_mult | 8764b483e5833a2dbef823d1fb06e4ee7ad7431a | [
"MIT"
] | null | null | null | server/physics.cpp | Silvman/arkanoid_mult | 8764b483e5833a2dbef823d1fb06e4ee7ad7431a | [
"MIT"
] | 1 | 2019-02-09T12:10:29.000Z | 2019-02-09T12:10:29.000Z | //
// Created by silvman on 09.05.17.
//
#include "headers/physics.hpp"
// const b2Vec2 ball_default_speed(0.0f, -9.0f);
const b2Vec2 player_default_speed(20.0f, 0.0f);
// blocksKickListener
void physics_scene::blocksKickListener::EndContact(b2Contact* contact) {
physic_body* bodyUserData_A = reinterpret_cast<physic_body *>(contact->GetFixtureA()->GetBody()->GetUserData());
physic_body* bodyUserData_B = reinterpret_cast<physic_body *>(contact->GetFixtureB()->GetBody()->GetUserData());
if ( bodyUserData_A->getId() == block_id ) {
reinterpret_cast<physic_block *>(bodyUserData_A)->setKicked();
}
if ( bodyUserData_B->getId() == block_id ) {
reinterpret_cast<physic_block *>(bodyUserData_B)->setKicked();
}
if ( bodyUserData_A->getId() == player_bottom_id ) {
reinterpret_cast<physic_player *>(bodyUserData_A)->setKicked();
reinterpret_cast<physic_ball *>(bodyUserData_B)->setOwner(player_bottom_id);
return;
}
if ( bodyUserData_A->getId() == player_top_id ) {
reinterpret_cast<physic_player *>(bodyUserData_A)->setKicked();
reinterpret_cast<physic_ball *>(bodyUserData_B)->setOwner(player_top_id);
return;
}
if ( bodyUserData_B->getId() == player_bottom_id ) {
reinterpret_cast<physic_player *>(bodyUserData_B)->setKicked();
reinterpret_cast<physic_ball *>(bodyUserData_A)->setOwner(player_bottom_id);
return;
}
if ( bodyUserData_B->getId() == player_top_id ) {
reinterpret_cast<physic_player *>(bodyUserData_B)->setKicked();
reinterpret_cast<physic_ball *>(bodyUserData_A)->setOwner(player_top_id);
return;
}
}
// physic_body
physics_scene::physic_body::physic_body(b2World& world, object_type id)
: world(world), id(id) { }
physics_scene::physic_body::~physic_body() {}
object_type physics_scene::physic_body::getId() const {
return id;
}
// physic_ball
physics_scene::physic_ball::physic_ball(b2World& world, const float play_pos_x, const float play_pos_y)
: physic_body(world, ball_id)
{
// последний параметр определяет где находится шарик - у верхнего (true) или у нижнего (false) игрока
ball = createBall(play_pos_x, play_pos_y, false);
}
physics_scene::physic_ball::~physic_ball() { world.DestroyBody(ball); }
b2Body* physics_scene::physic_ball::createBall(const float play_pos_x, const float play_pos_y, const bool is_top) {
b2Body* new_ball;
b2BodyDef ball_def;
ball_def.type = b2_dynamicBody;
if(is_top) {
owner = player_top_id;
ball_def.position.Set(play_pos_x, play_pos_y + 5 / PTM); // тут еще остается ptm TODO
} else {
owner = player_bottom_id;
ball_def.position.Set(play_pos_x, play_pos_y - 15 / PTM); // тут еще остается ptm
}
new_ball = world.CreateBody(&ball_def);
b2CircleShape ball_shape;
ball_shape.m_radius = 10/PTM;
b2FixtureDef ball_fixture_def;
ball_fixture_def.shape = &ball_shape;
ball_fixture_def.density = 10.1f;
ball_fixture_def.restitution = 1.01f;
ball_fixture_def.friction = 0.0f;
// из-за особенностей хранения userData
new_ball->CreateFixture(&ball_fixture_def);
new_ball->SetUserData(this);
new_ball->SetBullet(true);
return new_ball;
};
void physics_scene::physic_ball::restart(const b2Vec2& player_position, const bool is_top) {
world.DestroyBody(ball);
is_launched = false;
ball = createBall(player_position.x, player_position.y, is_top);
}
void physics_scene::physic_ball::lauch(const num_action push, const players pl) {
is_launched = true;
if (pl == bottom) {
switch (push) {
case push_vertical: {
ball->SetLinearVelocity(b2Vec2(0.0f, -9.0f));
break;
}
case push_left: {
ball->SetLinearVelocity(b2Vec2(-4.0f, -8.0f));
break;
}
case push_right: {
ball->SetLinearVelocity(b2Vec2(4.0f, -8.0f));
break;
}
case push_righter: {
ball->SetLinearVelocity(b2Vec2(5.0f, -5.0f));
break;
}
case push_lefter: {
ball->SetLinearVelocity(b2Vec2(-5.0f, -5.0f));
break;
}
default: {
break;
}
}
}
if (pl == top) {
switch (push) {
case push_vertical: {
ball->SetLinearVelocity(b2Vec2(0.0f, 9.0f));
break;
}
case push_left: {
ball->SetLinearVelocity(b2Vec2(-4.0f, 8.0f));
break;
}
case push_right: {
ball->SetLinearVelocity(b2Vec2(4.0f, 8.0f));
break;
}
case push_righter: {
ball->SetLinearVelocity(b2Vec2(5.0f, 5.0f));
break;
}
case push_lefter: {
ball->SetLinearVelocity(b2Vec2(-5.0f, 5.0f));
break;
}
default: {
break;
}
}
}
}
void physics_scene::physic_ball::move_with_player(const b2Vec2& speed, const num_move dest) {
switch (dest) {
case move_right: {
ball->SetLinearVelocity(speed);
break;
}
case move_left: {
ball->SetLinearVelocity(-speed);
break;
}
// дописал default, ибо не по православному без него
case stay:
default: {
ball->SetLinearVelocity(b2Vec2(0,0));
break;
}
}
}
void physics_scene::physic_ball::setOwner(object_type type) {
owner = type;
}
object_type physics_scene::physic_ball::getOwner() const {
return owner;
}
const b2Vec2& physics_scene::physic_ball::giveCoords() const {
return ball->GetPosition();
}
const b2Vec2 physics_scene::physic_ball::giveSpeed() const {
return ball->GetLinearVelocity();
}
bool physics_scene::physic_ball::isLaunched() const {
return is_launched;
}
// physic_player
physics_scene::physic_player::physic_player(b2World& world, const float start_x, const float start_y, const object_type id)
: physic_body(world, id), player_speed(player_default_speed)
{
b2BodyDef player_def;
player_def.type = b2_kinematicBody;
player_def.position.Set((start_x - 10) / PTM, (start_y - 10) / PTM);
player = world.CreateBody(&player_def);
b2PolygonShape player_shape;
player_shape.SetAsBox(50.0f/PTM, 5.0f/PTM);
b2FixtureDef player_fixture_def;
player_fixture_def.shape = &player_shape;
player_fixture_def.density = 10.1f;
player_fixture_def.restitution = 1;
player_fixture_def.friction = 0.0f;
player->CreateFixture(&player_fixture_def);
player->SetUserData(this);
}
physics_scene::physic_player::~physic_player() { world.DestroyBody(player); }
void physics_scene::physic_player::stop() {
player->SetLinearVelocity(b2Vec2(0,0));
}
void physics_scene::physic_player::move(const num_move dest) {
float x_player = player->GetPosition().x;
switch (dest) {
case move_right: {
player->SetLinearVelocity(player_speed);
if(x_player > (gc_window_size_x - 80) / PTM) {
stop();
}
break;
}
case move_left: {
player->SetLinearVelocity(-player_speed);
if(x_player < 70 / PTM) {
stop();
}
break;
}
default:
case stay: {
stop();
break;
}
}
}
bool physics_scene::physic_player::checkKicked() {
if(isKicked) {
isKicked = false;
return true;
}
return false;
}
const b2Vec2 physics_scene::physic_player::getSpeed() const {
return player->GetLinearVelocity();
}
void physics_scene::physic_player::setKicked() {
isKicked = true;
}
const b2Vec2& physics_scene::physic_player::giveCoords() const {
return player->GetPosition();
}
// physic_border
physics_scene::physic_border::physic_border(b2World& world, const float pos_x, const float pos_y, const float size_x, const float size_y)
: physic_body(world, border_id)
{
b2BodyDef border_def;
b2PolygonShape border_shape;
border_def.position.Set((pos_x - 10)/PTM, (pos_y - 10)/PTM);
border_shape.SetAsBox(size_x/PTM, size_y/PTM);
border = world.CreateBody(&border_def);
border->CreateFixture(&border_shape, 0.0f);
border->SetUserData(this);
}
physics_scene::physic_border::~physic_border() { world.DestroyBody(border); }
// physic_block
physics_scene::physic_block::physic_block(
b2World& world,
const float pos_x, const float pos_y,
const float size_x, const float size_y,
const float angle, const int number
) : physic_body(world, block_id), is_kicked(false), number(number)
{
b2BodyDef block_def;
b2PolygonShape block_shape;
block_def.position.Set((pos_x)/PTM, (pos_y)/PTM);
block_def.angle = angle / DEG;
block_shape.SetAsBox(size_x / 2 / PTM, size_y / 2 / PTM);
block = world.CreateBody(&block_def);
block->CreateFixture(&block_shape, 0.0f);
block->SetUserData(this);
}
physics_scene::physic_block::~physic_block() { world.DestroyBody(block); }
int physics_scene::physic_block::try_kick() {
if(is_kicked) {
block->SetActive(0);
is_kicked = false;
return number;
}
return -1;
}
void physics_scene::physic_block::setKicked() {
is_kicked = true;
}
// physics_scene
physics_scene::physics_scene(const float window_size_x, const float window_size_y)
: world(b2Vec2(0.0f, 0.0f)),
ball(world, (window_size_x/ 2), (window_size_y - 35)),
player_bottom(world, (window_size_x / 2), (window_size_y - 35), player_bottom_id),
player_top(world, (window_size_x / 2), 35, player_top_id),
right_border(world, (window_size_x - 10), (window_size_y / 2), 10.0f, window_size_y / 2),
left_border(world, 0.0f, (window_size_y / 2), 10.0f, window_size_y / 2),
broken_block(-1),
sound_player(false),
who_broke_the_block(undef)
{
world.SetContactListener(&listener);
// нужно для правильного индексирования блоков, считает число ячеек с нулём
int passaway = 0;
for(int i = 0; i < map_rows; i++) {
for(int j = 0; j < map_cols; j++){
if (map_blocks[i][j]) {
blocks.push_back(
new physic_block(
world,
map_start_x + j * map_width + j * map_space,
map_start_y + i * map_height + i * map_space,
map_width,
map_height,
0.0f,
(i * map_cols) + j - passaway
)
);
} else {
passaway++;
}
}
}
}
physics_scene::~physics_scene() {
for(auto it = blocks.begin(); it != blocks.end(); it++) {
delete(*it);
}
}
void physics_scene::analyseKeys(physic_player& player, const players who_leads_the_ball, const num_move move, const num_action action) {
switch (move) {
case move_left:
case move_right: {
player.move(move);
break;
}
default:
case stay: {
player.stop();
break;
}
}
if( !ball.isLaunched() ) {
switch (action) {
case push_vertical:
case push_right:
case push_righter:
case push_left:
case push_lefter: {
ball.lauch(action, who_leads_the_ball);
break;
}
default:
break;
}
}
}
void physics_scene::moveBall(physic_player& player, const num_move move) {
switch (move) {
case move_left: {
if( !ball.isLaunched() )
ball.move_with_player(-player.getSpeed(), move);
break;
}
case move_right: {
if( !ball.isLaunched() )
ball.move_with_player(player.getSpeed(), move);
break;
}
default:
case stay: {
if( !ball.isLaunched() )
ball.move_with_player(player.getSpeed(), stay);
break;
}
}
}
void physics_scene::calculate(
const num_move key_bottom_move, const num_action key_bottom_action,
const num_move key_top_move, const num_action key_top_action,
const players who_lost_the_ball, const players who_leads_the_ball
) {
dt = clock.getElapsedTime().asSeconds();
clock.restart();
broken_block = -1;
who_broke_the_block = undef;
switch (who_lost_the_ball) {
case bottom: {
// первый параметр передает координаты игрока, потерявшего шарик
// второй параметр - является ли положение верхним
ball.restart(player_bottom.giveCoords(), false);
break;
}
case top: {
ball.restart(player_top.giveCoords(), true);
break;
}
default: break;
}
analyseKeys(player_bottom, who_leads_the_ball, key_bottom_move, key_bottom_action);
analyseKeys(player_top, who_leads_the_ball, key_top_move, key_top_action);
if (who_leads_the_ball == bottom) {
moveBall(player_bottom, key_bottom_move);
} else {
moveBall(player_top, key_top_move);
}
int buf;
for (auto it = blocks.begin(); it != blocks.end(); it++) {
buf = (*it)->try_kick();
if (buf != -1) {
broken_block = buf;
who_broke_the_block = ball.getOwner();
break;
}
}
world.Step(dt, velocityIterations, positionIterations);
//std::cout << dt << std::endl;
}
bool physics_scene::checkPlayerKicked() {
return player_top.checkKicked() || player_bottom.checkKicked();
}
const sf::Vector2f physics_scene::givePlayerBottomCoords() const {
b2Vec2 coords = player_bottom.giveCoords();
return sf::Vector2f(coords.x * PTM, coords.y * PTM);
}
const sf::Vector2f physics_scene::givePlayerTopCoords() const {
b2Vec2 coords = player_top.giveCoords();
return sf::Vector2f(coords.x * PTM, coords.y * PTM);
}
const sf::Vector2f physics_scene::giveBallCoords() const {
b2Vec2 coords = ball.giveCoords();
return sf::Vector2f(coords.x * PTM, coords.y * PTM - 10);
}
const sf::Vector2f physics_scene::giveBallSpeed() const {
b2Vec2 coords = ball.giveSpeed();
return sf::Vector2f(coords.x * PTM, coords.y * PTM);
}
/*
const sf::Vector2f givePlayerBottomSpeed() const {
b2Vec2 coords = player_bottom.getSpeed();
return sf::Vector2f(coords.x * PTM, coords.y * PTM);
}
const sf::Vector2f givePlayerTopSpeed() const {
b2Vec2 coords = player_top.getSpeed();
return sf::Vector2f(coords.x * PTM, coords.y * PTM);
}
*/
const int physics_scene::getBrokenBlock() const {
return broken_block;
}
players physics_scene::getHitman() const {
switch (who_broke_the_block) {
case player_bottom_id: {
return bottom;
}
case player_top_id: {
return top;
}
default: {
return no;
}
}
} | 27.457243 | 137 | 0.59353 | [
"shape"
] |
618c1e5321591dd198dfa4ec17112dd2a4441bd2 | 1,239 | cpp | C++ | Src/renderer/ShaderIncludes.cpp | Kataglyphis/GraphicEngine | f3b87a36b761fe13e747011be9301f6f9fe0c3f0 | [
"BSD-3-Clause"
] | null | null | null | Src/renderer/ShaderIncludes.cpp | Kataglyphis/GraphicEngine | f3b87a36b761fe13e747011be9301f6f9fe0c3f0 | [
"BSD-3-Clause"
] | null | null | null | Src/renderer/ShaderIncludes.cpp | Kataglyphis/GraphicEngine | f3b87a36b761fe13e747011be9301f6f9fe0c3f0 | [
"BSD-3-Clause"
] | null | null | null | #include "ShaderIncludes.h"
#include "File.h"
#include <stdio.h>
#include <string.h>
#include <array>
#include <sstream>
#include <cassert>
// this method is setting all files we want to use in a shader per #include
// you have to specify the name(how file appears in shader)
// and its actual file location relatively
// https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shading_language_include.txt
ShaderIncludes::ShaderIncludes()
{
assert(includeNames.size() == file_locations_relative.size());
std::vector<std::string> file_locations_abs;
for (uint32_t i = 0; i < static_cast<uint32_t>(includeNames.size()); i++) {
std::stringstream aux;
aux << CMAKELISTS_DIR;
aux << file_locations_relative[i];
file_locations_abs.push_back(aux.str());
}
for (uint32_t i = 0; i < static_cast<uint32_t>(includeNames.size()); i++) {
File file(file_locations_abs[i]);
std::string file_content = file.read();
char tmpstr[200];
sprintf(tmpstr, "/%s", includeNames[i]);
glNamedStringARB(GL_SHADER_INCLUDE_ARB, strlen(tmpstr), tmpstr,
strlen(file_content.c_str()), file_content.c_str());
}
}
ShaderIncludes::~ShaderIncludes()
{
}
| 28.159091 | 90 | 0.677966 | [
"vector"
] |
618e8af689ea21cdecb03a6a5cee4e8007916958 | 6,283 | cpp | C++ | include/staff/FloorWorker.cpp | Karthick47v2/inventory-management-sys | fcebcc62d31cbb97988c7b86f63b4d00f95a0c6b | [
"MIT"
] | null | null | null | include/staff/FloorWorker.cpp | Karthick47v2/inventory-management-sys | fcebcc62d31cbb97988c7b86f63b4d00f95a0c6b | [
"MIT"
] | null | null | null | include/staff/FloorWorker.cpp | Karthick47v2/inventory-management-sys | fcebcc62d31cbb97988c7b86f63b4d00f95a0c6b | [
"MIT"
] | null | null | null | #include "FloorWorker.h"
extern std::vector<LocalSupply> localSupplyDataPending;
extern std::vector<InternationalSupply> internationalSupplyDataPending;
extern std::vector<LocalSupply> localSupplyDataApproved;
extern std::vector<InternationalSupply> internationalSupplyDataApproved;
int addOrRemoveStock(int x, Transaction *transaction = NULL);
extern int selectCategory();
extern void addNewItem(int Category);
FloorWorker::FloorWorker(){}
FloorWorker::FloorWorker(std::string fullName, std::string userName): Staff(fullName, "FloorWorker", userName){}
void FloorWorker::stockIncrement(bool isFloorWorker){
system("cls");
std::cout << "Current Supply Details \n";
int i = 0, j = 0, k = 1;
bool noneChk = true;
if(localSupplyDataPending.size() > 0){
std::cout << "\nLocal Supply Details\n\n";
std::cout << "ID\tItem name\t\tQuantity Date of Arrival Status\tName of Origin\tDate of Departure Vehicle\tVehicle RegNo.\n";
noneChk = false;
}
for(i; i < localSupplyDataPending.size(); i++){
std::cout << k++ << "\t"<< localSupplyDataPending[i].getItemName() << "\t\t\t" <<localSupplyDataPending[i].getQuantity() << "\t " << localSupplyDataPending[i].getDateOfArrival().day << "-"
<< localSupplyDataPending[i].getDateOfArrival().month << "-" << localSupplyDataPending[i].getDateOfArrival().year << "\t " << localSupplyDataPending[i].getStatus() << "\t "
<< localSupplyDataPending[i].getNameOfOrigin() << "\t " << localSupplyDataPending[i].getDateOfDeparture().day << "-" << localSupplyDataPending[i].getDateOfDeparture().month << "-"
<< localSupplyDataPending[i].getDateOfDeparture().year << "\t " << localSupplyDataPending[i].getVehicle() << "\t";
if(localSupplyDataPending[i].getVehicle() == "Van"){
std::cout << "\t";
}
std::cout << localSupplyDataPending[i].getVehicleRegNo() << "\n";
}
if(internationalSupplyDataPending.size() > 0){
std::cout << "\nInternational Supply Details\n\n";
std::cout << "ID\tItem name\t\tQuantity Date of Arrival Status\tCountry of Origin\t Arrival Date at Harbour Ship No\n";
noneChk = false;
}
for(j; j < internationalSupplyDataPending.size(); j++){
std::cout << k++ << "\t"<< internationalSupplyDataPending[j].getItemName() << "\t\t\t" <<internationalSupplyDataPending[j].getQuantity() << "\t " << internationalSupplyDataPending[j].getDateOfArrival().day << "-"
<< internationalSupplyDataPending[j].getDateOfArrival().month << "-" << internationalSupplyDataPending[j].getDateOfArrival().year << "\t " << internationalSupplyDataPending[j].getStatus() << "\t "
<< internationalSupplyDataPending[j].getcountryOfOrigin() << " \t " << internationalSupplyDataPending[j].getArrivalDateAtHarbour().day << "-" << internationalSupplyDataPending[j].getArrivalDateAtHarbour().month << "-"
<< internationalSupplyDataPending[j].getArrivalDateAtHarbour().year << "\t " << internationalSupplyDataPending[j].getShipNo() << "\n";
}
if(noneChk){
std::cout << "** NO DATA FOUND **\n";
system("pause");
return;
}
int n;
std::cout << "\n";
std::cout << "*Enter 0 if you want to go back*\n";
do{
std::cout << "Enter the id of supply detail to put it to stocks : ";
while (!(std::cin >> n)){
std::cin.clear(); // clear the fail bit
std::cin.ignore(100, '\n'); // ignore the invalid entry
std::cout << "Enter the no. of supply detail to put it to stocks : ";
}
if(n == 0) return;
}while(n < 1 || n > (i + j));
system("cls");
if(i < n){
std::cout << "Item name\t\tQuantity Date of Arrival Status\tCountry of Origin\t Arrival Date at Harbour Ship No\n";
j = n - i - 1;
std::cout << internationalSupplyDataPending[j].getItemName() << "\t\t\t" <<internationalSupplyDataPending[j].getQuantity() << "\t " << internationalSupplyDataPending[j].getDateOfArrival().day << "-"
<< internationalSupplyDataPending[j].getDateOfArrival().month << "-" << internationalSupplyDataPending[j].getDateOfArrival().year << "\t " << internationalSupplyDataPending[j].getStatus() << "\t "
<< internationalSupplyDataPending[j].getcountryOfOrigin() << " \t " << internationalSupplyDataPending[j].getArrivalDateAtHarbour().day << "-" << internationalSupplyDataPending[j].getArrivalDateAtHarbour().month << "-"
<< internationalSupplyDataPending[j].getArrivalDateAtHarbour().year << "\t " << internationalSupplyDataPending[j].getShipNo() << "\n";
}
else{
std::cout << "Item name\t\tQuantity Date of Arrival Status\tName of Origin\tDate of Departure Vehicle\tVehicle RegNo.\n";
j = n - 1 ;
std::cout << localSupplyDataPending[j].getItemName() << "\t\t\t" <<localSupplyDataPending[j].getQuantity() << "\t " << localSupplyDataPending[j].getDateOfArrival().day << "-"
<< localSupplyDataPending[j].getDateOfArrival().month << "-" << localSupplyDataPending[j].getDateOfArrival().year << "\t " << localSupplyDataPending[j].getStatus() << "\t "
<< localSupplyDataPending[j].getNameOfOrigin() << "\t " << localSupplyDataPending[j].getDateOfDeparture().day << "-" << localSupplyDataPending[j].getDateOfDeparture().month << "-"
<< localSupplyDataPending[j].getDateOfDeparture().year << "\t " << localSupplyDataPending[j].getVehicle() << "\t";
if(localSupplyDataPending[j].getVehicle() == "Van"){
std::cout << "\t";
}
std::cout << localSupplyDataPending[j].getVehicleRegNo() << "\n";
}
int chk = 0;
if(isFloorWorker){
chk = addOrRemoveStock(1); //add num items
}
else{
addNewItem(selectCategory()); //add new item
chk = 1;
}
if(chk != 0){
if(i < n){
internationalSupplyDataPending[n - i - 1].setStatus("Approved");
internationalSupplyDataApproved.emplace_back(internationalSupplyDataPending[n - i - 1]);
internationalSupplyDataPending.erase(internationalSupplyDataPending.begin() + n - i - 1);
}
else{
localSupplyDataPending[n - 1].setStatus("Approved");
localSupplyDataApproved.emplace_back(localSupplyDataPending[n - 1]);
localSupplyDataPending.erase(localSupplyDataPending.begin() + n - 1);
}
}
}
FloorWorker::~FloorWorker(){}
| 54.163793 | 236 | 0.660512 | [
"vector"
] |
6190849ec95ad832207ec3879332de6364beca37 | 3,246 | cpp | C++ | src/cxx/geometry.cpp | tardani95/iris-distro | dbb1ebbde2e52b4cc747b4aa2fe88518b238071a | [
"BSD-2-Clause"
] | 82 | 2016-03-30T15:32:47.000Z | 2022-03-28T03:03:08.000Z | src/cxx/geometry.cpp | tardani95/iris-distro | dbb1ebbde2e52b4cc747b4aa2fe88518b238071a | [
"BSD-2-Clause"
] | 49 | 2015-01-21T16:13:20.000Z | 2021-12-29T02:47:52.000Z | src/cxx/geometry.cpp | tardani95/iris-distro | dbb1ebbde2e52b4cc747b4aa2fe88518b238071a | [
"BSD-2-Clause"
] | 61 | 2015-03-20T18:49:31.000Z | 2022-01-27T12:35:38.000Z | #include "iris/geometry.h"
#include <Eigen/Core>
#include <Eigen/LU>
#include <iostream>
#include "iris_cdd.h"
namespace iris {
int factorial(int n) {
return n == 0 ? 1 : factorial(n - 1) * n;
}
double nSphereVolume(int dim, double radius) {
double v;
int k = std::floor(dim / 2);
if (dim % 2 == 0) {
v = std::pow(M_PI, k) / static_cast<double>(factorial(k));
} else {
v = (2.0 * factorial(k) * std::pow(4 * M_PI, k)) / static_cast<double>(factorial(2 * k + 1));
}
return v * std::pow(radius, dim);
}
Ellipsoid::Ellipsoid(int dim) :
C_(Eigen::MatrixXd(dim, dim)),
d_(Eigen::VectorXd(dim)) {}
Ellipsoid::Ellipsoid(Eigen::MatrixXd C, Eigen::VectorXd d):
C_(C),
d_(d) {}
const Eigen::MatrixXd& Ellipsoid::getC() const {
return C_;
}
const Eigen::VectorXd& Ellipsoid::getD() const {
return d_;
}
void Ellipsoid::setC(const Eigen::MatrixXd &C) {
C_ = C;
}
void Ellipsoid::setCEntry(Eigen::DenseIndex row,
Eigen::DenseIndex col, double value) {
C_(row, col) = value;
}
void Ellipsoid::setD(const Eigen::VectorXd &d) {
d_ = d;
}
void Ellipsoid::setDEntry(Eigen::DenseIndex index, double value) {
d_(index) = value;
}
int Ellipsoid::getDimension() const {
return C_.cols();
}
double Ellipsoid::getVolume() const {
return C_.determinant() * nSphereVolume(this->getDimension(), 1.0);
}
Ellipsoid Ellipsoid::fromNSphere(Eigen::VectorXd ¢er, double radius) {
const int dim = center.size();
Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim, dim);
C.diagonal().setConstant(radius);
Ellipsoid ellipsoid(C, center);
return ellipsoid;
}
Polyhedron::Polyhedron(int dim):
A_(0, dim),
b_(0, 1),
dd_representation_dirty_(true) {}
Polyhedron::Polyhedron(Eigen::MatrixXd A, Eigen::VectorXd b):
A_(A),
b_(b),
dd_representation_dirty_(true) {}
void Polyhedron::setA(const Eigen::MatrixXd &A) {
A_ = A;
dd_representation_dirty_ = true;
}
const Eigen::MatrixXd& Polyhedron::getA() const {
return A_;
}
void Polyhedron::setB(const Eigen::VectorXd &b) {
b_ = b;
dd_representation_dirty_ = true;
}
const Eigen::VectorXd& Polyhedron::getB() const {
return b_;
}
int Polyhedron::getDimension() const {
return A_.cols();
}
int Polyhedron::getNumberOfConstraints() const {
return A_.rows();
}
void Polyhedron::appendConstraints(const Polyhedron &other) {
A_.conservativeResize(A_.rows() + other.getA().rows(), A_.cols());
A_.bottomRows(other.getA().rows()) = other.getA();
b_.conservativeResize(b_.rows() + other.getB().rows());
b_.tail(other.getB().rows()) = other.getB();
dd_representation_dirty_ = true;
}
void Polyhedron::updateDDRepresentation() {
generator_points_.clear();
generator_rays_.clear();
getGenerators(A_, b_, generator_points_, generator_rays_);
dd_representation_dirty_ = false;
}
std::vector<Eigen::VectorXd> Polyhedron::generatorPoints() {
if (dd_representation_dirty_) {
updateDDRepresentation();
}
return generator_points_;
}
std::vector<Eigen::VectorXd> Polyhedron::generatorRays() {
if (dd_representation_dirty_) {
updateDDRepresentation();
}
return generator_rays_;
}
bool Polyhedron::contains(Eigen::VectorXd point, double tolerance) {
return (A_ * point - b_).maxCoeff() <= tolerance;
}
} | 27.05 | 97 | 0.682378 | [
"geometry",
"vector"
] |
61953ddf219ed69a77d4f52e7930accc977b6a8d | 666 | hpp | C++ | xtd.forms.native/include/xtd/forms/native/list_box.hpp | lineCode/xtd.forms | 53b126a41513b4009870498b9f8e522dfc94c8de | [
"MIT"
] | 1 | 2022-02-04T08:15:31.000Z | 2022-02-04T08:15:31.000Z | xtd.forms.native/include/xtd/forms/native/list_box.hpp | lineCode/xtd.forms | 53b126a41513b4009870498b9f8e522dfc94c8de | [
"MIT"
] | null | null | null | xtd.forms.native/include/xtd/forms/native/list_box.hpp | lineCode/xtd.forms | 53b126a41513b4009870498b9f8e522dfc94c8de | [
"MIT"
] | null | null | null | #pragma once
#include "../create_params.hpp"
#include <vector>
namespace xtd {
namespace forms {
namespace native {
class list_box {
public:
list_box() = delete;
static drawing::color default_back_color();
static drawing::color default_fore_color();
static void delete_item(intptr_t control, size_t index);
static size_t insert_item(intptr_t control, size_t index, const std::string& item);
static size_t selected_index(intptr_t control);
static void selected_index(intptr_t control, size_t index);
static std::vector<size_t> selected_indices(intptr_t control);
};
}
}
}
| 30.272727 | 91 | 0.674174 | [
"vector"
] |
619d92d440f3fdfe41b4c34247efae029e4c52b7 | 4,466 | hpp | C++ | ql/experimental/coupons/subperiodcoupons.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 1 | 2020-10-13T09:57:04.000Z | 2020-10-13T09:57:04.000Z | ql/experimental/coupons/subperiodcoupons.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 19 | 2020-11-23T08:36:10.000Z | 2022-03-28T10:06:53.000Z | ql/experimental/coupons/subperiodcoupons.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 2 | 2021-04-24T17:51:11.000Z | 2021-07-20T09:41:33.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008 Toyin Akin
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file subperiodcoupons.hpp
\brief averaging coupons
*/
#ifndef quantlib_sub_period_coupons_hpp
#define quantlib_sub_period_coupons_hpp
#include <ql/cashflows/couponpricer.hpp>
#include <ql/cashflows/floatingratecoupon.hpp>
#include <ql/time/schedule.hpp>
#include <vector>
namespace QuantLib {
class IborIndex;
class AveragingRatePricer;
class SubPeriodsCoupon: public FloatingRateCoupon {
public:
// The index object passed in has a tenor significantly less than the
// start/end dates.
// Thus endDate-startDate may equal 3M
// The Tenor used within the index object should be 1M for
// averaging/compounding across three coupons within the
// coupon period.
SubPeriodsCoupon(
const Date& paymentDate,
Real nominal,
const ext::shared_ptr<IborIndex>& index,
const Date& startDate,
const Date& endDate,
Natural fixingDays,
const DayCounter& dayCounter,
Real gearing,
Rate couponSpread, // Spread added to the computed
// averaging/compounding rate.
Rate rateSpread, // Spread to be added onto each
// fixing within the
// averaging/compounding calculation
const Date& refPeriodStart,
const Date& refPeriodEnd);
Spread rateSpread() const { return rateSpread_; }
Real startTime() const { return startTime_; }
Real endTime() const { return endTime_; }
Size observations() const { return observations_; }
const std::vector<Date>& observationDates() const {
return observationDates_;
}
const std::vector<Real>& observationTimes() const {
return observationTimes_;
}
ext::shared_ptr<Schedule> observationsSchedule() const { return observationsSchedule_; }
//! \name Visitability
//@{
virtual void accept(AcyclicVisitor&);
//@}
private:
Real startTime_; // S
Real endTime_; // T
ext::shared_ptr<Schedule> observationsSchedule_;
std::vector<Date> observationDates_;
std::vector<Real> observationTimes_;
Size observations_;
Rate rateSpread_;
};
class SubPeriodsPricer: public FloatingRateCouponPricer {
public:
virtual Rate swapletRate() const;
virtual Real capletPrice(Rate effectiveCap) const;
virtual Rate capletRate(Rate effectiveCap) const;
virtual Real floorletPrice(Rate effectiveFloor) const;
virtual Rate floorletRate(Rate effectiveFloor) const;
void initialize(const FloatingRateCoupon& coupon);
protected:
const SubPeriodsCoupon* coupon_;
Real startTime_;
Real endTime_;
Real accrualFactor_;
std::vector<Real> observationTimes_;
std::vector<Real> observationCvg_;
std::vector<Real> initialValues_;
std::vector<Date> observationIndexStartDates_;
std::vector<Date> observationIndexEndDates_;
Size observations_;
Real discount_;
Real gearing_;
Spread spread_;
Real spreadLegValue_;
};
class AveragingRatePricer: public SubPeriodsPricer {
public:
Real swapletPrice() const;
};
class CompoundingRatePricer: public SubPeriodsPricer {
public:
Real swapletPrice() const;
};
}
#endif
| 32.59854 | 96 | 0.631885 | [
"object",
"vector"
] |
61a47d01abf8ed65893fe8d15da1660ac734daf0 | 4,251 | cpp | C++ | benchmark.cpp | jevinskie/visit | 475932dcc72fd83538ffd76cea75f392526669fd | [
"BSL-1.0"
] | 23 | 2018-12-24T01:59:31.000Z | 2021-11-16T00:25:59.000Z | benchmark.cpp | jevinskie/visit | 475932dcc72fd83538ffd76cea75f392526669fd | [
"BSL-1.0"
] | 2 | 2021-02-14T11:16:31.000Z | 2021-02-17T17:38:11.000Z | benchmark.cpp | jevinskie/visit | 475932dcc72fd83538ffd76cea75f392526669fd | [
"BSL-1.0"
] | 7 | 2018-12-24T01:59:42.000Z | 2021-12-24T15:50:11.000Z | /*
* Copyright Björn Fahller 2018
*
* Use, modification and distribution is subject to 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)
*
* Project home: https://github.com/rollbear/visit
*/
#include <visit.hpp>
#include <benchmark/benchmark.h>
template <int>
struct type_;
template <>
struct type_<0> { using type = bool;};
template <>
struct type_<1> { using type = signed char;};
template <>
struct type_<2> { using type = char;};
template <>
struct type_<3> { using type = unsigned char;};
template <>
struct type_<4> { using type = short;};
template <>
struct type_<5> { using type = unsigned short;};
template <>
struct type_<6> { using type = int;};
template <>
struct type_<7> { using type = unsigned;};
template <>
struct type_<8> { using type = long; };
template <>
struct type_<9> { using type = unsigned long;};
template <>
struct type_<10> { using type = long long;};
template <>
struct type_<11> { using type = unsigned long long;};
template <int I>
using type = typename type_<I%12>::type;
template <int I>
struct V
{
type<I> i;
operator type<I>() const { return i;}
};
template <std::size_t ... I>
auto populate(std::index_sequence<I...>)
{
std::vector<std::variant<V<I>...>> v;
for (unsigned i = 0; i < 5000U/sizeof...(I); ++i)
{
(v.push_back(V<I>{(I&1) == 1}),...);
(v.push_back(V<I>{(I&1) == 0}),...);
}
return v;
}
constexpr auto nonzero =[](auto x) -> bool { return x;};
template <size_t I>
void rollbear_visit(benchmark::State& state)
{
auto values = populate(std::make_index_sequence<I>{});
for (auto _ : state) {
int sum = 0;
for (auto& v : values)
{
sum += rollbear::visit(nonzero,v);
}
benchmark::DoNotOptimize(sum);
}
}
template <size_t I>
void std_visit(benchmark::State& state)
{
auto values = populate(std::make_index_sequence<I>{});
for (auto _ : state) {
int sum = 0;
for (auto& v : values)
{
sum += std::visit(nonzero,v);
}
benchmark::DoNotOptimize(sum);
}
}
static void rollbear_visit_1(benchmark::State& state) { rollbear_visit<1>(state);}
static void rollbear_visit_2(benchmark::State& state) { rollbear_visit<2>(state);}
static void rollbear_visit_3(benchmark::State& state) { rollbear_visit<3>(state);}
static void rollbear_visit_5(benchmark::State& state) { rollbear_visit<5>(state);}
static void rollbear_visit_8(benchmark::State& state) { rollbear_visit<8>(state);}
static void rollbear_visit_13(benchmark::State& state) { rollbear_visit<13>(state);}
static void rollbear_visit_21(benchmark::State& state) { rollbear_visit<21>(state);}
static void rollbear_visit_34(benchmark::State& state) { rollbear_visit<34>(state);}
static void rollbear_visit_55(benchmark::State& state) { rollbear_visit<55>(state);}
static void rollbear_visit_89(benchmark::State& state) { rollbear_visit<89>(state);}
static void std_visit_1(benchmark::State& state) { std_visit<1>(state);}
static void std_visit_2(benchmark::State& state) { std_visit<2>(state);}
static void std_visit_3(benchmark::State& state) { std_visit<3>(state);}
static void std_visit_5(benchmark::State& state) { std_visit<5>(state);}
static void std_visit_8(benchmark::State& state) { std_visit<8>(state);}
static void std_visit_13(benchmark::State& state) { std_visit<13>(state);}
static void std_visit_21(benchmark::State& state) { std_visit<21>(state);}
static void std_visit_34(benchmark::State& state) { std_visit<34>(state);}
static void std_visit_55(benchmark::State& state) { std_visit<55>(state);}
static void std_visit_89(benchmark::State& state) { std_visit<89>(state);}
// Register the function as a benchmark
BENCHMARK(rollbear_visit_1);
BENCHMARK(rollbear_visit_2);
BENCHMARK(rollbear_visit_3);
BENCHMARK(rollbear_visit_5);
BENCHMARK(rollbear_visit_8);
BENCHMARK(rollbear_visit_13);
BENCHMARK(rollbear_visit_21);
BENCHMARK(rollbear_visit_34);
BENCHMARK(rollbear_visit_55);
BENCHMARK(rollbear_visit_89);
BENCHMARK(std_visit_1);
BENCHMARK(std_visit_2);
BENCHMARK(std_visit_3);
BENCHMARK(std_visit_5);
BENCHMARK(std_visit_8);
BENCHMARK(std_visit_13);
BENCHMARK(std_visit_21);
BENCHMARK(std_visit_34);
BENCHMARK(std_visit_55);
BENCHMARK(std_visit_89);
| 30.364286 | 84 | 0.713244 | [
"vector"
] |
61a927a83ae197f0924bdaae24c4ca727c76d0e4 | 883 | cpp | C++ | C++/0722-Remove-Comments/soln.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0722-Remove-Comments/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0722-Remove-Comments/soln.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
vector<string> removeComments(vector<string>& source) {
string s = "";
for (auto line : source) s += line + '\n';
int i = 0;
string left = "";
int n = s.length();
while (i < n) {
if (i < n - 1 && s[i] == '/' && s[i + 1] == '*') {
i = i + 2;
while (i < n - 1 && (s[i] != '*' || s[i + 1] != '/')) ++i;
i = i + 2;
} else if (i < n - 1 && s[i] == '/' && s[i + 1] == '/') {
i = i + 2;
while (i < n && s[i] != '\n') ++i;
} else {
left += s[i++];
}
}
vector<string> ans;
string line;
stringstream iss(left);
while (getline(iss, line)) {
if (!line.empty()) ans.push_back(line);
}
return ans;
}
};
| 29.433333 | 74 | 0.331823 | [
"vector"
] |
61ad27021b9b2a5388713d8600aa45424c9d8fe6 | 5,398 | cpp | C++ | oneflow/customized/kernels/softmax_kernel.cpp | xxg1413/oneflow | f2e3c85a25b8aecfb6c0c0af1737833b1a77e135 | [
"Apache-2.0"
] | 1 | 2020-12-04T03:06:16.000Z | 2020-12-04T03:06:16.000Z | oneflow/customized/kernels/softmax_kernel.cpp | xxg1413/oneflow | f2e3c85a25b8aecfb6c0c0af1737833b1a77e135 | [
"Apache-2.0"
] | null | null | null | oneflow/customized/kernels/softmax_kernel.cpp | xxg1413/oneflow | f2e3c85a25b8aecfb6c0c0af1737833b1a77e135 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/framework/framework.h"
#include "oneflow/core/kernel/new_kernel_util.h"
#include "oneflow/customized/kernels/softmax_kernel_util.h"
namespace oneflow {
namespace {
template<DeviceType device_type, typename T>
class SoftmaxKernel final : public user_op::OpKernel {
public:
SoftmaxKernel() = default;
~SoftmaxKernel() = default;
private:
void Compute(user_op::KernelComputeContext* ctx) const override {
const user_op::Tensor* x = ctx->Tensor4ArgNameAndIndex("in", 0);
user_op::Tensor* y = ctx->Tensor4ArgNameAndIndex("out", 0);
const int64_t num_classes = x->shape().At(x->shape().NumAxes() - 1);
const int64_t num_instances = x->shape().elem_cnt() / num_classes;
user_op::Tensor* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0);
const size_t temp_storage_bytes = x->shape().elem_cnt() * sizeof(T);
const size_t tmp_bytes = GetCudaAlignedSize(temp_storage_bytes / num_classes);
T* tmp_ptr = tmp_buffer->mut_dptr<T>();
void* temp_storage_ptr = reinterpret_cast<void*>(tmp_ptr + tmp_bytes / sizeof(T));
SoftmaxKernelUtil<device_type, T>::ComputeProb(ctx->device_ctx(), num_instances, num_classes,
x->dptr<T>(), tmp_ptr, y->mut_dptr<T>(),
temp_storage_ptr, temp_storage_bytes);
}
bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; }
};
template<typename T>
user_op::InferTmpSizeFn GenInferTmpSizeFn(const std::string& bn) {
return [bn](user_op::InferContext* ctx) {
const Shape* x = ctx->Shape4ArgNameAndIndex(bn, 0);
const size_t num_classes = x->dim_vec().back();
size_t temp_storage_bytes = GetCudaAlignedSize(x->elem_cnt() * sizeof(T)); // [i][j]
size_t tmp_or_sum_vec_bytes = GetCudaAlignedSize(temp_storage_bytes / num_classes); //[i]
return tmp_or_sum_vec_bytes + temp_storage_bytes;
};
}
#define REGISTER_SOFTMAX_KERNEL(device, dtype) \
REGISTER_USER_KERNEL("softmax") \
.SetCreateFn<SoftmaxKernel<device, dtype>>() \
.SetIsMatchedHob((user_op::HobDeviceType() == device) \
& (user_op::HobDataType("out", 0) == GetDataType<dtype>::value)) \
.SetInferTmpSizeFn(GenInferTmpSizeFn<dtype>("in"));
REGISTER_SOFTMAX_KERNEL(DeviceType::kCPU, float)
REGISTER_SOFTMAX_KERNEL(DeviceType::kCPU, double)
REGISTER_SOFTMAX_KERNEL(DeviceType::kGPU, float16)
REGISTER_SOFTMAX_KERNEL(DeviceType::kGPU, float)
REGISTER_SOFTMAX_KERNEL(DeviceType::kGPU, double)
template<DeviceType device_type, typename T>
class SoftmaxGradKernel final : public user_op::OpKernel {
public:
SoftmaxGradKernel() = default;
~SoftmaxGradKernel() = default;
private:
void Compute(user_op::KernelComputeContext* ctx) const override {
const user_op::Tensor* y = ctx->Tensor4ArgNameAndIndex("y", 0);
const user_op::Tensor* dy = ctx->Tensor4ArgNameAndIndex("dy", 0);
user_op::Tensor* dx = ctx->Tensor4ArgNameAndIndex("dx", 0);
const int64_t num_classes = y->shape().At(y->shape().NumAxes() - 1);
const int64_t num_instances = y->shape().elem_cnt() / num_classes;
user_op::Tensor* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0);
const size_t temp_storage_bytes = y->shape().elem_cnt() * sizeof(T);
const size_t sum_vec_bytes = GetCudaAlignedSize(temp_storage_bytes / num_classes);
T* sum_vec_ptr = tmp_buffer->mut_dptr<T>();
void* temp_storage_ptr = reinterpret_cast<void*>(sum_vec_ptr + sum_vec_bytes / sizeof(T));
SoftmaxKernelUtil<device_type, T>::ComputeDiff(
ctx->device_ctx(), num_instances, num_classes, dy->dptr<T>(), y->dptr<T>(), sum_vec_ptr,
dx->mut_dptr<T>(), temp_storage_ptr, temp_storage_bytes);
}
bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; }
};
#define REGISTER_SOFTMAX_GRAD_KERNEL(device, dtype) \
REGISTER_USER_KERNEL("softmax_grad") \
.SetCreateFn<SoftmaxGradKernel<device, dtype>>() \
.SetIsMatchedHob((user_op::HobDeviceType() == device) \
& (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \
.SetInferTmpSizeFn(GenInferTmpSizeFn<dtype>("dx"));
REGISTER_SOFTMAX_GRAD_KERNEL(DeviceType::kCPU, float)
REGISTER_SOFTMAX_GRAD_KERNEL(DeviceType::kCPU, double)
REGISTER_SOFTMAX_GRAD_KERNEL(DeviceType::kGPU, float16)
REGISTER_SOFTMAX_GRAD_KERNEL(DeviceType::kGPU, float)
REGISTER_SOFTMAX_GRAD_KERNEL(DeviceType::kGPU, double)
} // namespace
} // namespace oneflow
| 45.745763 | 98 | 0.679326 | [
"shape"
] |
61ad4515a8b3bd41981f193e16abdc7652aa40b0 | 7,829 | cpp | C++ | Algorithms/cses/Sorting and Searching/Restaurant_Customers.cpp | anand722000/algo_ds_101 | b3e25ce2b2e47e53024f8d349232b04de2837ce3 | [
"MIT"
] | null | null | null | Algorithms/cses/Sorting and Searching/Restaurant_Customers.cpp | anand722000/algo_ds_101 | b3e25ce2b2e47e53024f8d349232b04de2837ce3 | [
"MIT"
] | null | null | null | Algorithms/cses/Sorting and Searching/Restaurant_Customers.cpp | anand722000/algo_ds_101 | b3e25ce2b2e47e53024f8d349232b04de2837ce3 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag, tree_order_statistics_node_update> indset;
#define fo(i, n) for (ll i = 0; i < n; ++i)
#define ll long long
#define mod 1000000007
#define inf 1ll << 62
ll power(ll x, ll y, ll modd)
{
if (y == 0)
{
return 1;
}
else if (y == 1)
{
return (x % modd);
}
ll z = power(x % modd, y / 2, modd) % modd;
if ((y % modd) % 2)
{
return (((((z % modd) * (x % modd)) % modd) * (z % modd)) % modd);
}
else
{
return (((z % modd) * (z % modd)) % modd);
}
}
void sor(vector<ll> &x)
{
sort(x.begin(), x.end());
}
void rev(vector<ll> &x)
{
reverse(x.begin(), x.end());
}
ll gcd(ll x, ll y)
{
if (y == 0)
{
return x;
}
return gcd(y, x % y);
}
ll max(ll x, ll y)
{
if (x > y)
{
return x;
}
else
{
return y;
}
}
ll min(ll x, ll y)
{
if (x > y)
{
return y;
}
else
{
return x;
}
}
ll lcm(ll x, ll y)
{
return x * y / gcd(x, y);
}
ll bina(vector<ll> a, ll n, ll m)
{
ll start = 0, end = n - 1;
ll c = 0;
if (m >= a[n - 1])
{
return n;
}
while (start <= end)
{
ll mid = (start + end) / 2;
if (m >= a[mid])
{
c = mid + 1;
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return c;
}
ll binarySearch(vector<ll> arr, ll l, ll r, ll x)
{
if (r >= l)
{
ll mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
ll prime(ll n)
{
for (ll i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
{
return i;
}
}
return 0;
}
ll countBits(ll number)
{
return (ll)log2(number) + 1;
}
ll countDivisors(ll n)
{
ll cnt = 0;
for (ll i = 1; i <= sqrt(n); i++)
{
if (n % i == 0)
{
if (n / i == i)
cnt++;
else // Otherwise count both
cnt = cnt + 2;
}
}
return cnt;
}
ll fact(ll n)
{
ll res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}
ll nCr(ll n, ll r)
{
return fact(n) / (fact(r) * fact(n - r));
}
ll nCrModp(ll n, ll r)
{
if (r > n - r)
r = n - r;
ll C[r + 1];
memset(C, 0, sizeof(C));
C[0] = 1;
for (ll i = 1; i <= n; i++)
{
for (ll j = min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % mod;
}
return C[r];
}
/*
const ll mxn = (2 * 100000) + 1;
vector<ll> pr;
bool pri[mxn + 1];
vector<ll> no;
vector<ll> cop(10000001, 1);
void SieveOfEratosthenes(int n)
{
memset(pri, true, sizeof(pri));
pri[1] = false;
pri[0] = false;
fo(i, 10000001)
{
cop[i] = i;
}
for (int p = 2; p <= n; p++)
{
if (cop[p] == p)
{
//cop[p] = p - 1;
for (int i = p; i <= n; i += p)
{
cop[i] *= (p - 1);
cop[i] /= (p);
}
}
}
}
vector<vector<ll>> expo(ll n, vector<vector<ll>> a, vector<vector<ll>> one)
{
if (n <= 0)
{
return one;
}
else if (n == 1)
{
return a;
}
vector<vector<ll>> mat = expo(n / 2, a, one);
if (n % 2)
{
vector<vector<ll>> ans2;
fo(i, mat.size())
{
vector<ll> temp(mat.size(), 0);
ans2.push_back(temp);
}
fo(i, mat.size())
{
fo(j, mat.size())
{
fo(k, mat.size())
{
ans2[i][j] += mat[i][k] * a[k][j];
ans2[i][j] %= mod;
}
ans2[i][j] %= mod;
}
}
vector<vector<ll>> ans3;
fo(i, mat.size())
{
vector<ll> temp(mat.size(), 0);
ans3.push_back(temp);
}
fo(i, mat.size())
{
fo(j, mat.size())
{
fo(k, mat.size())
{
ans3[i][j] += ans2[i][k] * mat[k][j];
ans3[i][j] %= mod;
}
ans3[i][j] %= mod;
}
}
return ans3;
}
else
{
vector<vector<ll>> ans2;
fo(i, mat.size())
{
vector<ll> temp(mat.size(), 0);
ans2.push_back(temp);
}
fo(i, mat.size())
{
fo(j, mat.size())
{
fo(k, mat.size())
{
ans2[i][j] += mat[i][k] * mat[k][j];
ans2[i][j] %= mod;
}
ans2[i][j] %= mod;
}
}
return ans2;
}
}
vector<int> ninjaChess2021(string king, string ninja) {
}
ll v, source, graph[100][100];
vector<ll> dist(100, INT64_MAX);
ll vis[100];
ll parent[100];
void dijktras()
{
fo(i, v)
{
parent[i] = i;
}
dist[0] = 0;
fo(i, v)
{
ll mi = INT64_MAX;
ll minnode = 0;
fo(j, v)
{
if (!vis[j] && dist[j] < mi)
{
mi = dist[j];
minnode = j;
}
}
vis[minnode] = 1;
fo(j, v)
{
if (graph[minnode][j] != INT64_MAX && dist[j] < dist[minnode] + graph[minnode][j])
{
dist[j] = dist[minnode] + graph[minnode][j];
parent[j] = minnode;
}
}
}
}
//vector<ll> a;
vector<ll> adj[1000001];
queue<ll> q;
vector<bool> used(1000001);
vector<int> d(1000001);
vector<ll> level(1000001);
void bfs(ll s)
{
q.push(s);
used[s] = true;
d[s] = 0;
while (!q.empty())
{
int v = q.front();
q.pop();
for (int u : adj[v])
{
if (!used[u])
{
used[u] = true;
q.push(u);
d[u] = d[v] + 1;
level[d[u]]++;
//cout << u << " ";
}
}
}
}
void dfs(ll s, ll dd)
{
used[s] = 1;
d[s] = dd;
for (auto child : adj[s])
{
if (used[child] == 0)
{
dfs(child, dd);
}
}
}
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void perm(char *s, ll l, ll r)
{
if (l == r)
{
cout << s[l];
}
else
{
for (int i = l; i <= r; i++)
{
swap(s + l, s + i);
perm(s, l + 1, r);
swap(s + l, s + i);
cout << endl;
}
}
}
*/
void solve()
{
ll n;
cin >> n;
pair<ll, ll> p[2 * n];
for (int i = 0; i < 2 * n; i += 2)
{
ll q, w;
cin >> q >> w;
p[i] = {q, 0};
p[i + 1] = {w, 1};
}
sort(p, p + 2 * n);
ll ans = 0;
ll x = 0;
fo(i, 2 * n)
{
if (p[i].second == 1)
{
x--;
}
else
{
x++;
ans = max(ans, x);
}
}
cout << ans;
}
int main()
{
ios::sync_with_stdio(0), cout.tie(0), cin.tie(0);
// freopen("A.TXT", "r", stdin);
//freopen("A.OUT", "w", stdout);
//freopen("INPUT.TXT", "r", stdin);
//freopen("OUTPUT.TXT", "w", stdout);
//SieveOfEratosthenes(mxn);
ll t = 1;
//cin >> t;
fo(tt, t)
{
solve();
}
return 0;
}
| 17.320796 | 101 | 0.369779 | [
"vector"
] |
ba0d46eba3689357173ca1be8c1d779349bb6bf3 | 25,501 | hpp | C++ | neutrino/math/inc/transform_functions.hpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 1 | 2017-07-14T04:51:54.000Z | 2017-07-14T04:51:54.000Z | neutrino/math/inc/transform_functions.hpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 32 | 2017-02-02T14:49:41.000Z | 2019-06-25T19:38:27.000Z | neutrino/math/inc/transform_functions.hpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | null | null | null | #ifndef FRAMEWORK_MATH_DETAILS
#error You should include math/math.hpp instead of transform_functions.hpp
#endif
#ifndef FRAMEWORK_MATH_INC_TRANSFORM_FUNCTIONS_HPP
#define FRAMEWORK_MATH_INC_TRANSFORM_FUNCTIONS_HPP
#include <cassert>
#include <limits>
#include <math/inc/common_functions.hpp>
#include <math/inc/matrix_functions.hpp>
#include <math/inc/matrix_type.hpp>
#include <math/inc/trigonometric_functions.hpp>
namespace framework::math
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @addtogroup math_transform_functions
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name translate
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Builds a translation 3x3 Matrix created from a vector of 2 components.
///
/// @param m Matrix multiplied by this translation Matrix.
/// @param v Translation vector.
///
/// @return The Matrix which contains translation transformation.
template <typename T>
inline Matrix<3, 3, T> translate(const Matrix<3, 3, T>& m, const Vector<2, T>& v)
{
return Matrix<3, 3, T>(m[0], m[1], m[0] * v[0] + m[1] * v[1] + m[2]);
}
/// @brief Builds a translation 4x4 Matrix created from a vector of 3 components.
///
/// @param m Matrix multiplied by this translation Matrix.
/// @param v Translation vector.
///
/// @return The Matrix which contains translation transformation.
template <typename T>
inline Matrix<4, 4, T> translate(const Matrix<4, 4, T>& m, const Vector<3, T>& v)
{
// clang-format off
Matrix<4, 4, T> temp(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
v[0], v[1], v[2], 1);
// clang-format on
return m * temp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name rotate
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Builds a rotation 3x3 Matrix created from an angle.
///
/// @param m Matrix multiplied by this translation Matrix.
/// @param angle Rotation angle expressed in radians.
///
/// @return The Matrix which contains rotation transformation.
template <typename T, typename U>
inline Matrix<3, 3, T> rotate(const Matrix<3, 3, T>& m, const U angle)
{
const auto c = static_cast<T>(math::cos(angle));
const auto s = static_cast<T>(math::sin(angle));
// clang-format off
return Matrix<3, 3, T>(m[0] * c + m[1] * s,
m[0] * -s + m[1] * c,
m[2]);
// clang-format on
}
/// @brief Builds a rotation 4x4 Matrix created from an axis vector and an angle.
///
/// @param m Matrix multiplied by this rotation Matrix.
/// @param v Rotation axis, recommended to be normalized.
/// @param angle Rotation angle expressed in radians.
///
/// @return The Matrix which contains rotation transformation.
template <typename T, typename U>
inline Matrix<4, 4, T> rotate(const Matrix<4, 4, T>& m, const Vector<3, T>& v, const U angle)
{
const auto cos = static_cast<T>(framework::math::cos(angle));
const auto sin = static_cast<T>(framework::math::sin(angle));
const auto x_cos = v[0] * (1 - cos);
const auto y_cos = v[1] * (1 - cos);
const auto z_cos = v[2] * (1 - cos);
const auto x_sin = v[0] * sin;
const auto y_sin = v[1] * sin;
const auto z_sin = v[2] * sin;
// clang-format off
const Matrix<4, 4, T> temp(
v[0] * x_cos + cos, v[1] * x_cos + z_sin, v[2] * x_cos - y_sin, 0,
v[0] * y_cos - z_sin, v[1] * y_cos + cos, v[2] * y_cos + x_sin, 0,
v[0] * z_cos + y_sin, v[1] * z_cos - x_sin, v[2] * z_cos + cos, 0,
0, 0, 0, 1);
// clang-format on
return m * temp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name scale
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Builds a scale 3x3 Matrix created from a vector of 2 components.
///
/// @param m Matrix multiplied by this translation Matrix.
/// @param v Coordinates of a scale vector.
///
/// @return The Matrix which contains scale transformation.
template <typename T>
inline Matrix<3, 3, T> scale(const Matrix<3, 3, T>& m, const Vector<2, T>& v)
{
return Matrix<3, 3, T>(m[0] * v[0], m[1] * v[1], m[2]);
}
/// @brief Builds a scale 4x4 Matrix created from a vector of 3 components.
///
/// @param m Matrix multiplied by this scale Matrix.
/// @param v Ratio of scaling for each axis.
///
/// @return The Matrix which contains scale transformation.
template <typename T>
inline Matrix<4, 4, T> scale(const Matrix<4, 4, T>& m, const Vector<3, T>& v)
{
// clang-format off
const Matrix<4, 4, T> temp(v[0], 0, 0, 0,
0, v[1], 0, 0,
0, 0, v[2], 0,
0, 0, 0, 1);
// clang-format on
return m * temp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name shear
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Builds shear 3x3 Matrix.
///
/// @param m Matrix multiplied by this translation Matrix.
/// @param v Shear factor.
///
/// @return The Matrix which contains shear transformation.
template <typename T>
inline Matrix<3, 3, T> shear(const Matrix<3, 3, T>& m, const Vector<2, T>& v)
{
// clang-format off
const Matrix<3, 3, T> shear(1, v.x, 0,
v.y, 1, 0,
0, 0, 1);
// clang-format on
return m * shear;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name ortho
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Creates a Matrix for an orthographic parallel viewing volume,
/// using right-handedness.
///
/// @param left Left clipping plane.
/// @param right Right clipping plane.
/// @param bottom Bottom clipping plane.
/// @param top Top clipping plane.
/// @param near_val Near clipping plane.
/// @param far_val Far clipping plane.
///
/// @return The orthographic projection Matrix.
template <typename T>
inline Matrix<4, 4, T> ortho(const T left, const T right, const T bottom, const T top, const T near_val, const T far_val)
{
const T ortho_width = right - left;
const T ortho_height = top - bottom;
const T ortho_depth = far_val - near_val;
assert(framework::math::abs(ortho_width - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(ortho_height - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(ortho_depth - std::numeric_limits<T>::epsilon()) > T(0));
// clang-format off
return Matrix<4, 4, T> (
T(2) / ortho_width, 0, 0, 0,
0, T(2) / ortho_height, 0, 0,
0, 0, -T(2) / ortho_depth, 0,
-(right + left) / ortho_width, -(top + bottom) / ortho_height, -(far_val + near_val) / ortho_depth, 1
);
// clang-format on
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name ortho2d
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Creates a Matrix for projecting two-dimensional coordinates
/// onto the screen.
///
/// @param left Left clipping plane.
/// @param right Right clipping plane.
/// @param bottom Bottom clipping plane.
/// @param top Top clipping plane.
///
/// @return The orthographic projection Matrix for two-dimensional space.
template <typename T>
inline Matrix<4, 4, T> ortho2d(const T left, const T right, const T bottom, const T top)
{
return ortho(left, right, bottom, top, -T(1), T(1));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name frustum
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Creates a right handed frustum Matrix.
///
/// @param left Left clipping plane.
/// @param right Right clipping plane.
/// @param bottom Bottom clipping plane.
/// @param top Top clipping plane.
/// @param near_val Distance to the near clipping plane (always positive).
/// @param far_val Distance to the far clipping plane (always positive).
///
/// @return The frustum Matrix.
template <typename T>
inline Matrix<4, 4, T> frustum(const T left,
const T right,
const T bottom,
const T top,
const T near_val,
const T far_val)
{
assert(near_val > T(0));
assert(far_val > T(0));
const T width = right - left;
const T height = top - bottom;
const T depth = far_val - near_val;
assert(framework::math::abs(width - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(height - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(depth - std::numeric_limits<T>::epsilon()) > T(0));
// clang-format off
return Matrix<4, 4, T> (
(T(2) * near_val) / width, 0, 0, 0,
0, (T(2) * near_val) / height, 0, 0,
(right + left) / width, (top + bottom) / height, -(far_val + near_val) / depth, -1,
0, 0, -(T(2) * far_val * near_val) / depth, 0
);
// clang-format on
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name perspective
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Creates a Matrix for a right handed, symmetric perspective-view
/// frustum.
///
/// @param fov_y Specifies the field of view angle in the y direction,
/// in radians.
/// @param aspect Specifies the aspect ratio that determines the field of view
/// in the x direction. The aspect ratio is the ratio of
/// x (width) to y (height).
/// @param near_val Specifies the distance from the viewer to the near clipping
/// plane (always positive).
/// @param far_val Specifies the distance from the viewer to the far clipping
/// plane (always positive).
///
/// @return The perspective projection Matrix.
template <typename T>
inline Matrix<4, 4, T> perspective(T fov_y, T aspect, T near_val, T far_val)
{
assert(near_val > T(0));
assert(far_val > T(0));
const T depth = far_val - near_val;
const T tangent = tan(fov_y / T(2));
assert(framework::math::abs(aspect - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(depth - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(tangent - std::numeric_limits<T>::epsilon()) > T(0));
const T cotangent = T(1) / tangent;
// clang-format off
return Matrix<4, 4, T> (
cotangent / aspect, 0, 0, 0,
0, cotangent, 0, 0,
0, 0, -(far_val + near_val) / depth, -1,
0, 0, -(T(2) * far_val * near_val) / depth, 0
);
// clang-format on
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name perspective_fov
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Builds a right handed perspective projection Matrix based on a
/// field of view.
///
/// @param fov Expressed in radians.
/// @param width Width of the plane (always positive).
/// @param height Height of the plane (always positive).
/// @param near_val Specifies the distance from the viewer to the near clipping
/// plane (always positive).
/// @param far_val Specifies the distance from the viewer to the far clipping
/// plane (always positive).
///
/// @return The perspective projection Matrix.
template <typename T>
inline Matrix<4, 4, T> perspective_fov(T fov, T width, T height, T near_val, T far_val)
{
assert(width > T(0));
assert(height > T(0));
assert(near_val > T(0));
assert(far_val > T(0));
return perspective(fov, width / height, near_val, far_val);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name infinite_perspective
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Creates a Matrix for a right handed, symmetric perspective-view
/// frustum with far plane at infinite.
///
/// @param fov_y Specifies the field of view angle in the y direction,
/// in radians.
/// @param aspect Specifies the aspect ratio that determines the field of
/// view in the x direction. The aspect ratio is the ratio of
/// x (width) to y (height).
/// @param near_val Specifies the distance from the viewer to the near clipping
/// plane (always positive).
///
/// @return The perspective projection Matrix.
template <typename T>
inline Matrix<4, 4, T> infinite_perspective(T fov_y, T aspect, T near_val)
{
assert(near_val > T(0));
assert(framework::math::abs(aspect - std::numeric_limits<T>::epsilon()) > T(0));
const T tangent = math::tan(fov_y / T(2));
assert(framework::math::abs(tangent - std::numeric_limits<T>::epsilon()) > T(0));
const T cotangent = T(1) / tangent;
const T epsilon = std::numeric_limits<T>::epsilon();
// clang-format off
return Matrix<4, 4, T> (
cotangent / aspect, 0, 0, 0,
0, cotangent, 0, 0,
0, 0, epsilon - 1, -1,
0, 0, (epsilon - T(2)) * near_val, 0
);
// clang-format on
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name project
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Map the specified coordinates (v.x, v.y, v.z) into window coordinates.
///
/// @param v Specify the coordinates.
/// @param model Specifies the current model-view Matrix
/// @param projection Specifies the current projection Matrix
/// @param viewport Specifies the current viewport
///
/// @return Return the computed window coordinates.
template <typename T, typename U>
inline Vector<3, T> project(const Vector<3, T>& v,
const Matrix<4, 4, T>& model,
const Matrix<4, 4, T>& projection,
const Vector<4, U>& viewport)
{
Vector<4, T> temp(v, T(1));
temp = projection * model * temp;
assert(framework::math::abs(temp.w - std::numeric_limits<T>::epsilon()) > T(0));
temp /= temp.w;
temp = temp * T(0.5) + T(0.5);
const auto x = static_cast<T>(viewport[0]);
const auto y = static_cast<T>(viewport[1]);
const auto width = static_cast<T>(viewport[2]);
const auto height = static_cast<T>(viewport[3]);
temp[0] = temp[0] * width + x;
temp[1] = temp[1] * height + y;
return Vector<3, T>(temp);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name unproject
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Map the specified window coordinates (v.x, v.y, v.z)
/// into object coordinates.
///
/// @param v Specify the window coordinates to be mapped.
/// @param model Specifies the model-view Matrix
/// @param projection Specifies the projection Matrix
/// @param viewport Specifies the viewport
///
/// @return Returns the computed object coordinates.
template <typename T, typename U>
inline Vector<3, T> unproject(const Vector<3, T>& v,
const Matrix<4, 4, T>& model,
const Matrix<4, 4, T>& projection,
const Vector<4, U>& viewport)
{
const auto x = static_cast<T>(viewport[0]);
const auto y = static_cast<T>(viewport[1]);
const auto width = static_cast<T>(viewport[2]);
const auto height = static_cast<T>(viewport[3]);
assert(framework::math::abs(width - std::numeric_limits<T>::epsilon()) > T(0));
assert(framework::math::abs(height - std::numeric_limits<T>::epsilon()) > T(0));
const Matrix<4, 4, T> inverse = framework::math::inverse(projection * model);
Vector<4, T> temp(v, T(1));
temp.x = (temp.x - x) / width;
temp.y = (temp.y - y) / height;
temp = temp * T(2) - T(1);
Vector<4, T> object_matrix = inverse * temp;
assert(framework::math::abs(temp.w - std::numeric_limits<T>::epsilon()) > T(0));
object_matrix /= object_matrix.w;
return Vector<3, T>(object_matrix);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name pick_matrix
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Define a picking region.
///
/// Creates a projection Matrix that can be used to restrict drawing to
/// a small region of the viewport.
///
/// @param center Center of region in window coordinates.
/// @param delta Width and height of region in window coordinates.
/// @param viewport Specifies the viewport.
///
/// @return The region Matrix.
template <typename T, typename U>
inline Matrix<4, 4, T> pick_matrix(const Vector<2, T>& center, const Vector<2, T>& delta, const Vector<4, U>& viewport)
{
assert(delta.x > T(0));
assert(delta.y > T(0));
const auto x = static_cast<T>(viewport[0]);
const auto y = static_cast<T>(viewport[1]);
const auto width = static_cast<T>(viewport[2]);
const auto height = static_cast<T>(viewport[3]);
const Vector<3, T> translate_temp = {(width - T(2) * (center.x - x)) / delta.x,
(height - T(2) * (center.y - y)) / delta.y,
T(0)};
const Vector<3, T> scale_temp = {width / delta.x, height / delta.y, T(1)};
// Translate and scale the picked region to the entire window
// clang-format off
Matrix<4, 4, T> temp(scale_temp[0], 0, 0, 0,
0, scale_temp[1], 0, 0,
0, 0, scale_temp[2], 0,
translate_temp[0], translate_temp[1], translate_temp[2], 1);
// clang-format on
return temp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name look_at
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Build a right handed look at view Matrix.
///
/// Creates a viewing Matrix derived from an eye point,
/// a reference point indicating the center of the scene, and an up vector
///
/// @param eye Position of the camera
/// @param center Position where the camera is looking at
/// @param up Normalized up vector, how the camera is oriented.
/// Typically (0, 1, 0)
///
/// @return The viewing Matrix.
template <typename T>
inline Matrix<4, 4, T> look_at(const Vector<3, T>& eye, const Vector<3, T>& center, const Vector<3, T>& up)
{
const Vector<3, T> forward = normalize(center - eye);
const Vector<3, T> side = normalize(cross(forward, up));
const Vector<3, T> new_up = cross(side, forward);
// clang-format off
return Matrix<4, 4, T> {
side.x, new_up.x, -forward.x, 0,
side.y, new_up.y, -forward.y, 0,
side.z, new_up.z, -forward.z, 0,
-dot(side, eye), -dot(new_up, eye), dot(forward, eye), 1
};
// clang-format on
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace framework::math
#endif
| 42.930976 | 121 | 0.407592 | [
"object",
"vector",
"model"
] |
ba0ecb4a2019f1fa3560555d2f4ea96297fa93b2 | 3,436 | cpp | C++ | Calculate_lattice.cpp | camille-PM/cube_parametric_study | 38f8c4c5a1fd4586ba5285ba02341fe0ed682b2a | [
"Apache-2.0"
] | null | null | null | Calculate_lattice.cpp | camille-PM/cube_parametric_study | 38f8c4c5a1fd4586ba5285ba02341fe0ed682b2a | [
"Apache-2.0"
] | null | null | null | Calculate_lattice.cpp | camille-PM/cube_parametric_study | 38f8c4c5a1fd4586ba5285ba02341fe0ed682b2a | [
"Apache-2.0"
] | null | null | null | #include <fstream>
#include <iostream>
#include <vector>
#include "header.h"
using namespace std;
/************************************************************
CALCULATE LATTICE
Compute minimum and maximum lattice coordinates
depending on FEA geometry
*************************************************************/
void Calculate_lattice(vector<Nodes>& lattice_element, vector<Point_abaqus>& lattice_node_position, float Global_min[3], float Global_max[3])
{
float xmin,xmax;
float ymin,ymax;
float zmin,zmax;
int size_x,size_y,size_z;
int node,element;
int j;
node=lattice_element[0].n1;
xmin=lattice_node_position[node-1].x;
xmax=lattice_node_position[node-1].x;
ymin=lattice_node_position[node-1].y;
ymax=lattice_node_position[node-1].y;
zmin=lattice_node_position[node-1].z;
zmax=lattice_node_position[node-1].z;
for (element=0;element<lattice_element.size();element++) {
for (j=0;j<4;j++) {
if (j==0) {
node=lattice_element[element].n0;
}
if (j==1) {
node=lattice_element[element].n1;
}
if (j==2) {
node=lattice_element[element].n2;
}
if (j==3) {
node=lattice_element[element].n3;
}
if (lattice_node_position[node-1].x<xmin && lattice_node_position[node-1].x!=999999)
{
xmin=lattice_node_position[node-1].x;
}
if (lattice_node_position[node-1].x>xmax && lattice_node_position[node-1].x!=999999)
{
xmax=lattice_node_position[node-1].x;
}
if (lattice_node_position[node-1].y<ymin && lattice_node_position[node-1].y!=999999)
{
ymin=lattice_node_position[node-1].y;
}
if (lattice_node_position[node-1].y>ymax && lattice_node_position[node-1].y!=999999)
{
ymax=lattice_node_position[node-1].y;
}
if (lattice_node_position[node-1].z<zmin && lattice_node_position[node-1].z!=999999)
{
zmin=lattice_node_position[node-1].z;
}
if (lattice_node_position[node-1].z>zmax && lattice_node_position[node-1].z!=999999)
{
zmax=lattice_node_position[node-1].z;
}
//system("PAUSE");
}
}
Global_min[0]=xmin;
Global_min[1]=ymin;
Global_min[2]=zmin-0.5; // global min in the lattice model is 0.5mm lower than in Abaqus
// cout<<"Global minimum x: "<<Global_min[0]<<endl;
// cout<<"Global minimum y: "<<Global_min[1]<<endl;
// cout<<"Global minimum z: "<<Global_min[2]<<endl;
Global_max[0]=xmax;
Global_max[1]=ymax;
Global_max[2]=zmax+0.5;
/* cout<<"Global maximum x: "<<Global_max[0]<<endl;
cout<<"Global maximum y: "<<Global_max[1]<<endl;
cout<<"Global maximum z: "<<Global_max[2]<<endl;
// Global lattice dimensions
size_x=int(((xmax-xmin)/CELL_DIAMETER)+0.5)+1;
size_y=int(((ymax-ymin)/CELL_DIAMETER)+0.5)+1;
size_z=int(((zmax-zmin)/CELL_DIAMETER)+0.5)+1;
cout<<"number cells x direction: "<<x<<endl;
cout<<"number cells y direction: "<<y<<endl;
cout<<"number cells z direction: "<<z<<endl;
system("PAUSE"); */
}
| 32.72381 | 142 | 0.551222 | [
"geometry",
"vector",
"model"
] |
ba0f947fdd91a39a42e5ccdb0b8fbef43269e5c0 | 5,127 | cpp | C++ | pgadmin/hotdraw/main/hdDrawing.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 111 | 2015-01-02T15:39:46.000Z | 2022-01-08T05:08:20.000Z | pgadmin/hotdraw/main/hdDrawing.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 13 | 2015-07-08T20:26:20.000Z | 2019-06-17T12:45:35.000Z | pgadmin/hotdraw/main/hdDrawing.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 96 | 2015-03-11T14:06:44.000Z | 2022-02-07T10:04:45.000Z | //////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
//
// Copyright (C) 2002 - 2016, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// hdDrawing.cpp - Main storage class for all objects of the diagram,
// their functions are used by model and shouldn't be called directly
//////////////////////////////////////////////////////////////////////////
#include "pgAdmin3.h"
// wxWindows headers
#include <wx/wx.h>
// App headers
#include "hotdraw/main/hdDrawing.h"
#include "hotdraw/main/hdDrawingView.h"
#include "hotdraw/main/hdDrawingEditor.h"
#include "hotdraw/utilities/hdArrayCollection.h"
#include "hotdraw/utilities/hdRect.h"
#include "hotdraw/figures/hdIFigure.h"
hdDrawing::hdDrawing(hdDrawingEditor *owner)
{
figures = new hdCollection(new hdArrayCollection());
selection = new hdCollection(new hdArrayCollection());
usedView = NULL;
ownerEditor = owner;
drawingName = wxEmptyString;
}
hdDrawing::~hdDrawing()
{
//clear selection
if(selection)
{
selection->removeAll();
delete selection;
}
//Cannot delete figures, because they belong to model not to diagram
hdIFigure *tmp;
while(figures->count() > 0)
{
tmp = (hdIFigure *) figures->getItemAt(0);
figures->removeItemAt(0);
}
if(figures)
delete figures;
}
void hdDrawing::add(hdIFigure *figure)
{
if(figures)
figures->addItem(figure);
}
void hdDrawing::remove(hdIFigure *figure)
{
if(figures)
{
figures->removeItem(figure);
if(usedView)
figure->moveTo(usedView->getIdx(), -1, -1);
}
}
bool hdDrawing::includes(hdIFigure *figure)
{
if(figures)
return figures->existsObject(figure);
return false;
}
hdIFigure *hdDrawing::findFigure(int posIdx, int x, int y)
{
hdIFigure *tmp = NULL, *out = NULL;
hdIteratorBase *iterator = figures->createIterator();
while(iterator->HasNext())
{
tmp = (hdIFigure *)iterator->Next();
if(tmp->containsPoint(posIdx, x, y))
{
out = tmp;
break;
}
}
delete iterator;;
return out;
}
void hdDrawing::recalculateDisplayBox(int posIdx)
{
bool first = true;
hdIFigure *figure = NULL;
hdIteratorBase *iterator = figures->createIterator();
while(iterator->HasNext())
{
figure = (hdIFigure *)iterator->Next();
if(first)
{
displayBox = figure->displayBox().gethdRect(posIdx);
first = false;
}
else
{
displayBox.add(figure->displayBox().gethdRect(posIdx));
}
}
delete iterator;
}
void hdDrawing::bringToFront(hdIFigure *figure)
{
//To bring to front this figure need to be at last position when is draw
//because this reason sendToBack (last position) is used.
figures->sendToBack(figure);
}
void hdDrawing::sendToBack(hdIFigure *figure)
{
//To send to back this figure need to be at first position when is draw
//because this reason bringToFront (1st position) is used.
figures->bringToFront(figure);
}
hdRect &hdDrawing::DisplayBox()
{
return displayBox;
}
hdIteratorBase *hdDrawing::figuresEnumerator()
{
return figures->createIterator();
}
hdIteratorBase *hdDrawing::figuresInverseEnumerator()
{
return figures->createDownIterator();
}
void hdDrawing::deleteAllFigures()
{
selection->removeAll();
hdIFigure *tmp;
while(figures->count() > 0)
{
tmp = (hdIFigure *) figures->getItemAt(0);
figures->removeItemAt(0);
delete tmp;
}
//handles delete it together with figures
}
void hdDrawing::removeAllFigures()
{
selection->removeAll();
hdIFigure *tmp;
while(figures->count() > 0)
{
tmp = (hdIFigure *) figures->getItemAt(0);
figures->removeItemAt(0);
if(usedView)
tmp->moveTo(usedView->getIdx(), -1, -1);
}
}
void hdDrawing::deleteSelectedFigures()
{
//Allow to customize delete dialog at Editor
ownerEditor->remOrDelSelFigures(usedView->getIdx());
}
void hdDrawing::addToSelection(hdIFigure *figure)
{
if(!selection)
{
selection = new hdCollection(new hdArrayCollection());
}
if(figure)
{
figure->setSelected(usedView->getIdx(), true);
selection->addItem(figure);
}
}
void hdDrawing::addToSelection(hdCollection *figures)
{
}
void hdDrawing::removeFromSelection(hdIFigure *figure)
{
figure->setSelected(usedView->getIdx(), false);
if(selection)
selection->removeItem(figure);
}
void hdDrawing::toggleSelection(hdIFigure *figure)
{
if(figure->isSelected(usedView->getIdx()) && selection->existsObject(figure))
selection->removeItem(figure);
else if(!figure->isSelected(usedView->getIdx()) && this->includes(figure))
selection->addItem(figure);
figure->setSelected(usedView->getIdx(), !figure->isSelected(usedView->getIdx()));
}
void hdDrawing::clearSelection()
{
hdIFigure *tmp = NULL;
hdIteratorBase *iterator = selection->createIterator();
while(iterator->HasNext())
{
tmp = (hdIFigure *)iterator->Next();
tmp->setSelected(usedView->getIdx(), false);
}
selection->removeAll();
delete iterator;
}
bool hdDrawing::isFigureSelected(hdIFigure *figure)
{
return selection->existsObject(figure);
}
hdIteratorBase *hdDrawing::selectionFigures()
{
return selection->createIterator();
}
int hdDrawing::countSelectedFigures()
{
return selection->count();
}
| 20.841463 | 82 | 0.697094 | [
"model"
] |
ba144a4cb1d36082f830befd116aa303bce6e476 | 24,155 | cpp | C++ | src/irr/asset/CPLYMeshFileLoader.cpp | WieszKto/IrrlichtBAW | bcef8386c2ca7f06ff006b866c397035551a2351 | [
"Apache-2.0"
] | null | null | null | src/irr/asset/CPLYMeshFileLoader.cpp | WieszKto/IrrlichtBAW | bcef8386c2ca7f06ff006b866c397035551a2351 | [
"Apache-2.0"
] | null | null | null | src/irr/asset/CPLYMeshFileLoader.cpp | WieszKto/IrrlichtBAW | bcef8386c2ca7f06ff006b866c397035551a2351 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2009-2012 Gaz Davidson
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_PLY_LOADER_
#include <numeric>
#include "CPLYMeshFileLoader.h"
#include "irr/asset/IMeshManipulator.h"
#include "irr/video/CGPUMesh.h"
#include "IReadFile.h"
#include "os.h"
namespace irr
{
namespace asset
{
// input buffer must be at least twice as long as the longest line in the file
#define PLY_INPUT_BUFFER_SIZE 51200 // file is loaded in 50k chunks
// constructor
CPLYMeshFileLoader::CPLYMeshFileLoader()
{
}
CPLYMeshFileLoader::~CPLYMeshFileLoader()
{
}
bool CPLYMeshFileLoader::isALoadableFileFormat(io::IReadFile* _file) const
{
const char* headers[3]{
"format ascii 1.0",
"format binary_little_endian 1.0",
"format binary_big_endian 1.0"
};
const size_t prevPos = _file->getPos();
char buf[40];
_file->seek(0u);
_file->read(buf, sizeof(buf));
_file->seek(prevPos);
char* header = buf;
if (strncmp(header, "ply", 3u) != 0)
return false;
header += 4;
char* lf = strstr(header, "\n");
if (!lf)
return false;
*lf = 0;
for (uint32_t i = 0u; i < 3u; ++i)
if (strcmp(header, headers[i]) == 0)
return true;
return false;
}
//! creates/loads an animated mesh from the file.
asset::SAssetBundle CPLYMeshFileLoader::loadAsset(io::IReadFile* _file, const asset::IAssetLoader::SAssetLoadParams& _params, asset::IAssetLoader::IAssetLoaderOverride* _override, uint32_t _hierarchyLevel)
{
if (!_file)
return {};
SContext ctx;
ctx.File = _file;
ctx.File->grab();
// attempt to allocate the buffer and fill with data
if (!allocateBuffer(ctx))
{
return {};
}
core::smart_refctd_ptr<asset::CCPUMesh> mesh;
uint32_t vertCount = 0;
// Currently only supports ASCII meshes
if (strcmp(getNextLine(ctx), "ply"))
{
os::Printer::log("Not a valid PLY file", ctx.File->getFileName().c_str(), ELL_ERROR);
}
else
{
// cut the next line out
getNextLine(ctx);
// grab the word from this line
char* word = getNextWord(ctx);
// ignore comments
while (strcmp(word, "comment") == 0)
{
getNextLine(ctx);
word = getNextWord(ctx);
}
bool readingHeader = true;
bool continueReading = true;
ctx.IsBinaryFile = false;
ctx.IsWrongEndian= false;
do
{
if (strcmp(word, "format") == 0)
{
word = getNextWord(ctx);
if (strcmp(word, "binary_little_endian") == 0)
{
ctx.IsBinaryFile = true;
}
else if (strcmp(word, "binary_big_endian") == 0)
{
ctx.IsBinaryFile = true;
ctx.IsWrongEndian = true;
}
else if (strcmp(word, "ascii"))
{
// abort if this isn't an ascii or a binary mesh
os::Printer::log("Unsupported PLY mesh format", word, ELL_ERROR);
continueReading = false;
}
if (continueReading)
{
word = getNextWord(ctx);
if (strcmp(word, "1.0"))
{
os::Printer::log("Unsupported PLY mesh version", word, ELL_WARNING);
}
}
}
else if (strcmp(word, "property") == 0)
{
word = getNextWord(ctx);
if (!ctx.ElementList.size())
{
os::Printer::log("PLY property found before element", word, ELL_WARNING);
}
else
{
// get element
SPLYElement* el = ctx.ElementList[ctx.ElementList.size()-1];
// fill property struct
SPLYProperty prop;
prop.Type = getPropertyType(word);
el->KnownSize += prop.size();
if (prop.Type == EPLYPT_LIST)
{
el->IsFixedWidth = false;
word = getNextWord(ctx);
prop.Data.List.CountType = getPropertyType(word);
if (ctx.IsBinaryFile && prop.Data.List.CountType == EPLYPT_UNKNOWN)
{
os::Printer::log("Cannot read binary PLY file containing data types of unknown length", word, ELL_ERROR);
continueReading = false;
}
else
{
word = getNextWord(ctx);
prop.Data.List.ItemType = getPropertyType(word);
if (ctx.IsBinaryFile && prop.Data.List.ItemType == EPLYPT_UNKNOWN)
{
os::Printer::log("Cannot read binary PLY file containing data types of unknown length", word, ELL_ERROR);
continueReading = false;
}
}
}
else if (ctx.IsBinaryFile && prop.Type == EPLYPT_UNKNOWN)
{
os::Printer::log("Cannot read binary PLY file containing data types of unknown length", word, ELL_ERROR);
continueReading = false;
}
prop.Name = getNextWord(ctx);
// add property to element
el->Properties.push_back(prop);
}
}
else if (strcmp(word, "element") == 0)
{
SPLYElement* el = new SPLYElement;
el->Name = getNextWord(ctx);
el->Count = atoi(getNextWord(ctx));
el->IsFixedWidth = true;
el->KnownSize = 0;
ctx.ElementList.push_back(el);
if (el->Name == "vertex")
vertCount = el->Count;
}
else if (strcmp(word, "end_header") == 0)
{
readingHeader = false;
if (ctx.IsBinaryFile)
{
ctx.StartPointer = ctx.LineEndPointer + 1;
}
}
else if (strcmp(word, "comment") == 0)
{
// ignore line
}
else
{
os::Printer::log("Unknown item in PLY file", word, ELL_WARNING);
}
if (readingHeader && continueReading)
{
getNextLine(ctx);
word = getNextWord(ctx);
}
}
while (readingHeader && continueReading);
// now to read the actual data from the file
if (continueReading)
{
// create a mesh buffer
auto mb = core::make_smart_refctd_ptr<asset::ICPUMeshBuffer>();
auto desc = core::make_smart_refctd_ptr<asset::ICPUMeshDataFormatDesc>();
core::vector<core::vectorSIMDf> attribs[4];
core::vector<uint32_t> indices;
bool hasNormals = true;
// loop through each of the elements
for (uint32_t i=0; i<ctx.ElementList.size(); ++i)
{
// do we want this element type?
if (ctx.ElementList[i]->Name == "vertex")
{
// loop through vertex properties
for (uint32_t j=0; j<ctx.ElementList[i]->Count; ++j)
hasNormals &= readVertex(ctx, *ctx.ElementList[i], attribs, _params);
}
else if (ctx.ElementList[i]->Name == "face")
{
// read faces
for (uint32_t j=0; j < ctx.ElementList[i]->Count; ++j)
readFace(ctx, *ctx.ElementList[i], indices);
}
else
{
// skip these elements
for (uint32_t j = 0; j < ctx.ElementList[i]->Count; ++j)
skipElement(ctx, *ctx.ElementList[i]);
}
}
if (indices.size())
{
auto idxBuf = core::make_smart_refctd_ptr<asset::ICPUBuffer>(indices.size() * sizeof(uint32_t));
memcpy(idxBuf->getPointer(), indices.data(), idxBuf->getSize());
desc->setIndexBuffer(std::move(idxBuf));
mb->setIndexCount(indices.size());
mb->setIndexType(asset::EIT_32BIT);
mb->setPrimitiveType(asset::EPT_TRIANGLES);
}
else
{
mb->setPrimitiveType(asset::EPT_POINTS);
mb->setIndexCount(attribs[E_POS].size());
//mb->getMaterial().setFlag(video::EMF_POINTCLOUD, true);
}
mb->setMeshDataAndFormat(std::move(desc));
if (!genVertBuffersForMBuffer(mb.get(), attribs))
return {};
mb->recalculateBoundingBox();
//if (!hasNormals)
// SceneManager->getMeshManipulator()->recalculateNormals(mb);
mesh = core::make_smart_refctd_ptr<CCPUMesh>();
mesh->addMeshBuffer(std::move(mb));
mesh->recalculateBoundingBox(true);
}
}
return SAssetBundle({ mesh });
}
bool CPLYMeshFileLoader::readVertex(SContext& _ctx, const SPLYElement& Element, core::vector<core::vectorSIMDf> _outAttribs[4], const asset::IAssetLoader::SAssetLoadParams& _params)
{
if (!_ctx.IsBinaryFile)
getNextLine(_ctx);
std::pair<bool, core::vectorSIMDf> attribs[4];
attribs[E_COL].second.W = 1.f;
attribs[E_NORM].second.Y = 1.f;
bool result = false;
for (uint32_t i = 0; i < Element.Properties.size(); ++i)
{
E_PLY_PROPERTY_TYPE t = Element.Properties[i].Type;
if (Element.Properties[i].Name == "x")
{
attribs[E_POS].second.X = getFloat(_ctx, t);
attribs[E_POS].first = true;
}
else if (Element.Properties[i].Name == "y")
{
attribs[E_POS].second.Y = getFloat(_ctx, t);
attribs[E_POS].first = true;
}
else if (Element.Properties[i].Name == "z")
{
attribs[E_POS].second.Z = getFloat(_ctx, t);
attribs[E_POS].first = true;
}
else if (Element.Properties[i].Name == "nx")
{
attribs[E_NORM].second.X = getFloat(_ctx, t);
attribs[E_NORM].first = result = true;
}
else if (Element.Properties[i].Name == "ny")
{
attribs[E_NORM].second.Y = getFloat(_ctx, t);
attribs[E_NORM].first = result = true;
}
else if (Element.Properties[i].Name == "nz")
{
attribs[E_NORM].second.Z = getFloat(_ctx, t);
attribs[E_NORM].first = result = true;
}
// there isn't a single convention for the UV, some softwares like Blender or Assimp use "st" instead of "uv"
else if (Element.Properties[i].Name == "u" || Element.Properties[i].Name == "s")
{
attribs[E_UV].second.X = getFloat(_ctx, t);
attribs[E_UV].first = true;
}
else if (Element.Properties[i].Name == "v" || Element.Properties[i].Name == "t")
{
attribs[E_UV].second.Y = getFloat(_ctx, t);
attribs[E_UV].first = true;
}
else if (Element.Properties[i].Name == "red")
{
float value = Element.Properties[i].isFloat() ? getFloat(_ctx, t) : float(getInt(_ctx, t)) / 255.f;
attribs[E_COL].second.X = value;
attribs[E_COL].first = true;
}
else if (Element.Properties[i].Name == "green")
{
float value = Element.Properties[i].isFloat() ? getFloat(_ctx, t) : float(getInt(_ctx, t)) / 255.f;
attribs[E_COL].second.Y = value;
attribs[E_COL].first = true;
}
else if (Element.Properties[i].Name == "blue")
{
float value = Element.Properties[i].isFloat() ? getFloat(_ctx, t) : float(getInt(_ctx, t)) / 255.f;
attribs[E_COL].second.Z = value;
attribs[E_COL].first = true;
}
else if (Element.Properties[i].Name == "alpha")
{
float value = Element.Properties[i].isFloat() ? getFloat(_ctx, t) : float(getInt(_ctx, t)) / 255.f;
attribs[E_COL].second.W = value;
attribs[E_COL].first = true;
}
else
skipProperty(_ctx, Element.Properties[i]);
}
for (size_t i = 0u; i < 4u; ++i)
if (attribs[i].first)
{
if (_params.loaderFlags & E_LOADER_PARAMETER_FLAGS::ELPF_RIGHT_HANDED_MESHES)
{
if (i == E_POS)
performActionBasedOnOrientationSystem<float>(attribs[E_POS].second.X, [](float& varToFlip) { varToFlip = -varToFlip; });
else if (i == E_NORM)
performActionBasedOnOrientationSystem<float>(attribs[E_NORM].second.X, [](float& varToFlip) { varToFlip = -varToFlip; });
}
_outAttribs[i].push_back(attribs[i].second);
}
return result;
}
bool CPLYMeshFileLoader::readFace(SContext& _ctx, const SPLYElement& Element, core::vector<uint32_t>& _outIndices)
{
if (!_ctx.IsBinaryFile)
getNextLine(_ctx);
for (uint32_t i = 0; i < Element.Properties.size(); ++i)
{
if ((Element.Properties[i].Name == "vertex_indices" ||
Element.Properties[i].Name == "vertex_index") && Element.Properties[i].Type == EPLYPT_LIST)
{
int32_t count = getInt(_ctx, Element.Properties[i].Data.List.CountType);
//_IRR_DEBUG_BREAK_IF(count != 3)
uint32_t a = getInt(_ctx, Element.Properties[i].Data.List.ItemType),
b = getInt(_ctx, Element.Properties[i].Data.List.ItemType),
c = getInt(_ctx, Element.Properties[i].Data.List.ItemType);
int32_t j = 3;
_outIndices.push_back(a);
_outIndices.push_back(b);
_outIndices.push_back(c);
for (; j < count; ++j)
{
b = c;
c = getInt(_ctx, Element.Properties[i].Data.List.ItemType);
_outIndices.push_back(a);
_outIndices.push_back(c);
_outIndices.push_back(b);
}
}
else if (Element.Properties[i].Name == "intensity")
{
// todo: face intensity
skipProperty(_ctx, Element.Properties[i]);
}
else
skipProperty(_ctx, Element.Properties[i]);
}
return true;
}
// skips an element and all properties. return false on EOF
void CPLYMeshFileLoader::skipElement(SContext& _ctx, const SPLYElement& Element)
{
if (_ctx.IsBinaryFile)
if (Element.IsFixedWidth)
moveForward(_ctx, Element.KnownSize);
else
for (uint32_t i = 0; i < Element.Properties.size(); ++i)
skipProperty(_ctx, Element.Properties[i]);
else
getNextLine(_ctx);
}
void CPLYMeshFileLoader::skipProperty(SContext& _ctx, const SPLYProperty &Property)
{
if (Property.Type == EPLYPT_LIST)
{
int32_t count = getInt(_ctx, Property.Data.List.CountType);
for (int32_t i=0; i < count; ++i)
getInt(_ctx, Property.Data.List.CountType);
}
else
{
if (_ctx.IsBinaryFile)
moveForward(_ctx, Property.size());
else
getNextWord(_ctx);
}
}
bool CPLYMeshFileLoader::allocateBuffer(SContext& _ctx)
{
// Destroy the element list if it exists
for (uint32_t i=0; i<_ctx.ElementList.size(); ++i)
delete _ctx.ElementList[i];
_ctx.ElementList.clear();
if (!_ctx.Buffer)
_ctx.Buffer = new char[PLY_INPUT_BUFFER_SIZE];
// not enough memory?
if (!_ctx.Buffer)
return false;
// blank memory
memset(_ctx.Buffer, 0, PLY_INPUT_BUFFER_SIZE);
_ctx.StartPointer = _ctx.Buffer;
_ctx.EndPointer = _ctx.Buffer;
_ctx.LineEndPointer = _ctx.Buffer - 1;
_ctx.WordLength = -1;
_ctx.EndOfFile = false;
// get data from the file
fillBuffer(_ctx);
return true;
}
// gets more data from the file. returns false on EOF
void CPLYMeshFileLoader::fillBuffer(SContext& _ctx)
{
if (_ctx.EndOfFile)
return;
uint32_t length = (uint32_t)(_ctx.EndPointer - _ctx.StartPointer);
if (length && _ctx.StartPointer != _ctx.Buffer)
{
// copy the remaining data to the start of the buffer
memcpy(_ctx.Buffer, _ctx.StartPointer, length);
}
// reset start position
_ctx.StartPointer = _ctx.Buffer;
_ctx.EndPointer = _ctx.StartPointer + length;
if (_ctx.File->getPos() == _ctx.File->getSize())
{
_ctx.EndOfFile = true;
}
else
{
// read data from the file
uint32_t count = _ctx.File->read(_ctx.EndPointer, PLY_INPUT_BUFFER_SIZE - length);
// increment the end pointer by the number of bytes read
_ctx.EndPointer = _ctx.EndPointer + count;
// if we didn't completely fill the buffer
if (count != PLY_INPUT_BUFFER_SIZE - length)
{
// blank the rest of the memory
memset(_ctx.EndPointer, 0, _ctx.Buffer + PLY_INPUT_BUFFER_SIZE - _ctx.EndPointer);
// end of file
_ctx.EndOfFile = true;
}
}
}
// skips x bytes in the file, getting more data if required
void CPLYMeshFileLoader::moveForward(SContext& _ctx, uint32_t bytes)
{
if (_ctx.StartPointer + bytes >= _ctx.EndPointer)
fillBuffer(_ctx);
if (_ctx.StartPointer + bytes < _ctx.EndPointer)
_ctx.StartPointer += bytes;
else
_ctx.StartPointer = +_ctx.EndPointer;
}
bool CPLYMeshFileLoader::genVertBuffersForMBuffer(asset::ICPUMeshBuffer* _mbuf, const core::vector<core::vectorSIMDf> _attribs[4]) const
{
{
size_t check = _attribs[0].size();
for (size_t i = 1u; i < 4u; ++i)
{
if (_attribs[i].size() != 0u && _attribs[i].size() != check)
return false;
else if (_attribs[i].size() != 0u)
check = _attribs[i].size();
}
}
auto putAttr = [&_attribs](asset::ICPUMeshBuffer* _buf, size_t _attr, asset::E_VERTEX_ATTRIBUTE_ID _vaid)
{
size_t i = 0u;
for (const core::vectorSIMDf& v : _attribs[_attr])
_buf->setAttribute(v, _vaid, i++);
};
size_t sizes[4];
sizes[E_POS] = !_attribs[E_POS].empty() * 3 * sizeof(float);
sizes[E_COL] = !_attribs[E_COL].empty() * 4 * sizeof(float);
sizes[E_UV] = !_attribs[E_UV].empty() * 2 * sizeof(float);
sizes[E_NORM] = !_attribs[E_NORM].empty() * 3 * sizeof(float);
size_t offsets[4]{ 0u };
for (size_t i = 1u; i < 4u; ++i)
offsets[i] = offsets[i - 1] + sizes[i - 1];
const size_t stride = std::accumulate(sizes, sizes + 4, static_cast<size_t>(0));
{
auto desc = _mbuf->getMeshDataAndFormat();
auto buf = core::make_smart_refctd_ptr<asset::ICPUBuffer>(_attribs[E_POS].size() * stride);
memcpy(buf->getPointer(), _attribs[E_POS].data(), buf->getSize());
if (sizes[E_POS])
desc->setVertexAttrBuffer(core::smart_refctd_ptr(buf), asset::EVAI_ATTR0, asset::EF_R32G32B32_SFLOAT, stride, offsets[E_POS]);
if (sizes[E_COL])
desc->setVertexAttrBuffer(core::smart_refctd_ptr(buf), asset::EVAI_ATTR1, asset::EF_R32G32B32A32_SFLOAT, stride, offsets[E_COL]);
if (sizes[E_UV])
desc->setVertexAttrBuffer(core::smart_refctd_ptr(buf), asset::EVAI_ATTR2, asset::EF_R32G32_SFLOAT, stride, offsets[E_UV]);
if (sizes[E_NORM])
desc->setVertexAttrBuffer(core::smart_refctd_ptr(buf), asset::EVAI_ATTR3, asset::EF_R32G32B32_SFLOAT, stride, offsets[E_NORM]);
}
asset::E_VERTEX_ATTRIBUTE_ID vaids[4];
vaids[E_POS] = asset::EVAI_ATTR0;
vaids[E_COL] = asset::EVAI_ATTR1;
vaids[E_UV] = asset::EVAI_ATTR2;
vaids[E_NORM] = asset::EVAI_ATTR3;
for (size_t i = 0u; i < 4u; ++i)
{
if (sizes[i])
putAttr(_mbuf, i, vaids[i]);
}
return true;
}
E_PLY_PROPERTY_TYPE CPLYMeshFileLoader::getPropertyType(const char* typeString) const
{
if (strcmp(typeString, "char") == 0 ||
strcmp(typeString, "uchar") == 0 ||
strcmp(typeString, "int8") == 0 ||
strcmp(typeString, "uint8") == 0)
{
return EPLYPT_INT8;
}
else if (strcmp(typeString, "uint") == 0 ||
strcmp(typeString, "int16") == 0 ||
strcmp(typeString, "uint16") == 0 ||
strcmp(typeString, "short") == 0 ||
strcmp(typeString, "ushort") == 0)
{
return EPLYPT_INT16;
}
else if (strcmp(typeString, "int") == 0 ||
strcmp(typeString, "long") == 0 ||
strcmp(typeString, "ulong") == 0 ||
strcmp(typeString, "int32") == 0 ||
strcmp(typeString, "uint32") == 0)
{
return EPLYPT_INT32;
}
else if (strcmp(typeString, "float") == 0 ||
strcmp(typeString, "float32") == 0)
{
return EPLYPT_FLOAT32;
}
else if (strcmp(typeString, "float64") == 0 ||
strcmp(typeString, "double") == 0)
{
return EPLYPT_FLOAT64;
}
else if (strcmp(typeString, "list") == 0)
{
return EPLYPT_LIST;
}
else
{
// unsupported type.
// cannot be loaded in binary mode
return EPLYPT_UNKNOWN;
}
}
// Split the string data into a line in place by terminating it instead of copying.
char* CPLYMeshFileLoader::getNextLine(SContext& _ctx)
{
// move the start pointer along
_ctx.StartPointer = _ctx.LineEndPointer + 1;
// crlf split across buffer move
if (*_ctx.StartPointer == '\n')
{
*_ctx.StartPointer = '\0';
++_ctx.StartPointer;
}
// begin at the start of the next line
char* pos = _ctx.StartPointer;
while (pos < _ctx.EndPointer && *pos && *pos != '\r' && *pos != '\n')
++pos;
if (pos < _ctx.EndPointer && (*(pos + 1) == '\r' || *(pos + 1) == '\n'))
{
*pos = '\0';
++pos;
}
// we have reached the end of the buffer
if (pos >= _ctx.EndPointer)
{
// get data from the file
if (!_ctx.EndOfFile)
{
fillBuffer(_ctx);
// reset line end pointer
_ctx.LineEndPointer = _ctx.StartPointer - 1;
if (_ctx.StartPointer != _ctx.EndPointer)
return getNextLine(_ctx);
else
return _ctx.Buffer;
}
else
{
// EOF
_ctx.StartPointer = _ctx.EndPointer - 1;
*_ctx.StartPointer = '\0';
return _ctx.StartPointer;
}
}
else
{
// null terminate the string in place
*pos = '\0';
_ctx.LineEndPointer = pos;
_ctx.WordLength = -1;
// return pointer to the start of the line
return _ctx.StartPointer;
}
}
// null terminate the next word on the previous line and move the next word pointer along
// since we already have a full line in the buffer, we never need to retrieve more data
char* CPLYMeshFileLoader::getNextWord(SContext& _ctx)
{
// move the start pointer along
_ctx.StartPointer += _ctx.WordLength + 1;
if (!*_ctx.StartPointer)
getNextLine(_ctx);
if (_ctx.StartPointer == _ctx.LineEndPointer)
{
_ctx.WordLength = -1; //
return _ctx.LineEndPointer;
}
// begin at the start of the next word
char* pos = _ctx.StartPointer;
while (*pos && pos < _ctx.LineEndPointer && pos < _ctx.EndPointer && *pos != ' ' && *pos != '\t')
++pos;
while (*pos && pos < _ctx.LineEndPointer && pos < _ctx.EndPointer && (*pos == ' ' || *pos == '\t'))
{
// null terminate the string in place
*pos = '\0';
++pos;
}
--pos;
_ctx.WordLength = (int32_t)(pos - _ctx.StartPointer);
// return pointer to the start of the word
return _ctx.StartPointer;
}
// read the next float from the file and move the start pointer along
float CPLYMeshFileLoader::getFloat(SContext& _ctx, E_PLY_PROPERTY_TYPE t)
{
float retVal = 0.0f;
if (_ctx.IsBinaryFile)
{
if (_ctx.EndPointer - _ctx.StartPointer < 8)
fillBuffer(_ctx);
if (_ctx.EndPointer - _ctx.StartPointer > 0)
{
switch (t)
{
case EPLYPT_INT8:
retVal = *_ctx.StartPointer;
_ctx.StartPointer++;
break;
case EPLYPT_INT16:
if (_ctx.IsWrongEndian)
retVal = os::Byteswap::byteswap(*(reinterpret_cast<int16_t*>(_ctx.StartPointer)));
else
retVal = *(reinterpret_cast<int16_t*>(_ctx.StartPointer));
_ctx.StartPointer += 2;
break;
case EPLYPT_INT32:
if (_ctx.IsWrongEndian)
retVal = float(os::Byteswap::byteswap(*(reinterpret_cast<int32_t*>(_ctx.StartPointer))));
else
retVal = float(*(reinterpret_cast<int32_t*>(_ctx.StartPointer)));
_ctx.StartPointer += 4;
break;
case EPLYPT_FLOAT32:
if (_ctx.IsWrongEndian)
retVal = os::Byteswap::byteswap(*(reinterpret_cast<float*>(_ctx.StartPointer)));
else
retVal = *(reinterpret_cast<float*>(_ctx.StartPointer));
_ctx.StartPointer += 4;
break;
case EPLYPT_FLOAT64:
char tmp[8];
memcpy(tmp, _ctx.StartPointer, 8);
if (_ctx.IsWrongEndian)
for (size_t i = 0u; i < 4u; ++i)
std::swap(tmp[i], tmp[7u - i]);
retVal = float(*(reinterpret_cast<double*>(tmp)));
_ctx.StartPointer += 8;
break;
case EPLYPT_LIST:
case EPLYPT_UNKNOWN:
default:
retVal = 0.0f;
_ctx.StartPointer++; // ouch!
}
}
else
retVal = 0.0f;
}
else
{
char* word = getNextWord(_ctx);
switch (t)
{
case EPLYPT_INT8:
case EPLYPT_INT16:
case EPLYPT_INT32:
retVal = float(atoi(word));
break;
case EPLYPT_FLOAT32:
case EPLYPT_FLOAT64:
retVal = float(atof(word));
break;
case EPLYPT_LIST:
case EPLYPT_UNKNOWN:
default:
retVal = 0.0f;
}
}
return retVal;
}
// read the next int from the file and move the start pointer along
uint32_t CPLYMeshFileLoader::getInt(SContext& _ctx, E_PLY_PROPERTY_TYPE t)
{
uint32_t retVal = 0;
if (_ctx.IsBinaryFile)
{
if (!_ctx.EndOfFile && _ctx.EndPointer - _ctx.StartPointer < 8)
fillBuffer(_ctx);
if (_ctx.EndPointer - _ctx.StartPointer)
{
switch (t)
{
case EPLYPT_INT8:
retVal = *_ctx.StartPointer;
_ctx.StartPointer++;
break;
case EPLYPT_INT16:
if (_ctx.IsWrongEndian)
retVal = os::Byteswap::byteswap(*(reinterpret_cast<uint16_t*>(_ctx.StartPointer)));
else
retVal = *(reinterpret_cast<uint16_t*>(_ctx.StartPointer));
_ctx.StartPointer += 2;
break;
case EPLYPT_INT32:
if (_ctx.IsWrongEndian)
retVal = os::Byteswap::byteswap(*(reinterpret_cast<int32_t*>(_ctx.StartPointer)));
else
retVal = *(reinterpret_cast<int32_t*>(_ctx.StartPointer));
_ctx.StartPointer += 4;
break;
case EPLYPT_FLOAT32:
if (_ctx.IsWrongEndian)
retVal = (uint32_t)os::Byteswap::byteswap(*(reinterpret_cast<float*>(_ctx.StartPointer)));
else
retVal = (uint32_t)(*(reinterpret_cast<float*>(_ctx.StartPointer)));
_ctx.StartPointer += 4;
break;
case EPLYPT_FLOAT64:
// todo: byteswap 64-bit
retVal = (uint32_t)(*(reinterpret_cast<double*>(_ctx.StartPointer)));
_ctx.StartPointer += 8;
break;
case EPLYPT_LIST:
case EPLYPT_UNKNOWN:
default:
retVal = 0;
_ctx.StartPointer++; // ouch!
}
}
else
retVal = 0;
}
else
{
char* word = getNextWord(_ctx);
switch (t)
{
case EPLYPT_INT8:
case EPLYPT_INT16:
case EPLYPT_INT32:
retVal = atoi(word);
break;
case EPLYPT_FLOAT32:
case EPLYPT_FLOAT64:
retVal = uint32_t(atof(word));
break;
case EPLYPT_LIST:
case EPLYPT_UNKNOWN:
default:
retVal = 0;
}
}
return retVal;
}
} // end namespace scene
} // end namespace irr
#endif // _IRR_COMPILE_WITH_PLY_LOADER_
| 26.001076 | 205 | 0.656593 | [
"mesh",
"vector"
] |
ba17eae96cdad7c78951cfca5f58e2c2f45ed63e | 13,091 | cpp | C++ | aten/src/ATen/core/boxing/KernelFunction_test.cpp | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | null | null | null | aten/src/ATen/core/boxing/KernelFunction_test.cpp | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | null | null | null | aten/src/ATen/core/boxing/KernelFunction_test.cpp | wenhaopeter/read_pytorch_code | 491f989cd918cf08874dd4f671fb7f0142a0bc4f | [
"Intel",
"X11"
] | null | null | null | #include <gtest/gtest.h>
#include <ATen/core/boxing/KernelFunction.h>
#include <ATen/core/boxing/impl/test_helpers.h>
#include <ATen/core/op_registration/op_registration.h>
using std::vector;
using std::tuple;
using c10::optional;
using c10::IValue;
using c10::OperatorKernel;
using c10::OperatorHandle;
using c10::Stack;
using c10::KernelFunction;
namespace {
namespace kernels {
// This namespace contains several fake kernels.
// All kernels expect to be called with two int64_t arguments and store
// these arguments in called_with_args.
// The kernels with a return value return a single int value: 5.
// The expectXXX() functions further below use these invariants
// to check that calling a specific kernels works correctly.
optional<tuple<int64_t, int64_t>> called_with_args;
void boxed_func_with_return(const OperatorHandle& /*opHandle*/, Stack* stack) {
EXPECT_EQ(2, stack->size());
EXPECT_TRUE(stack->at(0).isInt());
EXPECT_TRUE(stack->at(1).isInt());
called_with_args = tuple<int64_t, int64_t>(stack->at(0).toInt(), stack->at(1).toInt());
stack->clear();
stack->push_back(5);
}
void boxed_func_without_return(const OperatorHandle& /*opHandle*/, Stack* stack) {
EXPECT_EQ(2, stack->size());
EXPECT_TRUE(stack->at(0).isInt());
EXPECT_TRUE(stack->at(1).isInt());
called_with_args = tuple<int64_t, int64_t>(stack->at(0).toInt(), stack->at(1).toInt());
stack->clear();
}
struct unboxed_functor_with_return final : OperatorKernel {
int64_t operator()(int64_t a, int64_t b) {
called_with_args = tuple<int64_t, int64_t>(a, b);
return 5;
}
};
struct unboxed_functor_without_return final : OperatorKernel {
void operator()(int64_t a, int64_t b) {
called_with_args = tuple<int64_t, int64_t>(a, b);
}
};
struct unboxed_functor_with_return_factory final {
std::unique_ptr<OperatorKernel> operator()() {
return std::make_unique<unboxed_functor_with_return>();
}
};
struct unboxed_functor_without_return_factory final {
std::unique_ptr<OperatorKernel> operator()() {
return std::make_unique<unboxed_functor_without_return>();
}
};
int64_t unboxed_function_with_return(int64_t a, int64_t b) {
called_with_args = tuple<int64_t, int64_t>(a, b);
return 5;
}
void unboxed_function_without_return(int64_t a, int64_t b) {
called_with_args = tuple<int64_t, int64_t>(a, b);
}
auto unboxed_lambda_with_return = [] (int64_t a, int64_t b) -> int64_t {
called_with_args = tuple<int64_t, int64_t>(a, b);
return 5;
};
auto unboxed_lambda_without_return = [] (int64_t a, int64_t b) -> void{
called_with_args = tuple<int64_t, int64_t>(a, b);
};
OperatorHandle makeDummyOperatorHandle() {
static auto registry = torch::RegisterOperators().op("my::dummy() -> ()");
return c10::Dispatcher::singleton().findSchema({"my::dummy", ""}).value();
}
void expectBoxedCallingWithReturnWorks(const KernelFunction& func) {
called_with_args = c10::nullopt;
vector<IValue> stack {3, 4};
OperatorHandle dummy = makeDummyOperatorHandle();
func.callBoxed(dummy, &stack);
EXPECT_TRUE(called_with_args.has_value());
EXPECT_EQ((tuple<int64_t, int64_t>(3, 4)), *called_with_args);
EXPECT_EQ(1, stack.size());
EXPECT_TRUE(stack[0].isInt());
EXPECT_EQ(5, stack[0].toInt());
}
void expectBoxedCallingWithoutReturnWorks(const KernelFunction& func) {
called_with_args = c10::nullopt;
vector<IValue> stack {3, 4};
OperatorHandle dummy = makeDummyOperatorHandle();
func.callBoxed(dummy, &stack);
EXPECT_TRUE(called_with_args.has_value());
EXPECT_EQ((tuple<int64_t, int64_t>(3, 4)), *called_with_args);
EXPECT_EQ(0, stack.size());
}
void expectBoxedCallingFailsWith(const KernelFunction& func, const char* errorMessage) {
called_with_args = c10::nullopt;
vector<IValue> stack {3, 4};
OperatorHandle dummy = makeDummyOperatorHandle();
expectThrows<c10::Error>([&] {
func.callBoxed(dummy, &stack);
}, errorMessage);
}
void expectUnboxedCallingWithReturnWorks(const KernelFunction& func) {
called_with_args = c10::nullopt;
OperatorHandle dummy = makeDummyOperatorHandle();
int64_t result = func.call<int64_t, int64_t, int64_t>(dummy, 3, 4);
EXPECT_TRUE(called_with_args.has_value());
EXPECT_EQ((tuple<int64_t, int64_t>(3, 4)), *called_with_args);
EXPECT_EQ(5, result);
}
void expectUnboxedCallingWithoutReturnWorks(const KernelFunction& func) {
called_with_args = c10::nullopt;
OperatorHandle dummy = makeDummyOperatorHandle();
func.call<void, int64_t, int64_t>(dummy, 3, 4);
EXPECT_TRUE(called_with_args.has_value());
EXPECT_EQ((tuple<int64_t, int64_t>(3, 4)), *called_with_args);
}
}
TEST(KernelFunctionTest, givenBoxedFunction_withReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromBoxedFunction<&kernels::boxed_func_with_return>();
kernels::expectBoxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenBoxedFunction_withoutReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromBoxedFunction<&kernels::boxed_func_without_return>();
kernels::expectBoxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenBoxedFunction_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromBoxedFunction<&kernels::boxed_func_with_return>();
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenBoxedFunction_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromBoxedFunction<&kernels::boxed_func_without_return>();
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunctor_withReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunctor<false, kernels::unboxed_functor_with_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_with_return>()));
kernels::expectBoxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunctor_withoutReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunctor<false, kernels::unboxed_functor_without_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_without_return>()));
kernels::expectBoxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunctor_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunctor<false, kernels::unboxed_functor_with_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_with_return>()));
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunctor_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunctor<false, kernels::unboxed_functor_without_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_without_return>()));
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunctor_withReturn_whenCallingBoxed_thenFails) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunctor<kernels::unboxed_functor_with_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_with_return>()));
kernels::expectBoxedCallingFailsWith(func, "Tried to call KernelFunction::callBoxed() on a KernelFunction that can only be called with KernelFunction::call()");
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunctor_withoutReturn_whenCallingBoxed_thenFails) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunctor<kernels::unboxed_functor_without_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_without_return>()));
kernels::expectBoxedCallingFailsWith(func, "Tried to call KernelFunction::callBoxed() on a KernelFunction that can only be called with KernelFunction::call()");
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunctor_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunctor<kernels::unboxed_functor_with_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_with_return>()));
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunctor_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunctor<kernels::unboxed_functor_without_return>(std::unique_ptr<OperatorKernel>(std::make_unique<kernels::unboxed_functor_without_return>()));
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunction_withReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunction(TORCH_FN(kernels::unboxed_function_with_return));
kernels::expectBoxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunction_withoutReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunction(TORCH_FN(kernels::unboxed_function_without_return));
kernels::expectBoxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunction_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunction(TORCH_FN(kernels::unboxed_function_with_return));
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedFunction_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedFunction(TORCH_FN(kernels::unboxed_function_without_return));
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunction_withReturn_whenCallingBoxed_thenFails) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunction(TORCH_FN(kernels::unboxed_function_with_return));
kernels::expectBoxedCallingFailsWith(func, "Tried to call KernelFunction::callBoxed() on a KernelFunction that can only be called with KernelFunction::call()");
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunction_withoutReturn_whenCallingBoxed_thenFails) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunction(TORCH_FN(kernels::unboxed_function_without_return));
kernels::expectBoxedCallingFailsWith(func, "Tried to call KernelFunction::callBoxed() on a KernelFunction that can only be called with KernelFunction::call()");
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunction_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunction(TORCH_FN(kernels::unboxed_function_with_return));
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedOnlyFunction_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedOnlyFunction(TORCH_FN(kernels::unboxed_function_without_return));
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedRuntimeFunction_withReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedRuntimeFunction(&kernels::unboxed_function_with_return);
kernels::expectBoxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedRuntimeFunction_withoutReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedRuntimeFunction(&kernels::unboxed_function_without_return);
kernels::expectBoxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedRuntimeFunction_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedRuntimeFunction(&kernels::unboxed_function_with_return);
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedRuntimeFunction_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedRuntimeFunction(&kernels::unboxed_function_without_return);
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedLambda_withReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedLambda(kernels::unboxed_lambda_with_return);
kernels::expectBoxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedLambda_withoutReturn_whenCallingBoxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedLambda(kernels::unboxed_lambda_without_return);
kernels::expectBoxedCallingWithoutReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedLambda_withReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedLambda(kernels::unboxed_lambda_with_return);
kernels::expectUnboxedCallingWithReturnWorks(func);
}
TEST(KernelFunctionTest, givenUnboxedLambda_withoutReturn_whenCallingUnboxed_thenWorks) {
KernelFunction func = KernelFunction::makeFromUnboxedLambda(kernels::unboxed_lambda_without_return);
kernels::expectUnboxedCallingWithoutReturnWorks(func);
}
}
// TODO Also test different variants of calling unboxed with wrong signatures
| 44.376271 | 205 | 0.816286 | [
"vector"
] |
ba1b4cf72c79e9a47f799f3393459ece99d381bf | 8,207 | hpp | C++ | pe.ui.object.hpp | FSMargoo/PhotoEditor | 5fdefd31c3a972003cc3d84a482dcb9c719acab8 | [
"MIT"
] | null | null | null | pe.ui.object.hpp | FSMargoo/PhotoEditor | 5fdefd31c3a972003cc3d84a482dcb9c719acab8 | [
"MIT"
] | null | null | null | pe.ui.object.hpp | FSMargoo/PhotoEditor | 5fdefd31c3a972003cc3d84a482dcb9c719acab8 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////
// pe.ui.obhect.h:
// @description : The basic head in UI kits
// @brith : 2022/1/24
//
#pragma once
#include "pe.ui.trigger.hpp"
#include <functional>
#include <map>
#ifdef _DEBUG
# include <time.h>
#endif
namespace PDotE
{
namespace UI
{
#define Rectangle 0
#define RoundedRectangle 1
#define Circle 2
class Object : public Trigger
{
protected:
bool batch_mode = false;
bool redraw = false;
protected:
bool used_to_focus = false;
bool is_invisble = true;
unsigned long child_id = 0;
unsigned long parent_id = 0;
short free_count = 0;
bool lock_status = false;
protected:
LOGFONT _font;
std::map<unsigned long, Object*> child_object;
Object* parent = nullptr;
short radius = 0;
short geomtery_type = Rectangle;
IMAGE* object_content;
// 0 : Normal
// 1 : On cover
// 2 : Pushed
short status = 0;
public:
virtual void PDraw(bool callFromParent = false)
{
settextstyle(&_font);
if (is_invisble == false)
{
if (parent != nullptr &&
callFromParent == false)
{
parent->PDraw();
return;
}
if (batch_mode == true)
{
redraw = true;
return;
}
object_content = new IMAGE(width, height);
SetWorkingImage();
if (parent != nullptr)
{
SetWorkingImage(parent->object_content);
}
getimage(object_content, x, y, width, height);
SetWorkingImage();
if (parent == nullptr)
{
Draw();
getimage(object_content, x, y, width, height);
}
else
{
SetWorkingImage(object_content);
Draw();
SetWorkingImage();
}
for (auto item = child_object.begin(); item != child_object.end(); ++item)
{
item->second->PDraw(true);
}
if (parent == nullptr)
{
object_content->Resize(width, height);
SetWorkingImage();
putimage(x, y, object_content);
}
else
{
SetWorkingImage(parent->object_content);
putimage(x, y, object_content);
SetWorkingImage();
}
delete object_content;
object_content = nullptr;
}
}
public:
virtual void Draw()
{
}
void Show()
{
is_invisble = false;
PDraw();
}
void Hide()
{
is_invisble = true;
if (parent != nullptr)
{
parent->PDraw();
}
}
virtual void Move(int nx, int ny)
{
x = nx;
y = ny;
PDraw();
}
virtual void Resize(int nwidth, int nheight)
{
width = nwidth;
height = nheight;
PDraw();
if (geomtery_type == 0)
{
CreateRectangleMask(width, height);
}
else if (geomtery_type == 1)
{
CreateRoundRectangleMask(width, height, radius);
}
else if (geomtery_type == 2)
{
CreateCircleMask(width, height);
}
}
public:
bool IsVisble()
{
return is_invisble;
}
public:
Object(int nwidth = 0, int nheight = 0, Object* nparent = nullptr)
{
if (GetHWnd() != NULL)
{
gettextstyle(&_font);
}
width = nwidth;
height = nheight;
if (geomtery_type == 0)
{
CreateRectangleMask(width, height);
}
else if (geomtery_type == 1)
{
CreateRoundRectangleMask(width, height, radius);
}
else if (geomtery_type == 2)
{
CreateCircleMask(width, height);
}
SetParent(nparent);
}
public:
void SetParent(Object* nparent)
{
if (parent != nullptr)
{
parent->child_object.erase(parent_id);
parent->PDraw();
}
parent = nparent;
if (parent != nullptr)
{
++nparent->child_id;
parent_id = nparent->child_id;
parent->child_object.insert(std::pair<unsigned long long, Object*>
(parent_id, this));
}
}
Object* GetParent()
{
return parent;
}
public:
virtual void LeftButtonOnClicked(ExMessage message)
{
}
virtual void RightButtonOnClicked(ExMessage message)
{
}
virtual void MouseCoverd(ExMessage message)
{
}
virtual void MouseLeft(ExMessage message)
{
}
public:
virtual void CheckMouseOut(ExMessage message)
{
if (is_invisble == true)
{
return;
}
if (IsTrigger(message) == false)
{
if (used_to_focus == true)
{
used_to_focus = false;
MouseLeft(message);
}
}
else
{
message.x -= x;
message.y -= y;
for (auto& child : child_object)
{
child.second->CheckMouseOut(message);
}
}
}
virtual bool ProcessMessage(ExMessage message, bool calle_from_parent = false)
{
if (is_invisble == true)
{
return false;
}
if (IsTrigger(message) == true)
{
used_to_focus = true;
message.x -= x;
message.y -= y;
bool repaint = false;
// Idk why , but i wrote this code and the program ran successfully :)
for (auto item = child_object.rbegin(); item != child_object.rend();
++item)
{
item->second->CheckMouseOut(message);
}
for (auto item = child_object.rbegin(); item != child_object.rend();
++item)
{
item->second->SetBatchDraw(false);
if (item->second->ProcessMessage(message, true) == true)
{
if (item->second->redraw == true)
{
item->second->redraw = false;
if (calle_from_parent == false)
{
repaint = true;
}
else
{
redraw = true;
}
}
if (calle_from_parent == false)
{
if (repaint == true)
{
PDraw();
}
FlushBatchDraw();
}
return true;
}
}
switch (message.message)
{
case WM_LBUTTONDOWN:
{
LeftButtonOnClicked(message);
break;
}
case WM_RBUTTONDOWN:
{
RightButtonOnClicked(message);
break;
}
default:
{
MouseCoverd(message);
break;
}
}
if (calle_from_parent == false)
{
FlushBatchDraw();
}
return true;
}
if (calle_from_parent == false)
{
FlushBatchDraw();
}
return false;
}
public:
void SetFontStyle(LOGFONT style, bool calle_from_parent = false)
{
int height = _font.lfHeight;
_font = style;
_font.lfHeight = height;
for (auto& item : child_object)
{
item.second->SetFontStyle(style, true);
}
if (calle_from_parent == false)
{
PDraw();
}
}
public:
void ShowOffChild(bool calle_from_parent = false)
{
is_invisble = false;
for (auto& item : child_object)
{
if (item.second->lock_status == false)
{
item.second->is_invisble = false;
item.second->ShowOffChild(true);
}
}
if (calle_from_parent == false)
{
PDraw();
}
}
void HideOffChild(bool calle_from_parent = false)
{
for (auto& item : child_object)
{
if (item.second->lock_status == false)
{
item.second->is_invisble = true;
item.second->HideOffChild(true);
}
}
if (calle_from_parent == false)
{
PDraw();
}
}
Object* GetChild(int id)
{
return child_object[id];
}
unsigned long GetID()
{
return parent_id;
}
void LockStatus(bool nstatus)
{
lock_status = nstatus;
}
void SetTextHeight(int fheight)
{
_font.lfHeight = fheight;
PDraw();
}
void SetBatchDraw(bool value)
{
batch_mode = value;
}
void SetRedraw(bool value)
{
redraw = value;
}
void ClearChild()
{
child_object.clear();
}
};
}
}
| 17.026971 | 82 | 0.516998 | [
"object"
] |
ba1c09090b77ca4278047bb665b2c919c879270a | 932 | cpp | C++ | 010958.cpp | anirudhkannanvp/UVA-OJ | e62029c2152f49c7e1229bd00be5309cce1352c8 | [
"MIT"
] | null | null | null | 010958.cpp | anirudhkannanvp/UVA-OJ | e62029c2152f49c7e1229bd00be5309cce1352c8 | [
"MIT"
] | null | null | null | 010958.cpp | anirudhkannanvp/UVA-OJ | e62029c2152f49c7e1229bd00be5309cce1352c8 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include<bitset>
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
ll _sieve_size;
bitset<1000000> bs;
vi primes;
void sieve(ll upper){
_sieve_size=upper+1;
bs.set();
bs[0]=bs[1]=0;
for(ll i=2;i<=_sieve_size;i++){
if(bs[i]){
for(ll j=2*i;j<=_sieve_size;j+=i)
{
bs[j]=0;
}
primes.push_back(i);
}
}
return;
}
ll numdiv(ll N){
ll PF_idx=0,PF=primes[PF_idx],ans=1;
while(PF * PF <=N){
ll power=0;
while(N%PF==0){N/=PF;power+=1;}
ans*=(power+1);
PF=primes[++PF_idx];
}
if(N!=1) ans*=2;
return ans;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
sieve(1000000);
ll m,n,p,i,ca;
ca=0;
while(cin>>m>>n>>p){
ca++;
if(m==n && n==p && p==0)
break;
cout<<"Case "<<ca<<": "<<2*numdiv(abs(m*n*p*p))-1<<"\n";
}return 0;
}
| 15.79661 | 72 | 0.51073 | [
"vector"
] |
ba1c2e8a9f044909b48bcf8081e282a098d6fb8e | 78,649 | cpp | C++ | code/model/modelinterp.cpp | SelfGamer/fs2open.github.com | 6a68300fccffa20f12cad45bb45325d8e43c364b | [
"Unlicense"
] | null | null | null | code/model/modelinterp.cpp | SelfGamer/fs2open.github.com | 6a68300fccffa20f12cad45bb45325d8e43c364b | [
"Unlicense"
] | null | null | null | code/model/modelinterp.cpp | SelfGamer/fs2open.github.com | 6a68300fccffa20f12cad45bb45325d8e43c364b | [
"Unlicense"
] | 1 | 2021-05-22T16:37:50.000Z | 2021-05-22T16:37:50.000Z | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#define MODEL_LIB
#include "bmpman/bmpman.h"
#include "cmdline/cmdline.h"
#include "debugconsole/console.h"
#include "gamesequence/gamesequence.h"
#include "gamesnd/gamesnd.h"
#include "globalincs/alphacolors.h"
#include "globalincs/linklist.h"
#include "graphics/2d.h"
#include "graphics/util/GPUMemoryHeap.h"
#include "io/key.h"
#include "io/timer.h"
#include "math/fvi.h"
#include "math/staticrand.h"
#include "mission/missionparse.h"
#include "model/modelrender.h"
#include "model/modelsinc.h"
#include "nebula/neb.h"
#include "parse/parselo.h"
#include "particle/particle.h"
#include "render/3dinternal.h"
#include "ship/ship.h"
#include "ship/shipfx.h"
#include "weapon/shockwave.h"
#include "tracing/Monitor.h"
#include "tracing/tracing.h"
#include <climits>
float model_radius = 0;
// Some debug variables used externally for displaying stats
#ifndef NDEBUG
int modelstats_num_polys = 0;
int modelstats_num_polys_drawn = 0;
int modelstats_num_verts = 0;
int modelstats_num_sortnorms = 0;
int modelstats_num_boxes = 0;
#endif
extern fix game_get_overall_frametime(); // for texture animation
typedef struct model_light {
ubyte r, g, b;
ubyte spec_r, spec_g, spec_b;
} model_light;
// a lighting object
typedef struct model_light_object {
model_light *lights;
int objnum;
int skip;
int skip_max;
} model_light_object;
struct bsp_vertex
{
vec3d position;
vec3d normal;
uv_pair tex_coord;
ubyte r, g, b, a;
};
struct bsp_polygon
{
uint Start_index;
uint Num_verts;
int texture;
};
class bsp_polygon_data
{
SCP_vector<vec3d> Vertex_list;
SCP_vector<vec3d> Normal_list;
SCP_vector<bsp_vertex> Polygon_vertices;
SCP_vector<bsp_polygon> Polygons;
ubyte* Lights;
int Num_polies[MAX_MODEL_TEXTURES];
int Num_verts[MAX_MODEL_TEXTURES];
int Num_flat_polies;
int Num_flat_verts;
void process_bsp(int offset, ubyte* bsp_data);
void process_defpoints(int off, ubyte* bsp_data);
void process_sortnorm(int offset, ubyte* bsp_data);
void process_tmap(int offset, ubyte* bsp_data);
void process_flat(int offset, ubyte* bsp_data);
public:
bsp_polygon_data(ubyte* bsp_data);
int get_num_triangles(int texture);
int get_num_lines(int texture);
void generate_triangles(int texture, vertex *vert_ptr, vec3d* norm_ptr);
void generate_lines(int texture, vertex *vert_ptr);
};
/**
* @brief Vertex structure for passing data to the GPU
*/
struct interp_vertex {
uv_pair uv;
vec3d normal;
vec4 tangent;
float modelId;
vec3d pos;
};
// -----------------------
// Local variables
//
static int Num_interp_verts_allocated = 0;
vec3d **Interp_verts = NULL;
static vertex *Interp_points = NULL;
static vertex *Interp_splode_points = NULL;
vec3d *Interp_splode_verts = NULL;
static int Interp_num_verts = 0;
static float Interp_box_scale = 1.0f; // this is used to scale both detail boxes and spheres
// -------------------------------------------------------------------
// lighting save stuff
//
model_light_object Interp_lighting_temp;
model_light_object *Interp_lighting = &Interp_lighting_temp;
int Interp_use_saved_lighting = 0;
int Interp_saved_lighting_full = 0;
//
// lighting save stuff
// -------------------------------------------------------------------
static int Num_interp_norms_allocated = 0;
static vec3d **Interp_norms = NULL;
static ubyte *Interp_light_applied = NULL;
static int Interp_num_norms = 0;
static ubyte *Interp_lights;
// Stuff to control rendering parameters
static color Interp_outline_color;
static int Interp_detail_level_locked = -1;
static uint Interp_flags = 0;
// If non-zero, then the subobject gets scaled by Interp_thrust_scale.
int Interp_thrust_scale_subobj = 0;
float Interp_thrust_scale = 0.1f;
static float Interp_thrust_scale_x = 0.0f;//added -bobboau
static float Interp_thrust_scale_y = 0.0f;//added -bobboau
static int Interp_thrust_bitmap = -1;
static int Interp_thrust_glow_bitmap = -1;
static float Interp_thrust_glow_noise = 1.0f;
static bool Interp_afterburner = false;
// Bobboau's thruster stuff
static int Interp_secondary_thrust_glow_bitmap = -1;
static int Interp_tertiary_thrust_glow_bitmap = -1;
static int Interp_distortion_thrust_bitmap = -1;
static float Interp_thrust_glow_rad_factor = 1.0f;
static float Interp_secondary_thrust_glow_rad_factor = 1.0f;
static float Interp_tertiary_thrust_glow_rad_factor = 1.0f;
static float Interp_distortion_thrust_rad_factor = 1.0f;
static float Interp_distortion_thrust_length_factor = 1.0f;
static float Interp_thrust_glow_len_factor = 1.0f;
static vec3d Interp_thrust_rotvel = ZERO_VECTOR;
static bool Interp_draw_distortion = true;
// Bobboau's warp stuff
static float Interp_warp_scale_x = 1.0f;
static float Interp_warp_scale_y = 1.0f;
static float Interp_warp_scale_z = 1.0f;
// if != -1, use this bitmap when rendering ship insignias
static int Interp_insignia_bitmap = -1;
// if != -1, use this bitmap when rendering with a forced texture
static int Interp_forced_bitmap = -1;
// our current level of detail (LOD)
int Interp_detail_level = 0;
// forward references
int model_should_render_engine_glow(int objnum, int bank_obj);
int model_interp_get_texture(texture_info *tinfo, fix base_frametime);
void model_deallocate_interp_data()
{
if (Interp_verts != NULL)
vm_free(Interp_verts);
if (Interp_points != NULL)
vm_free(Interp_points);
if (Interp_splode_points != NULL)
vm_free(Interp_splode_points);
if (Interp_splode_verts != NULL)
vm_free(Interp_splode_verts);
if (Interp_norms != NULL)
vm_free(Interp_norms);
if (Interp_light_applied != NULL)
vm_free(Interp_light_applied);
if (Interp_lighting_temp.lights != NULL)
vm_free(Interp_lighting_temp.lights);
Num_interp_verts_allocated = 0;
Num_interp_norms_allocated = 0;
}
extern void model_collide_allocate_point_list(int n_points);
extern void model_collide_free_point_list();
void model_allocate_interp_data(int n_verts, int n_norms)
{
static ubyte dealloc = 0;
if (!dealloc) {
atexit(model_deallocate_interp_data);
atexit(model_collide_free_point_list);
dealloc = 1;
}
Assert( (n_verts >= 0) && (n_norms >= 0) );
Assert( (n_verts || Num_interp_verts_allocated) && (n_norms || Num_interp_norms_allocated) );
if (n_verts > Num_interp_verts_allocated) {
if (Interp_verts != NULL) {
vm_free(Interp_verts);
Interp_verts = NULL;
}
// Interp_verts can't be reliably realloc'd so free and malloc it on each resize (no data needs to be carried over)
Interp_verts = (vec3d**) vm_malloc( n_verts * sizeof(vec3d *) );
Interp_points = (vertex*) vm_realloc( Interp_points, n_verts * sizeof(vertex) );
Interp_splode_points = (vertex*) vm_realloc( Interp_splode_points, n_verts * sizeof(vertex) );
Interp_splode_verts = (vec3d*) vm_realloc( Interp_splode_verts, n_verts * sizeof(vec3d) );
Num_interp_verts_allocated = n_verts;
// model collide needs a similar size to resize it based on this new value
model_collide_allocate_point_list( n_verts );
}
if (n_norms > Num_interp_norms_allocated) {
if (Interp_norms != NULL) {
vm_free(Interp_norms);
Interp_norms = NULL;
}
// Interp_norms can't be reliably realloc'd so free and malloc it on each resize (no data needs to be carried over)
Interp_norms = (vec3d**) vm_malloc( n_norms * sizeof(vec3d *) );
// these next two lighting things aren't values that need to be carried over, but we need to make sure they are 0 by default
if (Interp_light_applied != NULL) {
vm_free(Interp_light_applied);
Interp_light_applied = NULL;
}
if (Interp_lighting_temp.lights != NULL) {
vm_free(Interp_lighting_temp.lights);
Interp_lighting_temp.lights = NULL;
}
Interp_light_applied = (ubyte*) vm_malloc( n_norms * sizeof(ubyte) );
Interp_lighting_temp.lights = (model_light*) vm_malloc( n_norms * sizeof(model_light) );
memset( Interp_light_applied, 0, n_norms * sizeof(ubyte) );
memset( Interp_lighting_temp.lights, 0, n_norms * sizeof(model_light) );
Num_interp_norms_allocated = n_norms;
}
Interp_num_verts = n_verts;
Interp_num_norms = n_norms;
// check that everything is still usable (works in release and debug builds)
Verify( Interp_points != NULL );
Verify( Interp_splode_points != NULL );
Verify( Interp_verts != NULL );
Verify( Interp_splode_verts != NULL );
Verify( Interp_norms != NULL );
Verify( Interp_light_applied != NULL );
}
void interp_clear_instance()
{
Interp_thrust_scale = 0.1f;
Interp_thrust_scale_x = 0.0f;//added-Bobboau
Interp_thrust_scale_y = 0.0f;//added-Bobboau
Interp_thrust_bitmap = -1;
Interp_thrust_glow_bitmap = -1;
Interp_thrust_glow_noise = 1.0f;
Interp_insignia_bitmap = -1;
Interp_afterburner = false;
// Bobboau's thruster stuff
{
Interp_thrust_glow_rad_factor = 1.0f;
Interp_secondary_thrust_glow_bitmap = -1;
Interp_secondary_thrust_glow_rad_factor = 1.0f;
Interp_tertiary_thrust_glow_bitmap = -1;
Interp_tertiary_thrust_glow_rad_factor = 1.0f;
Interp_thrust_glow_len_factor = 1.0f;
vm_vec_zero(&Interp_thrust_rotvel);
}
Interp_box_scale = 1.0f;
Interp_detail_level_locked = -1;
Interp_forced_bitmap = -1;
}
/**
* Scales the engines thrusters by this much
*/
void model_set_thrust(int /*model_num*/, mst_info *mst)
{
if (mst == NULL) {
Int3();
return;
}
Interp_thrust_scale = mst->length.xyz.z;
Interp_thrust_scale_x = mst->length.xyz.x;
Interp_thrust_scale_y = mst->length.xyz.y;
CLAMP(Interp_thrust_scale, 0.1f, 1.0f);
Interp_thrust_bitmap = mst->primary_bitmap;
Interp_thrust_glow_bitmap = mst->primary_glow_bitmap;
Interp_secondary_thrust_glow_bitmap = mst->secondary_glow_bitmap;
Interp_tertiary_thrust_glow_bitmap = mst->tertiary_glow_bitmap;
Interp_distortion_thrust_bitmap = mst->distortion_bitmap;
Interp_thrust_glow_noise = mst->glow_noise;
Interp_afterburner = mst->use_ab;
Interp_thrust_rotvel = mst->rotvel;
Interp_thrust_glow_rad_factor = mst->glow_rad_factor;
Interp_secondary_thrust_glow_rad_factor = mst->secondary_glow_rad_factor;
Interp_tertiary_thrust_glow_rad_factor = mst->tertiary_glow_rad_factor;
Interp_thrust_glow_len_factor = mst->glow_length_factor;
Interp_distortion_thrust_rad_factor = mst->distortion_rad_factor;
Interp_distortion_thrust_length_factor = mst->distortion_length_factor;
Interp_draw_distortion = mst->draw_distortion;
}
bool splodeing = false;
int splodeingtexture = -1;
float splode_level = 0.0f;
float GEOMETRY_NOISE = 0.0f;
// Point list
// +0 int id
// +4 int size
// +8 int n_verts
// +12 int n_norms
// +16 int offset from start of chunk to vertex data
// +20 n_verts*char norm_counts
// +offset vertex data. Each vertex n is a point followed by norm_counts[n] normals.
void model_interp_splode_defpoints(ubyte * p, polymodel * /*pm*/, bsp_info * /*sm*/, float dist)
{
if(dist==0.0f)return;
if(dist<0.0f)dist*=-1.0f;
int n;
int nverts = w(p+8);
int offset = w(p+16);
int nnorms = 0;
ubyte * normcount = p+20;
vertex *dest = Interp_splode_points;
vec3d *src = vp(p+offset);
for (n = 0; n < nverts; n++) {
nnorms += normcount[n];
}
model_allocate_interp_data(nverts, nnorms);
vec3d dir;
for (n=0; n<nverts; n++ ) {
Interp_splode_verts[n] = *src;
src++;
vm_vec_avg_n(&dir, normcount[n], src);
vm_vec_normalize(&dir);
for(int i=0; i<normcount[n]; i++)src++;
vm_vec_scale_add2(&Interp_splode_verts[n], &dir, dist);
g3_rotate_vertex(dest, &Interp_splode_verts[n]);
dest++;
}
}
// Point list
// +0 int id
// +4 int size
// +8 int n_verts
// +12 int n_norms
// +16 int offset from start of chunk to vertex data
// +20 n_verts*char norm_counts
// +offset vertex data. Each vertex n is a point followed by norm_counts[n] normals.
void model_interp_defpoints(ubyte * p, polymodel *pm, bsp_info *sm)
{
if(splodeing)model_interp_splode_defpoints(p, pm, sm, splode_level*model_radius);
int i, n;
int nverts = w(p+8);
int offset = w(p+16);
int next_norm = 0;
int nnorms = 0;
ubyte * normcount = p+20;
vertex *dest = NULL;
vec3d *src = vp(p+offset);
// Get pointer to lights
Interp_lights = p+20+nverts;
for (i = 0; i < nverts; i++) {
nnorms += normcount[i];
}
// allocate new Interp data if size is greater than we already have ready to use
model_allocate_interp_data(nverts, nnorms);
dest = Interp_points;
Assert( dest != NULL );
#ifndef NDEBUG
modelstats_num_verts += nverts;
#endif
if (Interp_thrust_scale_subobj) {
// Only scale vertices that aren't on the "base" of
// the effect. Base is something Adam decided to be
// anything under 1.5 meters, hence the 1.5f.
float min_thruster_dist = -1.5f;
if ( Interp_flags & MR_IS_MISSILE ) {
min_thruster_dist = 0.5f;
}
for (n=0; n<nverts; n++ ) {
vec3d tmp;
Interp_verts[n] = src;
// Only scale vertices that aren't on the "base" of
// the effect. Base is something Adam decided to be
// anything under 1.5 meters, hence the 1.5f.
if ( src->xyz.z < min_thruster_dist ) {
tmp.xyz.x = src->xyz.x * 1.0f;
tmp.xyz.y = src->xyz.y * 1.0f;
tmp.xyz.z = src->xyz.z * Interp_thrust_scale;
} else {
tmp = *src;
}
g3_rotate_vertex(dest,&tmp);
src++; // move to normal
for (i=0; i<normcount[n]; i++ ) {
Interp_light_applied[next_norm] = 0;
Interp_norms[next_norm] = src;
next_norm++;
src++;
}
dest++;
}
} else if ( (Interp_warp_scale_x != 1.0f) || (Interp_warp_scale_y != 1.0f) || (Interp_warp_scale_z != 1.0f)) {
for (n=0; n<nverts; n++ ) {
vec3d tmp;
Interp_verts[n] = src;
tmp.xyz.x = (src->xyz.x) * Interp_warp_scale_x;
tmp.xyz.y = (src->xyz.y) * Interp_warp_scale_y;
tmp.xyz.z = (src->xyz.z) * Interp_warp_scale_z;
g3_rotate_vertex(dest,&tmp);
src++; // move to normal
for (i=0; i<normcount[n]; i++ ) {
Interp_light_applied[next_norm] = 0;
Interp_norms[next_norm] = src;
next_norm++;
src++;
}
dest++;
}
} else {
vec3d point;
for (n=0; n<nverts; n++ ) {
if(GEOMETRY_NOISE!=0.0f){
GEOMETRY_NOISE = model_radius / 50;
Interp_verts[n] = src;
point.xyz.x = src->xyz.x + frand_range(GEOMETRY_NOISE,-GEOMETRY_NOISE);
point.xyz.y = src->xyz.y + frand_range(GEOMETRY_NOISE,-GEOMETRY_NOISE);
point.xyz.z = src->xyz.z + frand_range(GEOMETRY_NOISE,-GEOMETRY_NOISE);
g3_rotate_vertex(dest, &point);
}else{
Interp_verts[n] = src;
g3_rotate_vertex(dest, src);
}
src++; // move to normal
for (i=0; i<normcount[n]; i++ ) {
Interp_light_applied[next_norm] = 0;
Interp_norms[next_norm] = src;
next_norm++;
src++;
}
dest++;
}
}
Interp_num_norms = next_norm;
}
void model_interp_edge_alpha( ubyte *param_r, ubyte *param_g, ubyte *param_b, vec3d *pnt, vec3d *norm, float alpha, bool invert = false)
{
vec3d r;
vm_vec_sub(&r, &View_position, pnt);
vm_vec_normalize(&r);
float d = vm_vec_dot(&r, norm);
if (d < 0.0f)
d = -d;
if (invert)
*param_r = *param_g = *param_b = ubyte( fl2i((1.0f - d) * 254.0f * alpha));
else
*param_r = *param_g = *param_b = ubyte( fl2i(d * 254.0f * alpha) );
}
int Interp_subspace = 0;
float Interp_subspace_offset_u = 0.0f;
float Interp_subspace_offset_v = 0.0f;
ubyte Interp_subspace_r = 255;
ubyte Interp_subspace_g = 255;
ubyte Interp_subspace_b = 255;
void model_draw_debug_points( polymodel *pm, bsp_info * submodel, uint flags )
{
if ( flags & MR_SHOW_OUTLINE_PRESET ) {
return;
}
// Draw a red pivot point
gr_set_color(128,0,0);
g3_draw_sphere_ez(&vmd_zero_vector, 2.0f );
// Draw a green center of mass when drawing the hull
if ( submodel && (submodel->parent==-1) ) {
gr_set_color(0,128,0);
g3_draw_sphere_ez( &pm->center_of_mass, 1.0f );
}
if ( submodel ) {
// Draw a blue center point
gr_set_color(0,0,128);
g3_draw_sphere_ez( &submodel->geometric_center, 0.9f );
}
// Draw the bounding box
int i;
vertex pts[8];
if ( submodel ) {
for (i=0; i<8; i++ ) {
g3_rotate_vertex( &pts[i], &submodel->bounding_box[i] );
}
gr_set_color(128,128,128);
g3_draw_line( &pts[0], &pts[1] );
g3_draw_line( &pts[1], &pts[2] );
g3_draw_line( &pts[2], &pts[3] );
g3_draw_line( &pts[3], &pts[0] );
g3_draw_line( &pts[4], &pts[5] );
g3_draw_line( &pts[5], &pts[6] );
g3_draw_line( &pts[6], &pts[7] );
g3_draw_line( &pts[7], &pts[4] );
g3_draw_line( &pts[0], &pts[4] );
g3_draw_line( &pts[1], &pts[5] );
g3_draw_line( &pts[2], &pts[6] );
g3_draw_line( &pts[3], &pts[7] );
} else {
gr_set_color(0,255,0);
int j;
for (j=0; j<8; j++ ) {
vec3d bounding_box[8]; // caclulated fron min/max
model_calc_bound_box(bounding_box,&pm->octants[j].min,&pm->octants[j].max);
for (i=0; i<8; i++ ) {
g3_rotate_vertex( &pts[i], &bounding_box[i] );
}
gr_set_color(128,0,0);
g3_draw_line( &pts[0], &pts[1] );
g3_draw_line( &pts[1], &pts[2] );
g3_draw_line( &pts[2], &pts[3] );
g3_draw_line( &pts[3], &pts[0] );
g3_draw_line( &pts[4], &pts[5] );
g3_draw_line( &pts[5], &pts[6] );
g3_draw_line( &pts[6], &pts[7] );
g3_draw_line( &pts[7], &pts[4] );
g3_draw_line( &pts[0], &pts[4] );
g3_draw_line( &pts[1], &pts[5] );
g3_draw_line( &pts[2], &pts[6] );
g3_draw_line( &pts[3], &pts[7] );
}
}
}
/**
* Debug code to show all the paths of a model
*/
void model_draw_paths_htl( int model_num, uint flags )
{
int i,j;
vec3d pnt;
vec3d prev_pnt;
polymodel * pm;
if ( flags & MR_SHOW_OUTLINE_PRESET ) {
return;
}
pm = model_get(model_num);
if (pm->n_paths<1){
return;
}
int cull = gr_set_cull(0);
for (i=0; i<pm->n_paths; i++ ) {
for (j=0; j<pm->paths[i].nverts; j++ )
{
// Rotate point into world coordinates
pnt = pm->paths[i].verts[j].pos;
// Pnt is now the x,y,z world coordinates of this vert.
// For this example, I am just drawing a sphere at that
// point.
vertex tmp;
g3_rotate_vertex(&tmp,&pnt);
if ( pm->paths[i].verts[j].nturrets > 0 ){
gr_set_color( 0, 0, 255 ); // draw points covered by turrets in blue
} else {
gr_set_color( 255, 0, 0 );
}
g3_render_sphere(&pnt, 0.5f);
if (j)
{
//g3_draw_htl_line(&prev_pnt, &pnt);
g3_render_line_3d(true, &prev_pnt, &pnt);
}
prev_pnt = pnt;
}
}
gr_set_cull(cull);
}
/**
* Docking bay and fighter bay paths
*/
void model_draw_bay_paths_htl(int model_num)
{
int idx, s_idx;
vec3d v1, v2;
polymodel *pm = model_get(model_num);
if(pm == NULL){
return;
}
int cull = gr_set_cull(0);
// render docking bay normals
gr_set_color(0, 255, 0);
for(idx=0; idx<pm->n_docks; idx++){
for(s_idx=0; s_idx<pm->docking_bays[idx].num_slots; s_idx++){
v1 = pm->docking_bays[idx].pnt[s_idx];
vm_vec_scale_add(&v2, &v1, &pm->docking_bays[idx].norm[s_idx], 10.0f);
// draw the point and normal
g3_render_sphere(&v1, 2.0);
//g3_draw_htl_line(&v1, &v2);
g3_render_line_3d(true, &v1, &v2);
}
}
// render figher bay paths
gr_set_color(0, 255, 255);
// iterate through the paths that exist in the polymodel, searching for $bayN pathnames
for (idx = 0; idx<pm->n_paths; idx++) {
if ( !strnicmp(pm->paths[idx].name, NOX("$bay"), 4) ) {
for(s_idx=0; s_idx<pm->paths[idx].nverts-1; s_idx++){
v1 = pm->paths[idx].verts[s_idx].pos;
v2 = pm->paths[idx].verts[s_idx+1].pos;
//g3_draw_htl_line(&v1, &v2);
g3_render_line_3d(true, &v1, &v2);
}
}
}
gr_set_cull(cull);
}
static const int MAX_ARC_SEGMENT_POINTS = 50;
int Num_arc_segment_points = 0;
vec3d Arc_segment_points[MAX_ARC_SEGMENT_POINTS];
void interp_render_arc_segment( vec3d *v1, vec3d *v2, int depth )
{
float d = vm_vec_dist_quick( v1, v2 );
const float scaler = 0.30f;
if ( (d < scaler) || (depth > 4) ) {
// the real limit appears to be 33, so we should never hit this unless the code changes
Assert( Num_arc_segment_points < MAX_ARC_SEGMENT_POINTS );
memcpy( &Arc_segment_points[Num_arc_segment_points++], v2, sizeof(vec3d) );
} else {
// divide in half
vec3d tmp;
vm_vec_avg( &tmp, v1, v2 );
tmp.xyz.x += (frand() - 0.5f) * d * scaler;
tmp.xyz.y += (frand() - 0.5f) * d * scaler;
tmp.xyz.z += (frand() - 0.5f) * d * scaler;
// add additional point
interp_render_arc_segment( v1, &tmp, depth+1 );
interp_render_arc_segment( &tmp, v2, depth+1 );
}
}
int Interp_lightning = 1;
DCF_BOOL( Arcs, Interp_lightning )
// Returns one of the following
#define IBOX_ALL_OFF 0
#define IBOX_ALL_ON 1
#define IBOX_SOME_ON_SOME_OFF 2
int interp_box_offscreen( vec3d *min, vec3d *max )
{
if ( keyd_pressed[KEY_LSHIFT] ) {
return IBOX_ALL_ON;
}
vec3d v[8];
v[0].xyz.x = min->xyz.x; v[0].xyz.y = min->xyz.y; v[0].xyz.z = min->xyz.z;
v[1].xyz.x = max->xyz.x; v[1].xyz.y = min->xyz.y; v[1].xyz.z = min->xyz.z;
v[2].xyz.x = max->xyz.x; v[2].xyz.y = max->xyz.y; v[2].xyz.z = min->xyz.z;
v[3].xyz.x = min->xyz.x; v[3].xyz.y = max->xyz.y; v[3].xyz.z = min->xyz.z;
v[4].xyz.x = min->xyz.x; v[4].xyz.y = min->xyz.y; v[4].xyz.z = max->xyz.z;
v[5].xyz.x = max->xyz.x; v[5].xyz.y = min->xyz.y; v[5].xyz.z = max->xyz.z;
v[6].xyz.x = max->xyz.x; v[6].xyz.y = max->xyz.y; v[6].xyz.z = max->xyz.z;
v[7].xyz.x = min->xyz.x; v[7].xyz.y = max->xyz.y; v[7].xyz.z = max->xyz.z;
ubyte and_codes = 0xff;
ubyte or_codes = 0xff;
int i;
for (i=0; i<8; i++ ) {
vertex tmp;
ubyte codes=g3_rotate_vertex( &tmp, &v[i] );
or_codes |= codes;
and_codes &= codes;
}
// If and_codes is set this means that all points lie off to the
// same side of the screen.
if (and_codes) {
return IBOX_ALL_OFF; //all points off screen
}
// If this is set it means at least one of the points is offscreen,
// but they aren't all off to the same side.
if (or_codes) {
return IBOX_SOME_ON_SOME_OFF;
}
// They are all onscreen.
return IBOX_ALL_ON;
}
void model_render_shields( polymodel * pm, uint flags )
{
int i, j;
shield_tri *tri;
vertex pnt0, prev_pnt, tmp = vertex();
if ( flags & MR_SHOW_OUTLINE_PRESET ) {
return;
}
gr_set_color(0, 0, 200 );
// Scan all the triangles in the mesh.
for (i=0; i<pm->shield.ntris; i++ ) {
tri = &pm->shield.tris[i];
if (g3_check_normal_facing(&pm->shield.verts[tri->verts[0]].pos,&tri->norm ) ) {
// Process the vertices.
// Note this rotates each vertex each time it's needed, very dumb.
for (j=0; j<3; j++ ) {
g3_rotate_vertex(&tmp, &pm->shield.verts[tri->verts[j]].pos );
if (j)
g3_draw_line(&prev_pnt, &tmp);
else
pnt0 = tmp;
prev_pnt = tmp;
}
g3_draw_line(&pnt0, &prev_pnt);
}
}
}
int Model_texturing = 1;
int Model_polys = 1;
DCF_BOOL( model_texturing, Model_texturing )
DCF_BOOL( model_polys, Model_polys )
MONITOR( NumModelsRend )
MONITOR( NumHiModelsRend )
MONITOR( NumMedModelsRend )
MONITOR( NumLowModelsRend )
/**
* Draws a bitmap with the specified 3d width & height
* @return 1 if off screen, 0 if not
*/
int model_get_rotated_bitmap_points(vertex *pnt,float angle, float rad, vertex *v)
{
float sa, ca;
int i;
Assert( G3_count == 1 );
sa = sinf(angle);
ca = cosf(angle);
float width, height;
width = height = rad;
v[0].world.xyz.x = (-width*ca - height*sa)*Matrix_scale.xyz.x + pnt->world.xyz.x;
v[0].world.xyz.y = (-width*sa + height*ca)*Matrix_scale.xyz.y + pnt->world.xyz.y;
v[0].world.xyz.z = pnt->world.xyz.z;
v[0].screen.xyw.w = 0.0f;
v[0].texture_position.u = 0.0f;
v[0].texture_position.v = 0.0f;
v[1].world.xyz.x = (width*ca - height*sa)*Matrix_scale.xyz.x + pnt->world.xyz.x;
v[1].world.xyz.y = (width*sa + height*ca)*Matrix_scale.xyz.y + pnt->world.xyz.y;
v[1].world.xyz.z = pnt->world.xyz.z;
v[1].screen.xyw.w = 0.0f;
v[1].texture_position.u = 1.0f;
v[1].texture_position.v = 0.0f;
v[2].world.xyz.x = (width*ca + height*sa)*Matrix_scale.xyz.x + pnt->world.xyz.x;
v[2].world.xyz.y = (width*sa - height*ca)*Matrix_scale.xyz.y + pnt->world.xyz.y;
v[2].world.xyz.z = pnt->world.xyz.z;
v[2].screen.xyw.w = 0.0f;
v[2].texture_position.u = 1.0f;
v[2].texture_position.v = 1.0f;
v[3].world.xyz.x = (-width*ca + height*sa)*Matrix_scale.xyz.x + pnt->world.xyz.x;
v[3].world.xyz.y = (-width*sa - height*ca)*Matrix_scale.xyz.y + pnt->world.xyz.y;
v[3].world.xyz.z = pnt->world.xyz.z;
v[3].screen.xyw.w = 0.0f;
v[3].texture_position.u = 0.0f;
v[3].texture_position.v = 1.0f;
ubyte codes_and=0xff;
float sw,z;
z = pnt->world.xyz.z - rad / 4.0f;
if ( z < 0.0f ) z = 0.0f;
sw = 1.0f / z;
for (i=0; i<4; i++ ) {
//now code the four points
codes_and &= g3_code_vertex(&v[i]);
v[i].flags = 0; // mark as not yet projected
g3_project_vertex(&v[i]);
v[i].screen.xyw.w = sw;
}
if (codes_and)
return 1; //1 means off screen
return 0;
}
float Interp_depth_scale = 1500.0f;
DCF(model_darkening,"Makes models darker with distance")
{
if (dc_optional_string_either("help", "--help")) {
dc_printf( "Usage: model_darkening <float>\n" );
dc_printf("Sets the distance at which to start blacking out models (namely asteroids).\n");
return;
}
if (dc_optional_string_either("status", "--status") || dc_optional_string_either("?", "--?")) {
dc_printf( "model_darkening = %.1f\n", Interp_depth_scale );
return;
}
dc_stuff_float(&Interp_depth_scale);
dc_printf("model_darkening set to %.1f\n", Interp_depth_scale);
}
// tmp_detail_level
// 0 - Max
// 1
// 2
// 3
// 4 - None
#if MAX_DETAIL_LEVEL != 4
#error MAX_DETAIL_LEVEL is assumed to be 4 in ModelInterp.cpp
#endif
/**
* Find the distance-squared from p0 to the closest point on a box. Fills in closest_pt.
* The box's dimensions are from 'min' to 'max'.
*/
float interp_closest_dist_sq_to_box( vec3d *closest_pt, const vec3d *p0, const vec3d *min, const vec3d *max )
{
auto origin = p0->a1d;
auto minB = min->a1d;
auto maxB = max->a1d;
auto coord = closest_pt->a1d;
bool inside = true;
int i;
for (i=0; i<3; i++ ) {
if ( origin[i] < minB[i] ) {
coord[i] = minB[i];
inside = false;
} else if (origin[i] > maxB[i] ) {
coord[i] = maxB[i];
inside = false;
} else {
coord[i] = origin[i];
}
}
if ( inside ) {
return 0.0f;
}
return vm_vec_dist_squared(closest_pt, p0);
}
// Finds the closest point on a model to a point in space. Actually only finds a point
// on the bounding box of the model.
// Given:
// model_num Which model
// orient Orientation of the model
// pos Position of the model
// eye_pos Point that you want to find the closest point to
// Returns:
// distance from eye_pos to closest_point. 0 means eye_pos is
// on or inside the bounding box.
// Also fills in outpnt with the actual closest point (in local coordinates).
float model_find_closest_point( vec3d *outpnt, int model_num, int submodel_num, const matrix *orient, const vec3d *pos, const vec3d *eye_pos )
{
vec3d tempv, eye_rel_pos;
polymodel *pm = model_get(model_num);
if ( submodel_num < 0 ) {
submodel_num = pm->detail[0];
}
// Rotate eye pos into object coordinates
vm_vec_sub(&tempv, pos, eye_pos);
vm_vec_rotate(&eye_rel_pos, &tempv, orient);
return fl_sqrt( interp_closest_dist_sq_to_box( outpnt, &eye_rel_pos, &pm->submodel[submodel_num].min, &pm->submodel[submodel_num].max ) );
}
// Like the above, but finds the closest two points to each other.
float model_find_closest_points(vec3d *outpnt1, int model_num1, int submodel_num1, const matrix *orient1, const vec3d *pos1, vec3d *outpnt2, int model_num2, int submodel_num2, const matrix *orient2, const vec3d *pos2)
{
polymodel *pm1 = model_get(model_num1);
if (submodel_num1 < 0)
submodel_num1 = pm1->detail[0];
polymodel *pm2 = model_get(model_num2);
if (submodel_num2 < 0)
submodel_num2 = pm2->detail[0];
// determine obj2's bounding box
vec3d bounding_box[8];
model_calc_bound_box(bounding_box, &pm2->submodel[submodel_num2].min, &pm2->submodel[submodel_num2].max);
float closest_dist_sq = -1.0f;
// check each point on it
for (const auto &pt : bounding_box)
{
vec3d temp, rel_pt;
// find world coordinates of this point
vm_vec_unrotate(&temp, &pt, orient2);
vm_vec_add(&rel_pt, &temp, pos2);
// now find coordinates relative to obj1
vm_vec_sub(&temp, pos1, &rel_pt);
vm_vec_rotate(&rel_pt, &temp, orient1);
// test this point
float dist_sq = interp_closest_dist_sq_to_box(&temp, &rel_pt, &pm1->submodel[submodel_num1].min, &pm1->submodel[submodel_num1].max);
if (closest_dist_sq < 0.0f || dist_sq < closest_dist_sq)
{
closest_dist_sq = dist_sq;
// Note: As in the other function, both of these points are
// in local coordinates relative to each of their models.
*outpnt1 = temp;
*outpnt2 = pt;
}
}
// we have now found the closest point
return fl_sqrt(closest_dist_sq);
}
int tiling = 1;
DCF(tiling, "Toggles rendering of tiled textures (default is on)")
{
if (dc_optional_string_either("status", "--status") || dc_optional_string_either("?", "--?")) {
dc_printf("Tiled textures are %s", tiling ? "ON" : "OFF");
return;
}
tiling = !tiling;
if(tiling){
dc_printf("Tiled textures\n");
} else {
dc_printf("Non-tiled textures\n");
}
}
void moldel_calc_facing_pts( vec3d *top, vec3d *bot, vec3d *fvec, vec3d *pos, float w, float /*z_add*/, vec3d *Eyeposition )
{
vec3d uvec, rvec;
vec3d temp;
temp = *pos;
vm_vec_sub( &rvec, Eyeposition, &temp );
vm_vec_normalize( &rvec );
vm_vec_cross(&uvec,fvec,&rvec);
vm_vec_normalize(&uvec);
vm_vec_scale_add( top, &temp, &uvec, w/2.0f );
vm_vec_scale_add( bot, &temp, &uvec, -w/2.0f );
}
// Fills in an array with points from a model.
// Only gets up to max_num verts;
// Returns number of verts found;
static int submodel_get_points_internal(int model_num, int submodel_num)
{
polymodel * pm;
pm = model_get(model_num);
if ( submodel_num < 0 ) {
submodel_num = pm->detail[0];
}
ubyte *p = pm->submodel[submodel_num].bsp_data;
int chunk_type, chunk_size;
chunk_type = w(p);
chunk_size = w(p+4);
while (chunk_type != OP_EOF) {
switch (chunk_type) {
case OP_DEFPOINTS: {
int n;
int nverts = w(p+8);
int offset = w(p+16);
int nnorms = 0;
ubyte * normcount = p+20;
vec3d *src = vp(p+offset);
for (n = 0; n < nverts; n++) {
nnorms += normcount[n];
}
model_allocate_interp_data(nverts, nnorms);
// this must happen only after the interp_data allocation call (since the address changes)
vec3d **verts = Interp_verts;
vec3d **norms = Interp_norms;
for (n=0; n<nverts; n++ ) {
*verts++ = src;
*norms++ = src + 1; // first normal associated with the point
src += normcount[n]+1;
}
return nverts; // Read in 'n' points
}
break;
case OP_FLATPOLY: break;
case OP_TMAPPOLY: break;
case OP_SORTNORM: break;
case OP_BOUNDBOX: break;
default:
mprintf(( "Bad chunk type %d, len=%d in submodel_get_points\n", chunk_type, chunk_size ));
Int3(); // Bad chunk type!
return 0;
}
p += chunk_size;
chunk_type = w(p);
chunk_size = w(p+4);
}
return 0; // Couldn't find 'em
}
/**
* Gets two random points on a model
*/
void submodel_get_two_random_points(int model_num, int submodel_num, vec3d *v1, vec3d *v2, vec3d *n1, vec3d *n2 )
{
int nv = submodel_get_points_internal(model_num, submodel_num);
// this is not only because of the immediate div-0 error but also because of the less immediate expectation for at least one point (preferably two) to be found
if (nv <= 0) {
polymodel *pm = model_get(model_num);
Error(LOCATION, "Model %d ('%s') must have at least one point from submodel_get_points_internal!", model_num, (pm == NULL) ? "<null model?!?>" : pm->filename);
// in case people ignore the error...
vm_vec_zero(v1);
vm_vec_zero(v2);
if (n1 != NULL) {
vm_vec_zero(n1);
}
if (n2 != NULL) {
vm_vec_zero(n2);
}
return;
}
#ifndef NDEBUG
if (RAND_MAX < nv)
{
static int submodel_get_two_random_points_warned = false;
if (!submodel_get_two_random_points_warned)
{
polymodel *pm = model_get(model_num);
Warning(LOCATION, "RAND_MAX is only %d, but submodel %d for model %s has %d vertices! Explosions will not propagate through the entire model!\n", RAND_MAX, submodel_num, pm->filename, nv);
submodel_get_two_random_points_warned = true;
}
}
#endif
int vn1 = myrand() % nv;
int vn2 = myrand() % nv;
*v1 = *Interp_verts[vn1];
*v2 = *Interp_verts[vn2];
if(n1 != NULL){
*n1 = *Interp_norms[vn1];
}
if(n2 != NULL){
*n2 = *Interp_norms[vn2];
}
}
void submodel_get_two_random_points_better(int model_num, int submodel_num, vec3d *v1, vec3d *v2)
{
polymodel *pm = model_get(model_num);
if (pm != NULL) {
if ( submodel_num < 0 ) {
submodel_num = pm->detail[0];
}
// the Shivan Comm Node does not have a collision tree, for one
if (pm->submodel[submodel_num].collision_tree_index < 0) {
nprintf(("Model", "In submodel_get_two_random_points_better(), model %s does not have a collision tree! Falling back to submodel_get_two_random_points().\n", pm->filename));
submodel_get_two_random_points(model_num, submodel_num, v1, v2);
return;
}
bsp_collision_tree *tree = model_get_bsp_collision_tree(pm->submodel[submodel_num].collision_tree_index);
int nv = tree->n_verts;
// this is not only because of the immediate div-0 error but also because of the less immediate expectation for at least one point (preferably two) to be found
if (nv <= 0) {
Error(LOCATION, "Model %d ('%s') must have at least one point from submodel_get_points_internal!", model_num, (pm == NULL) ? "<null model?!?>" : pm->filename);
// in case people ignore the error...
vm_vec_zero(v1);
vm_vec_zero(v2);
return;
}
#ifndef NDEBUG
if (RAND_MAX < nv)
{
static int submodel_get_two_random_points_warned = false;
if (!submodel_get_two_random_points_warned)
{
Warning(LOCATION, "RAND_MAX is only %d, but submodel %d for model %s has %d vertices! Explosions will not propagate through the entire model!\n", RAND_MAX, submodel_num, pm->filename, nv);
submodel_get_two_random_points_warned = true;
}
}
#endif
int vn1 = myrand() % nv;
int vn2 = myrand() % nv;
*v1 = tree->point_list[vn1];
*v2 = tree->point_list[vn2];
}
}
// If MR_FLAG_OUTLINE bit set this color will be used for outlines.
// This defaults to black.
void model_set_outline_color(int r, int g, int b )
{
gr_init_color( &Interp_outline_color, r, g, b );
}
// IF MR_LOCK_DETAIL is set, then it will always draw detail level 'n'
// This defaults to 0. (0=highest, larger=lower)
void model_set_detail_level(int n)
{
Interp_detail_level_locked = n;
}
/**
* Returns number of tmaps & flat polys in a submodel;
*/
int submodel_get_num_polys_sub( ubyte *p )
{
int chunk_type = w(p);
int chunk_size = w(p+4);
int n = 0;
while (chunk_type != OP_EOF) {
switch (chunk_type) {
case OP_DEFPOINTS: break;
case OP_FLATPOLY: n++; break;
case OP_TMAPPOLY: n++; break;
case OP_SORTNORM: {
int frontlist = w(p+36);
int backlist = w(p+40);
int prelist = w(p+44);
int postlist = w(p+48);
int onlist = w(p+52);
n += submodel_get_num_polys_sub(p+frontlist);
n += submodel_get_num_polys_sub(p+backlist);
n += submodel_get_num_polys_sub(p+prelist);
n += submodel_get_num_polys_sub(p+postlist );
n += submodel_get_num_polys_sub(p+onlist );
}
break;
case OP_BOUNDBOX: break;
default:
mprintf(( "Bad chunk type %d, len=%d in submodel_get_num_polys\n", chunk_type, chunk_size ));
Int3(); // Bad chunk type!
return 0;
}
p += chunk_size;
chunk_type = w(p);
chunk_size = w(p+4);
}
return n;
}
/**
* Returns number of tmaps & flat polys in a submodel
*/
int submodel_get_num_polys(int model_num, int submodel_num )
{
polymodel * pm;
pm = model_get(model_num);
return submodel_get_num_polys_sub( pm->submodel[submodel_num].bsp_data );
}
/**
* See if the given texture is used by the passed model. 0 if not used, 1 if used, -1 on error
*/
int model_find_texture(int model_num, int bitmap)
{
polymodel * pm;
int idx;
// get a handle to the model
pm = model_get(model_num);
if(pm == NULL){
return -1;
}
// find the texture
for(idx=0; idx<pm->n_textures; idx++)
{
if(pm->maps[idx].FindTexture(bitmap) > -1)
{
return 1;
}
}
// no texture
return 0;
}
// find closest point on extended bounding box (the bounding box plus all the planes that make it up)
// returns closest distance to extended box
// positive return value means start_point is outside extended box
// displaces closest point an optional amount delta to the outside of the box
// closest_box_point can be NULL.
float get_model_closest_box_point_with_delta(vec3d *closest_box_point, vec3d *start_point, int modelnum, int *is_inside, float delta)
{
int i, idx;
vec3d box_point, ray_direction, *extremes;
float dist, best_dist;
polymodel *pm;
int inside = 0;
int masks[6] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20};
int mask_inside = 0x3f;
best_dist = FLT_MAX;
pm = model_get(modelnum);
for (i=0; i<6; i++) {
idx = i / 2; // which row vector of Identity matrix
memcpy(&ray_direction, vmd_identity_matrix.a2d[idx], sizeof(vec3d));
// do negative, then positive plane for each axis
if (2 * idx == i) {
extremes = &pm->mins;
vm_vec_negate(&ray_direction);
} else {
extremes = &pm->maxs;
}
// a negative distance means started outside the box
dist = fvi_ray_plane(&box_point, extremes, &ray_direction, start_point, &ray_direction, 0.0f);
if (dist > 0) {
inside |= masks[i];
}
if (fabs(dist) < fabs(best_dist)) {
best_dist = dist;
if (closest_box_point) {
vm_vec_scale_add(closest_box_point, &box_point, &ray_direction, delta);
}
}
}
// is start_point inside the box
if (is_inside) {
*is_inside = (inside == mask_inside);
}
return -best_dist;
}
// find closest point on extended bounding box (the bounding box plus all the planes that make it up)
// returns closest distance to extended box
// positive return value means start_point is outside extended box
// displaces closest point an optional amount delta to the outside of the box
// closest_box_point can be NULL.
float get_world_closest_box_point_with_delta(vec3d *closest_box_point, object *box_obj, vec3d *start_point, int *is_inside, float delta)
{
vec3d temp, box_start;
float dist;
int modelnum;
// get modelnum
modelnum = Ship_info[Ships[box_obj->instance].ship_info_index].model_num;
// rotate start_point to box_obj RF
vm_vec_sub(&temp, start_point, &box_obj->pos);
vm_vec_rotate(&box_start, &temp, &box_obj->orient);
dist = get_model_closest_box_point_with_delta(closest_box_point, &box_start, modelnum, is_inside, delta);
// rotate closest_box_point to world RF
if (closest_box_point) {
vm_vec_unrotate(&temp, closest_box_point, &box_obj->orient);
vm_vec_add(closest_box_point, &temp, &box_obj->pos);
}
return dist;
}
/**
* Given a newly loaded model, page in all textures
*/
void model_page_in_textures(int modelnum, int ship_info_index)
{
int i, idx;
polymodel *pm = model_get(modelnum);
// bogus
if (pm == NULL)
return;
for (idx = 0; idx < pm->n_textures; idx++) {
pm->maps[idx].PageIn();
}
for (i = 0; i < pm->n_glow_point_banks; i++) {
glow_point_bank *bank = &pm->glow_point_banks[i];
bm_page_in_texture(bank->glow_bitmap);
bm_page_in_texture(bank->glow_neb_bitmap);
}
if (ship_info_index >= 0)
ship_page_in_textures(ship_info_index);
}
// unload all textures for a given model
// "release" should only be set if called from model_unload()!!!
void model_page_out_textures(int model_num, bool release)
{
int i, j;
if (model_num < 0)
return;
polymodel *pm = model_get(model_num);
if (pm == NULL)
return;
if (release && (pm->used_this_mission > 0))
return;
for (i = 0; i < pm->n_textures; i++) {
pm->maps[i].PageOut(release);
}
// NOTE: "release" doesn't work here for some, as of yet unknown, reason - taylor
for (j = 0; j < pm->n_glow_point_banks; j++) {
glow_point_bank *bank = &pm->glow_point_banks[j];
if (bank->glow_bitmap >= 0) {
// if (release) {
// bm_release(bank->glow_bitmap);
// bank->glow_bitmap = -1;
// } else {
bm_unload(bank->glow_bitmap);
// }
}
if (bank->glow_neb_bitmap >= 0) {
// if (release) {
// bm_release(bank->glow_neb_bitmap);
// bank->glow_neb_bitmap = -1;
// } else {
bm_unload(bank->glow_neb_bitmap);
// }
}
}
}
//**********vertex buffer stuff**********//
int tri_count[MAX_MODEL_TEXTURES];
poly_list polygon_list[MAX_MODEL_TEXTURES];
void parse_defpoint(int off, ubyte *bsp_data)
{
int i, n;
int nverts = w(off+bsp_data+8);
int offset = w(off+bsp_data+16);
int next_norm = 0;
ubyte *normcount = off+bsp_data+20;
vec3d *src = vp(off+bsp_data+offset);
// Get pointer to lights
Interp_lights = off+bsp_data+20+nverts;
#ifndef NDEBUG
modelstats_num_verts += nverts;
#endif
for (n = 0; n < nverts; n++) {
Interp_verts[n] = src;
src++; // move to normal
for (i = 0; i < normcount[n]; i++) {
Interp_norms[next_norm] = src;
next_norm++;
src++;
}
}
}
int check_values(vec3d *N)
{
// Values equal to -1.#IND0
if(!is_valid_vec(N))
{
N->xyz.x = 1.0f;
N->xyz.y = 0.0f;
N->xyz.z = 0.0f;
return 1;
}
return 0;
}
int Parse_normal_problem_count = 0;
void parse_tmap(int offset, ubyte *bsp_data)
{
int pof_tex = w(bsp_data+offset+40);
int n_vert = w(bsp_data+offset+36);
ubyte *p = &bsp_data[offset+8];
model_tmap_vert *tverts;
tverts = (model_tmap_vert *)&bsp_data[offset+44];
vertex *V;
vec3d *v;
vec3d *N;
int problem_count = 0;
for (int i = 1; i < (n_vert-1); i++) {
V = &polygon_list[pof_tex].vert[(polygon_list[pof_tex].n_verts)];
N = &polygon_list[pof_tex].norm[(polygon_list[pof_tex].n_verts)];
v = Interp_verts[(int)tverts[0].vertnum];
V->world.xyz.x = v->xyz.x;
V->world.xyz.y = v->xyz.y;
V->world.xyz.z = v->xyz.z;
V->texture_position.u = tverts[0].u;
V->texture_position.v = tverts[0].v;
*N = *Interp_norms[(int)tverts[0].normnum];
if ( IS_VEC_NULL(N) )
*N = *vp(p);
problem_count += check_values(N);
vm_vec_normalize_safe(N);
V = &polygon_list[pof_tex].vert[(polygon_list[pof_tex].n_verts)+1];
N = &polygon_list[pof_tex].norm[(polygon_list[pof_tex].n_verts)+1];
v = Interp_verts[(int)tverts[i].vertnum];
V->world.xyz.x = v->xyz.x;
V->world.xyz.y = v->xyz.y;
V->world.xyz.z = v->xyz.z;
V->texture_position.u = tverts[i].u;
V->texture_position.v = tverts[i].v;
*N = *Interp_norms[(int)tverts[i].normnum];
if ( IS_VEC_NULL(N) )
*N = *vp(p);
problem_count += check_values(N);
vm_vec_normalize_safe(N);
V = &polygon_list[pof_tex].vert[(polygon_list[pof_tex].n_verts)+2];
N = &polygon_list[pof_tex].norm[(polygon_list[pof_tex].n_verts)+2];
v = Interp_verts[(int)tverts[i+1].vertnum];
V->world.xyz.x = v->xyz.x;
V->world.xyz.y = v->xyz.y;
V->world.xyz.z = v->xyz.z;
V->texture_position.u = tverts[i+1].u;
V->texture_position.v = tverts[i+1].v;
*N = *Interp_norms[(int)tverts[i+1].normnum];
if ( IS_VEC_NULL(N) )
*N = *vp(p);
problem_count += check_values(N);
vm_vec_normalize_safe(N);
polygon_list[pof_tex].n_verts += 3;
}
Parse_normal_problem_count += problem_count;
}
void parse_sortnorm(int offset, ubyte *bsp_data);
void parse_bsp(int offset, ubyte *bsp_data)
{
int id = w(bsp_data+offset);
int size = w(bsp_data+offset+4);
while (id != 0) {
switch (id)
{
case OP_DEFPOINTS:
parse_defpoint(offset, bsp_data);
break;
case OP_SORTNORM:
parse_sortnorm(offset, bsp_data);
break;
case OP_FLATPOLY:
break;
case OP_TMAPPOLY:
parse_tmap(offset, bsp_data);
break;
case OP_BOUNDBOX:
break;
default:
return;
}
offset += size;
id = w(bsp_data+offset);
size = w(bsp_data+offset+4);
if (size < 1)
id = OP_EOF;
}
}
void parse_sortnorm(int offset, ubyte *bsp_data)
{
int frontlist, backlist, prelist, postlist, onlist;
frontlist = w(bsp_data+offset+36);
backlist = w(bsp_data+offset+40);
prelist = w(bsp_data+offset+44);
postlist = w(bsp_data+offset+48);
onlist = w(bsp_data+offset+52);
if (prelist) parse_bsp(offset+prelist,bsp_data);
if (backlist) parse_bsp(offset+backlist, bsp_data);
if (onlist) parse_bsp(offset+onlist, bsp_data);
if (frontlist) parse_bsp(offset+frontlist, bsp_data);
if (postlist) parse_bsp(offset+postlist, bsp_data);
}
void find_tmap(int offset, ubyte *bsp_data)
{
int pof_tex = w(bsp_data+offset+40);
int n_vert = w(bsp_data+offset+36);
tri_count[pof_tex] += n_vert-2;
}
void find_defpoint(int off, ubyte *bsp_data)
{
int n;
int nverts = w(off+bsp_data+8);
ubyte * normcount = off+bsp_data+20;
// Get pointer to lights
Interp_lights = off+bsp_data+20+nverts;
#ifndef NDEBUG
modelstats_num_verts += nverts;
#endif
int norm_num = 0;
for (n = 0; n < nverts; n++) {
norm_num += normcount[n];
}
Interp_num_verts = nverts;
Interp_num_norms = norm_num;
}
void find_sortnorm(int offset, ubyte *bsp_data);
// tri_count
void find_tri_counts(int offset, ubyte *bsp_data)
{
int id = w(bsp_data+offset);
int size = w(bsp_data+offset+4);
while (id != 0) {
switch (id)
{
case OP_DEFPOINTS:
find_defpoint(offset, bsp_data);
break;
case OP_SORTNORM:
find_sortnorm(offset, bsp_data);
break;
case OP_FLATPOLY:
break;
case OP_TMAPPOLY:
find_tmap(offset, bsp_data);
break;
case OP_BOUNDBOX:
break;
default:
return;
}
offset += size;
id = w(bsp_data+offset);
size = w(bsp_data+offset+4);
if (size < 1)
id = OP_EOF;
}
}
void find_sortnorm(int offset, ubyte *bsp_data)
{
int frontlist, backlist, prelist, postlist, onlist;
frontlist = w(bsp_data+offset+36);
backlist = w(bsp_data+offset+40);
prelist = w(bsp_data+offset+44);
postlist = w(bsp_data+offset+48);
onlist = w(bsp_data+offset+52);
if (prelist) find_tri_counts(offset+prelist,bsp_data);
if (backlist) find_tri_counts(offset+backlist, bsp_data);
if (onlist) find_tri_counts(offset+onlist, bsp_data);
if (frontlist) find_tri_counts(offset+frontlist, bsp_data);
if (postlist) find_tri_counts(offset+postlist, bsp_data);
}
void model_interp_submit_buffers(indexed_vertex_source *vert_src, size_t vertex_stride)
{
Assert(vert_src != NULL);
if ( !(vert_src->Vertex_list_size > 0 && vert_src->Index_list_size > 0 ) ) {
return;
}
if ( vert_src->Vertex_list != NULL ) {
size_t offset;
gr_heap_allocate(GpuHeap::ModelVertex, vert_src->Vertex_list_size, vert_src->Vertex_list, offset, vert_src->Vbuffer_handle);
// If this happens then someone must have allocated something from the heap with a different stride than what we
// are using.
Assertion(offset % vertex_stride == 0, "Offset returned by GPU heap allocation does not match stride value!");
vert_src->Base_vertex_offset = offset / vertex_stride;
vert_src->Vertex_offset = offset;
vm_free(vert_src->Vertex_list);
vert_src->Vertex_list = NULL;
}
if ( vert_src->Index_list != NULL ) {
gr_heap_allocate(GpuHeap::ModelIndex, vert_src->Index_list_size, vert_src->Index_list, vert_src->Index_offset, vert_src->Ibuffer_handle);
vm_free(vert_src->Index_list);
vert_src->Index_list = NULL;
}
}
bool model_interp_pack_buffer(indexed_vertex_source *vert_src, vertex_buffer *vb)
{
if ( vert_src == NULL ) {
return false;
}
Assertion(vb != nullptr, "Invalid vertex buffer specified!");
int i, n_verts = 0;
size_t j;
if ( vert_src->Vertex_list == NULL ) {
vert_src->Vertex_list = vm_malloc(vert_src->Vertex_list_size);
// return invalid if we don't have the memory
if ( vert_src->Vertex_list == NULL ) {
return false;
}
memset(vert_src->Vertex_list, 0, vert_src->Vertex_list_size);
}
if ( vert_src->Index_list == NULL ) {
vert_src->Index_list = vm_malloc(vert_src->Index_list_size);
// return invalid if we don't have the memory
if ( vert_src->Index_list == NULL ) {
return false;
}
memset(vert_src->Index_list, 0, vert_src->Index_list_size);
}
// bump to our index in the array
auto array = reinterpret_cast<interp_vertex*>(static_cast<uint8_t*>(vert_src->Vertex_list) + (vb->vertex_offset));
// generate the vertex array
n_verts = vb->model_list->n_verts;
for ( i = 0; i < n_verts; i++ ) {
vertex *vl = &vb->model_list->vert[i];
auto outVert = &array[i];
// don't try to generate more data than what's available
Assert(((i * sizeof(interp_vertex)) + sizeof(interp_vertex)) <= (vert_src->Vertex_list_size - vb->vertex_offset));
// NOTE: UV->NORM->TSB->MODEL_ID->VERT, This array order *must* be preserved!!
// tex coords
if ( vb->flags & VB_FLAG_UV1 ) {
outVert->uv = vl->texture_position;
} else {
outVert->uv.u = 1.0f;
outVert->uv.v = 1.0f;
}
// normals
if ( vb->flags & VB_FLAG_NORMAL ) {
Assert(vb->model_list->norm != NULL);
outVert->normal = vb->model_list->norm[i];
} else {
outVert->normal.xyz.x = 0.0f;
outVert->normal.xyz.y = 0.0f;
outVert->normal.xyz.z = 1.0f;
}
// tangent space data
if ( vb->flags & VB_FLAG_TANGENT ) {
Assert(vb->model_list->tsb != NULL);
tsb_t *tsb = &vb->model_list->tsb[i];
outVert->tangent.xyzw.x = tsb->tangent.xyz.x;
outVert->tangent.xyzw.y = tsb->tangent.xyz.y;
outVert->tangent.xyzw.z = tsb->tangent.xyz.z;
outVert->tangent.xyzw.w = tsb->scaler;
} else {
outVert->tangent.xyzw.x = 1.0f;
outVert->tangent.xyzw.y = 0.0f;
outVert->tangent.xyzw.z = 0.0f;
outVert->tangent.xyzw.w = 0.0f;
}
if ( vb->flags & VB_FLAG_MODEL_ID ) {
Assert(vb->model_list->submodels != NULL);
outVert->modelId = (float)vb->model_list->submodels[i];
} else {
outVert->modelId = 0.0f;
}
// verts
outVert->pos = vl->world;
}
// generate the index array
for ( j = 0; j < vb->tex_buf.size(); j++ ) {
buffer_data* tex_buf = &vb->tex_buf[j];
n_verts = (int)tex_buf->n_verts;
auto offset = tex_buf->index_offset;
const uint *index = tex_buf->get_index();
// bump to our spot in the buffer
auto ibuf = static_cast<uint8_t*>(vert_src->Index_list) + offset;
if ( vb->tex_buf[j].flags & VB_FLAG_LARGE_INDEX ) {
memcpy(ibuf, index, n_verts * sizeof(uint));
} else {
ushort *mybuf = (ushort*)ibuf;
for ( i = 0; i < n_verts; i++ ) {
mybuf[i] = (ushort)index[i];
}
}
}
return true;
}
void interp_pack_vertex_buffers(polymodel *pm, int mn)
{
Assert( (mn >= 0) && (mn < pm->n_models) );
bsp_info *model = &pm->submodel[mn];
if ( !model->buffer.model_list ) {
return;
}
bool rval = model_interp_pack_buffer(&pm->vert_source, &model->buffer);
if ( model->trans_buffer.flags & VB_FLAG_TRANS && !model->trans_buffer.tex_buf.empty() ) {
model_interp_pack_buffer(&pm->vert_source, &model->trans_buffer);
}
if ( !rval ) {
Error( LOCATION, "Unable to pack vertex buffer for '%s'\n", pm->filename );
}
}
void model_interp_set_buffer_layout(vertex_layout *layout)
{
Assert(layout != NULL);
// Similarly to model_interp_config_buffer, we add all vectex components even if they aren't used
// This reduces the amount of vertex format respecification and since the data contains valid data there is no risk
// of reading garbage data on the GPU
layout->add_vertex_component(vertex_format_data::TEX_COORD2, sizeof(interp_vertex), offsetof(interp_vertex, uv));
layout->add_vertex_component(vertex_format_data::NORMAL, sizeof(interp_vertex), offsetof(interp_vertex, normal));
layout->add_vertex_component(vertex_format_data::TANGENT, sizeof(interp_vertex), offsetof(interp_vertex, tangent));
layout->add_vertex_component(vertex_format_data::MODEL_ID, sizeof(interp_vertex), offsetof(interp_vertex, modelId));
layout->add_vertex_component(vertex_format_data::POSITION3, sizeof(interp_vertex), offsetof(interp_vertex, pos));
}
bool model_interp_config_buffer(indexed_vertex_source *vert_src, vertex_buffer *vb, bool update_ibuffer_only)
{
if ( vb == NULL ) {
return false;
}
if ( !(vb->flags & VB_FLAG_POSITION) ) {
Int3();
return false;
}
// pad out the vertex buffer even if it doesn't use certain attributes
// we require consistent stride across vertex buffers so we can use base vertex offsetting for performance reasons
vb->stride = sizeof(interp_vertex);
model_interp_set_buffer_layout(&vb->layout);
// offsets for this chunk
if ( !update_ibuffer_only ) {
vb->vertex_offset = vert_src->Vertex_list_size;
vb->vertex_num_offset = vb->vertex_offset / vb->stride;
vert_src->Vertex_list_size += (uint)(vb->stride * vb->model_list->n_verts);
}
for ( size_t idx = 0; idx < vb->tex_buf.size(); idx++ ) {
buffer_data *bd = &vb->tex_buf[idx];
bd->index_offset = vert_src->Index_list_size;
vert_src->Index_list_size += (uint)(bd->n_verts * ((bd->flags & VB_FLAG_LARGE_INDEX) ? sizeof(uint) : sizeof(ushort)));
// even out index buffer so we are always word aligned
vert_src->Index_list_size += (uint)(vert_src->Index_list_size % sizeof(uint));
}
return true;
}
void interp_configure_vertex_buffers(polymodel *pm, int mn)
{
TRACE_SCOPE(tracing::ModelConfigureVertexBuffers);
int i, j, first_index;
uint total_verts = 0;
SCP_vector<int> vertex_list;
Assert( (mn >= 0) && (mn < pm->n_models) );
bsp_info *model = &pm->submodel[mn];
for (i = 0; i < MAX_MODEL_TEXTURES; i++) {
polygon_list[i].n_verts = 0;
tri_count[i] = 0;
}
int milliseconds = timer_get_milliseconds();
bsp_polygon_data *bsp_polies = new bsp_polygon_data(model->bsp_data);
for (i = 0; i < MAX_MODEL_TEXTURES; i++) {
int vert_count = bsp_polies->get_num_triangles(i) * 3;
tri_count[i] = vert_count / 3;
total_verts += vert_count;
polygon_list[i].allocate(vert_count);
bsp_polies->generate_triangles(i, polygon_list[i].vert, polygon_list[i].norm);
polygon_list[i].n_verts = vert_count;
// set submodel ID
for ( j = 0; j < polygon_list[i].n_verts; ++j ) {
polygon_list[i].submodels[j] = mn;
}
// for the moment we can only support INT_MAX worth of verts per index buffer
if (total_verts > INT_MAX) {
Error( LOCATION, "Unable to generate vertex buffer data because model '%s' with %i verts is over the maximum of %i verts!\n", pm->filename, total_verts, INT_MAX);
}
}
// figure out if we have an outline
int outline_n_lines = bsp_polies->get_num_lines(-1);
if ( outline_n_lines > 0 ) {
model->n_verts_outline = outline_n_lines * 2;
model->outline_buffer = (vertex*)vm_malloc(sizeof(vertex) * model->n_verts_outline);
bsp_polies->generate_lines(-1, model->outline_buffer);
}
// done with the bsp now that we have the vertex data
delete bsp_polies;
int time_elapsed = timer_get_milliseconds() - milliseconds;
nprintf(("Model", "BSP Parse took %d milliseconds.\n", time_elapsed));
if (total_verts < 1) {
return;
}
total_verts = 0;
for (i = 0; i < MAX_MODEL_TEXTURES; i++) {
total_verts += polygon_list[i].n_verts;
}
poly_list *model_list = new(std::nothrow) poly_list;
if ( !model_list ) {
Error( LOCATION, "Unable to allocate memory for poly_list!\n" );
}
model->buffer.model_list = model_list;
model_list->allocate( (int)total_verts );
for (i = 0; i < MAX_MODEL_TEXTURES; i++) {
if ( !polygon_list[i].n_verts )
continue;
memcpy( (model_list->vert) + model_list->n_verts, polygon_list[i].vert, sizeof(vertex) * polygon_list[i].n_verts );
memcpy( (model_list->norm) + model_list->n_verts, polygon_list[i].norm, sizeof(vec3d) * polygon_list[i].n_verts );
if (Cmdline_normal) {
memcpy( (model_list->tsb) + model_list->n_verts, polygon_list[i].tsb, sizeof(tsb_t) * polygon_list[i].n_verts );
}
memcpy( (model_list->submodels) + model_list->n_verts, polygon_list[i].submodels, sizeof(int) * polygon_list[i].n_verts );
model_list->n_verts += polygon_list[i].n_verts;
}
// no read file so we'll have to generate
model_list->make_index_buffer(vertex_list);
vertex_list.clear(); // done
int vertex_flags = (VB_FLAG_POSITION | VB_FLAG_NORMAL | VB_FLAG_UV1);
if (model_list->tsb != NULL) {
Assert( Cmdline_normal );
vertex_flags |= VB_FLAG_TANGENT;
}
if ( model_list->submodels != NULL ) {
vertex_flags |= VB_FLAG_MODEL_ID;
}
model->buffer.flags = vertex_flags;
for (i = 0; i < MAX_MODEL_TEXTURES; i++) {
if ( !polygon_list[i].n_verts )
continue;
buffer_data new_buffer(polygon_list[i].n_verts);
Verify( new_buffer.get_index() != NULL );
for (j = 0; j < polygon_list[i].n_verts; j++) {
first_index = model_list->find_index_fast(&polygon_list[i], j);
Assert(first_index != -1);
new_buffer.assign(j, first_index);
}
new_buffer.texture = i;
new_buffer.flags = 0;
if (polygon_list[i].n_verts >= USHRT_MAX) {
new_buffer.flags |= VB_FLAG_LARGE_INDEX;
}
model->buffer.tex_buf.push_back( new_buffer );
}
bool rval = model_interp_config_buffer(&pm->vert_source, &model->buffer, false);
if ( !rval ) {
Error( LOCATION, "Unable to configure vertex buffer for '%s'\n", pm->filename );
}
}
void interp_copy_index_buffer(vertex_buffer *src, vertex_buffer *dest, size_t *index_counts)
{
size_t i, j, k;
size_t src_buff_size;
buffer_data *src_buffer;
buffer_data *dest_buffer;
size_t vert_offset = src->vertex_num_offset; // assuming all submodels crunched into this index buffer have the same stride
//int vert_offset = 0;
for ( i = 0; i < dest->tex_buf.size(); ++i ) {
dest_buffer = &dest->tex_buf[i];
for ( j = 0; j < src->tex_buf.size(); ++j ) {
if ( dest_buffer->texture != src->tex_buf[j].texture ) {
continue;
}
src_buffer = &src->tex_buf[j];
src_buff_size = (size_t)src_buffer->n_verts;
for ( k = 0; k < src_buff_size; ++k ) {
dest_buffer->assign(dest_buffer->n_verts, (uint32_t)(src_buffer->get_index()[k] + vert_offset)); // take into account the vertex offset.
dest_buffer->n_verts++;
Assert(dest_buffer->n_verts <= index_counts[dest_buffer->texture]);
}
}
}
}
void interp_fill_detail_index_buffer(SCP_vector<int> &submodel_list, polymodel *pm, vertex_buffer *buffer)
{
size_t index_counts[MAX_MODEL_TEXTURES];
int i, j;
int model_num;
for ( i = 0; i < MAX_MODEL_TEXTURES; ++i ) {
index_counts[i] = 0;
}
buffer->vertex_offset = 0;
buffer->vertex_num_offset = 0;
buffer->model_list = new(std::nothrow) poly_list;
int num_buffers;
int tex_num;
// need to first count how many indexes there are in this entire detail model hierarchy
for ( i = 0; i < (int)submodel_list.size(); ++i ) {
model_num = submodel_list[i];
if ( pm->submodel[model_num].is_thruster ) {
continue;
}
num_buffers = (int)pm->submodel[model_num].buffer.tex_buf.size();
buffer->flags |= pm->submodel[model_num].buffer.flags;
for ( j = 0; j < num_buffers; ++j ) {
tex_num = pm->submodel[model_num].buffer.tex_buf[j].texture;
index_counts[tex_num] += pm->submodel[model_num].buffer.tex_buf[j].n_verts;
}
}
// allocate the respective texture buffers with indexes for our detail buffer
for ( i = 0; i < MAX_MODEL_TEXTURES; ++i ) {
if ( index_counts[i] == 0 ) {
continue;
}
buffer->tex_buf.push_back(buffer_data(index_counts[i]));
buffer_data &new_buffer = buffer->tex_buf.back();
//new_buffer.n_verts = 0;
new_buffer.texture = i;
}
for ( i = 0; i < (int)buffer->tex_buf.size(); ++i ) {
buffer->tex_buf[i].n_verts = 0;
}
// finally copy over the indexes
for ( i = 0; i < (int)submodel_list.size(); ++i ) {
model_num = submodel_list[i];
if (pm->submodel[model_num].is_thruster) {
continue;
}
interp_copy_index_buffer(&pm->submodel[model_num].buffer, buffer, index_counts);
}
// check which buffers need to have the > USHORT flag
for ( i = 0; i < (int)buffer->tex_buf.size(); ++i ) {
if ( buffer->tex_buf[i].i_last >= USHRT_MAX ) {
buffer->tex_buf[i].flags |= VB_FLAG_LARGE_INDEX;
}
}
}
void interp_create_detail_index_buffer(polymodel *pm, int detail_num)
{
TRACE_SCOPE(tracing::ModelCreateDetailIndexBuffers);
SCP_vector<int> submodel_list;
submodel_list.clear();
model_get_submodel_tree_list(submodel_list, pm, pm->detail[detail_num]);
if ( submodel_list.empty() ) {
return;
}
interp_fill_detail_index_buffer(submodel_list, pm, &pm->detail_buffers[detail_num]);
// check if anything was even put into this buffer
if ( pm->detail_buffers[detail_num].tex_buf.empty() ) {
return;
}
model_interp_config_buffer(&pm->vert_source, &pm->detail_buffers[detail_num], true);
}
void interp_create_transparency_index_buffer(polymodel *pm, int mn)
{
TRACE_SCOPE(tracing::ModelCreateTransparencyIndexBuffer);
const int NUM_VERTS_PER_TRI = 3;
bsp_info *sub_model = &pm->submodel[mn];
vertex_buffer *trans_buffer = &sub_model->trans_buffer;
trans_buffer->model_list = new(std::nothrow) poly_list;
trans_buffer->vertex_offset = pm->submodel[mn].buffer.vertex_offset;
trans_buffer->vertex_num_offset = pm->submodel[mn].buffer.vertex_num_offset;
trans_buffer->stride = pm->submodel[mn].buffer.stride;
trans_buffer->flags = pm->submodel[mn].buffer.flags;
poly_list *model_list = pm->submodel[mn].buffer.model_list;
// bail out if this buffer is empty
if ( model_list == NULL || model_list->n_verts < 1 ) {
return;
}
SCP_vector<buffer_data> &tex_buffers = pm->submodel[mn].buffer.tex_buf;
uint current_tri[NUM_VERTS_PER_TRI];
bool transparent_tri = false;
int num_tris = 0;
for ( int i = 0; i < (int)tex_buffers.size(); ++i ) {
buffer_data *tex_buf = &tex_buffers[i];
if ( tex_buf->n_verts < 1 ) {
continue;
}
const uint *indices = tex_buf->get_index();
texture_map *tmap = &pm->maps[tex_buf->texture];
// skip if this is already designated to be a transparent pass by the modeller
// if ( tmap->is_transparent ) {
// continue;
// }
int bitmap_handle = tmap->textures[TM_BASE_TYPE].GetTexture();
if ( bitmap_handle < 0 || !bm_has_alpha_channel(bitmap_handle) ) {
continue;
}
bitmap_lookup texture_lookup(bitmap_handle);
if ( !texture_lookup.valid() ) {
continue;
}
SCP_vector<int> transparent_indices;
transparent_tri = false;
num_tris = 0;
for ( size_t j = 0; j < tex_buf->n_verts; ++j ) {
uint index = indices[j];
// need the uv coords of the vert at this index
float u = model_list->vert[index].texture_position.u;
float v = model_list->vert[index].texture_position.v;
if ( texture_lookup.get_channel_alpha(u, v) < 0.95f) {
transparent_tri = true;
}
current_tri[num_tris] = index;
num_tris++;
if ( num_tris == NUM_VERTS_PER_TRI ) {
if ( transparent_tri ) {
// we have a triangle and it's transparent.
// shove index into the transparency buffer
transparent_indices.push_back(current_tri[0]);
transparent_indices.push_back(current_tri[1]);
transparent_indices.push_back(current_tri[2]);
}
transparent_tri = false;
num_tris = 0;
}
}
if ( transparent_indices.empty() ) {
continue;
}
pm->flags |= PM_FLAG_TRANS_BUFFER;
trans_buffer->flags |= VB_FLAG_TRANS;
trans_buffer->tex_buf.push_back ( buffer_data ( transparent_indices.size() ) );
buffer_data &new_buff = trans_buffer->tex_buf.back();
new_buff.texture = tex_buf->texture;
for ( int j = 0; j < (int)transparent_indices.size(); ++j ) {
new_buff.assign(j, transparent_indices[j]);
}
}
if ( trans_buffer->flags & VB_FLAG_TRANS ) {
model_interp_config_buffer(&pm->vert_source, trans_buffer, true);
}
}
void model_interp_process_shield_mesh(polymodel * pm)
{
SCP_vector<vec3d> buffer;
if ( pm->shield.nverts <= 0 ) {
return;
}
int n_verts = 0;
for ( int i = 0; i < pm->shield.ntris; i++ ) {
shield_tri *tri = &pm->shield.tris[i];
vec3d a = pm->shield.verts[tri->verts[0]].pos;
vec3d b = pm->shield.verts[tri->verts[1]].pos;
vec3d c = pm->shield.verts[tri->verts[2]].pos;
// recalculate triangle normals to solve some issues regarding triangle collision
vec3d b_a;
vec3d c_a;
vm_vec_sub(&b_a, &b, &a);
vm_vec_sub(&c_a, &c, &a);
vm_vec_cross(&tri->norm, &b_a, &c_a);
vm_vec_normalize_safe(&tri->norm);
buffer.push_back(a);
buffer.push_back(tri->norm);
buffer.push_back(b);
buffer.push_back(tri->norm);
buffer.push_back(c);
buffer.push_back(tri->norm);
n_verts += 3;
}
if ( !buffer.empty() ) {
pm->shield.buffer_id = gr_create_buffer(BufferType::Vertex, BufferUsageHint::Static);
pm->shield.buffer_n_verts = n_verts;
gr_update_buffer_data(pm->shield.buffer_id, buffer.size() * sizeof(vec3d), &buffer[0]);
pm->shield.layout.add_vertex_component(vertex_format_data::POSITION3, sizeof(vec3d) * 2, 0);
pm->shield.layout.add_vertex_component(vertex_format_data::NORMAL, sizeof(vec3d) * 2, sizeof(vec3d));
} else {
pm->shield.buffer_id = gr_buffer_handle::invalid();
}
}
// returns 1 if the thruster should be drawn
// 0 if it shouldn't
int model_should_render_engine_glow(int objnum, int bank_obj)
{
if ((bank_obj <= -1) || (objnum <= -1))
return 1;
object *obj = &Objects[objnum];
if (obj->type == OBJ_SHIP) {
ship_subsys *ssp;
ship *shipp = &Ships[obj->instance];
ship_info *sip = &Ship_info[shipp->ship_info_index];
Assert( bank_obj < sip->n_subsystems );
char subname[MAX_NAME_LEN];
// shipp->subsystems isn't always valid here so don't use it
strcpy_s(subname, sip->subsystems[bank_obj].subobj_name);
ssp = GET_FIRST(&shipp->subsys_list);
while ( ssp != END_OF_LIST( &shipp->subsys_list ) ) {
if ( !strcmp(subname, ssp->system_info->subobj_name) ) {
// this subsystem has 0 or less hits, ie. it's destroyed
if ( ssp->current_hits <= 0 )
return 0;
// see if the subsystem is disrupted, in which case it should be inoperable
if ( ship_subsys_disrupted(ssp) )
return 0;
return 1;
}
ssp = GET_NEXT( ssp );
}
} else if (obj->type == OBJ_WEAPON) {
// for weapons, if needed in the future
}
// default to render glow
return 1;
}
// Goober5000
// uses same algorithms as in ship_do_thruster_frame
int model_interp_get_texture(texture_info *tinfo, fix base_frametime)
{
int texture, frame, num_frames;
float cur_time, total_time;
// get texture
num_frames = tinfo->GetNumFrames();
texture = tinfo->GetTexture();
total_time = tinfo->GetTotalTime();
// maybe animate it
if (texture >= 0 && num_frames > 1)
{
// sanity check total_time first thing
Assert(total_time > 0.0f);
cur_time = f2fl((game_get_overall_frametime() - base_frametime) % fl2f(total_time));
// get animation frame
frame = fl2i((cur_time * num_frames) / total_time);
CLAMP(frame, 0, num_frames - 1);
// advance to the correct frame
texture += frame;
}
// done
return texture;
}
void model_mix_two_team_colors(team_color* dest, team_color* a, team_color* b, float mix_factor)
{
dest->base.r = a->base.r * (1.0f - mix_factor) + b->base.r * mix_factor;
dest->base.g = a->base.g * (1.0f - mix_factor) + b->base.g * mix_factor;
dest->base.b = a->base.b * (1.0f - mix_factor) + b->base.b * mix_factor;
dest->stripe.r = a->stripe.r * (1.0f - mix_factor) + b->stripe.r * mix_factor;
dest->stripe.g = a->stripe.g * (1.0f - mix_factor) + b->stripe.g * mix_factor;
dest->stripe.b = a->stripe.b * (1.0f - mix_factor) + b->stripe.b * mix_factor;
}
bool model_get_team_color( team_color *clr, const SCP_string &team, const SCP_string &secondaryteam, fix timestamp, int fadetime )
{
Assert(clr != NULL);
if ( !stricmp(secondaryteam.c_str(), "none") ) {
if (Team_Colors.find(team) != Team_Colors.end()) {
*clr = Team_Colors[team];
return true;
} else
return false;
} else {
if ( Team_Colors.find(secondaryteam) != Team_Colors.end()) {
team_color temp_color;
team_color start;
if (Team_Colors.find(team) != Team_Colors.end()) {
start = Team_Colors[team];
} else {
start.base.r = 0.0f;
start.base.g = 0.0f;
start.base.b = 0.0f;
start.stripe.r = 0.0f;
start.stripe.g = 0.0f;
start.stripe.b = 0.0f;
}
team_color end = Team_Colors[secondaryteam];
float time_remaining = 0.0f;
if (fadetime != 0) // avoid potential div-by-zero
time_remaining = (f2fl(Missiontime - timestamp) * 1000)/fadetime;
CLAMP(time_remaining, 0.0f, 1.0f);
model_mix_two_team_colors(&temp_color, &start, &end, time_remaining);
*clr = temp_color;
return true;
} else
return false;
}
}
//********************-----CLASS: texture_info-----********************//
texture_info::texture_info()
{
clear();
}
texture_info::texture_info(int bm_handle)
{
if(!bm_is_valid(bm_handle))
{
clear();
return;
}
this->original_texture = bm_handle;
this->ResetTexture();
}
void texture_info::clear()
{
texture = original_texture = -1;
num_frames = 0;
total_time = 1.0f;
}
int texture_info::GetNumFrames()
{
return num_frames;
}
int texture_info::GetOriginalTexture()
{
return original_texture;
}
int texture_info::GetTexture()
{
return texture;
}
float texture_info::GetTotalTime()
{
return total_time;
}
int texture_info::LoadTexture(const char *filename, const char *dbg_name)
{
if (strlen(filename) + 4 >= NAME_LENGTH) //Filenames are passed in without extension
{
mprintf(("Generated texture name %s is too long. Skipping...\n", filename));
return -1;
}
this->original_texture = bm_load_either(filename, NULL, NULL, NULL, true, CF_TYPE_MAPS);
if(this->original_texture < 0)
nprintf(("Maps", "For \"%s\" I couldn't find %s.ani\n", dbg_name, filename));
this->ResetTexture();
return texture;
}
void texture_info::PageIn()
{
bm_page_in_texture(texture);
}
void texture_info::PageOut(bool release)
{
if (texture >= 0) {
if (release) {
bm_release(texture);
texture = -1;
num_frames = 0;
total_time = 1.0f;
} else {
bm_unload(texture);
}
}
}
int texture_info::ResetTexture()
{
return this->SetTexture(original_texture);
}
int texture_info::SetTexture(int n_tex)
{
if(n_tex != -1 && !bm_is_valid(n_tex))
return texture;
//Set the new texture
texture = n_tex;
//If it is intentionally invalid, blank everything else
if(n_tex == -1)
{
num_frames = 0;
total_time = 1.0f;
}
else
{
//Determine the num_frames and total_time values.
int fps = 0;
this->num_frames = 1;
bm_get_info(texture, NULL, NULL, NULL, &this->num_frames, &fps);
this->total_time = (num_frames / ((fps > 0) ? (float)fps : 1.0f));
}
return texture;
}
//********************-----CLASS: texture_map-----********************//
int texture_map::FindTexture(int bm_handle)
{
if(!bm_is_valid(bm_handle))
return -1;
for(int i = 0; i < TM_NUM_TYPES; i++)
{
if (this->textures[i].GetTexture() == bm_handle)
return i;
}
return -1;
}
int texture_map::FindTexture(const char* fname)
{
if(fname == NULL || !strlen(fname))
return -1;
char buf[NAME_LENGTH];
for(int i = 0; i < TM_NUM_TYPES; i++)
{
bm_get_filename(this->textures[i].GetTexture(), buf);
if (!strextcmp(buf, fname)) {
return i;
}
}
return -1;
}
void texture_map::PageIn()
{
for(int i = 0; i < TM_NUM_TYPES; i++)
this->textures[i].PageIn();
}
void texture_map::PageOut(bool release)
{
for(int i = 0; i < TM_NUM_TYPES; i++)
this->textures[i].PageOut(release);
}
void texture_map::Clear()
{
is_ambient = false;
is_transparent = false;
for(int i = 0; i < TM_NUM_TYPES; i++)
this->textures[i].clear();
}
void texture_map::ResetToOriginal()
{
for(int i = 0; i < TM_NUM_TYPES; i++)
this->textures[i].ResetTexture();
}
bsp_polygon_data::bsp_polygon_data(ubyte* bsp_data)
{
Polygon_vertices.clear();
Polygons.clear();
for (int i = 0; i < MAX_MODEL_TEXTURES; ++i) {
Num_verts[i] = 0;
Num_polies[i] = 0;
}
Num_flat_verts = 0;
Num_flat_polies = 0;
process_bsp(0, bsp_data);
}
void bsp_polygon_data::process_bsp(int offset, ubyte* bsp_data)
{
int id = w(bsp_data + offset);
int size = w(bsp_data + offset + 4);
while (id != 0) {
switch (id)
{
case OP_DEFPOINTS:
process_defpoints(offset, bsp_data);
break;
case OP_SORTNORM:
process_sortnorm(offset, bsp_data);
break;
case OP_FLATPOLY:
process_flat(offset, bsp_data);
break;
case OP_TMAPPOLY:
process_tmap(offset, bsp_data);
break;
case OP_BOUNDBOX:
break;
default:
return;
}
offset += size;
id = w(bsp_data + offset);
size = w(bsp_data + offset + 4);
if (size < 1)
id = OP_EOF;
}
}
void bsp_polygon_data::process_defpoints(int off, ubyte* bsp_data)
{
int i, n;
int nverts = w(off + bsp_data + 8);
int offset = w(off + bsp_data + 16);
ubyte *normcount = off + bsp_data + 20;
vec3d *src = vp(off + bsp_data + offset);
// Get pointer to lights
Lights = off + bsp_data + 20 + nverts;
#ifndef NDEBUG
modelstats_num_verts += nverts;
#endif
Vertex_list.clear();
Normal_list.clear();
for (n = 0; n < nverts; n++) {
Vertex_list.push_back(*src);
src++; // move to normal
for (i = 0; i < normcount[n]; i++) {
Normal_list.push_back(*src);
src++;
}
}
}
void bsp_polygon_data::process_sortnorm(int offset, ubyte* bsp_data)
{
int frontlist, backlist, prelist, postlist, onlist;
frontlist = w(bsp_data + offset + 36);
backlist = w(bsp_data + offset + 40);
prelist = w(bsp_data + offset + 44);
postlist = w(bsp_data + offset + 48);
onlist = w(bsp_data + offset + 52);
if (prelist) process_bsp(offset + prelist, bsp_data);
if (backlist) process_bsp(offset + backlist, bsp_data);
if (onlist) process_bsp(offset + onlist, bsp_data);
if (frontlist) process_bsp(offset + frontlist, bsp_data);
if (postlist) process_bsp(offset + postlist, bsp_data);
}
void bsp_polygon_data::process_tmap(int offset, ubyte* bsp_data)
{
int pof_tex = w(bsp_data + offset + 40);
int n_vert = w(bsp_data + offset + 36);
if ( n_vert < 3 ) {
// don't parse degenerate polygons
return;
}
ubyte *p = &bsp_data[offset + 8];
model_tmap_vert *tverts;
tverts = (model_tmap_vert *)&bsp_data[offset + 44];
int problem_count = 0;
// make a polygon
bsp_polygon polygon;
polygon.Start_index = (uint)Polygon_vertices.size();
polygon.Num_verts = n_vert;
polygon.texture = pof_tex;
// this polygon will be broken up into a triangle fan. first three verts make up the first triangle
// additional verts are made into new tris
Num_polies[pof_tex]++;
Num_verts[pof_tex] += n_vert;
// stuff data making up the vertices of this polygon
for ( int i = 0; i < n_vert; ++i ) {
bsp_vertex vert;
vert.position = Vertex_list[(int)tverts[i].vertnum];
vert.tex_coord.u = tverts[i].u;
vert.tex_coord.v = tverts[i].v;
vert.normal = Normal_list[(int)tverts[i].normnum];
// see if this normal is okay
if (IS_VEC_NULL(&vert.normal))
vert.normal = *vp(p);
problem_count += check_values(&vert.normal);
vm_vec_normalize_safe(&vert.normal);
Polygon_vertices.push_back(vert);
}
Polygons.push_back(polygon);
Parse_normal_problem_count += problem_count;
}
void bsp_polygon_data::process_flat(int offset, ubyte* bsp_data)
{
int n_vert = w(bsp_data + offset + 36);
if (n_vert < 3) {
// don't parse degenerate polygons
return;
}
short * verts = (short *)(bsp_data + offset + 44);
ubyte r = *(bsp_data + offset + 40);
ubyte g = *(bsp_data + offset + 41);
ubyte b = *(bsp_data + offset + 42);
bsp_polygon polygon;
polygon.Start_index = (uint)Polygon_vertices.size();
polygon.Num_verts = n_vert;
polygon.texture = -1;
Num_flat_polies++;
Num_flat_verts += n_vert;
for (int i = 0; i < n_vert; i++) {
bsp_vertex vert;
int vertnum = verts[i * 2 + 0];
int norm = verts[i * 2 + 1];
vert.position = Vertex_list[vertnum];
vert.normal = Normal_list[norm];
vert.r = r;
vert.g = g;
vert.b = b;
vert.a = 255;
Polygon_vertices.push_back(vert);
}
Polygons.push_back(polygon);
}
int bsp_polygon_data::get_num_triangles(int texture)
{
if ( texture < 0 ) {
return MAX(Num_flat_verts - 2 * Num_flat_polies, 0);
}
return MAX(Num_verts[texture] - 2 * Num_polies[texture], 0);
}
int bsp_polygon_data::get_num_lines(int texture)
{
if (texture < 0) {
return Num_flat_verts;
}
return Num_verts[texture];
}
void bsp_polygon_data::generate_triangles(int texture, vertex *vert_ptr, vec3d* norm_ptr)
{
int num_verts = 0;
for ( uint i = 0; i < Polygons.size(); ++i ) {
if ( Polygons[i].texture != texture ) {
continue;
}
uint start_index = Polygons[i].Start_index;
uint end_index = Polygons[i].Start_index + Polygons[i].Num_verts;
for ( uint j = start_index + 1; j < end_index - 1; ++j ) {
// first vertex of this triangle. Always the first vertex of the polygon
vertex* vert = &vert_ptr[num_verts];
vert->world = Polygon_vertices[start_index].position;
vert->texture_position = Polygon_vertices[start_index].tex_coord;
vec3d* norm = &norm_ptr[num_verts];
*norm = Polygon_vertices[start_index].normal;
// second vertex of this triangle.
vert = &vert_ptr[num_verts + 1];
vert->world = Polygon_vertices[j].position;
vert->texture_position = Polygon_vertices[j].tex_coord;
norm = &norm_ptr[num_verts + 1];
*norm = Polygon_vertices[j].normal;
// third vertex of this triangle.
vert = &vert_ptr[num_verts + 2];
vert->world = Polygon_vertices[j+1].position;
vert->texture_position = Polygon_vertices[j+1].tex_coord;
norm = &norm_ptr[num_verts + 2];
*norm = Polygon_vertices[j+1].normal;
num_verts += 3;
}
}
}
void bsp_polygon_data::generate_lines(int texture, vertex *vert_ptr)
{
int num_verts = 0;
for (uint i = 0; i < Polygons.size(); ++i) {
if (Polygons[i].texture != texture) {
continue;
}
uint start_index = Polygons[i].Start_index;
uint end_index = Polygons[i].Start_index + Polygons[i].Num_verts;
for (uint j = start_index; j < end_index; ++j) {
// first vertex of this triangle. Always the first vertex of the polygon
vertex* vert = &vert_ptr[num_verts];
vert->world = Polygon_vertices[j].position;
vert->r = Polygon_vertices[j].r;
vert->g = Polygon_vertices[j].g;
vert->b = Polygon_vertices[j].b;
vert->a = Polygon_vertices[j].a;
if ( j == end_index - 1 ) {
vert = &vert_ptr[num_verts + 1];
vert->world = Polygon_vertices[start_index].position;
vert->r = Polygon_vertices[start_index].r;
vert->g = Polygon_vertices[start_index].g;
vert->b = Polygon_vertices[start_index].b;
vert->a = Polygon_vertices[start_index].a;
} else {
vert = &vert_ptr[num_verts + 1];
vert->world = Polygon_vertices[j + 1].position;
vert->r = Polygon_vertices[j + 1].r;
vert->g = Polygon_vertices[j + 1].g;
vert->b = Polygon_vertices[j + 1].b;
vert->a = Polygon_vertices[j + 1].a;
}
num_verts += 2;
}
}
}
| 25.527102 | 217 | 0.679983 | [
"mesh",
"render",
"object",
"vector",
"model",
"3d"
] |
ba20b0abd7ef01064e5cfad4e9c3eabdb7a12a91 | 9,598 | cpp | C++ | template/diy/modules/log.cpp | cjryan/znc-openshift-manifest | 7874275a5d41e5a312d4ed77349f3b9d0b8f3b1e | [
"Apache-2.0"
] | 1 | 2015-03-21T07:19:24.000Z | 2015-03-21T07:19:24.000Z | modules/log.cpp | trisk/znc | 97207113d0e4cb3d8d73203b60bef8d88572f8b2 | [
"Apache-2.0"
] | null | null | null | modules/log.cpp | trisk/znc | 97207113d0e4cb3d8d73203b60bef8d88572f8b2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2004-2014 ZNC, see the NOTICE file for details.
* Copyright (C) 2006-2007, CNU <bshalm@broadpark.no> (http://cnu.dieplz.net/znc)
*
* 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 <znc/FileUtils.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Chan.h>
#include <znc/Server.h>
using std::vector;
class CLogMod: public CModule {
public:
MODCONSTRUCTOR(CLogMod)
{
m_bSanitize = false;
}
void PutLog(const CString& sLine, const CString& sWindow = "status");
void PutLog(const CString& sLine, const CChan& Channel);
void PutLog(const CString& sLine, const CNick& Nick);
CString GetServer();
virtual bool OnLoad(const CString& sArgs, CString& sMessage);
virtual void OnIRCConnected();
virtual void OnIRCDisconnected();
virtual EModRet OnBroadcast(CString& sMessage);
virtual void OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs);
virtual void OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage);
virtual void OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans);
virtual void OnJoin(const CNick& Nick, CChan& Channel);
virtual void OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage);
virtual void OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans);
virtual EModRet OnTopic(CNick& Nick, CChan& Channel, CString& sTopic);
/* notices */
virtual EModRet OnUserNotice(CString& sTarget, CString& sMessage);
virtual EModRet OnPrivNotice(CNick& Nick, CString& sMessage);
virtual EModRet OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage);
/* actions */
virtual EModRet OnUserAction(CString& sTarget, CString& sMessage);
virtual EModRet OnPrivAction(CNick& Nick, CString& sMessage);
virtual EModRet OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage);
/* msgs */
virtual EModRet OnUserMsg(CString& sTarget, CString& sMessage);
virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage);
virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage);
private:
CString m_sLogPath;
bool m_bSanitize;
};
void CLogMod::PutLog(const CString& sLine, const CString& sWindow /*= "Status"*/)
{
CString sPath;
time_t curtime;
time(&curtime);
// Generate file name
sPath = CUtils::FormatTime(curtime, m_sLogPath, m_pUser->GetTimezone());
if (sPath.empty())
{
DEBUG("Could not format log path [" << sPath << "]");
return;
}
// $WINDOW has to be handled last, since it can contain %
sPath.Replace("$NETWORK", (m_pNetwork ? m_pNetwork->GetName() : "znc"));
sPath.Replace("$WINDOW", sWindow.Replace_n("/", "-").Replace_n("\\", "-"));
sPath.Replace("$USER", (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"));
// Check if it's allowed to write in this specific path
sPath = CDir::CheckPathPrefix(GetSavePath(), sPath);
if (sPath.empty())
{
DEBUG("Invalid log path ["<<m_sLogPath<<"].");
return;
}
CFile LogFile(sPath);
CString sLogDir = LogFile.GetDir();
struct stat ModDirInfo;
CFile::GetInfo(GetSavePath(), ModDirInfo);
if (!CFile::Exists(sLogDir)) CDir::MakeDir(sLogDir, ModDirInfo.st_mode);
if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
{
LogFile.Write(CUtils::FormatTime(curtime, "[%H:%M:%S] ", m_pUser->GetTimezone()) + (m_bSanitize ? sLine.StripControls_n() : sLine) + "\n");
} else
DEBUG("Could not open log file [" << sPath << "]: " << strerror(errno));
}
void CLogMod::PutLog(const CString& sLine, const CChan& Channel)
{
PutLog(sLine, Channel.GetName());
}
void CLogMod::PutLog(const CString& sLine, const CNick& Nick)
{
PutLog(sLine, Nick.GetNick());
}
CString CLogMod::GetServer()
{
CServer* pServer = m_pNetwork->GetCurrentServer();
CString sSSL;
if (!pServer)
return "(no server)";
if (pServer->IsSSL())
sSSL = "+";
return pServer->GetName() + " " + sSSL + CString(pServer->GetPort());
}
bool CLogMod::OnLoad(const CString& sArgs, CString& sMessage)
{
size_t uIndex = 0;
if (sArgs.Token(0).Equals("-sanitize"))
{
m_bSanitize = true;
++uIndex;
}
// Use load parameter as save path
m_sLogPath = sArgs.Token(uIndex);
// Add default filename to path if it's a folder
if (GetType() == CModInfo::UserModule) {
if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) {
if (!m_sLogPath.empty()) {
m_sLogPath += "/";
}
m_sLogPath += "$NETWORK_$WINDOW_%Y%m%d.log";
}
} else if (GetType() == CModInfo::NetworkModule) {
if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$WINDOW") == CString::npos) {
if (!m_sLogPath.empty()) {
m_sLogPath += "/";
}
m_sLogPath += "$WINDOW_%Y%m%d.log";
}
} else {
if (m_sLogPath.Right(1) == "/" || m_sLogPath.find("$USER") == CString::npos || m_sLogPath.find("$WINDOW") == CString::npos || m_sLogPath.find("$NETWORK") == CString::npos) {
if (!m_sLogPath.empty()) {
m_sLogPath += "/";
}
m_sLogPath += "$USER_$NETWORK_$WINDOW_%Y%m%d.log";
}
}
// Check if it's allowed to write in this path in general
m_sLogPath = CDir::CheckPathPrefix(GetSavePath(), m_sLogPath);
if (m_sLogPath.empty())
{
sMessage = "Invalid log path ["+m_sLogPath+"].";
return false;
} else {
sMessage = "Logging to ["+m_sLogPath+"].";
return true;
}
}
void CLogMod::OnIRCConnected()
{
PutLog("Connected to IRC (" + GetServer() + ")");
}
void CLogMod::OnIRCDisconnected()
{
PutLog("Disconnected from IRC (" + GetServer() + ")");
}
CModule::EModRet CLogMod::OnBroadcast(CString& sMessage)
{
PutLog("Broadcast: " + sMessage);
return CONTINUE;
}
void CLogMod::OnRawMode(const CNick& OpNick, CChan& Channel, const CString& sModes, const CString& sArgs)
{
PutLog("*** " + OpNick.GetNick() + " sets mode: " + sModes + " " + sArgs, Channel);
}
void CLogMod::OnKick(const CNick& OpNick, const CString& sKickedNick, CChan& Channel, const CString& sMessage)
{
PutLog("*** " + sKickedNick + " was kicked by " + OpNick.GetNick() + " (" + sMessage + ")", Channel);
}
void CLogMod::OnQuit(const CNick& Nick, const CString& sMessage, const vector<CChan*>& vChans)
{
for (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan)
PutLog("*** Quits: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", **pChan);
}
void CLogMod::OnJoin(const CNick& Nick, CChan& Channel)
{
PutLog("*** Joins: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ")", Channel);
}
void CLogMod::OnPart(const CNick& Nick, CChan& Channel, const CString& sMessage)
{
PutLog("*** Parts: " + Nick.GetNick() + " (" + Nick.GetIdent() + "@" + Nick.GetHost() + ") (" + sMessage + ")", Channel);
}
void CLogMod::OnNick(const CNick& OldNick, const CString& sNewNick, const vector<CChan*>& vChans)
{
for (std::vector<CChan*>::const_iterator pChan = vChans.begin(); pChan != vChans.end(); ++pChan)
PutLog("*** " + OldNick.GetNick() + " is now known as " + sNewNick, **pChan);
}
CModule::EModRet CLogMod::OnTopic(CNick& Nick, CChan& Channel, CString& sTopic)
{
PutLog("*** " + Nick.GetNick() + " changes topic to '" + sTopic + "'", Channel);
return CONTINUE;
}
/* notices */
CModule::EModRet CLogMod::OnUserNotice(CString& sTarget, CString& sMessage)
{
if (m_pNetwork) {
PutLog("-" + m_pNetwork->GetCurNick() + "- " + sMessage, sTarget);
}
return CONTINUE;
}
CModule::EModRet CLogMod::OnPrivNotice(CNick& Nick, CString& sMessage)
{
PutLog("-" + Nick.GetNick() + "- " + sMessage, Nick);
return CONTINUE;
}
CModule::EModRet CLogMod::OnChanNotice(CNick& Nick, CChan& Channel, CString& sMessage)
{
PutLog("-" + Nick.GetNick() + "- " + sMessage, Channel);
return CONTINUE;
}
/* actions */
CModule::EModRet CLogMod::OnUserAction(CString& sTarget, CString& sMessage)
{
if (m_pNetwork) {
PutLog("* " + m_pNetwork->GetCurNick() + " " + sMessage, sTarget);
}
return CONTINUE;
}
CModule::EModRet CLogMod::OnPrivAction(CNick& Nick, CString& sMessage)
{
PutLog("* " + Nick.GetNick() + " " + sMessage, Nick);
return CONTINUE;
}
CModule::EModRet CLogMod::OnChanAction(CNick& Nick, CChan& Channel, CString& sMessage)
{
PutLog("* " + Nick.GetNick() + " " + sMessage, Channel);
return CONTINUE;
}
/* msgs */
CModule::EModRet CLogMod::OnUserMsg(CString& sTarget, CString& sMessage)
{
if (m_pNetwork) {
PutLog("<" + m_pNetwork->GetCurNick() + "> " + sMessage, sTarget);
}
return CONTINUE;
}
CModule::EModRet CLogMod::OnPrivMsg(CNick& Nick, CString& sMessage)
{
PutLog("<" + Nick.GetNick() + "> " + sMessage, Nick);
return CONTINUE;
}
CModule::EModRet CLogMod::OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage)
{
PutLog("<" + Nick.GetNick() + "> " + sMessage, Channel);
return CONTINUE;
}
template<> void TModInfo<CLogMod>(CModInfo& Info) {
Info.AddType(CModInfo::NetworkModule);
Info.AddType(CModInfo::GlobalModule);
Info.SetHasArgs(true);
Info.SetArgsHelpText("[-sanitize] Optional path where to store logs.");
Info.SetWikiPage("log");
}
USERMODULEDEFS(CLogMod, "Write IRC logs")
| 30.861736 | 175 | 0.677537 | [
"vector"
] |
ba20b8acdf719ef3984a96369222f19976d5a9eb | 4,475 | cc | C++ | src/bringup/bin/bootsvc/bootfs-loader-service-test.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/bringup/bin/bootsvc/bootfs-loader-service-test.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/bringup/bin/bootsvc/bootfs-loader-service-test.cc | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/bringup/bin/bootsvc/bootfs-loader-service.h"
#include <lib/fit/defer.h>
#include <lib/zx/vmar.h>
#include <zircon/boot/bootfs.h>
#include <zircon/errors.h>
#include <cstddef>
#include <gtest/gtest.h>
#include "src/lib/loader_service/loader_service_test_fixture.h"
#define ASSERT_OK(expr) ASSERT_EQ(ZX_OK, expr)
#define EXPECT_OK(expr) EXPECT_EQ(ZX_OK, expr)
namespace bootsvc {
namespace {
using namespace loader::test;
namespace fldsvc = fuchsia_ldsvc;
struct BootfsDirectoryEntry {
std::string path;
std::string file_contents;
};
static zx::status<zx::vmo> GenerateBootfs(std::vector<BootfsDirectoryEntry> config) {
// Simplified VMO size calculation assuming each file's contents is no larger than a page (checked
// below) and dirents are max size.
uint64_t data_start =
ZBI_BOOTFS_PAGE_ALIGN(sizeof(zbi_bootfs_header_t) +
config.size() * ZBI_BOOTFS_DIRENT_SIZE(ZBI_BOOTFS_MAX_NAME_LEN));
uint64_t vmo_size = data_start + config.size() * ZBI_BOOTFS_PAGE_SIZE;
zx::vmo vmo;
zx_status_t status = zx::vmo::create(vmo_size, 0, &vmo);
if (status != ZX_OK) {
return zx::error(status);
}
uintptr_t mapped = 0;
status =
zx::vmar::root_self()->map(ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, vmo_size, &mapped);
if (status != ZX_OK) {
return zx::error(status);
}
auto unmap = fit::defer([=] { zx::vmar::root_self()->unmap(mapped, vmo_size); });
// Write directory entries and data.
uintptr_t dirent_ptr = mapped + sizeof(zbi_bootfs_header_t);
uintptr_t data_ptr = mapped + data_start;
for (auto entry : config) {
auto dirent = reinterpret_cast<zbi_bootfs_dirent_t*>(dirent_ptr);
char* data = reinterpret_cast<char*>(data_ptr);
dirent->name_len = entry.path.size() + 1;
dirent->data_len = entry.file_contents.size() + 1;
if (dirent->data_len > ZBI_BOOTFS_PAGE_SIZE) {
// Check assumption made above when sizing VMO.
return zx::error(ZX_ERR_INTERNAL);
}
dirent->data_off = data_ptr - mapped;
memcpy(dirent->name, entry.path.c_str(), dirent->name_len);
memcpy(data, entry.file_contents.c_str(), dirent->data_len);
dirent_ptr += ZBI_BOOTFS_DIRENT_SIZE(dirent->name_len);
data_ptr += ZBI_BOOTFS_PAGE_SIZE;
}
// Write main header now that we know exact size of dirents.
auto hdr = reinterpret_cast<zbi_bootfs_header_t*>(mapped);
hdr->magic = ZBI_BOOTFS_MAGIC;
hdr->dirsize = dirent_ptr - mapped - sizeof(zbi_bootfs_header_t);
return zx::ok(std::move(vmo));
}
class BootfsLoaderServiceTest : public LoaderServiceTest {
public:
void CreateTestLoader(std::vector<BootfsDirectoryEntry> config,
std::shared_ptr<BootfsLoaderService>* loader) {
zx::resource vmex;
zx::status<zx::unowned_resource> unowned_vmex = GetVmexResource();
ASSERT_OK(unowned_vmex.status_value());
ASSERT_TRUE(unowned_vmex.value()->is_valid());
ASSERT_OK(unowned_vmex.value()->duplicate(ZX_RIGHT_SAME_RIGHTS, &vmex));
fbl::RefPtr<BootfsService> bootfs_svc;
ASSERT_OK(BootfsService::Create(fs_loop().dispatcher(), std::move(vmex), &bootfs_svc));
auto bootfs_vmo = GenerateBootfs(std::move(config));
ASSERT_OK(bootfs_vmo.status_value());
ASSERT_OK(bootfs_svc->AddBootfs(std::move(bootfs_vmo).value()));
*loader = BootfsLoaderService::Create(loader_loop().dispatcher(), std::move(bootfs_svc));
ASSERT_OK(fs_loop().StartThread("fs_loop"));
ASSERT_OK(loader_loop().StartThread("loader_loop"));
}
};
TEST_F(BootfsLoaderServiceTest, LoadObject) {
std::shared_ptr<BootfsLoaderService> loader;
std::vector<BootfsDirectoryEntry> config = {
{"lib/libfoo.so", "foo"},
{"lib/asan/libfoo.so", "asan foo"},
};
ASSERT_NO_FATAL_FAILURE(CreateTestLoader(std::move(config), &loader));
auto status = loader->Connect();
ASSERT_TRUE(status.is_ok());
fidl::WireSyncClient<fldsvc::Loader> client(std::move(status.value()));
EXPECT_NO_FATAL_FAILURE(LoadObject(client, "missing", zx::error(ZX_ERR_NOT_FOUND)));
EXPECT_NO_FATAL_FAILURE(LoadObject(client, "libfoo.so", zx::ok("foo")));
ASSERT_NO_FATAL_FAILURE(Config(client, "asan", zx::ok(ZX_OK)));
EXPECT_NO_FATAL_FAILURE(LoadObject(client, "libfoo.so", zx::ok("asan foo")));
}
} // namespace
} // namespace bootsvc
| 34.689922 | 100 | 0.712179 | [
"vector"
] |
ba251d4fa2bb4b39d828ac2bab93cdf157be5fc8 | 3,468 | cc | C++ | src/thirdparty/harfbuzz/src/hb-ot-shape-complex-syllabic.cc | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | src/thirdparty/harfbuzz/src/hb-ot-shape-complex-syllabic.cc | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | src/thirdparty/harfbuzz/src/hb-ot-shape-complex-syllabic.cc | devbrain/neutrino | 5e7cd7c93b5c264a5f1da6ae88312e14253de10d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2021 Behdad Esfahbod.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include "hb.hh"
#ifndef HB_NO_OT_SHAPE
#include "hb-ot-shape-complex-syllabic.hh"
void
hb_syllabic_insert_dotted_circles (hb_font_t* font,
hb_buffer_t* buffer,
unsigned int broken_syllable_type,
unsigned int dottedcircle_category,
int repha_category,
int dottedcircle_position) {
if (unlikely (buffer->flags & HB_BUFFER_FLAG_DO_NOT_INSERT_DOTTED_CIRCLE))
return;
/* Note: This loop is extra overhead, but should not be measurable.
* TODO Use a buffer scratch flag to remove the loop. */
bool has_broken_syllables = false;
unsigned int count = buffer->len;
hb_glyph_info_t* info = buffer->info;
for (unsigned int i = 0; i < count; i++)
if ((info[i].syllable() & 0x0F) == broken_syllable_type) {
has_broken_syllables = true;
break;
}
if (likely (!has_broken_syllables))
return;
hb_codepoint_t dottedcircle_glyph;
if (!font->get_nominal_glyph (0x25CCu, &dottedcircle_glyph))
return;
hb_glyph_info_t dottedcircle = {0};
dottedcircle.codepoint = 0x25CCu;
dottedcircle.complex_var_u8_category() = dottedcircle_category;
if (dottedcircle_position != -1)
dottedcircle.complex_var_u8_auxiliary() = dottedcircle_position;
dottedcircle.codepoint = dottedcircle_glyph;
buffer->clear_output ();
buffer->idx = 0;
unsigned int last_syllable = 0;
while (buffer->idx < buffer->len && buffer->successful) {
unsigned int syllable = buffer->cur ().syllable();
if (unlikely (last_syllable != syllable && (syllable & 0x0F) == broken_syllable_type)) {
last_syllable = syllable;
hb_glyph_info_t ginfo = dottedcircle;
ginfo.cluster = buffer->cur ().cluster;
ginfo.mask = buffer->cur ().mask;
ginfo.syllable() = buffer->cur ().syllable();
/* Insert dottedcircle after possible Repha. */
if (repha_category != -1) {
while (buffer->idx < buffer->len && buffer->successful &&
last_syllable == buffer->cur ().syllable() &&
buffer->cur ().complex_var_u8_category() == (unsigned) repha_category)
(void) buffer->next_glyph ();
}
(void) buffer->output_info (ginfo);
}
else
(void) buffer->next_glyph ();
}
buffer->swap_buffers ();
}
#endif
| 36.125 | 92 | 0.672145 | [
"shape"
] |
ba26ce6df43dcf2776623c25f56c156462d231c8 | 14,911 | cpp | C++ | FECore/FELinearConstraintManager.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | FECore/FELinearConstraintManager.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | FECore/FELinearConstraintManager.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FELinearConstraintManager.h"
#include "FEMesh.h"
#include "FEModel.h"
#include "FEAnalysis.h"
#include "DumpStream.h"
#include "FEDomain.h"
//-----------------------------------------------------------------------------
FELinearConstraintManager::FELinearConstraintManager(FEModel* fem) : m_fem(fem)
{
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::Clear()
{
for (size_t i = 0; i < m_LinC.size(); ++i) delete m_LinC[i];
m_LinC.clear();
}
//-----------------------------------------------------------------------------
FELinearConstraintManager::~FELinearConstraintManager()
{
Clear();
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::CopyFrom(const FELinearConstraintManager& lcm)
{
Clear();
for (int i=0; i<lcm.LinearConstraints(); ++i)
{
FELinearConstraint* lc = new FELinearConstraint(m_fem);
lc->CopyFrom(lcm.LinearConstraint(i));
m_LinC.push_back(lc);
}
InitTable();
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::AddLinearConstraint(FELinearConstraint* lc)
{
m_LinC.push_back(lc);
}
//-----------------------------------------------------------------------------
int FELinearConstraintManager::LinearConstraints() const
{
return (int)m_LinC.size();
}
//-----------------------------------------------------------------------------
const FELinearConstraint& FELinearConstraintManager::LinearConstraint(int i) const
{
return *m_LinC[i];
}
//-----------------------------------------------------------------------------
FELinearConstraint& FELinearConstraintManager::LinearConstraint(int i)
{
return *m_LinC[i];
}
//-----------------------------------------------------------------------------
//! remove a linear constraint
void FELinearConstraintManager::RemoveLinearConstraint(int i)
{
FELinearConstraint& lc = *m_LinC[i];
if (lc.IsActive()) lc.Deactivate();
m_LinC.erase(m_LinC.begin() + i);
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::Serialize(DumpStream& ar)
{
if (ar.IsShallow()) return;
if (ar.IsSaving())
{
ar << m_LinC;
int nr = m_LCT.rows();
int nc = m_LCT.columns();
ar << nr << nc;
if (nr*nc > 0)
{
ar.write(&m_LCT(0,0), sizeof(int), nr*nc);
}
}
else
{
FEModel& fem = ar.GetFEModel();
// linear constraints
ar >> m_LinC;
int nr, nc;
ar >> nr >> nc;
if (nr*nc > 0)
{
m_LCT.resize(nr, nc);
ar.read(&m_LCT(0,0), sizeof(int), nr*nc);
}
}
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::BuildMatrixProfile(FEGlobalMatrix& G)
{
int nlin = (int)m_LinC.size();
if (nlin == 0) return;
FEAnalysis* pstep = m_fem->GetCurrentStep();
FEMesh& mesh = m_fem->GetMesh();
// Add linear constraints to the profile
// TODO: we need to add a function build_add(lmi, lmj) for
// this type of "elements". Now we allocate too much memory
vector<int> lm, elm;
// do the cross-term
// TODO: I have to make this easier. For instance,
// keep a list that stores for each node the list of
// elements connected to that node.
// loop over all solid elements
for (int nd = 0; nd<pstep->Domains(); ++nd)
{
FEDomain& dom = *pstep->Domain(nd);
for (int i = 0; i<dom.Elements(); ++i)
{
FEElement& el = dom.ElementRef(i);
dom.UnpackLM(el, elm);
int ne = (int)elm.size();
// keep a list of the constraints this element connects to
vector<int> constraintList;
// see if this element connects to the
// parent node of a linear constraint ...
int m = el.Nodes();
for (int j = 0; j<m; ++j)
{
int ncols = m_LCT.columns();
for (int k = 0; k<ncols; ++k)
{
int n = m_LCT(el.m_node[j], k);
if (n >= 0)
{
// ... it does so we need to connect the
// element to the linear constraint
FELinearConstraint* plc = m_LinC[n];
constraintList.push_back(n);
int ns = (int)plc->Size();
lm.resize(ne + ns);
for (int l = 0; l<ne; ++l) lm[l] = elm[l];
FELinearConstraint::dof_iterator is = plc->begin();
for (int l = ne; l<ne + ns; ++l, ++is)
{
int neq = mesh.Node((*is)->node).m_ID[(*is)->dof];
lm[l] = neq;
}
G.build_add(lm);
}
}
}
// This replaces the commented out section below, which sets up the connectivity
// for the constraint block of the stiffness matrix.
// The problem is that this will only work for linear constraints that are connected
// the element, so not for constraints connected to contact "elements". Howerver, I
// don't think this was working anyway, so this is okay for now.
// TODO: Replace this with a more generic algorithm that looks at the matrix profile
// directly instead of element by element.
if (constraintList.empty() == false)
{
// do the constraint term
int n = 0;
for (int i = 0; i<constraintList.size(); ++i) n += (int)m_LinC[constraintList[i]]->Size();
lm.resize(n);
n = 0;
for (int i = 0; i<constraintList.size(); ++i)
{
FELinearConstraint& lc = *m_LinC[constraintList[i]];
int ni = (int)lc.Size();
for (int j = 0; j<ni; ++j)
{
const FELinearConstraint::DOF& sj = lc.GetChildDof(j);
int neq = mesh.Node(sj.node).m_ID[sj.dof];
lm[n++] = neq;
}
}
G.build_add(lm);
}
}
}
// do the constraint term
// NOTE: This block was replaced by the section above which reduces the size
// of the stiffness matrix, but might be less generic (altough not entirely sure
// about that).
/* vector<FELinearConstraint>::iterator ic = m_LinC.begin();
int n = 0;
for (int i = 0; i<nlin; ++i, ++ic) n += (int) ic->m_childDof.size();
lm.resize(n);
ic = m_LinC.begin();
n = 0;
for (int i = 0; i<nlin; ++i, ++ic)
{
int ni = (int)ic->m_childDof.size();
vector<FELinearConstraint::DOF>::iterator is = ic->m_childDof.begin();
for (int j = 0; j<ni; ++j, ++is)
{
int neq = mesh.Node(is->node).m_ID[is->dof];
lm[n++] = neq;
}
}
G.build_add(lm);
*/
}
//-----------------------------------------------------------------------------
//! This function initializes the linear constraint table (LCT). This table
//! contains for each dof the linear constraint it belongs to. (or -1 if it is
//! not constraint)
bool FELinearConstraintManager::Initialize()
{
return true;
}
void FELinearConstraintManager::PrepStep()
{
FEMesh& mesh = m_fem->GetMesh();
for (int i=0; i<m_LinC.size(); ++i)
{
FELinearConstraint& lc = *m_LinC[i];
FENode& node = mesh.Node(lc.GetParentNode());
double u = node.get(lc.GetParentDof());
double v = 0;
for (int j=0; j<lc.Size(); ++j)
{
const FELinearConstraint::DOF& dofj = lc.GetChildDof(j);
FENode& nj = mesh.Node(dofj.node);
v += dofj.val* nj.get(dofj.dof);
}
m_up[i] = v + lc.GetOffset() - u;
}
}
void FELinearConstraintManager::InitTable()
{
FEMesh& mesh = m_fem->GetMesh();
// create the linear constraint table
DOFS& fedofs = m_fem->GetDOFS();
int MAX_NDOFS = fedofs.GetTotalDOFS();
m_LCT.resize(mesh.Nodes(), MAX_NDOFS, -1);
m_LCT.set(-1);
vector<FELinearConstraint*>::iterator ic = m_LinC.begin();
int nlin = LinearConstraints();
for (int i = 0; i<nlin; ++i, ++ic)
{
FELinearConstraint& lc = *(*ic);
int n = lc.GetParentNode();
int m = lc.GetParentDof();
m_LCT(n, m) = i;
}
}
//-----------------------------------------------------------------------------
// This gets called during model activation, i.e. activation of permanent model components.
bool FELinearConstraintManager::Activate()
{
int nlin = LinearConstraints();
if (nlin == 0) return true;
// initialize the lookup table
InitTable();
// ensure that none of the parent nodes are child nodes in any of the active linear constraints
for (int i = 0; i<nlin; ++i)
{
FELinearConstraint& lci = *m_LinC[i];
if (lci.IsActive())
{
int n = (int)lci.Size();
for (int k = 0; k<n; ++k)
{
const FELinearConstraint::DOF& childDOF = lci.GetChildDof(k);
int n = m_LCT(childDOF.node, childDOF.dof);
if (n != -1)
{
return false;
}
}
}
}
// set the prescribed value array
m_up.assign(m_LinC.size(), 0.0);
if (m_LinC.size())
{
vector<FELinearConstraint*>::iterator il = m_LinC.begin();
for (int l = 0; l<(int)m_LinC.size(); ++l, ++il)
{
if ((*il)->IsActive()) (*il)->Activate();
}
}
return true;
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::AssembleResidual(vector<double>& R, vector<int>& en, vector<int>& elm, vector<double>& fe)
{
FEMesh& mesh = m_fem->GetMesh();
int ndof = (int)fe.size();
int ndn = ndof / (int)en.size();
const int nodes = (int)en.size();
// loop over all degrees of freedom of this element
for (int i = 0; i<ndof; ++i)
{
int nodei = i / ndn;
if (nodei < nodes) {
// see if this dof belongs to a linear constraint
int l = m_LCT(en[nodei], i%ndn);
if (l >= 0)
{
// if so, get the linear constraint
FELinearConstraint& lc = *m_LinC[l];
assert(elm[i] == -1);
// now loop over all child nodes and
// add the contribution to the residual
int ns = (int)lc.Size();
FELinearConstraint::dof_iterator is = lc.begin();
for (int j = 0; j < ns; ++j, ++is)
{
int I = mesh.Node((*is)->node).m_ID[(*is)->dof];
if (I >= 0)
{
double A = (*is)->val;
#pragma omp atomic
R[I] += A*fe[i];
}
}
}
}
}
}
//-----------------------------------------------------------------------------
void FELinearConstraintManager::AssembleStiffness(FEGlobalMatrix& G, vector<double>& R, vector<double>& ui, const vector<int>& en, const vector<int>& lmi, const vector<int>& lmj, const matrix& ke)
{
FEMesh& mesh = m_fem->GetMesh();
int ndof = ke.rows();
int ndn = ndof / (int)en.size();
const int nodes = (int)en.size();
SparseMatrix& K = *(&G);
// loop over all stiffness components
// and correct for linear constraints
for (int i = 0; i<ndof; ++i)
{
int nodei = i / ndn;
int li = (nodei < nodes ? m_LCT(en[nodei], i%ndn) : -1);
for (int j = 0; j < ndof; ++j)
{
int nodej = j / ndn;
int lj = (nodej < nodes ? m_LCT(en[nodej], j%ndn) : -1);
if ((li >= 0) && (lj < 0))
{
// dof i is constrained
FELinearConstraint& Li = *m_LinC[li];
assert(lmi[i] == -1);
FELinearConstraint::dof_iterator is = Li.begin();
for (int k = 0; k < (int)Li.Size(); ++k, ++is)
{
int I = mesh.Node((*is)->node).m_ID[(*is)->dof];
int J = lmj[j];
double kij = (*is)->val*ke[i][j];
if ((J >= 0) && (I >= 0)) K.add(I, J, kij);
else
{
// adjust for prescribed dofs
J = -J - 2;
if ((J >= 0) && (I >= 0)) R[I] -= kij*ui[J];
}
}
}
else if ((lj >= 0) && (li < 0))
{
// dof j is constrained
FELinearConstraint& Lj = *m_LinC[lj];
assert(lmj[j] == -1);
FELinearConstraint::dof_iterator js = Lj.begin();
for (int k = 0; k < (int)Lj.Size(); ++k, ++js)
{
int I = lmi[i];
int J = mesh.Node((*js)->node).m_ID[(*js)->dof];
double kij = (*js)->val*ke[i][j];
if ((J >= 0) && (I >= 0)) K.add(I, J, kij);
else
{
// adjust for prescribed dofs
J = -J - 2;
if ((J >= 0) && (I >= 0)) R[I] -= kij*ui[J];
}
}
// adjust right-hand side for inhomogeneous linear constraints
if (Lj.GetOffset() != 0.0)
{
double ri = ke[i][j] * m_up[lj];
int I = lmi[i];
if (I >= 0) R[i] -= ri;
}
}
else if ((li >= 0) && (lj >= 0))
{
// both dof i and j are constrained
FELinearConstraint& Li = *m_LinC[li];
FELinearConstraint& Lj = *m_LinC[lj];
FELinearConstraint::dof_iterator is = Li.begin();
FELinearConstraint::dof_iterator js = Lj.begin();
assert(lmi[i] == -1);
assert(lmj[j] == -1);
for (int k = 0; k < (int)Li.Size(); ++k, ++is)
{
js = Lj.begin();
for (int l = 0; l < (int)Lj.Size(); ++l, ++js)
{
int I = mesh.Node((*is)->node).m_ID[(*is)->dof];
int J = mesh.Node((*js)->node).m_ID[(*js)->dof];;
double kij = ke[i][j] * (*is)->val*(*js)->val;
if ((J >= 0) && (I >= 0)) K.add(I, J, kij);
else
{
// adjust for prescribed dofs
J = -J - 2;
if ((J >= 0) && (I >= 0)) R[I] -= kij*ui[J];
}
}
}
// adjust for inhomogeneous linear constraints
if (Lj.GetOffset() != 0.0)
{
is = Li.begin();
for (int k = 0; k < (int)Li.Size(); ++k, ++is)
{
int I = mesh.Node((*is)->node).m_ID[(*is)->dof];
double ri = (*is)->val * ke[i][j] * m_up[lj];
if (I >= 0) R[i] -= ri;
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// This updates the nodal degrees of freedom of the parent nodes.
void FELinearConstraintManager::Update()
{
FEMesh& mesh = m_fem->GetMesh();
int nlin = LinearConstraints();
for (int n = 0; n<nlin; ++n)
{
FELinearConstraint& lc = LinearConstraint(n);
// evaluate the linear constraint
double d = 0;
int ns = (int)lc.Size();
FELinearConstraint::dof_iterator si = lc.begin();
for (int i = 0; i<ns; ++i, ++si)
{
FENode& childNode = mesh.Node((*si)->node);
d += (*si)->val*childNode.get((*si)->dof);
}
// assign to parent node
FENode& parentNode = mesh.Node(lc.GetParentNode());
parentNode.set(lc.GetParentDof(), d + lc.GetOffset());
}
m_up.assign(m_LinC.size(), 0.0);
}
| 27.664193 | 196 | 0.560593 | [
"mesh",
"vector",
"model",
"solid"
] |
ba29ad277ed053c5d5d016687ae1e7d241951000 | 38,021 | cc | C++ | ns-allinone-3.35/ns-3.35/src/wifi/helper/wifi-helper.cc | usi-systems/cc | 487aa9e322b2b01b6af3a92e38545c119e4980a3 | [
"Apache-2.0"
] | null | null | null | ns-allinone-3.35/ns-3.35/src/wifi/helper/wifi-helper.cc | usi-systems/cc | 487aa9e322b2b01b6af3a92e38545c119e4980a3 | [
"Apache-2.0"
] | null | null | null | ns-allinone-3.35/ns-3.35/src/wifi/helper/wifi-helper.cc | usi-systems/cc | 487aa9e322b2b01b6af3a92e38545c119e4980a3 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 INRIA
* Copyright (c) 2009 MIRKO BANCHI
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
* Mirko Banchi <mk.banchi@gmail.com>
*/
#include "ns3/wifi-net-device.h"
#include "ns3/ap-wifi-mac.h"
#include "ns3/ampdu-subframe-header.h"
#include "ns3/mobility-model.h"
#include "ns3/log.h"
#include "ns3/pointer.h"
#include "ns3/radiotap-header.h"
#include "ns3/config.h"
#include "ns3/names.h"
#include "ns3/net-device-queue-interface.h"
#include "ns3/wifi-mac-queue.h"
#include "ns3/qos-utils.h"
#include "ns3/ht-configuration.h"
#include "ns3/vht-configuration.h"
#include "ns3/he-configuration.h"
#include "ns3/obss-pd-algorithm.h"
#include "wifi-helper.h"
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("WifiHelper");
/**
* ASCII trace PHY transmit sink with context
* \param stream the output stream
* \param context the context name
* \param p the packet
* \param mode the wifi mode
* \param preamble the wifi preamble
* \param txLevel the transmit power level
*/
static void
AsciiPhyTransmitSinkWithContext (
Ptr<OutputStreamWrapper> stream,
std::string context,
Ptr<const Packet> p,
WifiMode mode,
WifiPreamble preamble,
uint8_t txLevel)
{
NS_LOG_FUNCTION (stream << context << p << mode << preamble << txLevel);
*stream->GetStream () << "t " << Simulator::Now ().GetSeconds () << " " << context << " " << mode << " " << *p << std::endl;
}
/**
* ASCII trace PHY transmit sink without context
* \param stream the output stream
* \param p the packet
* \param mode the wifi mode
* \param preamble the wifi preamble
* \param txLevel the transmit power level
*/
static void
AsciiPhyTransmitSinkWithoutContext (
Ptr<OutputStreamWrapper> stream,
Ptr<const Packet> p,
WifiMode mode,
WifiPreamble preamble,
uint8_t txLevel)
{
NS_LOG_FUNCTION (stream << p << mode << preamble << txLevel);
*stream->GetStream () << "t " << Simulator::Now ().GetSeconds () << " " << mode << " " << *p << std::endl;
}
/**
* ASCII trace PHY receive sink with context
* \param stream the output stream
* \param context the context name
* \param p the packet
* \param snr the SNR
* \param mode the wifi mode
* \param preamble the wifi preamble
*/
static void
AsciiPhyReceiveSinkWithContext (
Ptr<OutputStreamWrapper> stream,
std::string context,
Ptr<const Packet> p,
double snr,
WifiMode mode,
WifiPreamble preamble)
{
NS_LOG_FUNCTION (stream << context << p << snr << mode << preamble);
*stream->GetStream () << "r " << Simulator::Now ().GetSeconds () << " " << mode << "" << context << " " << *p << std::endl;
}
/**
* ASCII trace PHY receive sink without context
* \param stream the output stream
* \param p the packet
* \param snr the SNR
* \param mode the wifi mode
* \param preamble the wifi preamble
*/
static void
AsciiPhyReceiveSinkWithoutContext (
Ptr<OutputStreamWrapper> stream,
Ptr<const Packet> p,
double snr,
WifiMode mode,
WifiPreamble preamble)
{
NS_LOG_FUNCTION (stream << p << snr << mode << preamble);
*stream->GetStream () << "r " << Simulator::Now ().GetSeconds () << " " << mode << " " << *p << std::endl;
}
WifiPhyHelper::WifiPhyHelper ()
: m_pcapDlt (PcapHelper::DLT_IEEE802_11)
{
SetPreambleDetectionModel ("ns3::ThresholdPreambleDetectionModel");
}
WifiPhyHelper::~WifiPhyHelper ()
{
}
void
WifiPhyHelper::Set (std::string name, const AttributeValue &v)
{
m_phy.Set (name, v);
}
void
WifiPhyHelper::SetErrorRateModel (std::string name,
std::string n0, const AttributeValue &v0,
std::string n1, const AttributeValue &v1,
std::string n2, const AttributeValue &v2,
std::string n3, const AttributeValue &v3,
std::string n4, const AttributeValue &v4,
std::string n5, const AttributeValue &v5,
std::string n6, const AttributeValue &v6,
std::string n7, const AttributeValue &v7)
{
m_errorRateModel = ObjectFactory ();
m_errorRateModel.SetTypeId (name);
m_errorRateModel.Set (n0, v0);
m_errorRateModel.Set (n1, v1);
m_errorRateModel.Set (n2, v2);
m_errorRateModel.Set (n3, v3);
m_errorRateModel.Set (n4, v4);
m_errorRateModel.Set (n5, v5);
m_errorRateModel.Set (n6, v6);
m_errorRateModel.Set (n7, v7);
}
void
WifiPhyHelper::SetFrameCaptureModel (std::string name,
std::string n0, const AttributeValue &v0,
std::string n1, const AttributeValue &v1,
std::string n2, const AttributeValue &v2,
std::string n3, const AttributeValue &v3,
std::string n4, const AttributeValue &v4,
std::string n5, const AttributeValue &v5,
std::string n6, const AttributeValue &v6,
std::string n7, const AttributeValue &v7)
{
m_frameCaptureModel = ObjectFactory ();
m_frameCaptureModel.SetTypeId (name);
m_frameCaptureModel.Set (n0, v0);
m_frameCaptureModel.Set (n1, v1);
m_frameCaptureModel.Set (n2, v2);
m_frameCaptureModel.Set (n3, v3);
m_frameCaptureModel.Set (n4, v4);
m_frameCaptureModel.Set (n5, v5);
m_frameCaptureModel.Set (n6, v6);
m_frameCaptureModel.Set (n7, v7);
}
void
WifiPhyHelper::SetPreambleDetectionModel (std::string name,
std::string n0, const AttributeValue &v0,
std::string n1, const AttributeValue &v1,
std::string n2, const AttributeValue &v2,
std::string n3, const AttributeValue &v3,
std::string n4, const AttributeValue &v4,
std::string n5, const AttributeValue &v5,
std::string n6, const AttributeValue &v6,
std::string n7, const AttributeValue &v7)
{
m_preambleDetectionModel = ObjectFactory ();
m_preambleDetectionModel.SetTypeId (name);
m_preambleDetectionModel.Set (n0, v0);
m_preambleDetectionModel.Set (n1, v1);
m_preambleDetectionModel.Set (n2, v2);
m_preambleDetectionModel.Set (n3, v3);
m_preambleDetectionModel.Set (n4, v4);
m_preambleDetectionModel.Set (n5, v5);
m_preambleDetectionModel.Set (n6, v6);
m_preambleDetectionModel.Set (n7, v7);
}
void
WifiPhyHelper::DisablePreambleDetectionModel ()
{
m_preambleDetectionModel.SetTypeId (TypeId ());
}
void
WifiPhyHelper::PcapSniffTxEvent (
Ptr<PcapFileWrapper> file,
Ptr<const Packet> packet,
uint16_t channelFreqMhz,
WifiTxVector txVector,
MpduInfo aMpdu,
uint16_t staId)
{
uint32_t dlt = file->GetDataLinkType ();
switch (dlt)
{
case PcapHelper::DLT_IEEE802_11:
file->Write (Simulator::Now (), packet);
return;
case PcapHelper::DLT_PRISM_HEADER:
{
NS_FATAL_ERROR ("PcapSniffTxEvent(): DLT_PRISM_HEADER not implemented");
return;
}
case PcapHelper::DLT_IEEE802_11_RADIO:
{
Ptr<Packet> p = packet->Copy ();
RadiotapHeader header;
GetRadiotapHeader (header, p, channelFreqMhz, txVector, aMpdu, staId);
p->AddHeader (header);
file->Write (Simulator::Now (), p);
return;
}
default:
NS_ABORT_MSG ("PcapSniffTxEvent(): Unexpected data link type " << dlt);
}
}
void
WifiPhyHelper::PcapSniffRxEvent (
Ptr<PcapFileWrapper> file,
Ptr<const Packet> packet,
uint16_t channelFreqMhz,
WifiTxVector txVector,
MpduInfo aMpdu,
SignalNoiseDbm signalNoise,
uint16_t staId)
{
uint32_t dlt = file->GetDataLinkType ();
switch (dlt)
{
case PcapHelper::DLT_IEEE802_11:
file->Write (Simulator::Now (), packet);
return;
case PcapHelper::DLT_PRISM_HEADER:
{
NS_FATAL_ERROR ("PcapSniffRxEvent(): DLT_PRISM_HEADER not implemented");
return;
}
case PcapHelper::DLT_IEEE802_11_RADIO:
{
Ptr<Packet> p = packet->Copy ();
RadiotapHeader header;
GetRadiotapHeader (header, p, channelFreqMhz, txVector, aMpdu, staId, signalNoise);
p->AddHeader (header);
file->Write (Simulator::Now (), p);
return;
}
default:
NS_ABORT_MSG ("PcapSniffRxEvent(): Unexpected data link type " << dlt);
}
}
void
WifiPhyHelper::GetRadiotapHeader (
RadiotapHeader &header,
Ptr<Packet> packet,
uint16_t channelFreqMhz,
WifiTxVector txVector,
MpduInfo aMpdu,
uint16_t staId,
SignalNoiseDbm signalNoise)
{
header.SetAntennaSignalPower (signalNoise.signal);
header.SetAntennaNoisePower (signalNoise.noise);
GetRadiotapHeader (header, packet, channelFreqMhz, txVector, aMpdu, staId);
}
void
WifiPhyHelper::GetRadiotapHeader (
RadiotapHeader &header,
Ptr<Packet> packet,
uint16_t channelFreqMhz,
WifiTxVector txVector,
MpduInfo aMpdu,
uint16_t staId)
{
WifiPreamble preamble = txVector.GetPreambleType ();
uint8_t frameFlags = RadiotapHeader::FRAME_FLAG_NONE;
header.SetTsft (Simulator::Now ().GetMicroSeconds ());
//Our capture includes the FCS, so we set the flag to say so.
frameFlags |= RadiotapHeader::FRAME_FLAG_FCS_INCLUDED;
if (preamble == WIFI_PREAMBLE_SHORT)
{
frameFlags |= RadiotapHeader::FRAME_FLAG_SHORT_PREAMBLE;
}
if (txVector.GetGuardInterval () == 400)
{
frameFlags |= RadiotapHeader::FRAME_FLAG_SHORT_GUARD;
}
header.SetFrameFlags (frameFlags);
uint64_t rate = 0;
if (txVector.GetMode (staId).GetModulationClass () != WIFI_MOD_CLASS_HT
&& txVector.GetMode (staId).GetModulationClass () != WIFI_MOD_CLASS_VHT
&& txVector.GetMode (staId).GetModulationClass () != WIFI_MOD_CLASS_HE)
{
rate = txVector.GetMode (staId).GetDataRate (txVector.GetChannelWidth (), txVector.GetGuardInterval (), 1) * txVector.GetNss (staId) / 500000;
header.SetRate (static_cast<uint8_t> (rate));
}
uint16_t channelFlags = 0;
switch (rate)
{
case 2: //1Mbps
case 4: //2Mbps
case 10: //5Mbps
case 22: //11Mbps
channelFlags |= RadiotapHeader::CHANNEL_FLAG_CCK;
break;
default:
channelFlags |= RadiotapHeader::CHANNEL_FLAG_OFDM;
break;
}
if (channelFreqMhz < 2500)
{
channelFlags |= RadiotapHeader::CHANNEL_FLAG_SPECTRUM_2GHZ;
}
else
{
channelFlags |= RadiotapHeader::CHANNEL_FLAG_SPECTRUM_5GHZ;
}
header.SetChannelFrequencyAndFlags (channelFreqMhz, channelFlags);
if (txVector.GetMode (staId).GetModulationClass () == WIFI_MOD_CLASS_HT)
{
uint8_t mcsKnown = RadiotapHeader::MCS_KNOWN_NONE;
uint8_t mcsFlags = RadiotapHeader::MCS_FLAGS_NONE;
mcsKnown |= RadiotapHeader::MCS_KNOWN_INDEX;
mcsKnown |= RadiotapHeader::MCS_KNOWN_BANDWIDTH;
if (txVector.GetChannelWidth () == 40)
{
mcsFlags |= RadiotapHeader::MCS_FLAGS_BANDWIDTH_40;
}
mcsKnown |= RadiotapHeader::MCS_KNOWN_GUARD_INTERVAL;
if (txVector.GetGuardInterval () == 400)
{
mcsFlags |= RadiotapHeader::MCS_FLAGS_GUARD_INTERVAL;
}
mcsKnown |= RadiotapHeader::MCS_KNOWN_HT_FORMAT;
mcsKnown |= RadiotapHeader::MCS_KNOWN_NESS;
if (txVector.GetNess () & 0x01) //bit 1
{
mcsFlags |= RadiotapHeader::MCS_FLAGS_NESS_BIT_0;
}
if (txVector.GetNess () & 0x02) //bit 2
{
mcsKnown |= RadiotapHeader::MCS_KNOWN_NESS_BIT_1;
}
mcsKnown |= RadiotapHeader::MCS_KNOWN_FEC_TYPE; //only BCC is currently supported
mcsKnown |= RadiotapHeader::MCS_KNOWN_STBC;
if (txVector.IsStbc ())
{
mcsFlags |= RadiotapHeader::MCS_FLAGS_STBC_STREAMS;
}
header.SetMcsFields (mcsKnown, mcsFlags, txVector.GetMode (staId).GetMcsValue ());
}
if (txVector.IsAggregation ())
{
uint16_t ampduStatusFlags = RadiotapHeader::A_MPDU_STATUS_NONE;
ampduStatusFlags |= RadiotapHeader::A_MPDU_STATUS_LAST_KNOWN;
/* For PCAP file, MPDU Delimiter and Padding should be removed by the MAC Driver */
AmpduSubframeHeader hdr;
uint32_t extractedLength;
packet->RemoveHeader (hdr);
extractedLength = hdr.GetLength ();
packet = packet->CreateFragment (0, static_cast<uint32_t> (extractedLength));
if (aMpdu.type == LAST_MPDU_IN_AGGREGATE || (hdr.GetEof () == true && hdr.GetLength () > 0))
{
ampduStatusFlags |= RadiotapHeader::A_MPDU_STATUS_LAST;
}
header.SetAmpduStatus (aMpdu.mpduRefNumber, ampduStatusFlags, 1 /*CRC*/);
}
if (txVector.GetMode (staId).GetModulationClass () == WIFI_MOD_CLASS_VHT)
{
uint16_t vhtKnown = RadiotapHeader::VHT_KNOWN_NONE;
uint8_t vhtFlags = RadiotapHeader::VHT_FLAGS_NONE;
uint8_t vhtBandwidth = 0;
uint8_t vhtMcsNss[4] = {0,0,0,0};
uint8_t vhtCoding = 0;
uint8_t vhtGroupId = 0;
uint16_t vhtPartialAid = 0;
vhtKnown |= RadiotapHeader::VHT_KNOWN_STBC;
if (txVector.IsStbc ())
{
vhtFlags |= RadiotapHeader::VHT_FLAGS_STBC;
}
vhtKnown |= RadiotapHeader::VHT_KNOWN_GUARD_INTERVAL;
if (txVector.GetGuardInterval () == 400)
{
vhtFlags |= RadiotapHeader::VHT_FLAGS_GUARD_INTERVAL;
}
vhtKnown |= RadiotapHeader::VHT_KNOWN_BEAMFORMED; //Beamforming is currently not supported
vhtKnown |= RadiotapHeader::VHT_KNOWN_BANDWIDTH;
//not all bandwidth values are currently supported
if (txVector.GetChannelWidth () == 40)
{
vhtBandwidth = 1;
}
else if (txVector.GetChannelWidth () == 80)
{
vhtBandwidth = 4;
}
else if (txVector.GetChannelWidth () == 160)
{
vhtBandwidth = 11;
}
//only SU PPDUs are currently supported
vhtMcsNss[0] |= (txVector.GetNss (staId) & 0x0f);
vhtMcsNss[0] |= ((txVector.GetMode (staId).GetMcsValue () << 4) & 0xf0);
header.SetVhtFields (vhtKnown, vhtFlags, vhtBandwidth, vhtMcsNss, vhtCoding, vhtGroupId, vhtPartialAid);
}
if (txVector.GetMode (staId).GetModulationClass () == WIFI_MOD_CLASS_HE)
{
uint16_t data1 = RadiotapHeader::HE_DATA1_BSS_COLOR_KNOWN | RadiotapHeader::HE_DATA1_DATA_MCS_KNOWN | RadiotapHeader::HE_DATA1_BW_RU_ALLOC_KNOWN;
if (preamble == WIFI_PREAMBLE_HE_ER_SU)
{
data1 |= RadiotapHeader::HE_DATA1_FORMAT_EXT_SU;
}
else if (preamble == WIFI_PREAMBLE_HE_MU)
{
data1 |= RadiotapHeader::HE_DATA1_FORMAT_MU;
data1 |= RadiotapHeader::HE_DATA1_SPTL_REUSE2_KNOWN;
}
else if (preamble == WIFI_PREAMBLE_HE_TB)
{
data1 |= RadiotapHeader::HE_DATA1_FORMAT_TRIG;
}
uint16_t data2 = RadiotapHeader::HE_DATA2_GI_KNOWN;
if (preamble == WIFI_PREAMBLE_HE_MU || preamble == WIFI_PREAMBLE_HE_TB)
{
data2 |= RadiotapHeader::HE_DATA2_RU_OFFSET_KNOWN;
//HeRu indices start at 1 whereas RadioTap starts at 0
data2 |= (((txVector.GetHeMuUserInfo (staId).ru.GetIndex () - 1) << 8) & 0x3f00);
data2 |= (((!txVector.GetHeMuUserInfo (staId).ru.GetPrimary80MHz ()) << 15) & 0x8000);
}
uint16_t data3 = 0;
data3 |= (txVector.GetBssColor () & 0x003f);
data3 |= ((txVector.GetMode (staId).GetMcsValue () << 8) & 0x0f00);
uint16_t data4 = 0;
if (preamble == WIFI_PREAMBLE_HE_MU)
{
data4 |= ((staId << 4) & 0x7ff0);
}
uint16_t data5 = 0;
if (preamble == WIFI_PREAMBLE_HE_MU || preamble == WIFI_PREAMBLE_HE_TB)
{
HeRu::RuType ruType = txVector.GetHeMuUserInfo (staId).ru.GetRuType ();
switch (ruType)
{
case HeRu::RU_26_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_26T;
break;
case HeRu::RU_52_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_52T;
break;
case HeRu::RU_106_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_106T;
break;
case HeRu::RU_242_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_242T;
break;
case HeRu::RU_484_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_484T;
break;
case HeRu::RU_996_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_996T;
break;
case HeRu::RU_2x996_TONE:
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_2x996T;
break;
default:
NS_ABORT_MSG ("Unexpected RU type");
}
}
else if (txVector.GetChannelWidth () == 40)
{
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_40MHZ;
}
else if (txVector.GetChannelWidth () == 80)
{
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_80MHZ;
}
else if (txVector.GetChannelWidth () == 160)
{
data5 |= RadiotapHeader::HE_DATA5_DATA_BW_RU_ALLOC_160MHZ;
}
if (txVector.GetGuardInterval () == 1600)
{
data5 |= RadiotapHeader::HE_DATA5_GI_1_6;
}
else if (txVector.GetGuardInterval () == 3200)
{
data5 |= RadiotapHeader::HE_DATA5_GI_3_2;
}
header.SetHeFields (data1, data2, data3, data4, data5, 0);
}
if (preamble == WIFI_PREAMBLE_HE_MU)
{
//TODO: fill in fields (everything is set to 0 so far)
std::array<uint8_t, 4> ruChannel1, ruChannel2;
header.SetHeMuFields (0, 0, ruChannel1, ruChannel2);
header.SetHeMuPerUserFields (0, 0, 0, 0);
}
}
void
WifiPhyHelper::SetPcapDataLinkType (SupportedPcapDataLinkTypes dlt)
{
switch (dlt)
{
case DLT_IEEE802_11:
m_pcapDlt = PcapHelper::DLT_IEEE802_11;
return;
case DLT_PRISM_HEADER:
m_pcapDlt = PcapHelper::DLT_PRISM_HEADER;
return;
case DLT_IEEE802_11_RADIO:
m_pcapDlt = PcapHelper::DLT_IEEE802_11_RADIO;
return;
default:
NS_ABORT_MSG ("WifiPhyHelper::SetPcapFormat(): Unexpected format");
}
}
PcapHelper::DataLinkType
WifiPhyHelper::GetPcapDataLinkType (void) const
{
return m_pcapDlt;
}
void
WifiPhyHelper::EnablePcapInternal (std::string prefix, Ptr<NetDevice> nd, bool promiscuous, bool explicitFilename)
{
NS_LOG_FUNCTION (this << prefix << nd << promiscuous << explicitFilename);
//All of the Pcap enable functions vector through here including the ones
//that are wandering through all of devices on perhaps all of the nodes in
//the system. We can only deal with devices of type WifiNetDevice.
Ptr<WifiNetDevice> device = nd->GetObject<WifiNetDevice> ();
if (device == 0)
{
NS_LOG_INFO ("WifiHelper::EnablePcapInternal(): Device " << &device << " not of type ns3::WifiNetDevice");
return;
}
Ptr<WifiPhy> phy = device->GetPhy ();
NS_ABORT_MSG_IF (phy == 0, "WifiPhyHelper::EnablePcapInternal(): Phy layer in WifiNetDevice must be set");
PcapHelper pcapHelper;
std::string filename;
if (explicitFilename)
{
filename = prefix;
}
else
{
filename = pcapHelper.GetFilenameFromDevice (prefix, device);
}
Ptr<PcapFileWrapper> file = pcapHelper.CreateFile (filename, std::ios::out, m_pcapDlt);
phy->TraceConnectWithoutContext ("MonitorSnifferTx", MakeBoundCallback (&WifiPhyHelper::PcapSniffTxEvent, file));
phy->TraceConnectWithoutContext ("MonitorSnifferRx", MakeBoundCallback (&WifiPhyHelper::PcapSniffRxEvent, file));
}
void
WifiPhyHelper::EnableAsciiInternal (
Ptr<OutputStreamWrapper> stream,
std::string prefix,
Ptr<NetDevice> nd,
bool explicitFilename)
{
//All of the ASCII enable functions vector through here including the ones
//that are wandering through all of devices on perhaps all of the nodes in
//the system. We can only deal with devices of type WifiNetDevice.
Ptr<WifiNetDevice> device = nd->GetObject<WifiNetDevice> ();
if (device == 0)
{
NS_LOG_INFO ("WifiHelper::EnableAsciiInternal(): Device " << device << " not of type ns3::WifiNetDevice");
return;
}
//Our trace sinks are going to use packet printing, so we have to make sure
//that is turned on.
Packet::EnablePrinting ();
uint32_t nodeid = nd->GetNode ()->GetId ();
uint32_t deviceid = nd->GetIfIndex ();
std::ostringstream oss;
//If we are not provided an OutputStreamWrapper, we are expected to create
//one using the usual trace filename conventions and write our traces
//without a context since there will be one file per context and therefore
//the context would be redundant.
if (stream == 0)
{
//Set up an output stream object to deal with private ofstream copy
//constructor and lifetime issues. Let the helper decide the actual
//name of the file given the prefix.
AsciiTraceHelper asciiTraceHelper;
std::string filename;
if (explicitFilename)
{
filename = prefix;
}
else
{
filename = asciiTraceHelper.GetFilenameFromDevice (prefix, device);
}
Ptr<OutputStreamWrapper> theStream = asciiTraceHelper.CreateFileStream (filename);
//We could go poking through the PHY and the state looking for the
//correct trace source, but we can let Config deal with that with
//some search cost. Since this is presumably happening at topology
//creation time, it doesn't seem much of a price to pay.
oss.str ("");
oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << "/$ns3::WifiNetDevice/Phy/State/RxOk";
Config::ConnectWithoutContext (oss.str (), MakeBoundCallback (&AsciiPhyReceiveSinkWithoutContext, theStream));
oss.str ("");
oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << "/$ns3::WifiNetDevice/Phy/State/Tx";
Config::ConnectWithoutContext (oss.str (), MakeBoundCallback (&AsciiPhyTransmitSinkWithoutContext, theStream));
return;
}
//If we are provided an OutputStreamWrapper, we are expected to use it, and
//to provide a context. We are free to come up with our own context if we
//want, and use the AsciiTraceHelper Hook*WithContext functions, but for
//compatibility and simplicity, we just use Config::Connect and let it deal
//with coming up with a context.
oss.str ("");
oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << "/$ns3::WifiNetDevice/Phy/State/RxOk";
Config::Connect (oss.str (), MakeBoundCallback (&AsciiPhyReceiveSinkWithContext, stream));
oss.str ("");
oss << "/NodeList/" << nodeid << "/DeviceList/" << deviceid << "/$ns3::WifiNetDevice/Phy/State/Tx";
Config::Connect (oss.str (), MakeBoundCallback (&AsciiPhyTransmitSinkWithContext, stream));
}
WifiHelper::~WifiHelper ()
{
}
WifiHelper::WifiHelper ()
: m_standard (WIFI_STANDARD_80211a),
m_selectQueueCallback (&SelectQueueByDSField)
{
SetRemoteStationManager ("ns3::ArfWifiManager");
}
void
WifiHelper::SetRemoteStationManager (std::string type,
std::string n0, const AttributeValue &v0,
std::string n1, const AttributeValue &v1,
std::string n2, const AttributeValue &v2,
std::string n3, const AttributeValue &v3,
std::string n4, const AttributeValue &v4,
std::string n5, const AttributeValue &v5,
std::string n6, const AttributeValue &v6,
std::string n7, const AttributeValue &v7)
{
m_stationManager = ObjectFactory ();
m_stationManager.SetTypeId (type);
m_stationManager.Set (n0, v0);
m_stationManager.Set (n1, v1);
m_stationManager.Set (n2, v2);
m_stationManager.Set (n3, v3);
m_stationManager.Set (n4, v4);
m_stationManager.Set (n5, v5);
m_stationManager.Set (n6, v6);
m_stationManager.Set (n7, v7);
}
void
WifiHelper::SetObssPdAlgorithm (std::string type,
std::string n0, const AttributeValue &v0,
std::string n1, const AttributeValue &v1,
std::string n2, const AttributeValue &v2,
std::string n3, const AttributeValue &v3,
std::string n4, const AttributeValue &v4,
std::string n5, const AttributeValue &v5,
std::string n6, const AttributeValue &v6,
std::string n7, const AttributeValue &v7)
{
m_obssPdAlgorithm = ObjectFactory ();
m_obssPdAlgorithm.SetTypeId (type);
m_obssPdAlgorithm.Set (n0, v0);
m_obssPdAlgorithm.Set (n1, v1);
m_obssPdAlgorithm.Set (n2, v2);
m_obssPdAlgorithm.Set (n3, v3);
m_obssPdAlgorithm.Set (n4, v4);
m_obssPdAlgorithm.Set (n5, v5);
m_obssPdAlgorithm.Set (n6, v6);
m_obssPdAlgorithm.Set (n7, v7);
}
void
WifiHelper::SetStandard (WifiStandard standard)
{
m_standard = standard;
}
void
WifiHelper::SetSelectQueueCallback (SelectQueueCallback f)
{
m_selectQueueCallback = f;
}
NetDeviceContainer
WifiHelper::Install (const WifiPhyHelper &phyHelper,
const WifiMacHelper &macHelper,
NodeContainer::Iterator first,
NodeContainer::Iterator last) const
{
NetDeviceContainer devices;
for (NodeContainer::Iterator i = first; i != last; ++i)
{
Ptr<Node> node = *i;
Ptr<WifiNetDevice> device = CreateObject<WifiNetDevice> ();
auto it = wifiStandards.find (m_standard);
if (it == wifiStandards.end ())
{
NS_FATAL_ERROR ("Selected standard is not defined!");
return devices;
}
if (it->second.phyStandard >= WIFI_PHY_STANDARD_80211n)
{
Ptr<HtConfiguration> htConfiguration = CreateObject<HtConfiguration> ();
device->SetHtConfiguration (htConfiguration);
}
if ((it->second.phyStandard >= WIFI_PHY_STANDARD_80211ac) && (it->second.phyBand != WIFI_PHY_BAND_2_4GHZ))
{
Ptr<VhtConfiguration> vhtConfiguration = CreateObject<VhtConfiguration> ();
device->SetVhtConfiguration (vhtConfiguration);
}
if (it->second.phyStandard >= WIFI_PHY_STANDARD_80211ax)
{
Ptr<HeConfiguration> heConfiguration = CreateObject<HeConfiguration> ();
device->SetHeConfiguration (heConfiguration);
}
Ptr<WifiRemoteStationManager> manager = m_stationManager.Create<WifiRemoteStationManager> ();
Ptr<WifiPhy> phy = phyHelper.Create (node, device);
phy->ConfigureStandardAndBand (it->second.phyStandard, it->second.phyBand);
device->SetPhy (phy);
Ptr<WifiMac> mac = macHelper.Create (device, m_standard);
device->SetMac (mac);
device->SetRemoteStationManager (manager);
node->AddDevice (device);
if ((it->second.phyStandard >= WIFI_PHY_STANDARD_80211ax) && (m_obssPdAlgorithm.IsTypeIdSet ()))
{
Ptr<ObssPdAlgorithm> obssPdAlgorithm = m_obssPdAlgorithm.Create<ObssPdAlgorithm> ();
device->AggregateObject (obssPdAlgorithm);
obssPdAlgorithm->ConnectWifiNetDevice (device);
}
devices.Add (device);
NS_LOG_DEBUG ("node=" << node << ", mob=" << node->GetObject<MobilityModel> ());
// Aggregate a NetDeviceQueueInterface object if a RegularWifiMac is installed
Ptr<RegularWifiMac> rmac = DynamicCast<RegularWifiMac> (mac);
if (rmac)
{
Ptr<NetDeviceQueueInterface> ndqi;
BooleanValue qosSupported;
Ptr<WifiMacQueue> wmq;
rmac->GetAttributeFailSafe ("QosSupported", qosSupported);
if (qosSupported.Get ())
{
ndqi = CreateObjectWithAttributes<NetDeviceQueueInterface> ("NTxQueues",
UintegerValue (4));
for (auto& ac : {AC_BE, AC_BK, AC_VI, AC_VO})
{
Ptr<QosTxop> qosTxop = rmac->GetQosTxop (ac);
wmq = qosTxop->GetWifiMacQueue ();
ndqi->GetTxQueue (static_cast<std::size_t> (ac))->ConnectQueueTraces (wmq);
}
ndqi->SetSelectQueueCallback (m_selectQueueCallback);
}
else
{
ndqi = CreateObject<NetDeviceQueueInterface> ();
wmq = rmac->GetTxop ()->GetWifiMacQueue ();
ndqi->GetTxQueue (0)->ConnectQueueTraces (wmq);
}
device->AggregateObject (ndqi);
}
}
return devices;
}
NetDeviceContainer
WifiHelper::Install (const WifiPhyHelper &phyHelper,
const WifiMacHelper &macHelper, NodeContainer c) const
{
return Install (phyHelper, macHelper, c.Begin (), c.End ());
}
NetDeviceContainer
WifiHelper::Install (const WifiPhyHelper &phy,
const WifiMacHelper &mac, Ptr<Node> node) const
{
return Install (phy, mac, NodeContainer (node));
}
NetDeviceContainer
WifiHelper::Install (const WifiPhyHelper &phy,
const WifiMacHelper &mac, std::string nodeName) const
{
Ptr<Node> node = Names::Find<Node> (nodeName);
return Install (phy, mac, NodeContainer (node));
}
void
WifiHelper::EnableLogComponents (void)
{
LogComponentEnableAll (LOG_PREFIX_TIME);
LogComponentEnableAll (LOG_PREFIX_NODE);
LogComponentEnable ("AarfWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("AarfcdWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("AdhocWifiMac", LOG_LEVEL_ALL);
LogComponentEnable ("AmrrWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("ApWifiMac", LOG_LEVEL_ALL);
LogComponentEnable ("AparfWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("ArfWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("BlockAckAgreement", LOG_LEVEL_ALL);
LogComponentEnable ("RecipientBlockAckAgreement", LOG_LEVEL_ALL);
LogComponentEnable ("BlockAckManager", LOG_LEVEL_ALL);
LogComponentEnable ("CaraWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("ChannelAccessManager", LOG_LEVEL_ALL);
LogComponentEnable ("ConstantObssPdAlgorithm", LOG_LEVEL_ALL);
LogComponentEnable ("ConstantRateWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("ChannelAccessManager", LOG_LEVEL_ALL);
LogComponentEnable ("DsssErrorRateModel", LOG_LEVEL_ALL);
LogComponentEnable ("DsssPhy", LOG_LEVEL_ALL);
LogComponentEnable ("DsssPpdu", LOG_LEVEL_ALL);
LogComponentEnable ("ErpOfdmPhy", LOG_LEVEL_ALL);
LogComponentEnable ("ErpOfdmPpdu", LOG_LEVEL_ALL);
LogComponentEnable ("FrameExchangeManager", LOG_LEVEL_ALL);
LogComponentEnable ("HeConfiguration", LOG_LEVEL_ALL);
LogComponentEnable ("HeFrameExchangeManager", LOG_LEVEL_ALL);
LogComponentEnable ("HePhy", LOG_LEVEL_ALL);
LogComponentEnable ("HePpdu", LOG_LEVEL_ALL);
LogComponentEnable ("HtConfiguration", LOG_LEVEL_ALL);
LogComponentEnable ("HtFrameExchangeManager", LOG_LEVEL_ALL);
LogComponentEnable ("HtPhy", LOG_LEVEL_ALL);
LogComponentEnable ("HtPpdu", LOG_LEVEL_ALL);
LogComponentEnable ("IdealWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("InterferenceHelper", LOG_LEVEL_ALL);
LogComponentEnable ("MacRxMiddle", LOG_LEVEL_ALL);
LogComponentEnable ("MacTxMiddle", LOG_LEVEL_ALL);
LogComponentEnable ("MinstrelHtWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("MinstrelWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("MpduAggregator", LOG_LEVEL_ALL);
LogComponentEnable ("MsduAggregator", LOG_LEVEL_ALL);
LogComponentEnable ("MultiUserScheduler", LOG_LEVEL_ALL);
LogComponentEnable ("NistErrorRateModel", LOG_LEVEL_ALL);
LogComponentEnable ("ObssPdAlgorithm", LOG_LEVEL_ALL);
LogComponentEnable ("OfdmPhy", LOG_LEVEL_ALL);
LogComponentEnable ("OnoeWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("OriginatorBlockAckAgreement", LOG_LEVEL_ALL);
LogComponentEnable ("OfdmPpdu", LOG_LEVEL_ALL);
LogComponentEnable ("ParfWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("PhyEntity", LOG_LEVEL_ALL);
LogComponentEnable ("QosFrameExchangeManager", LOG_LEVEL_ALL);
LogComponentEnable ("QosTxop", LOG_LEVEL_ALL);
LogComponentEnable ("RegularWifiMac", LOG_LEVEL_ALL);
LogComponentEnable ("RraaWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("RrMultiUserScheduler", LOG_LEVEL_ALL);
LogComponentEnable ("RrpaaWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("SimpleFrameCaptureModel", LOG_LEVEL_ALL);
LogComponentEnable ("SpectrumWifiPhy", LOG_LEVEL_ALL);
LogComponentEnable ("StaWifiMac", LOG_LEVEL_ALL);
LogComponentEnable ("SupportedRates", LOG_LEVEL_ALL);
LogComponentEnable ("TableBasedErrorRateModel", LOG_LEVEL_ALL);
LogComponentEnable ("ThompsonSamplingWifiManager", LOG_LEVEL_ALL);
LogComponentEnable ("ThresholdPreambleDetectionModel", LOG_LEVEL_ALL);
LogComponentEnable ("Txop", LOG_LEVEL_ALL);
LogComponentEnable ("VhtConfiguration", LOG_LEVEL_ALL);
LogComponentEnable ("VhtFrameExchangeManager", LOG_LEVEL_ALL);
LogComponentEnable ("VhtPhy", LOG_LEVEL_ALL);
LogComponentEnable ("VhtPpdu", LOG_LEVEL_ALL);
LogComponentEnable ("WifiAckManager", LOG_LEVEL_ALL);
LogComponentEnable ("WifiDefaultAckManager", LOG_LEVEL_ALL);
LogComponentEnable ("WifiDefaultProtectionManager", LOG_LEVEL_ALL);
LogComponentEnable ("WifiMac", LOG_LEVEL_ALL);
LogComponentEnable ("WifiMacQueue", LOG_LEVEL_ALL);
LogComponentEnable ("WifiMacQueueItem", LOG_LEVEL_ALL);
LogComponentEnable ("WifiNetDevice", LOG_LEVEL_ALL);
LogComponentEnable ("WifiPhyStateHelper", LOG_LEVEL_ALL);
LogComponentEnable ("WifiPhy", LOG_LEVEL_ALL);
LogComponentEnable ("WifiPhyOperatingChannel", LOG_LEVEL_ALL);
LogComponentEnable ("WifiPpdu", LOG_LEVEL_ALL);
LogComponentEnable ("WifiProtectionManager", LOG_LEVEL_ALL);
LogComponentEnable ("WifiPsdu", LOG_LEVEL_ALL);
LogComponentEnable ("WifiRadioEnergyModel", LOG_LEVEL_ALL);
LogComponentEnable ("WifiRemoteStationManager", LOG_LEVEL_ALL);
LogComponentEnable ("WifiSpectrumPhyInterface", LOG_LEVEL_ALL);
LogComponentEnable ("WifiSpectrumSignalParameters", LOG_LEVEL_ALL);
LogComponentEnable ("WifiTxCurrentModel", LOG_LEVEL_ALL);
LogComponentEnable ("WifiTxParameters", LOG_LEVEL_ALL);
LogComponentEnable ("WifiTxTimer", LOG_LEVEL_ALL);
LogComponentEnable ("YansErrorRateModel", LOG_LEVEL_ALL);
LogComponentEnable ("YansWifiChannel", LOG_LEVEL_ALL);
LogComponentEnable ("YansWifiPhy", LOG_LEVEL_ALL);
//From Spectrum
LogComponentEnable ("WifiSpectrumValueHelper", LOG_LEVEL_ALL);
}
int64_t
WifiHelper::AssignStreams (NetDeviceContainer c, int64_t stream)
{
int64_t currentStream = stream;
Ptr<NetDevice> netDevice;
for (NetDeviceContainer::Iterator i = c.Begin (); i != c.End (); ++i)
{
netDevice = (*i);
Ptr<WifiNetDevice> wifi = DynamicCast<WifiNetDevice> (netDevice);
if (wifi)
{
//Handle any random numbers in the PHY objects.
currentStream += wifi->GetPhy ()->AssignStreams (currentStream);
//Handle any random numbers in the station managers.
currentStream += wifi->GetRemoteStationManager ()->AssignStreams (currentStream);
//Handle any random numbers in the MAC objects.
Ptr<WifiMac> mac = wifi->GetMac ();
Ptr<RegularWifiMac> rmac = DynamicCast<RegularWifiMac> (mac);
if (rmac)
{
PointerValue ptr;
rmac->GetAttribute ("Txop", ptr);
Ptr<Txop> txop = ptr.Get<Txop> ();
currentStream += txop->AssignStreams (currentStream);
rmac->GetAttribute ("VO_Txop", ptr);
Ptr<QosTxop> vo_txop = ptr.Get<QosTxop> ();
currentStream += vo_txop->AssignStreams (currentStream);
rmac->GetAttribute ("VI_Txop", ptr);
Ptr<QosTxop> vi_txop = ptr.Get<QosTxop> ();
currentStream += vi_txop->AssignStreams (currentStream);
rmac->GetAttribute ("BE_Txop", ptr);
Ptr<QosTxop> be_txop = ptr.Get<QosTxop> ();
currentStream += be_txop->AssignStreams (currentStream);
rmac->GetAttribute ("BK_Txop", ptr);
Ptr<QosTxop> bk_txop = ptr.Get<QosTxop> ();
currentStream += bk_txop->AssignStreams (currentStream);
//if an AP, handle any beacon jitter
Ptr<ApWifiMac> apmac = DynamicCast<ApWifiMac> (rmac);
if (apmac)
{
currentStream += apmac->AssignStreams (currentStream);
}
}
}
}
return (currentStream - stream);
}
} //namespace ns3
| 36.699807 | 151 | 0.653244 | [
"object",
"vector",
"model"
] |
ba2ad597cb56dba76c123323ac1355b84e433f12 | 16,661 | cpp | C++ | test/testbuilder.cpp | zqianem/pebble | 481c272bbb12ca1b16b776255cc9227696d3edef | [
"MIT"
] | 11 | 2020-07-08T19:53:09.000Z | 2021-09-12T03:44:24.000Z | test/testbuilder.cpp | zqianem/pebble | 481c272bbb12ca1b16b776255cc9227696d3edef | [
"MIT"
] | 18 | 2020-07-07T18:48:09.000Z | 2020-09-29T18:03:59.000Z | test/testbuilder.cpp | zqianem/pebble | 481c272bbb12ca1b16b776255cc9227696d3edef | [
"MIT"
] | 3 | 2020-07-09T01:10:27.000Z | 2020-08-27T22:43:15.000Z | #include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <ctype.h>
#include <map>
// ---------------------------------------------------------------------------------------------------------------------
// TODO
// 1. Make 'ModifiedMethodCall' more robust
// 2.
// ---------------------------------------------------------------------------------------------------------------------
// Terminology
// methodCall: MethodName(Params)
inline const std::string c_comment = "\n// generated by TestBuilder\n";
inline const std::string c_tabString = " ";
namespace TestBuild
{
std::string currentMethodCall;
bool insideMethodCall = false;
std::string outputBuffer;
int contextLevel;
int baseContextLevel = 0;
bool insideMethodDef = false;
bool AddTrace = false;
/// true if [c] is a letter, number, or underscore
bool IsNameComp(char c)
{
return std::isalnum(c) || c == '_';
}
/// true if line is an assignment operation
bool LineIsAssignment(const std::string& line)
{
return line.find("=") != std::string::npos;
}
/// true if line is a typedef operation
bool LineIsTypeDef(const std::string& line)
{
return line.find("typedef") != std::string::npos;
}
/// true if line is a template operation
bool LineIsTemplate(const std::string& line)
{
return line.find("template") != std::string::npos;
}
// TODO: this is slighly buggy
/// changes the baseContext level depending on whether the reader is inside a namespace/class
void ChangeBaseContextLevel(const std::string& line)
{
if(line.find("namespace") != std::string::npos && line.find("using") == std::string::npos)
{
baseContextLevel = baseContextLevel + 1;
return;
}
// if(contextLevel < baseContextLevel)
// baseContextLevel = contextLevel;
}
/// sets insideMethodCall to true if the line is the method call part of a method definition or was in a method call
/// previously
void LineBeginsMethodCall(const std::string& line)
{
insideMethodCall = insideMethodCall || (
((contextLevel == baseContextLevel && line.find("(") != std::string::npos) || LineIsTemplate(line))
&& !LineIsAssignment(line)
&& !LineIsTypeDef(line));
}
/// adds whatever part of [line] is a method call to currentMethod and returns true if [excess] is not empty
/// where [excess] stores line information not part of the method definition. assumes that the reader is
/// currently parsing through a method definition
bool MethodCallEnds(const std::string& line, std::string& excess)
{
size_t endPos = line.find("{");
/// if the method block start is found
if(endPos != std::string::npos)
{
insideMethodCall = false;
insideMethodDef = true;
currentMethodCall.append(line.c_str(), endPos);
excess = line.substr(endPos, std::string::npos);
return true;
}
else
{
currentMethodCall.append(line);
currentMethodCall.append("\n");
return false;
}
}
/// updates the global contextLevel based on what block the head is in
void ChangeContextLevel(const std::string& line)
{
for(auto it = line.begin(); it != line.end(); it++)
{
if(*it == '{')
contextLevel++;
else if(*it == '}')
contextLevel--;
}
}
/// makes the currentMethod into an internal definition (i.e. {METHOD_NAME}_INTERNAL)
std::string ModifiedMethodCall()
{
std::string newMethodCall;
for(size_t i=0; i<currentMethodCall.size(); i++)
{
if(currentMethodCall.at(i) == '(')
newMethodCall += "_INTERNAL";
newMethodCall += currentMethodCall.at(i);
}
return newMethodCall;
}
/// return the first contiguous name starting before [pos] in [str]
std::string GetNameBeforePos(const std::string& str, int pos)
{
std::string name;
name.reserve(32);
int i;
for(i=pos; i>=0 && !IsNameComp(str.at(i)); i--); // move to end of first 'name' before pos
for(; i>=0 && IsNameComp(str.at(i)); i--); // move to head of first 'name' before pos
i++; // on first char of 'name'
for(; static_cast<size_t>(i)<str.size() && IsNameComp(str.at(i)); i++)
name += str.at(i);
return name;
}
/// returns the name a method from a methodCall
std::string MethodName(const std::string& methodCall)
{
std::string methodName;
int parenPos = methodCall.find('(');
return GetNameBeforePos(methodCall, parenPos);
}
/// gets the next parameter and sets it to the next non-space symbol
std::string GetParam(const std::string& methodCall, size_t& i)
{
i++;
while(i < methodCall.size() && methodCall.at(i) != ',' && methodCall.at(i) != ')') i++;
return GetNameBeforePos(methodCall, i);
}
/// true if a methodCall takes no parameters
bool HasNoParams(const std::string& methodCall)
{
size_t i = methodCall.find('(');
while(++i<methodCall.size() && methodCall.at(i) != ')')
{
if(IsNameComp(methodCall.at(i)))
return false;
}
return true;
}
std::vector<std::string> MethodParams(const std::string& methodCall)
{
std::vector<std::string> params;
if(HasNoParams(methodCall))
return params;
size_t i = methodCall.find("(");
while(methodCall.at(i) != ')')
{
params.push_back(GetParam(methodCall, i));
}
return params;
}
/// true if exited definition block of method
bool LineFinishesMethodDef(const std::string& line)
{
// will be true if returns to baseContextLevel and was previously insideMethodDef
if(contextLevel == baseContextLevel && insideMethodDef)
{
insideMethodDef = false;
return true;
}
return false;
}
/// true if method has return type (non-void)
bool NonVoidReturn(const std::string& call)
{
return call.find("void ") == std::string::npos;
}
/// removes anything past the right paren of a method call
std::string CleanRightOfMethodCall(const std::string str)
{
int i;
for(i=str.size()-1; i >=0 && str.at(i) != ')'; i--);
return str.substr(0, i+1);
}
/// returns a declaration for the original method
std::string OriginalMethodDeclaration()
{
return "\n" + CleanRightOfMethodCall(currentMethodCall);
}
/// generates a method call for the internal method
std::string GenerateInternalMethodCall()
{
std::string methodInterface = c_comment + currentMethodCall;
std::vector<std::string> methodParams = MethodParams(currentMethodCall);
std::string modifiedMethodCall = MethodName(ModifiedMethodCall());
if(methodParams.size() == 0)
modifiedMethodCall += "();\n";
else
{
modifiedMethodCall += "(" + methodParams.at(0);
for(size_t i=1; i<methodParams.size(); i++)
modifiedMethodCall += ", " + methodParams.at(i);
modifiedMethodCall += ");\n";
}
return modifiedMethodCall;
}
/// generates a return to the internal method call
std::string GenerateReturnForInternalMethodCall()
{
if(NonVoidReturn(currentMethodCall))
return "return " + GenerateInternalMethodCall();
return GenerateInternalMethodCall();
}
std::string GenerateTraceLine()
{
if(!AddTrace)
return "";
auto methodName = MethodName(currentMethodCall);
return c_tabString + "LogIt(LogSeverityType::Sev3_Critical, \"" + methodName + "\", \"\");\n";
}
std::string GenerateFunctionInjectPoint()
{
auto methodName = MethodName(currentMethodCall);
auto params = MethodParams(currentMethodCall);
auto str = c_tabString + "if(FunctionInjections.count(\"" + methodName +"\") == 1){\n";
str += c_tabString + "Params p;\n";
for(auto param: params)
{
str += c_tabString + "p.push_back(static_cast<const void*>(&" + param + "));\n";
}
str += c_tabString + "FunctionInjections[\"" + methodName +"\"](p);\n";
str += c_tabString + "}\n";
return str;
}
std::string GenerateHitCounter()
{
auto methodName = MethodName(currentMethodCall);
return "methodHitMap[\"" + methodName + "\"]++;\n";
}
std::string GenerateTraceLineV2()
{
auto methodName = MethodName(currentMethodCall);
return "TEST_Tracer(\"" + methodName + "\");\n";
}
/// generates the stubbed method interface
std::string GenerateStubbedInterface()
{
std::string methodInterface = c_comment + currentMethodCall;
methodInterface += "{\n";
methodInterface += c_tabString + GenerateTraceLineV2();
methodInterface += GenerateTraceLine();
methodInterface += c_tabString + GenerateHitCounter();
methodInterface += GenerateFunctionInjectPoint();
methodInterface += c_tabString + GenerateReturnForInternalMethodCall();
methodInterface += "}\n";
return methodInterface;
}
/// adds the stubbed method public interface to the buffer
void BufferMethodInterface()
{
std::string methodInterface = GenerateStubbedInterface();
outputBuffer.append(methodInterface.c_str(), methodInterface.size());
currentMethodCall.clear();
}
/// true if [line] is entirely a comment
bool LineIsComment(const std::string& line)
{
size_t i;
for(i=0; i<line.size() && line.at(i) == ' '; i++);
return i+1 < line.size() && line.at(i) == '/' && line.at(i+1) == '/';
}
std::string FileNameFromPath(const std::string& filepath)
{
std::string filename;
filename.reserve(32);
size_t i;
for(i=filepath.size(); i>=0 && filepath[i] != '/' && filepath[i] != '/'; i--);
while(++i<filepath.size())
filename.push_back(filepath[i]);
return filename;
}
/// stubs all methods in [filename] so that all methods become {METHOD_NAME}_INTERNAL
void StubFile(std::string filepath)
{
outputBuffer.clear();
currentMethodCall.clear();
outputBuffer.reserve(2048);
currentMethodCall.reserve(256);
std::cout << "on " << filepath << std::endl;
std::string filename = FileNameFromPath(filepath);
std::fstream file;
file.open(filepath, std::ios::in);
std::fstream outFile;
outFile.open("./test/src/" + filename, std::ios::out);
std::string testInclude = "#include \"test.h\"\n";
outFile.write(testInclude.c_str(), testInclude.size());
std::string line;
line.reserve(256);
while(std::getline(file, line))
{
ChangeBaseContextLevel(line); // changes baseContextLevel as necessary
if(LineIsComment(line)) // skip comments
continue;
LineBeginsMethodCall(line); // decide if the line begins a methodCall
std::string excess;
if(insideMethodCall)
{
if(MethodCallEnds(line, excess)) // if the method call ends, add the modified
{ // version to the buffer
// if the method involves resolving scope, skip it for now
// or if it involves generics
if(currentMethodCall.find("::") != std::string::npos
|| currentMethodCall.find("template <") != std::string::npos)
{
outputBuffer.append("\n");
outputBuffer.append(currentMethodCall);
outputBuffer.append(excess);
outputBuffer.append("\n");
currentMethodCall.clear();
insideMethodDef = false;
}
else
{
outputBuffer.append("\n");
outputBuffer.append(ModifiedMethodCall());
outputBuffer.append(excess);
outputBuffer.append("\n");
}
}
}
else // if not a method call, just buffer line
{
outputBuffer.append(line.c_str(), line.size());
outputBuffer.append("\n");
}
ChangeContextLevel(line); // changes context level by presence of { }
if(LineFinishesMethodDef(line))
{
outputBuffer = OriginalMethodDeclaration() + // add a declaration for the original method
";\n" + // and then the modifed method to the buffer
outputBuffer;
BufferMethodInterface();
}
if(!insideMethodDef) // output content when exited method def and
{ // clear buffer
outFile.write(outputBuffer.c_str(), outputBuffer.size());
outputBuffer.clear();
}
}
}
/// copy a file directly
void CopyFile(const std::string& filepath)
{
std::fstream file;
file.open(filepath, std::ios::in);
std::cout << "copy " << filepath << std::endl;
std::string filename = FileNameFromPath(filepath);
std::fstream outFile;
outFile.open("./test/src/" + filename, std::ios::out);
std::string line;
while(std::getline(file, line))
{
outFile.write(line.c_str(), line.size());
outFile.write("\n", 1);
}
file.close();
outFile.close();
}
void RewriteMain()
{
std::fstream file;
file.open("./test/src/main.cpp", std::ios::out);
std::fstream overrideFile;
overrideFile.open("./assets/test_main.cpp", std::ios::in);
std::string testInclude = "#include \"test.h\"\n";
file.write(testInclude.c_str(), testInclude.size());
std::string line;
while(std::getline(overrideFile, line))
{
file.write(line.c_str(), line.size());
file.write("\n", 1);
}
file.close();
overrideFile.close();
}
}
inline const std::string c_traceFlag = "--trace";
/// true it [str] is an h file
bool IsH(const std::string& str)
{
return str.at(str.size()-1) == 'h';
}
/// special files get copied
/// 1. utils get copied b/c it's a library
/// 2. diagnostics gets copied b/c use of VA args is not supported
bool IsSpecial(const std::string& str)
{
std::string name = TestBuild::FileNameFromPath(str);
return name == "utils.cpp" || name == "diagnostics.cpp";
}
void HandleFlag(const std::string& str)
{
if(str == c_traceFlag)
{
TestBuild::AddTrace = true;
}
}
int main(int argc, char* argv[])
{
std::cout << "starting..." << std::endl;
for(int i=1; i<argc; i++)
{
std::string str = argv[i];
HandleFlag(str);
}
for(int i=1; i<argc; i++)
{
std::string str = argv[i];
if(IsH(str) || IsSpecial(str))
{
TestBuild::CopyFile(str);
}
else
{
TestBuild::StubFile(str);
}
}
TestBuild::RewriteMain();
std::cout << "finished\n";
return 0;
}
| 31.795802 | 138 | 0.52896 | [
"vector"
] |
ba3d24c4e15fa29d68d57c8130bb473b8b1745a5 | 15,987 | cc | C++ | chromium/mandoline/ui/desktop_ui/browser_window.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/mandoline/ui/desktop_ui/browser_window.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/mandoline/ui/desktop_ui/browser_window.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 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 "mandoline/ui/desktop_ui/browser_window.h"
#include <stdint.h>
#include <utility>
#include "base/command_line.h"
#include "base/macros.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "components/mus/public/cpp/event_matcher.h"
#include "components/mus/public/cpp/scoped_window_ptr.h"
#include "components/mus/public/cpp/window_tree_host_factory.h"
#include "mandoline/ui/desktop_ui/browser_commands.h"
#include "mandoline/ui/desktop_ui/browser_manager.h"
#include "mandoline/ui/desktop_ui/find_bar_view.h"
#include "mandoline/ui/desktop_ui/public/interfaces/omnibox.mojom.h"
#include "mandoline/ui/desktop_ui/toolbar_view.h"
#include "mojo/common/common_type_converters.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/services/tracing/public/cpp/switches.h"
#include "mojo/services/tracing/public/interfaces/tracing.mojom.h"
#include "ui/gfx/canvas.h"
#include "ui/mojo/init/ui_init.h"
#include "ui/views/background.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/layout/layout_manager.h"
#include "ui/views/mus/aura_init.h"
#include "ui/views/mus/display_converter.h"
#include "ui/views/mus/native_widget_mus.h"
#include "ui/views/widget/widget_delegate.h"
namespace mandoline {
class ProgressView : public views::View {
public:
ProgressView() : progress_(0.f), loading_(false) {}
~ProgressView() override {}
void SetProgress(double progress) {
progress_ = progress;
SchedulePaint();
}
void SetIsLoading(bool loading) {
if (loading == loading_)
return;
loading_ = loading;
progress_ = 0.f;
SchedulePaint();
}
private:
void OnPaint(gfx::Canvas* canvas) override {
if (loading_) {
canvas->FillRect(GetLocalBounds(), SK_ColorGREEN);
gfx::Rect progress_rect = GetLocalBounds();
progress_rect.set_width(progress_rect.width() * progress_);
canvas->FillRect(progress_rect, SK_ColorRED);
} else {
canvas->FillRect(GetLocalBounds(), SK_ColorGRAY);
}
}
double progress_;
bool loading_;
DISALLOW_COPY_AND_ASSIGN(ProgressView);
};
class BrowserWindow::LayoutManagerImpl : public views::LayoutManager {
public:
explicit LayoutManagerImpl(BrowserWindow* window) : window_(window) {}
~LayoutManagerImpl() override {}
private:
// views::LayoutManager:
gfx::Size GetPreferredSize(const views::View* view) const override {
return gfx::Size();
}
void Layout(views::View* host) override {
window_->Layout(host);
}
BrowserWindow* window_;
DISALLOW_COPY_AND_ASSIGN(LayoutManagerImpl);
};
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, public:
BrowserWindow::BrowserWindow(mojo::ApplicationImpl* app,
mus::mojom::WindowTreeHostFactory* host_factory,
BrowserManager* manager)
: app_(app),
host_client_binding_(this),
manager_(manager),
toolbar_view_(nullptr),
progress_bar_(nullptr),
find_bar_view_(nullptr),
root_(nullptr),
content_(nullptr),
omnibox_view_(nullptr),
find_active_(0),
find_count_(0),
web_view_(this) {
mus::mojom::WindowTreeHostClientPtr host_client;
host_client_binding_.Bind(GetProxy(&host_client));
mus::CreateWindowTreeHost(host_factory, std::move(host_client), this, &host_,
nullptr, nullptr);
}
void BrowserWindow::LoadURL(const GURL& url) {
// Haven't been embedded yet, can't embed.
// TODO(beng): remove this.
if (!root_) {
default_url_ = url;
return;
}
if (!url.is_valid()) {
ShowOmnibox();
return;
}
mojo::URLRequestPtr request(mojo::URLRequest::New());
request->url = url.spec();
Embed(std::move(request));
}
void BrowserWindow::Close() {
if (root_)
mus::ScopedWindowPtr::DeleteWindowOrWindowManager(root_);
else
delete this;
}
void BrowserWindow::ShowOmnibox() {
TRACE_EVENT0("desktop_ui", "BrowserWindow::ShowOmnibox");
if (!omnibox_.get()) {
omnibox_connection_ = app_->ConnectToApplication("mojo:omnibox");
omnibox_connection_->AddService<ViewEmbedder>(this);
omnibox_connection_->ConnectToService(&omnibox_);
omnibox_connection_->SetRemoteServiceProviderConnectionErrorHandler(
[this]() {
// This will cause the connection to be re-established the next time
// we come through this codepath.
omnibox_.reset();
});
}
omnibox_->ShowForURL(mojo::String::From(current_url_.spec()));
}
void BrowserWindow::ShowFind() {
TRACE_EVENT0("desktop_ui", "BrowserWindow::ShowFind");
toolbar_view_->SetVisible(false);
find_bar_view_->Show();
}
void BrowserWindow::GoBack() {
TRACE_EVENT0("desktop_ui", "BrowserWindow::GoBack");
web_view_.web_view()->GoBack();
}
void BrowserWindow::GoForward() {
TRACE_EVENT0("desktop_ui", "BrowserWindow::GoForward");
web_view_.web_view()->GoForward();
}
BrowserWindow::~BrowserWindow() {
DCHECK(!root_);
manager_->BrowserWindowClosed(this);
}
float BrowserWindow::DIPSToPixels(float value) const {
return value * root_->viewport_metrics().device_pixel_ratio;
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, mus::ViewTreeDelegate implementation:
void BrowserWindow::OnEmbed(mus::Window* root) {
TRACE_EVENT0("desktop_ui", "BrowserWindow::OnEmbed");
// BrowserWindow does not support being embedded more than once.
CHECK(!root_);
// Record when the browser window was displayed, used for performance testing.
const base::TimeTicks display_ticks = base::TimeTicks::Now();
root_ = root;
host_->SetTitle("Mandoline");
content_ = root_->connection()->NewWindow();
Init(root_);
host_->SetSize(mojo::Size::From(gfx::Size(1280, 800)));
root_->AddChild(content_);
host_->AddActivationParent(root_->id());
content_->SetVisible(true);
web_view_.Init(app_, content_);
host_->AddAccelerator(
static_cast<uint32_t>(BrowserCommand::CLOSE),
mus::CreateKeyMatcher(mus::mojom::KEYBOARD_CODE_W,
mus::mojom::EVENT_FLAGS_CONTROL_DOWN),
mus::mojom::WindowTreeHost::AddAcceleratorCallback());
host_->AddAccelerator(
static_cast<uint32_t>(BrowserCommand::FOCUS_OMNIBOX),
mus::CreateKeyMatcher(mus::mojom::KEYBOARD_CODE_L,
mus::mojom::EVENT_FLAGS_CONTROL_DOWN),
mus::mojom::WindowTreeHost::AddAcceleratorCallback());
host_->AddAccelerator(
static_cast<uint32_t>(BrowserCommand::NEW_WINDOW),
mus::CreateKeyMatcher(mus::mojom::KEYBOARD_CODE_N,
mus::mojom::EVENT_FLAGS_CONTROL_DOWN),
mus::mojom::WindowTreeHost::AddAcceleratorCallback());
host_->AddAccelerator(
static_cast<uint32_t>(BrowserCommand::SHOW_FIND),
mus::CreateKeyMatcher(mus::mojom::KEYBOARD_CODE_F,
mus::mojom::EVENT_FLAGS_CONTROL_DOWN),
mus::mojom::WindowTreeHost::AddAcceleratorCallback());
host_->AddAccelerator(static_cast<uint32_t>(BrowserCommand::GO_BACK),
mus::CreateKeyMatcher(mus::mojom::KEYBOARD_CODE_LEFT,
mus::mojom::EVENT_FLAGS_ALT_DOWN),
mus::mojom::WindowTreeHost::AddAcceleratorCallback());
host_->AddAccelerator(static_cast<uint32_t>(BrowserCommand::GO_FORWARD),
mus::CreateKeyMatcher(mus::mojom::KEYBOARD_CODE_RIGHT,
mus::mojom::EVENT_FLAGS_ALT_DOWN),
mus::mojom::WindowTreeHost::AddAcceleratorCallback());
// Now that we're ready, load the default url.
LoadURL(default_url_);
// Record the time spent opening initial tabs, used for performance testing.
const base::TimeDelta open_tabs_delta =
base::TimeTicks::Now() - display_ticks;
// Record the browser startup time metrics, used for performance testing.
static bool recorded_browser_startup_metrics = false;
if (!recorded_browser_startup_metrics &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
tracing::kEnableStatsCollectionBindings)) {
tracing::StartupPerformanceDataCollectorPtr collector;
app_->ConnectToService("mojo:tracing", &collector);
collector->SetBrowserWindowDisplayTicks(display_ticks.ToInternalValue());
collector->SetBrowserOpenTabsTimeDelta(open_tabs_delta.ToInternalValue());
collector->SetBrowserMessageLoopStartTicks(
manager_->startup_ticks().ToInternalValue());
recorded_browser_startup_metrics = true;
}
}
void BrowserWindow::OnConnectionLost(mus::WindowTreeConnection* connection) {
root_ = nullptr;
delete this;
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, mus::ViewTreeHostClient implementation:
void BrowserWindow::OnAccelerator(uint32_t id, mus::mojom::EventPtr event) {
switch (static_cast<BrowserCommand>(id)) {
case BrowserCommand::CLOSE:
Close();
break;
case BrowserCommand::NEW_WINDOW:
manager_->CreateBrowser(GURL());
break;
case BrowserCommand::FOCUS_OMNIBOX:
ShowOmnibox();
break;
case BrowserCommand::SHOW_FIND:
ShowFind();
break;
case BrowserCommand::GO_BACK:
GoBack();
break;
case BrowserCommand::GO_FORWARD:
GoForward();
break;
default:
NOTREACHED();
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, web_view::mojom::WebViewClient implementation:
void BrowserWindow::TopLevelNavigateRequest(mojo::URLRequestPtr request) {
OnHideFindBar();
Embed(std::move(request));
}
void BrowserWindow::TopLevelNavigationStarted(const mojo::String& url) {
GURL gurl(url);
bool changed = current_url_ != gurl;
current_url_ = gurl;
if (changed)
toolbar_view_->SetOmniboxText(base::UTF8ToUTF16(current_url_.spec()));
}
void BrowserWindow::LoadingStateChanged(bool is_loading, double progress) {
progress_bar_->SetIsLoading(is_loading);
progress_bar_->SetProgress(progress);
}
void BrowserWindow::BackForwardChanged(
web_view::mojom::ButtonState back_button,
web_view::mojom::ButtonState forward_button) {
toolbar_view_->SetBackForwardEnabled(
back_button == web_view::mojom::ButtonState::BUTTON_STATE_ENABLED,
forward_button == web_view::mojom::ButtonState::BUTTON_STATE_ENABLED);
}
void BrowserWindow::TitleChanged(const mojo::String& title) {
base::string16 formatted =
title.is_null() ? base::ASCIIToUTF16("Untitled")
: title.To<base::string16>() +
base::ASCIIToUTF16(" - Mandoline");
host_->SetTitle(mojo::String::From(formatted));
}
void BrowserWindow::FindInPageMatchCountUpdated(int32_t request_id,
int32_t count,
bool final_update) {
find_count_ = count;
find_bar_view_->SetMatchLabel(find_active_, find_count_);
}
void BrowserWindow::FindInPageSelectionUpdated(int32_t request_id,
int32_t active_match_ordinal) {
find_active_ = active_match_ordinal;
find_bar_view_->SetMatchLabel(find_active_, find_count_);
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, ViewEmbedder implementation:
void BrowserWindow::Embed(mojo::URLRequestPtr request) {
const std::string string_url = request->url.To<std::string>();
if (string_url == "mojo:omnibox") {
EmbedOmnibox();
return;
}
web_view_.web_view()->LoadRequest(std::move(request));
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, mojo::InterfaceFactory<ViewEmbedder> implementation:
void BrowserWindow::Create(mojo::ApplicationConnection* connection,
mojo::InterfaceRequest<ViewEmbedder> request) {
view_embedder_bindings_.AddBinding(this, std::move(request));
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, FindBarDelegate implementation:
void BrowserWindow::OnDoFind(const std::string& find, bool forward) {
web_view_.web_view()->Find(mojo::String::From(find), forward);
}
void BrowserWindow::OnHideFindBar() {
toolbar_view_->SetVisible(true);
find_bar_view_->Hide();
web_view_.web_view()->StopFinding();
}
////////////////////////////////////////////////////////////////////////////////
// BrowserWindow, private:
void BrowserWindow::Init(mus::Window* root) {
DCHECK_GT(root->viewport_metrics().device_pixel_ratio, 0);
if (!aura_init_) {
ui_init_.reset(new ui::mojo::UIInit(views::GetDisplaysFromWindow(root)));
aura_init_.reset(new views::AuraInit(app_, "mandoline_ui.pak"));
}
root_ = root;
omnibox_view_ = root_->connection()->NewWindow();
root_->AddChild(omnibox_view_);
views::WidgetDelegateView* widget_delegate = new views::WidgetDelegateView;
widget_delegate->GetContentsView()->set_background(
views::Background::CreateSolidBackground(0xFFDDDDDD));
toolbar_view_ = new ToolbarView(this);
progress_bar_ = new ProgressView;
widget_delegate->GetContentsView()->AddChildView(toolbar_view_);
widget_delegate->GetContentsView()->AddChildView(progress_bar_);
widget_delegate->GetContentsView()->SetLayoutManager(
new LayoutManagerImpl(this));
find_bar_view_ = new FindBarView(this);
widget_delegate->GetContentsView()->AddChildView(find_bar_view_);
views::Widget* widget = new views::Widget;
views::Widget::InitParams params(
views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.native_widget = new views::NativeWidgetMus(
widget, app_->shell(), root, mus::mojom::SURFACE_TYPE_DEFAULT);
params.delegate = widget_delegate;
params.bounds = root_->bounds();
widget->Init(params);
widget->Show();
root_->SetFocus();
}
void BrowserWindow::EmbedOmnibox() {
mus::mojom::WindowTreeClientPtr view_tree_client;
omnibox_->GetWindowTreeClient(GetProxy(&view_tree_client));
omnibox_view_->Embed(std::move(view_tree_client));
// TODO(beng): This should be handled sufficiently by
// OmniboxImpl::ShowWindow() but unfortunately view manager policy
// currently prevents the embedded app from changing window z for
// its own window.
omnibox_view_->MoveToFront();
}
void BrowserWindow::Layout(views::View* host) {
// TODO(fsamuel): All bounds should be in physical pixels.
gfx::Rect bounds_in_physical_pixels(host->bounds());
float inverse_device_pixel_ratio =
1.0f / root_->viewport_metrics().device_pixel_ratio;
gfx::Rect toolbar_bounds = gfx::ScaleToEnclosingRect(
bounds_in_physical_pixels, inverse_device_pixel_ratio);
toolbar_bounds.Inset(10, 10, 10, toolbar_bounds.height() - 40);
toolbar_view_->SetBoundsRect(toolbar_bounds);
find_bar_view_->SetBoundsRect(toolbar_bounds);
gfx::Rect progress_bar_bounds(toolbar_bounds.x(), toolbar_bounds.bottom() + 2,
toolbar_bounds.width(), 5);
// The content view bounds are in physical pixels.
gfx::Rect content_bounds(DIPSToPixels(progress_bar_bounds.x()),
DIPSToPixels(progress_bar_bounds.bottom() + 10), 0,
0);
content_bounds.set_width(DIPSToPixels(progress_bar_bounds.width()));
content_bounds.set_height(host->bounds().height() - content_bounds.y() -
DIPSToPixels(10));
content_->SetBounds(content_bounds);
// The omnibox view bounds are in physical pixels.
omnibox_view_->SetBounds(bounds_in_physical_pixels);
}
} // namespace mandoline
| 34.678959 | 80 | 0.677238 | [
"geometry"
] |
ba458d58bbd994bf23b3b7caab908b2bb4bf04c9 | 4,020 | cpp | C++ | InSight/src/InSight/Shader/SSAOShader.cpp | I-Hudson/InSightEngine | a766c87a7be51a19ab796a81888fbbf93a8a43be | [
"Apache-2.0"
] | 3 | 2019-05-26T19:22:27.000Z | 2019-07-09T21:42:18.000Z | InSight/src/InSight/Shader/SSAOShader.cpp | I-Hudson/InSightEngine | a766c87a7be51a19ab796a81888fbbf93a8a43be | [
"Apache-2.0"
] | 15 | 2019-05-26T09:32:22.000Z | 2019-06-11T11:31:03.000Z | InSight/src/InSight/Shader/SSAOShader.cpp | I-Hudson/Insight-Engine | a766c87a7be51a19ab796a81888fbbf93a8a43be | [
"Apache-2.0"
] | null | null | null | #include "Shader/SSAOShader.h"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <random>
#include "Utilities.h"
SSAOShader::SSAOShader()
{
}
SSAOShader::SSAOShader(const char* aVertexPath, const char* aControlpath, const char* aEvaluationpath,
const char* aGeometryPath, const char* aFragmentPath, unsigned int aInputCount /*= 3*/,
const char* aInputs[] /*= nullptr*/, unsigned int aOutputCount /*= 1*/, const char* aOutputs[] /*= nullptr*/) :
BaseShader(aVertexPath, aControlpath, aEvaluationpath, aGeometryPath, aFragmentPath, aInputCount, aInputs, aOutputCount, aOutputs)
{
//create view normal BaseShader
const char* pressaoInputs[] = { "Position", "Normal" };
mViewNormalShader = new BaseShader(
"./shaders/ssao/vertex_preSSAO.glsl",
"",
"",
"",
"./shaders/ssao/fragment_preSSAO.glsl",
2, pressaoInputs
);
//create blur BaseShader
const char* ssaoInputs[] = { "Position", "TexCoord1" };
mBlurShader = new BaseShader(
"./shaders/pp/pp_gaussianBlurVertex.glsl",
"",
"",
"",
"./shaders/pp/pp_gaussianBlurFragment.glsl",
2, ssaoInputs
);
//create framebuffer
mSSAOBuffer.createFrameBuffer();
mSSAOBuffer.attachTextureToFrameBuffer(0, GL_RGBA, 1920, 1080, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0, GL_COLOR_ATTACHMENT0, "Colour Eval Blur");
//gnereate quad
generateQuad();
//mKernel.reserve(64);
//std::uniform_real_distribution<double> randomFloats(0.0, 1.0);
//std::default_random_engine generator;
//for (int i = 0; i < 64; i++)
//{
// glm::vec3 sample(randomFloats(generator) * 2.0 - 1.0, randomFloats(generator) * 2.0 - 1.0, randomFloats(randomFloats));
// sample = glm::normalize(sample);
// sample *= randomFloats(generator);
// float scale = float(i) / 64.0f;
// scale = lerp(0.1f, 1.0f, scale * scale);
// sample *= scale;
// mKernel.push_back(sample);
//}
//load texture from file
Utility::loadTextureFromFile("ssaoNoise.jpg", mNoiseTexture);
setUnsignedIntUniforms("randomMapTexture", mNoiseTexture);
}
SSAOShader::~SSAOShader()
{
}
void SSAOShader::destroy()
{
//destroy/delete
mKernel.clear();
glDeleteTextures(1, &mNoiseTexture);
glDeleteVertexArrays(1, &mVAO);
glDeleteBuffers(1, &mVBO);
glDeleteBuffers(1, &mIBO);
mViewNormalShader->destroy();
delete mViewNormalShader;
mSSAOBuffer.destroy();
mBlurShader->destroy();
delete mBlurShader;
BaseShader::destroy();
}
void SSAOShader::useShader(bool aClear)
{
//bind buffer
mSSAOBuffer.bindBuffer();
BaseShader::useShaderPP(true);
//set kernal uniform
//unsigned int loc = glGetUniformLocation(mShaderID, "gKernel");
//glUniform3fv(loc, 1, glm::value_ptr(*mKernel));
//render
renderQuad();
glUseProgram(0);
mSSAOBuffer.unBindBuffer();
}
void SSAOShader::renderQuad()
{
//Draw Mesh
glBindVertexArray(mVAO);
glDrawElements(GL_TRIANGLES, (GLsizei)6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void SSAOShader::generateQuad()
{
//full screen vertices
FSVertex mVertices[4];
mVertices[0] = FSVertex(glm::vec4(-1.f, -1.f, 0.f, 1.f), glm::vec2(0.f, 0.f));
mVertices[1] = FSVertex(glm::vec4(1.f, -1.f, 0.f, 1.f), glm::vec2(1.f, 0.f));
mVertices[2] = FSVertex(glm::vec4(-1.f, 1.f, 0.f, 1.f), glm::vec2(0.f, 1.f));
mVertices[3] = FSVertex(glm::vec4(1.f, 1.f, 0.f, 1.f), glm::vec2(1.f, 1.f));
unsigned int indics[6] = { 0,1,2,1,3,2 };
//gen buffers
glGenVertexArrays(1, &mVAO);
glGenBuffers(1, &mVBO);
glGenBuffers(1, &mIBO);
glBindVertexArray(mVAO);
//bind buffer data
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(FSVertex), mVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indics, GL_STATIC_DRAW);
//set vertex attributes
glEnableVertexAttribArray(0); //Pos
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(FSVertex), ((char *)0) + 0);
glEnableVertexAttribArray(1); //Tex1
glVertexAttribPointer(1, 2, GL_FLOAT, GL_TRUE, sizeof(FSVertex), ((char *)0) + 16);
glBindVertexArray(0);
}
| 27.162162 | 139 | 0.70796 | [
"mesh",
"render"
] |
ba49d460cc5043945acec4efa08681f9a0db99b6 | 147,376 | cpp | C++ | source/Lib/EncoderLib/EncCu.cpp | jbrdbg/vvenc | f7c9b30b21e47a7af6109e940ab303e66944fa37 | [
"BSD-3-Clause"
] | null | null | null | source/Lib/EncoderLib/EncCu.cpp | jbrdbg/vvenc | f7c9b30b21e47a7af6109e940ab303e66944fa37 | [
"BSD-3-Clause"
] | null | null | null | source/Lib/EncoderLib/EncCu.cpp | jbrdbg/vvenc | f7c9b30b21e47a7af6109e940ab303e66944fa37 | [
"BSD-3-Clause"
] | null | null | null | /* -----------------------------------------------------------------------------
The copyright in this software is being made available under the BSD
License, included below. No patent rights, trademark rights and/or
other Intellectual Property Rights other than the copyrights concerning
the Software are granted under this license.
For any license concerning other Intellectual Property rights than the software,
especially patent licenses, a separate Agreement needs to be closed.
For more information please contact:
Fraunhofer Heinrich Hertz Institute
Einsteinufer 37
10587 Berlin, Germany
www.hhi.fraunhofer.de/vvc
vvc@hhi.fraunhofer.de
Copyright (c) 2019-2021, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Fraunhofer nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------------------- */
/** \file EncCu.cpp
\brief Coding Unit (CU) encoder class
*/
#include "EncCu.h"
#include "EncLib.h"
#include "Analyze.h"
#include "EncPicture.h"
#include "EncModeCtrl.h"
#include "BitAllocation.h"
#include "CommonLib/dtrace_codingstruct.h"
#include "CommonLib/Picture.h"
#include "CommonLib/UnitTools.h"
#include "CommonLib/dtrace_buffer.h"
#include "CommonLib/TimeProfiler.h"
#include "CommonLib/SearchSpaceCounter.h"
#include <mutex>
#include <cmath>
#include <algorithm>
//! \ingroup EncoderLib
//! \{
namespace vvenc {
const uint8_t EncCu::m_GeoModeTest[GEO_MAX_NUM_CANDS][2] = { {0, 1}, {1, 0}, {0, 2}, {1, 2}, {2, 0}, {2, 1}, {0, 3}, {1, 3},
{2, 3}, {3, 0}, {3, 1}, {3, 2}, {0, 4}, {1, 4}, {2, 4}, {3, 4},
{4, 0}, {4, 1}, {4, 2}, {4, 3}, {0, 5}, {1, 5}, {2, 5}, {3, 5},
{4, 5}, {5, 0}, {5, 1}, {5, 2}, {5, 3}, {5, 4} };
// ====================================================================================================================
EncCu::EncCu()
: m_CtxCache ( nullptr )
, m_globalCtuQpVector ( nullptr )
, m_wppMutex ( nullptr )
, m_rcMutex ( nullptr )
, m_CABACEstimator ( nullptr )
{
}
void EncCu::initPic( Picture* pic )
{
const ReshapeData& reshapeData = pic->reshapeData;
m_cRdCost.setReshapeParams( reshapeData.getReshapeLumaLevelToWeightPLUT(), reshapeData.getChromaWeight() );
m_cInterSearch.setSearchRange( pic->cs->slice, *m_pcEncCfg );
m_wppMutex = (m_pcEncCfg->m_numThreads > 0 ) ? &pic->wppMutex : nullptr;
}
void EncCu::initSlice( const Slice* slice )
{
m_cTrQuant.setLambdas( slice->getLambdas() );
m_cRdCost.setLambda( slice->getLambdas()[0], slice->sps->bitDepths );
}
void EncCu::setCtuEncRsrc( CABACWriter* cabacEstimator, CtxCache* ctxCache, ReuseUniMv* pReuseUniMv, BlkUniMvInfoBuffer* pBlkUniMvInfoBuffer, AffineProfList* pAffineProfList, IbcBvCand* pCachedBvs )
{
m_CABACEstimator = cabacEstimator;
m_CtxCache = ctxCache;
m_cIntraSearch.setCtuEncRsrc( cabacEstimator, ctxCache );
m_cInterSearch.setCtuEncRsrc( cabacEstimator, ctxCache, pReuseUniMv, pBlkUniMvInfoBuffer, pAffineProfList, pCachedBvs );
}
void EncCu::setUpLambda (Slice& slice, const double dLambda, const int iQP, const bool setSliceLambda, const bool saveUnadjusted)
{
// store lambda
m_cRdCost.setLambda( dLambda, slice.sps->bitDepths );
// for RDO
// in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
double dLambdas[MAX_NUM_COMP] = { dLambda };
for( uint32_t compIdx = 1; compIdx < MAX_NUM_COMP; compIdx++ )
{
const ComponentID compID = ComponentID( compIdx );
int chromaQPOffset = slice.pps->chromaQpOffset[compID] + slice.sliceChromaQpDelta[ compID ];
int qpc = slice.sps->chromaQpMappingTable.getMappedChromaQpValue(compID, iQP) + chromaQPOffset;
double tmpWeight = pow( 2.0, ( iQP - qpc ) / 3.0 ); // takes into account of the chroma qp mapping and chroma qp Offset
if( m_pcEncCfg->m_DepQuantEnabled/* && !( m_pcEncCfg->getLFNST() ) */)
{
tmpWeight *= ( m_pcEncCfg->m_GOPSize >= 8 ? pow( 2.0, 0.1/3.0 ) : pow( 2.0, 0.2/3.0 ) ); // increase chroma weight for dependent quantization (in order to reduce bit rate shift from chroma to luma)
}
m_cRdCost.setDistortionWeight( compID, tmpWeight );
dLambdas[compIdx] = dLambda / tmpWeight;
}
// for RDOQ
m_cTrQuant.setLambdas( dLambdas );
// for SAO, ALF
if (setSliceLambda)
{
slice.setLambdas( dLambdas );
}
if( saveUnadjusted )
{
m_cRdCost.saveUnadjustedLambda();
}
}
void EncCu::updateLambda(const Slice& slice, const double ctuLambda, const int ctuQP, const int newQP, const bool saveUnadjusted)
{
const double corrFactor = pow (2.0, double (newQP - ctuQP) / 3.0);
const double newLambda = ctuLambda * corrFactor;
const double* oldLambdas = slice.getLambdas(); // assumes prior setUpLambda (slice, ctuLambda) call!
const double newLambdas[MAX_NUM_COMP] = { oldLambdas[COMP_Y] * corrFactor, oldLambdas[COMP_Cb] * corrFactor, oldLambdas[COMP_Cr] * corrFactor };
m_cTrQuant.setLambdas ( newLambdas);
m_cRdCost.setLambda ( newLambda, slice.sps->bitDepths);
if (saveUnadjusted)
{
m_cRdCost.saveUnadjustedLambda(); // TODO hlm: check if this actually improves the overall quality
}
}
void EncCu::init( const VVEncCfg& encCfg, const SPS& sps, std::vector<int>* const globalCtuQpVector, Ctx* syncPicCtx, RateCtrl* pRateCtrl )
{
DecCu::init( &m_cTrQuant, &m_cIntraSearch, &m_cInterSearch, encCfg.m_internChromaFormat );
m_cRdCost.create ();
m_cRdCost.setCostMode( encCfg.m_costMode );
if ( encCfg.m_lumaReshapeEnable || encCfg.m_lumaLevelToDeltaQPEnabled )
{
m_cRdCost.setReshapeInfo( encCfg.m_lumaReshapeEnable ? encCfg.m_reshapeSignalType : RESHAPE_SIGNAL_PQ, encCfg.m_internalBitDepth[ CH_L ], encCfg.m_internChromaFormat );
}
m_modeCtrl.init ( encCfg, &m_cRdCost );
m_cIntraSearch.init ( encCfg, &m_cTrQuant, &m_cRdCost, &m_SortedPelUnitBufs, m_unitCache );
m_cInterSearch.init ( encCfg, &m_cTrQuant, &m_cRdCost, &m_modeCtrl, m_cIntraSearch.getSaveCSBuf() );
m_cTrQuant.init ( nullptr, encCfg.m_RDOQ, encCfg.m_useRDOQTS, encCfg.m_useSelectiveRDOQ, false, true, false /*m_useTransformSkipFast*/, encCfg.m_quantThresholdVal );
m_syncPicCtx = syncPicCtx; ///< context storage for state of contexts at the wavefront/WPP/entropy-coding-sync second CTU of tile-row used for estimation
m_pcRateCtrl = pRateCtrl;
m_rcMutex = (encCfg.m_numThreads > 0) ? &m_pcRateCtrl->rcMutex : nullptr;
// Initialise scaling lists: The encoder will only use the SPS scaling lists. The PPS will never be marked present.
const int maxLog2TrDynamicRange[ MAX_NUM_CH ] = { sps.getMaxLog2TrDynamicRange( CH_L ), sps.getMaxLog2TrDynamicRange( CH_C ) };
m_cTrQuant.getQuant()->setFlatScalingList( maxLog2TrDynamicRange, sps.bitDepths );
m_pcEncCfg = &encCfg;
m_GeoCostList.init(GEO_NUM_PARTITION_MODE, encCfg.m_maxNumGeoCand );
m_AFFBestSATDCost = MAX_DOUBLE;
unsigned uiMaxSize = encCfg.m_CTUSize;
ChromaFormat chromaFormat = encCfg.m_internChromaFormat;
Area ctuArea = Area( 0, 0, uiMaxSize, uiMaxSize );
for( int i = 0; i < maxCuDepth; i++ )
{
Area area = Area( 0, 0, uiMaxSize >> ( i >> 1 ), uiMaxSize >> ( ( i + 1 ) >> 1 ) );
if( area.width < (1 << MIN_CU_LOG2) || area.height < (1 << MIN_CU_LOG2) )
{
m_pTempCS[i] = m_pBestCS[i] = nullptr;
continue;
}
m_pTempCS[i] = new CodingStructure( m_unitCache, nullptr );
m_pBestCS[i] = new CodingStructure( m_unitCache, nullptr );
m_pTempCS[i]->create( chromaFormat, area, false );
m_pBestCS[i]->create( chromaFormat, area, false );
m_pOrgBuffer[i].create( chromaFormat, area );
m_pRspBuffer[i].create( CHROMA_400, area );
}
m_pTempCS2 = new CodingStructure( m_unitCache, nullptr );
m_pBestCS2 = new CodingStructure( m_unitCache, nullptr );
m_pTempCS2->create( chromaFormat, ctuArea, false );
m_pBestCS2->create( chromaFormat, ctuArea, false );
m_cuChromaQpOffsetIdxPlus1 = 0;
m_tempQpDiff = 0;
m_globalCtuQpVector = globalCtuQpVector;
m_SortedPelUnitBufs.create( chromaFormat, uiMaxSize, uiMaxSize );
for( uint8_t i = 0; i < MAX_TMP_BUFS; i++)
{
m_aTmpStorageLCU[i].create(chromaFormat, Area(0, 0, uiMaxSize, uiMaxSize));
}
for (unsigned ui = 0; ui < MRG_MAX_NUM_CANDS; ui++)
{
m_acMergeTmpBuffer[ui].create(chromaFormat, Area(0, 0, uiMaxSize, uiMaxSize));
}
const unsigned maxDepth = 2 * MAX_CU_SIZE_IDX;
m_CtxBuffer.resize( maxDepth );
m_CurrCtx = 0;
if( encCfg.m_EDO )
m_dbBuffer.create( chromaFormat, Area( 0, 0, uiMaxSize, uiMaxSize ), 0, 8 );
}
void EncCu::destroy()
{
for( int i = 0; i < maxCuDepth; i++ )
{
if( m_pTempCS[i] )
{
m_pTempCS[i]->destroy();
delete m_pTempCS[i]; m_pTempCS[i] = nullptr;
}
if( m_pBestCS[i] )
{
m_pBestCS[i]->destroy();
delete m_pBestCS[i]; m_pBestCS[i] = nullptr;
}
m_pOrgBuffer[i].destroy();
m_pRspBuffer[i].destroy();
}
m_pTempCS2->destroy();
m_pBestCS2->destroy();
delete m_pTempCS2; m_pTempCS2 = nullptr;
delete m_pBestCS2; m_pBestCS2 = nullptr;
m_SortedPelUnitBufs.destroy();
for( uint8_t i = 0; i < MAX_TMP_BUFS; i++)
{
m_aTmpStorageLCU[i].destroy();
}
for (unsigned ui = 0; ui < MRG_MAX_NUM_CANDS; ui++)
{
m_acMergeTmpBuffer[ui].destroy();
}
m_dbBuffer.destroy();
}
EncCu::~EncCu()
{
destroy();
}
// ====================================================================================================================
// Public member functions
// ====================================================================================================================
void EncCu::encodeCtu( Picture* pic, int (&prevQP)[MAX_NUM_CH], uint32_t ctuXPosInCtus, uint32_t ctuYPosInCtus )
{
CodingStructure& cs = *pic->cs;
Slice* slice = cs.slice;
const PreCalcValues& pcv = *cs.pcv;
const uint32_t widthInCtus = pcv.widthInCtus;
#if ENABLE_MEASURE_SEARCH_SPACE
if( ctuXPosInCtus == 0 && ctuYPosInCtus == 0 )
{
g_searchSpaceAcc.picW = pic->lwidth();
g_searchSpaceAcc.picH = pic->lheight();
g_searchSpaceAcc.addSlice( slice->isIntra(), slice->depth );
}
#endif
const int ctuRsAddr = ctuYPosInCtus * pcv.widthInCtus + ctuXPosInCtus;
const uint32_t firstCtuRsAddrOfTile = 0;
const uint32_t tileXPosInCtus = firstCtuRsAddrOfTile % widthInCtus;
const Position pos (ctuXPosInCtus * pcv.maxCUSize, ctuYPosInCtus * pcv.maxCUSize);
const UnitArea ctuArea( cs.area.chromaFormat, Area( pos.x, pos.y, pcv.maxCUSize, pcv.maxCUSize ) );
DTRACE_UPDATE( g_trace_ctx, std::make_pair( "ctu", ctuRsAddr ) );
if ((cs.slice->sliceType != VVENC_I_SLICE || cs.sps->IBC) && ctuXPosInCtus == tileXPosInCtus)
{
cs.motionLutBuf[ctuYPosInCtus].lut.resize(0);
cs.motionLutBuf[ctuYPosInCtus].lutIbc.resize(0);
}
if( m_pcEncCfg->m_ensureWppBitEqual && ctuXPosInCtus == 0 )
{
if( ctuYPosInCtus > 0 )
{
m_CABACEstimator->initCtxModels( *slice );
}
if( m_pcEncCfg->m_entropyCodingSyncEnabled && ctuYPosInCtus )
{
m_CABACEstimator->getCtx() = m_syncPicCtx[ctuYPosInCtus-1];
}
prevQP[CH_L] = prevQP[CH_C] = slice->sliceQp; // hlm: call CU::predictQP() here!
}
else if (ctuRsAddr == firstCtuRsAddrOfTile )
{
m_CABACEstimator->initCtxModels( *slice );
prevQP[CH_L] = prevQP[CH_C] = slice->sliceQp; // hlm: call CU::predictQP() here!
}
else if (ctuXPosInCtus == tileXPosInCtus && m_pcEncCfg->m_entropyCodingSyncEnabled)
{
// reset and then update contexts to the state at the end of the top-right CTU (if within current slice and tile).
m_CABACEstimator->initCtxModels( *slice );
if( cs.getCURestricted( pos.offset(0, -1), pos, slice->independentSliceIdx, 0, CH_L, TREE_D ) )
{
// Top-right is available, we use it.
m_CABACEstimator->getCtx() = m_syncPicCtx[ctuYPosInCtus-1];
}
prevQP[CH_L] = prevQP[CH_C] = slice->sliceQp; // hlm: call CU::predictQP() here!
}
xCompressCtu( cs, ctuArea, ctuRsAddr, prevQP );
m_CABACEstimator->resetBits();
m_CABACEstimator->coding_tree_unit( cs, ctuArea, prevQP, ctuRsAddr, true, true );
// Store probabilities of second CTU in line into buffer - used only if wavefront-parallel-processing is enabled.
if( ctuXPosInCtus == tileXPosInCtus && m_pcEncCfg->m_entropyCodingSyncEnabled )
{
m_syncPicCtx[ctuYPosInCtus] = m_CABACEstimator->getCtx();
}
const int numberOfWrittenBits = int( m_CABACEstimator->getEstFracBits() >> SCALE_BITS );
xUpdateAfterCtuRC( slice, numberOfWrittenBits, ctuRsAddr );
}
// ====================================================================================================================
// Protected member functions
// ====================================================================================================================
void EncCu::xCompressCtu( CodingStructure& cs, const UnitArea& area, const unsigned ctuRsAddr, const int prevQP[] )
{
m_modeCtrl.initCTUEncoding( *cs.slice );
// init the partitioning manager
Partitioner *partitioner = &m_partitioner;
partitioner->initCtu( area, CH_L, *cs.slice );
if( m_pcEncCfg->m_IBCMode )
{
m_cInterSearch.resetCtuRecordIBC();
}
// init current context pointer
m_CurrCtx = m_CtxBuffer.data();
PelStorage* orgBuffer = &m_pOrgBuffer[0];
PelStorage* rspBuffer = &m_pRspBuffer[0];
CodingStructure *tempCS = m_pTempCS [0];
CodingStructure *bestCS = m_pBestCS [0];
cs.initSubStructure( *tempCS, partitioner->chType, partitioner->currArea(), false, orgBuffer, rspBuffer );
cs.initSubStructure( *bestCS, partitioner->chType, partitioner->currArea(), false, orgBuffer, rspBuffer );
m_CABACEstimator->determineNeighborCus( *tempCS, partitioner->currArea(), partitioner->chType, partitioner->treeType );
// copy the relevant area
UnitArea clippedArea = clipArea( partitioner->currArea(), cs.area );
CPelUnitBuf org = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getRspOrigBuf( clippedArea ) : cs.picture->getOrigBuf( clippedArea );
tempCS->getOrgBuf( clippedArea ).copyFrom( org );
const ReshapeData& reshapeData = cs.picture->reshapeData;
if( cs.slice->lmcsEnabled && reshapeData.getCTUFlag() )
{
tempCS->getRspOrgBuf( clippedArea.Y() ).rspSignal( org.get( COMP_Y) , reshapeData.getFwdLUT() );
}
tempCS->currQP[CH_L] = bestCS->currQP[CH_L] =
tempCS->baseQP = bestCS->baseQP = cs.slice->sliceQp;
tempCS->prevQP[CH_L] = bestCS->prevQP[CH_L] = prevQP[CH_L];
xCompressCU( tempCS, bestCS, *partitioner );
// all signals were already copied during compression if the CTU was split - at this point only the structures are copied to the top level CS
// Ensure that a coding was found
// Selected mode's RD-cost must be not MAX_DOUBLE.
CHECK( bestCS->cus.empty() , "No possible encoding found" );
CHECK( bestCS->cus[0]->predMode == NUMBER_OF_PREDICTION_MODES, "No possible encoding found" );
CHECK( bestCS->cost == MAX_DOUBLE , "No possible encoding found" );
if ( m_wppMutex ) m_wppMutex->lock();
cs.useSubStructure( *bestCS, partitioner->chType, TREE_D, CS::getArea( *bestCS, area, partitioner->chType, partitioner->treeType ), true );
if ( m_wppMutex ) m_wppMutex->unlock();
if( CS::isDualITree( cs ) && isChromaEnabled( cs.pcv->chrFormat ) )
{
m_CABACEstimator->getCtx() = m_CurrCtx->start;
partitioner->initCtu( area, CH_C, *cs.slice );
cs.initSubStructure( *tempCS, partitioner->chType, partitioner->currArea(), false, orgBuffer, rspBuffer );
cs.initSubStructure( *bestCS, partitioner->chType, partitioner->currArea(), false, orgBuffer, rspBuffer );
m_CABACEstimator->determineNeighborCus( *tempCS, partitioner->currArea(), partitioner->chType, partitioner->treeType );
tempCS->currQP[CH_C] = bestCS->currQP[CH_C] =
tempCS->baseQP = bestCS->baseQP = cs.slice->sliceQp;
tempCS->prevQP[CH_C] = bestCS->prevQP[CH_C] = prevQP[CH_C];
xCompressCU( tempCS, bestCS, *partitioner );
// Ensure that a coding was found
// Selected mode's RD-cost must be not MAX_DOUBLE.
CHECK( bestCS->cus.empty() , "No possible encoding found" );
CHECK( bestCS->cus[0]->predMode == NUMBER_OF_PREDICTION_MODES, "No possible encoding found" );
CHECK( bestCS->cost == MAX_DOUBLE , "No possible encoding found" );
if ( m_wppMutex ) m_wppMutex->lock();
cs.useSubStructure( *bestCS, partitioner->chType, TREE_D, CS::getArea( *bestCS, area, partitioner->chType, partitioner->treeType ), true );
if ( m_wppMutex ) m_wppMutex->unlock();
}
if ( m_pcEncCfg->m_RCTargetBitrate > 0 )
{
cs.slice->pic->encRCPic->lcu[ ctuRsAddr ].actualMSE = (double)bestCS->dist / (double)cs.slice->pic->encRCPic->lcu[ ctuRsAddr ].numberOfPixel;
}
// reset context states and uninit context pointer
m_CABACEstimator->getCtx() = m_CurrCtx->start;
m_CurrCtx = 0;
}
bool EncCu::xCheckBestMode( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode, const bool useEDO )
{
bool bestCSUpdated = false;
if( !tempCS->cus.empty() )
{
if( tempCS->cus.size() == 1 )
{
const CodingUnit& cu = *tempCS->cus.front();
CHECK( cu.skip && !cu.mergeFlag, "Skip flag without a merge flag is not allowed!" );
}
DTRACE_BEST_MODE( tempCS, bestCS, m_cRdCost.getLambda(true), useEDO );
if( m_modeCtrl.useModeResult( encTestMode, tempCS, partitioner, useEDO ) )
{
std::swap( tempCS, bestCS );
// store temp best CI for next CU coding
m_CurrCtx->best = m_CABACEstimator->getCtx();
bestCSUpdated = true;
}
}
// reset context states
m_CABACEstimator->getCtx() = m_CurrCtx->start;
return bestCSUpdated;
}
void EncCu::xCompressCU( CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& partitioner )
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_COMPRESS_CU, tempCS, partitioner.chType );
const Area& lumaArea = tempCS->area.Y();
Slice& slice = *tempCS->slice;
const PPS &pps = *tempCS->pps;
const SPS &sps = *tempCS->sps;
const uint32_t uiLPelX = tempCS->area.Y().lumaPos().x;
const uint32_t uiTPelY = tempCS->area.Y().lumaPos().y;
m_modeCtrl.initBlk( tempCS->area, slice.pic->poc );
if (m_pcEncCfg->m_usePerceptQPA && pps.useDQP && isLuma (partitioner.chType) && partitioner.currQgEnable())
{
const PreCalcValues &pcv = *pps.pcv;
Picture* const pic = bestCS->picture;
const uint32_t ctuRsAddr = getCtuAddr (partitioner.currQgPos, pcv);
const bool rateCtrlFrame = m_pcEncCfg->m_RCTargetBitrate > 0;
if (partitioner.currSubdiv == 0) // CTU-level QP adaptation
{
if ((m_pcEncCfg->m_usePerceptQPATempFiltISlice == 2) || rateCtrlFrame)
{
if (rateCtrlFrame)
{
// frame-level or GOP-level RC + QPA
pic->ctuAdaptedQP[ ctuRsAddr ] += pic->encRCPic->picQPOffsetQPA;
pic->ctuAdaptedQP[ ctuRsAddr ] = Clip3( 0, MAX_QP, (int)pic->ctuAdaptedQP[ ctuRsAddr ] );
pic->ctuQpaLambda[ ctuRsAddr ] *= pic->encRCPic->picLambdaOffsetQPA;
pic->ctuQpaLambda[ ctuRsAddr ] = Clip3( m_pcRateCtrl->encRCGOP->minEstLambda, m_pcRateCtrl->encRCGOP->maxEstLambda, pic->ctuQpaLambda[ ctuRsAddr ] );
}
m_tempQpDiff = pic->ctuAdaptedQP[ctuRsAddr] - BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, lumaArea );
}
if ((!slice.isIntra() || slice.sps->IBC) && // Museum fix
(uiLPelX + (pcv.maxCUSize >> 1) < (m_pcEncCfg->m_PadSourceWidth)) &&
(uiTPelY + (pcv.maxCUSize >> 1) < (m_pcEncCfg->m_PadSourceHeight)))
{
const uint32_t h = lumaArea.height >> 1;
const uint32_t w = lumaArea.width >> 1;
const int adQPTL = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + 0, uiTPelY + 0, w, h));
const int adQPTR = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + w, uiTPelY + 0, w, h));
const int adQPBL = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + 0, uiTPelY + h, w, h));
const int adQPBR = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, Area (uiLPelX + w, uiTPelY + h, w, h));
tempCS->currQP[partitioner.chType] = tempCS->baseQP =
bestCS->currQP[partitioner.chType] = bestCS->baseQP = std::min (std::min (adQPTL, adQPTR), std::min (adQPBL, adQPBR));
if ((m_pcEncCfg->m_usePerceptQPATempFiltISlice == 2) || rateCtrlFrame)
{
if ((m_pcEncCfg->m_usePerceptQPATempFiltISlice == 2) && (m_globalCtuQpVector->size() > ctuRsAddr) && (slice.TLayer == 0) // last CTU row of non-Intra key-frame
&& (m_pcEncCfg->m_IntraPeriod == 2 * m_pcEncCfg->m_GOPSize) && (ctuRsAddr >= pcv.widthInCtus) && (uiTPelY + pcv.maxCUSize > m_pcEncCfg->m_PadSourceHeight))
{
m_globalCtuQpVector->at (ctuRsAddr) = m_globalCtuQpVector->at (ctuRsAddr - pcv.widthInCtus); // copy the pumping reducing QP offset from the top CTU neighbor
tempCS->currQP[partitioner.chType] = tempCS->baseQP =
bestCS->currQP[partitioner.chType] = bestCS->baseQP = tempCS->baseQP - m_globalCtuQpVector->at (ctuRsAddr);
}
tempCS->currQP[partitioner.chType] = tempCS->baseQP =
bestCS->currQP[partitioner.chType] = bestCS->baseQP = Clip3 (0, MAX_QP, tempCS->baseQP + m_tempQpDiff);
}
}
else
{
tempCS->currQP[partitioner.chType] = tempCS->baseQP =
bestCS->currQP[partitioner.chType] = bestCS->baseQP = pic->ctuAdaptedQP[ctuRsAddr];
}
setUpLambda ( slice, pic->ctuQpaLambda[ctuRsAddr], pic->ctuAdaptedQP[ctuRsAddr], false, true );
}
else if (slice.isIntra() && !slice.sps->IBC) // sub-CTU QPA
{
CHECK ((partitioner.currArea().lwidth() >= pcv.maxCUSize) || (partitioner.currArea().lheight() >= pcv.maxCUSize), "sub-CTU delta-QP error");
tempCS->currQP[partitioner.chType] = tempCS->baseQP = BitAllocation::applyQPAdaptationSubCtu (&slice, m_pcEncCfg, lumaArea);
if ((m_pcEncCfg->m_usePerceptQPATempFiltISlice == 2) || rateCtrlFrame)
{
tempCS->currQP[partitioner.chType] = tempCS->baseQP = Clip3 (0, MAX_QP, tempCS->baseQP + m_tempQpDiff);
}
updateLambda (slice, pic->ctuQpaLambda[ctuRsAddr], pic->ctuAdaptedQP[ctuRsAddr], tempCS->baseQP, true );
}
}
m_modeCtrl.initCULevel( partitioner, *tempCS );
m_sbtCostSave[0] = m_sbtCostSave[1] = MAX_DOUBLE;
m_CurrCtx->start = m_CABACEstimator->getCtx();
m_cuChromaQpOffsetIdxPlus1 = 0;
if( slice.chromaQpAdjEnabled )
{
// TODO M0133 : double check encoder decisions with respect to chroma QG detection and actual encode
int lgMinCuSize = sps.log2MinCodingBlockSize +
std::max<int>(0, floorLog2(sps.CTUSize - sps.log2MinCodingBlockSize - int((slice.isIntra() ? slice.picHeader->cuChromaQpOffsetSubdivIntra : slice.picHeader->cuChromaQpOffsetSubdivInter) / 2)));
if( partitioner.currQgChromaEnable() )
{
m_cuChromaQpOffsetIdxPlus1 = ( ( uiLPelX >> lgMinCuSize ) + ( uiTPelY >> lgMinCuSize ) ) % ( pps.chromaQpOffsetListLen + 1 );
}
}
DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cux", uiLPelX ) );
DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cuy", uiTPelY ) );
DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cuw", tempCS->area.lwidth() ) );
DTRACE_UPDATE( g_trace_ctx, std::make_pair( "cuh", tempCS->area.lheight() ) );
DTRACE( g_trace_ctx, D_COMMON, "@(%4d,%4d) [%2dx%2d]\n", tempCS->area.lx(), tempCS->area.ly(), tempCS->area.lwidth(), tempCS->area.lheight() );
if( tempCS->slice->checkLDC )
{
m_bestBcwCost[0] = m_bestBcwCost[1] = std::numeric_limits<double>::max();
m_bestBcwIdx[0] = m_bestBcwIdx[1] = -1;
}
m_cInterSearch.resetSavedAffineMotion();
{
const ComprCUCtx &cuECtx = *m_modeCtrl.comprCUCtx;
const CodingStructure& cs = *tempCS;
const PartSplit implicitSplit = partitioner.getImplicitSplit( cs );
const bool isBoundary = implicitSplit != CU_DONT_SPLIT;
const bool lossless = false;
int qp = cs.baseQP;
#if ENABLE_MEASURE_SEARCH_SPACE
if( !isBoundary )
{
g_searchSpaceAcc.addPartition( partitioner.currArea(), partitioner.isSepTree( *tempCS ) ? partitioner.chType : MAX_NUM_CH );
}
#endif
if( ! isBoundary )
{
if (pps.useDQP && partitioner.isSepTree (*tempCS) && isChroma (partitioner.chType))
{
const ChromaFormat chromaFm = tempCS->area.chromaFormat;
const Position chromaCentral (tempCS->area.Cb().chromaPos().offset (tempCS->area.Cb().chromaSize().width >> 1, tempCS->area.Cb().chromaSize().height >> 1));
const Position lumaRefPos (chromaCentral.x << getChannelTypeScaleX (CH_C, chromaFm), chromaCentral.y << getChannelTypeScaleY (CH_C, chromaFm));
const CodingUnit* colLumaCu = bestCS->refCS->getCU (lumaRefPos, CH_L, TREE_D);
// update qp
qp = colLumaCu->qp;
}
m_cIntraSearch.reset();
bool isReuseCU = m_modeCtrl.isReusingCuValid( cs, partitioner, qp );
bool checkIbc = m_pcEncCfg->m_IBCMode && bestCS->picture->useScIBC && (partitioner.chType == CH_L);
if ((m_pcEncCfg->m_IBCFastMethod>3) && (cs.area.lwidth() * cs.area.lheight()) > (16 * 16))
{
checkIbc = false;
}
if( isReuseCU )
{
xReuseCachedResult( tempCS, bestCS, partitioner );
}
else
{
// add first pass modes
if ( !slice.isIRAP() && !( cs.area.lwidth() == 4 && cs.area.lheight() == 4 ) && !partitioner.isConsIntra() )
{
// add inter modes
EncTestMode encTestModeSkip = { ETM_MERGE_SKIP, ETO_STANDARD, qp, lossless };
if (m_modeCtrl.tryMode(encTestModeSkip, cs, partitioner))
{
xCheckRDCostMerge(tempCS, bestCS, partitioner, encTestModeSkip);
CodingUnit* cu = bestCS->getCU(partitioner.chType, partitioner.treeType);
if (cu)
cu->mmvdSkip = cu->skip == false ? false : cu->mmvdSkip;
}
if (m_pcEncCfg->m_Geo && cs.slice->isInterB())
{
EncTestMode encTestModeGeo = { ETM_MERGE_GEO, ETO_STANDARD, qp, lossless };
if (m_modeCtrl.tryMode(encTestModeGeo, cs, partitioner))
{
xCheckRDCostMergeGeo(tempCS, bestCS, partitioner, encTestModeGeo);
}
}
EncTestMode encTestMode = { ETM_INTER_ME, ETO_STANDARD, qp, lossless };
if (m_modeCtrl.tryMode(encTestMode, cs, partitioner))
{
xCheckRDCostInter(tempCS, bestCS, partitioner, encTestMode);
}
if (m_pcEncCfg->m_AMVRspeed)
{
double bestIntPelCost = MAX_DOUBLE;
EncTestMode encTestMode = {ETM_INTER_IMV, ETO_STANDARD, qp, lossless};
if( m_modeCtrl.tryMode( encTestMode, cs, partitioner ) )
{
const bool skipAltHpelIF = ( int( ( encTestMode.opts & ETO_IMV ) >> ETO_IMV_SHIFT ) == 4 ) && ( bestIntPelCost > 1.25 * bestCS->cost );
if (!skipAltHpelIF)
{
tempCS->bestCS = bestCS;
xCheckRDCostInterIMV(tempCS, bestCS, partitioner, encTestMode );
tempCS->bestCS = nullptr;
}
}
}
}
if( m_pcEncCfg->m_EDO && bestCS->cost != MAX_DOUBLE )
{
xCalDebCost(*bestCS, partitioner);
}
if (checkIbc && !partitioner.isConsInter())
{
EncTestMode encTestModeIBCMerge = { ETM_IBC_MERGE, ETO_STANDARD, qp, lossless };
if ((m_pcEncCfg->m_IBCFastMethod < 4) && (partitioner.chType == CH_L) && m_modeCtrl.tryMode(encTestModeIBCMerge, cs, partitioner))
{
xCheckRDCostIBCModeMerge2Nx2N(tempCS, bestCS, partitioner, encTestModeIBCMerge);
}
EncTestMode encTestModeIBC = { ETM_IBC, ETO_STANDARD, qp, lossless };
if (m_modeCtrl.tryMode(encTestModeIBC, cs, partitioner))
{
xCheckRDCostIBCMode(tempCS, bestCS, partitioner, encTestModeIBC);
}
}
// add intra modes
EncTestMode encTestMode( {ETM_INTRA, ETO_STANDARD, qp, lossless} );
if( !partitioner.isConsInter() && m_modeCtrl.tryMode( encTestMode, cs, partitioner ) )
{
xCheckRDCostIntra( tempCS, bestCS, partitioner, encTestMode );
}
} // reusing cu
m_modeCtrl.beforeSplit( partitioner );
if (cuECtx.bestCS && ((cuECtx.bestCostNoImv == (MAX_DOUBLE * .5) || cuECtx.isReusingCu) && !slice.isIntra()) )
{
m_cInterSearch.loadGlobalUniMvs( lumaArea, *pps.pcv );
}
} //boundary
//////////////////////////////////////////////////////////////////////////
// split modes
EncTestMode lastTestMode;
if( cuECtx.qtBeforeBt )
{
EncTestMode encTestMode( { ETM_SPLIT_QT, ETO_STANDARD, qp, false } );
if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
{
lastTestMode = encTestMode;
xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
}
}
if( partitioner.canSplit( CU_HORZ_SPLIT, cs ) )
{
// add split modes
EncTestMode encTestMode( { ETM_SPLIT_BT_H, ETO_STANDARD, qp, false } );
if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
{
lastTestMode = encTestMode;
xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
}
}
if( partitioner.canSplit( CU_VERT_SPLIT, cs ) )
{
// add split modes
EncTestMode encTestMode( { ETM_SPLIT_BT_V, ETO_STANDARD, qp, false } );
if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
{
lastTestMode = encTestMode;
xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
}
}
if( partitioner.canSplit( CU_TRIH_SPLIT, cs ) )
{
// add split modes
EncTestMode encTestMode( { ETM_SPLIT_TT_H, ETO_STANDARD, qp, false } );
if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
{
lastTestMode = encTestMode;
xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
}
}
if( partitioner.canSplit( CU_TRIV_SPLIT, cs ) )
{
// add split modes
EncTestMode encTestMode( { ETM_SPLIT_TT_V, ETO_STANDARD, qp, false } );
if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
{
lastTestMode = encTestMode;
xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
}
}
if( !cuECtx.qtBeforeBt )
{
EncTestMode encTestMode( { ETM_SPLIT_QT, ETO_STANDARD, qp, false } );
if( m_modeCtrl.trySplit( encTestMode, cs, partitioner, lastTestMode ) )
{
lastTestMode = encTestMode;
xCheckModeSplit( tempCS, bestCS, partitioner, encTestMode );
}
}
}
if( bestCS->cus.empty() )
{
m_modeCtrl.finishCULevel( partitioner );
return;
}
//////////////////////////////////////////////////////////////////////////
// Finishing CU
// set context states
m_CABACEstimator->getCtx() = m_CurrCtx->best;
// QP from last processed CU for further processing
//copy the qp of the last non-chroma CU
int numCUInThisNode = (int)bestCS->cus.size();
if( numCUInThisNode > 1 && bestCS->cus.back()->chType == CH_C && !CS::isDualITree( *bestCS ) )
{
CHECK( bestCS->cus[numCUInThisNode-2]->chType != CH_L, "wrong chType" );
bestCS->prevQP[partitioner.chType] = bestCS->cus[numCUInThisNode-2]->qp;
}
else
{
bestCS->prevQP[partitioner.chType] = bestCS->cus.back()->qp;
}
if ((!slice.isIntra() || slice.sps->IBC)
&& partitioner.chType == CH_L
&& bestCS->cus.size() == 1 && (bestCS->cus.back()->predMode == MODE_INTER || bestCS->cus.back()->predMode == MODE_IBC)
&& bestCS->area.Y() == (*bestCS->cus.back()).Y()
)
{
const CodingUnit& cu = *bestCS->cus.front();
bool isIbcSmallBlk = CU::isIBC(cu) && (cu.lwidth() * cu.lheight() <= 16);
if (!cu.affine && !cu.geo && !isIbcSmallBlk)
{
const MotionInfo &mi = cu.getMotionInfo();
HPMVInfo hMi( mi, (mi.interDir == 3) ? cu.BcwIdx : BCW_DEFAULT, cu.imv == IMV_HPEL );
cu.cs->addMiToLut( CU::isIBC(cu) ? cu.cs->motionLut.lutIbc : cu.cs->motionLut.lut, hMi);
}
}
m_modeCtrl.finishCULevel( partitioner );
if( m_cIntraSearch.getSaveCuCostInSCIPU() && bestCS->cus.size() == 1 )
{
m_cIntraSearch.saveCuAreaCostInSCIPU( Area( partitioner.currArea().lumaPos(), partitioner.currArea().lumaSize() ), bestCS->cost );
}
// Assert if Best prediction mode is NONE
// Selected mode's RD-cost must be not MAX_DOUBLE.
CHECK( bestCS->cus.empty() , "No possible encoding found" );
CHECK( bestCS->cus[0]->predMode == NUMBER_OF_PREDICTION_MODES, "No possible encoding found" );
CHECK( bestCS->cost == MAX_DOUBLE , "No possible encoding found" );
}
void EncCu::xCheckModeSplit(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode )
{
const ModeType modeTypeParent = partitioner.modeType;
const TreeType treeTypeParent = partitioner.treeType;
const ChannelType chTypeParent = partitioner.chType;
int signalModeConsVal = tempCS->signalModeCons( getPartSplit( encTestMode ), partitioner, modeTypeParent );
int numRoundRdo = signalModeConsVal == LDT_MODE_TYPE_SIGNAL ? 2 : 1;
bool skipInterPass = false;
for( int i = 0; i < numRoundRdo; i++ )
{
//change cons modes
if( signalModeConsVal == LDT_MODE_TYPE_SIGNAL )
{
CHECK( numRoundRdo != 2, "numRoundRdo shall be 2 - [LDT_MODE_TYPE_SIGNAL]" );
partitioner.modeType = (i == 0) ? MODE_TYPE_INTER : MODE_TYPE_INTRA;
}
else if( signalModeConsVal == LDT_MODE_TYPE_INFER )
{
CHECK( numRoundRdo != 1, "numRoundRdo shall be 1 - [LDT_MODE_TYPE_INFER]" );
partitioner.modeType = MODE_TYPE_INTRA;
}
else if( signalModeConsVal == LDT_MODE_TYPE_INHERIT )
{
CHECK( numRoundRdo != 1, "numRoundRdo shall be 1 - [LDT_MODE_TYPE_INHERIT]" );
partitioner.modeType = modeTypeParent;
}
//for lite intra encoding fast algorithm, set the status to save inter coding info
if( modeTypeParent == MODE_TYPE_ALL && partitioner.modeType == MODE_TYPE_INTER )
{
m_cIntraSearch.setSaveCuCostInSCIPU( true );
m_cIntraSearch.setNumCuInSCIPU( 0 );
}
else if( modeTypeParent == MODE_TYPE_ALL && partitioner.modeType != MODE_TYPE_INTER )
{
m_cIntraSearch.setSaveCuCostInSCIPU( false );
if( partitioner.modeType == MODE_TYPE_ALL )
{
m_cIntraSearch.setNumCuInSCIPU( 0 );
}
}
xCheckModeSplitInternal( tempCS, bestCS, partitioner, encTestMode, modeTypeParent, skipInterPass );
//recover cons modes
partitioner.modeType = modeTypeParent;
partitioner.treeType = treeTypeParent;
partitioner.chType = chTypeParent;
if( modeTypeParent == MODE_TYPE_ALL )
{
m_cIntraSearch.setSaveCuCostInSCIPU( false );
if( numRoundRdo == 2 && partitioner.modeType == MODE_TYPE_INTRA )
{
m_cIntraSearch.initCuAreaCostInSCIPU();
}
}
if( skipInterPass )
{
break;
}
}
}
void EncCu::xCheckModeSplitInternal(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode, const ModeType modeTypeParent, bool& skipInterPass )
{
const int qp = encTestMode.qp;
const int oldPrevQp = tempCS->prevQP[partitioner.chType];
const auto oldMotionLut = tempCS->motionLut;
const ReshapeData& reshapeData = tempCS->picture->reshapeData;
const PartSplit split = getPartSplit( encTestMode );
const ModeType modeTypeChild = partitioner.modeType;
CHECK( split == CU_DONT_SPLIT, "No proper split provided!" );
tempCS->initStructData( qp );
m_CABACEstimator->getCtx() = m_CurrCtx->start;
const uint16_t split_ctx_size = Ctx::SplitFlag.size() + Ctx::SplitQtFlag.size() + Ctx::SplitHvFlag.size() + Ctx::Split12Flag.size() + Ctx::ModeConsFlag.size();
const TempCtx ctxSplitFlags( m_CtxCache, SubCtx(CtxSet(Ctx::SplitFlag(), split_ctx_size), m_CABACEstimator->getCtx()));
m_CABACEstimator->resetBits();
m_CABACEstimator->split_cu_mode( split, *tempCS, partitioner );
m_CABACEstimator->mode_constraint( split, *tempCS, partitioner, modeTypeChild );
int numChild = 3;
if( split == CU_VERT_SPLIT || split == CU_HORZ_SPLIT ) numChild--;
else if( split == CU_QUAD_SPLIT ) numChild++;
int64_t approxBits = m_pcEncCfg->m_qtbttSpeedUp > 0 ? numChild << SCALE_BITS : 0;
const double factor = ( tempCS->currQP[partitioner.chType] > 30 ? 1.1 : 1.075 )
+ ( m_pcEncCfg->m_qtbttSpeedUp > 0 ? 0.01 : 0.0 )
+ ( ( m_pcEncCfg->m_qtbttSpeedUp > 0 && isChroma( partitioner.chType ) ) ? 0.2 : 0.0 );
const double cost = m_cRdCost.calcRdCost( uint64_t( m_CABACEstimator->getEstFracBits() + approxBits + ( ( bestCS->fracBits ) / factor ) ), Distortion( bestCS->dist / factor ) ) + bestCS->costDbOffset / factor;
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::SplitFlag(), split_ctx_size), ctxSplitFlags);
if (cost > bestCS->cost + bestCS->costDbOffset )
{
// DTRACE( g_trace_ctx, D_TMP, "%d exit split %f %f %f\n", g_trace_ctx->getChannelCounter(D_TMP), cost, bestCS->cost, bestCS->costDbOffset );
xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
return;
}
const bool chromaNotSplit = modeTypeParent == MODE_TYPE_ALL && modeTypeChild == MODE_TYPE_INTRA ? true : false;
if( partitioner.treeType == TREE_D )
{
if( chromaNotSplit )
{
CHECK( partitioner.chType != CH_L, "chType must be luma" );
partitioner.treeType = TREE_L;
}
else
{
partitioner.treeType = TREE_D;
}
}
CHECK(!(split == CU_QUAD_SPLIT || split == CU_HORZ_SPLIT || split == CU_VERT_SPLIT
|| split == CU_TRIH_SPLIT || split == CU_TRIV_SPLIT), "invalid split type");
partitioner.splitCurrArea( split, *tempCS );
bool qgEnableChildren = partitioner.currQgEnable(); // QG possible at children level
m_CurrCtx++;
AffineMVInfo tmpMVInfo;
bool isAffMVInfoSaved = m_cInterSearch.m_AffineProfList->savePrevAffMVInfo(0, tmpMVInfo );
BlkUniMvInfo tmpUniMvInfo;
bool isUniMvInfoSaved = false;
if (!tempCS->slice->isIntra())
{
m_cInterSearch.m_BlkUniMvInfoBuffer->savePrevUniMvInfo(tempCS->area.Y(), tmpUniMvInfo, isUniMvInfoSaved);
}
DeriveCtx deriveCtx = m_CABACEstimator->getDeriveCtx();
do
{
const auto &subCUArea = partitioner.currArea();
if( tempCS->picture->Y().contains( subCUArea.lumaPos() ) )
{
PelStorage* orgBuffer = &m_pOrgBuffer[partitioner.currDepth];
PelStorage* rspBuffer = &m_pRspBuffer[partitioner.currDepth];
CodingStructure *tempSubCS = m_pTempCS[partitioner.currDepth];
CodingStructure *bestSubCS = m_pBestCS[partitioner.currDepth];
tempCS->initSubStructure( *tempSubCS, partitioner.chType, subCUArea, false, orgBuffer, rspBuffer );
tempCS->initSubStructure( *bestSubCS, partitioner.chType, subCUArea, false, orgBuffer, rspBuffer );
// copy org buffer, need to be done after initSubStructure because of reshaping!
orgBuffer->copyFrom( tempCS->getOrgBuf( subCUArea ) );
if( tempCS->slice->lmcsEnabled && reshapeData.getCTUFlag() )
{
rspBuffer->Y().copyFrom( tempCS->getRspOrgBuf( subCUArea.Y() ) );
}
m_CABACEstimator->determineNeighborCus( *tempSubCS, partitioner.currArea(), partitioner.chType, partitioner.treeType );
tempSubCS->bestParent = bestSubCS->bestParent = bestCS;
xCompressCU(tempSubCS, bestSubCS, partitioner );
tempSubCS->bestParent = bestSubCS->bestParent = nullptr;
if( bestSubCS->cost == MAX_DOUBLE )
{
CHECK( split == CU_QUAD_SPLIT, "Split decision reusing cannot skip quad split" );
tempCS->cost = MAX_DOUBLE;
tempCS->costDbOffset = 0;
m_CurrCtx--;
partitioner.exitCurrSplit();
xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
if( partitioner.chType == CH_L )
{
tempCS->motionLut = oldMotionLut;
}
m_CABACEstimator->getDeriveCtx() = deriveCtx;
return;
}
tempCS->useSubStructure( *bestSubCS, partitioner.chType, TREE_D, CS::getArea( *tempCS, subCUArea, partitioner.chType, partitioner.treeType ), true );
if( partitioner.currQgEnable() )
{
tempCS->prevQP[partitioner.chType] = bestSubCS->prevQP[partitioner.chType];
}
if( partitioner.isConsInter() )
{
for( int i = 0; i < bestSubCS->cus.size(); i++ )
{
CHECK( bestSubCS->cus[i]->predMode != MODE_INTER, "all CUs must be inter mode in an Inter coding region (SCIPU)" );
}
}
else if( partitioner.isConsIntra() )
{
for( int i = 0; i < bestSubCS->cus.size(); i++ )
{
CHECK( bestSubCS->cus[i]->predMode == MODE_INTER, "all CUs must not be inter mode in an Intra coding region (SCIPU)" );
}
}
tempSubCS->releaseIntermediateData();
bestSubCS->releaseIntermediateData();
if( !tempCS->slice->isIntra() && partitioner.isConsIntra() )
{
tempCS->cost = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
if( tempCS->cost > bestCS->cost )
{
tempCS->cost = MAX_DOUBLE;
tempCS->costDbOffset = 0;
m_CurrCtx--;
partitioner.exitCurrSplit();
if( partitioner.chType == CH_L )
{
tempCS->motionLut = oldMotionLut;
}
m_CABACEstimator->getDeriveCtx() = deriveCtx;
return;
}
}
}
} while( partitioner.nextPart( *tempCS ) );
partitioner.exitCurrSplit();
m_CurrCtx--;
m_CABACEstimator->getDeriveCtx() = deriveCtx;
if( chromaNotSplit )
{
//Note: In local dual tree region, the chroma CU refers to the central luma CU's QP.
//If the luma CU QP shall be predQP (no residual in it and before it in the QG), it must be revised to predQP before encoding the chroma CU
//Otherwise, the chroma CU uses predQP+deltaQP in encoding but is decoded as using predQP, thus causing encoder-decoded mismatch on chroma qp.
if( tempCS->pps->useDQP )
{
//find parent CS that including all coded CUs in the QG before this node
CodingStructure* qgCS = tempCS;
bool deltaQpCodedBeforeThisNode = false;
if( partitioner.currArea().lumaPos() != partitioner.currQgPos )
{
int numParentNodeToQgCS = 0;
while( qgCS->area.lumaPos() != partitioner.currQgPos )
{
CHECK( qgCS->parent == nullptr, "parent of qgCS shall exsit" );
qgCS = qgCS->parent;
numParentNodeToQgCS++;
}
//check whether deltaQP has been coded (in luma CU or luma&chroma CU) before this node
CodingStructure* parentCS = tempCS->parent;
for( int i = 0; i < numParentNodeToQgCS; i++ )
{
//checking each parent
CHECK( parentCS == nullptr, "parentCS shall exsit" );
for( const auto &cu : parentCS->cus )
{
if( cu->rootCbf && !isChroma( cu->chType ) )
{
deltaQpCodedBeforeThisNode = true;
break;
}
}
parentCS = parentCS->parent;
}
}
//revise luma CU qp before the first luma CU with residual in the SCIPU to predQP
if( !deltaQpCodedBeforeThisNode )
{
//get pred QP of the QG
const CodingUnit* cuFirst = qgCS->getCU( CH_L, TREE_D );
CHECK( cuFirst->lumaPos() != partitioner.currQgPos, "First cu of the Qg is wrong" );
int predQp = CU::predictQP( *cuFirst, qgCS->prevQP[CH_L] );
//revise to predQP
int firstCuHasResidual = (int)tempCS->cus.size();
for( int i = 0; i < tempCS->cus.size(); i++ )
{
if( tempCS->cus[i]->rootCbf )
{
firstCuHasResidual = i;
break;
}
}
for( int i = 0; i < firstCuHasResidual; i++ )
{
tempCS->cus[i]->qp = predQp;
}
}
}
partitioner.chType = CH_C;
partitioner.treeType = TREE_C;
m_CurrCtx++;
CodingStructure *tempCSChroma = m_pTempCS2;
CodingStructure *bestCSChroma = m_pBestCS2;
tempCS->initSubStructure( *tempCSChroma, partitioner.chType, partitioner.currArea(), false );
tempCS->initSubStructure( *bestCSChroma, partitioner.chType, partitioner.currArea(), false );
m_CABACEstimator->determineNeighborCus( *bestCSChroma, partitioner.currArea(), partitioner.chType, partitioner.treeType );
tempCSChroma->refCS = tempCS;
bestCSChroma->refCS = tempCS;
xCompressCU( tempCSChroma, bestCSChroma, partitioner );
//attach chromaCS to luma CS and update cost
tempCS->useSubStructure( *bestCSChroma, partitioner.chType, TREE_D, CS::getArea( *bestCSChroma, partitioner.currArea(), partitioner.chType, partitioner.treeType ), true );
//release tmp resource
tempCSChroma->releaseIntermediateData();
bestCSChroma->releaseIntermediateData();
m_CurrCtx--;
//recover luma tree status
partitioner.chType = CH_L;
partitioner.treeType = TREE_D;
partitioner.modeType = MODE_TYPE_ALL;
}
// Finally, generate split-signaling bits for RD-cost check
const PartSplit implicitSplit = partitioner.getImplicitSplit( *tempCS );
{
bool enforceQT = implicitSplit == CU_QUAD_SPLIT;
// LARGE CTU bug
if( m_pcEncCfg->m_useFastLCTU )
{
unsigned minDepth = m_modeCtrl.comprCUCtx->minDepth;
if( minDepth > partitioner.currQtDepth )
{
// enforce QT
enforceQT = true;
}
}
if( !enforceQT )
{
m_CABACEstimator->resetBits();
m_CABACEstimator->split_cu_mode( split, *tempCS, partitioner );
partitioner.modeType = modeTypeParent;
m_CABACEstimator->mode_constraint( split, *tempCS, partitioner, modeTypeChild );
tempCS->fracBits += m_CABACEstimator->getEstFracBits(); // split bits
}
}
tempCS->cost = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
// Check Delta QP bits for splitted structure
if( !qgEnableChildren ) // check at deepest QG level only
xCheckDQP( *tempCS, partitioner, true );
// If the configuration being tested exceeds the maximum number of bytes for a slice / slice-segment, then
// a proper RD evaluation cannot be performed. Therefore, termination of the
// slice/slice-segment must be made prior to this CTU.
// This can be achieved by forcing the decision to be that of the rpcTempCU.
// The exception is each slice / slice-segment must have at least one CTU.
if (bestCS->cost == MAX_DOUBLE)
{
bestCS->costDbOffset = 0;
}
if( tempCS->cus.size() > 0 && modeTypeParent == MODE_TYPE_ALL && modeTypeChild == MODE_TYPE_INTER )
{
int areaSizeNoResiCu = 0;
for( int k = 0; k < tempCS->cus.size(); k++ )
{
areaSizeNoResiCu += (tempCS->cus[k]->rootCbf == false) ? tempCS->cus[k]->lumaSize().area() : 0;
}
if( areaSizeNoResiCu >= (tempCS->area.lumaSize().area() >> 1) )
{
skipInterPass = true;
}
}
// RD check for sub partitioned coding structure.
xCheckBestMode( tempCS, bestCS, partitioner, encTestMode, m_pcEncCfg->m_EDO );
if( isAffMVInfoSaved)
{
m_cInterSearch.m_AffineProfList->addAffMVInfo(tmpMVInfo);
}
if (!tempCS->slice->isIntra() && isUniMvInfoSaved)
{
m_cInterSearch.m_BlkUniMvInfoBuffer->addUniMvInfo(tmpUniMvInfo);
}
tempCS->motionLut = oldMotionLut;
tempCS->releaseIntermediateData();
tempCS->prevQP[partitioner.chType] = oldPrevQp;
}
void EncCu::xCheckRDCostIntra( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode )
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_INTRA, tempCS, partitioner.chType );
tempCS->initStructData( encTestMode.qp );
CodingUnit &cu = tempCS->addCU( CS::getArea( *tempCS, tempCS->area, partitioner.chType, partitioner.treeType ), partitioner.chType );
partitioner.setCUData( cu );
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.skip = false;
cu.mmvdSkip = false;
cu.predMode = MODE_INTRA;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.ispMode = NOT_INTRA_SUBPARTITIONS;
cu.initPuData();
m_cIntraSearch.m_ispTestedModes[0].init(0, 0, 1);
if (m_pcEncCfg->m_FastIntraTools)
{
m_modeCtrl.comprCUCtx->intraWasTested = false;
m_cIntraSearch.m_ispTestedModes[0].relatedCuIsValid = m_modeCtrl.comprCUCtx->relatedCuIsValid;
if (!bestCS->cus.empty())
{
if ((bestCS->cus[0]->mergeFlag || bestCS->cus[0]->imv || bestCS->cus[0]->affine) && (!bestCS->cus[0]->ciip))
{
m_cIntraSearch.m_ispTestedModes[0].bestBefore[0] = -1;
}
}
if (!bestCS->slice->isIntra())
{
const Position posBL = cu.Y().bottomLeft();
const Position posTR = cu.Y().topRight();
for (int i = 0; i < 2; i++)
{
const CodingUnit* neigh = i ? cu.cs->getCURestricted(posTR.offset(0, -1), cu, CH_L) :cu.cs->getCURestricted(posBL.offset(-1, 0), cu, CH_L);
m_cIntraSearch.m_ispTestedModes[0].bestBefore[i+1] = -1;
if (neigh != nullptr)
{
int bestMode = neigh->firstTU->mtsIdx[0] ? 4 : 0;
bestMode |= neigh->lfnstIdx ? 2 : 0;
bestMode |= neigh->ispMode ? 1 : 0;
m_cIntraSearch.m_ispTestedModes[0].bestBefore[i+1] = bestMode;
}
}
}
}
tempCS->interHad = m_modeCtrl.comprCUCtx->interHad;
double maxCostAllowedForChroma = MAX_DOUBLE;
if( isLuma( partitioner.chType ) )
{
if (!tempCS->slice->isIntra() && bestCS)
{
m_cIntraSearch.estIntraPredLumaQT(cu, partitioner, bestCS->cost);
}
else
{
m_cIntraSearch.estIntraPredLumaQT(cu, partitioner);
}
if (m_pcEncCfg->m_FastIntraTools)
{
m_modeCtrl.comprCUCtx->bestIntraMode = m_cIntraSearch.m_ispTestedModes[0].bestIntraMode;
if (m_cIntraSearch.m_ispTestedModes[0].intraWasTested)
{
m_modeCtrl.comprCUCtx->intraWasTested = m_cIntraSearch.m_ispTestedModes[0].intraWasTested;
}
}
if( !partitioner.isSepTree( *tempCS ) )
{
tempCS->lumaCost = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
}
if (m_pcEncCfg->m_usePbIntraFast && tempCS->dist == MAX_DISTORTION && tempCS->interHad == 0)
{
// JEM assumes only perfect reconstructions can from now on beat the inter mode
m_modeCtrl.comprCUCtx->interHad = 0;
return;
}
}
if( tempCS->area.chromaFormat != CHROMA_400 && ( partitioner.chType == CH_C || !CU::isSepTree(cu) ) )
{
bool useIntraSubPartitions = cu.ispMode != NOT_INTRA_SUBPARTITIONS;
Partitioner subTuPartitioner = partitioner;
if ((m_pcEncCfg->m_ISP >= 3) && (!partitioner.isSepTree(*tempCS) && useIntraSubPartitions))
{
maxCostAllowedForChroma = bestCS->cost < MAX_DOUBLE ? bestCS->cost - tempCS->lumaCost : MAX_DOUBLE;
}
m_cIntraSearch.estIntraPredChromaQT(
cu, (!useIntraSubPartitions || (CU::isSepTree(cu) && !isLuma(CH_C))) ? partitioner : subTuPartitioner,
maxCostAllowedForChroma);
if ((m_pcEncCfg->m_ISP >= 3) && useIntraSubPartitions && !cu.ispMode)
{
return;
}
}
cu.rootCbf = false;
for (uint32_t t = 0; t < getNumberValidTBlocks(*cu.cs->pcv); t++)
{
cu.rootCbf |= cu.firstTU->cbf[t] != 0;
}
// Get total bits for current mode: encode CU
m_CABACEstimator->resetBits();
if ((!cu.cs->slice->isIntra() || cu.cs->slice->sps->IBC) && cu.Y().valid())
{
m_CABACEstimator->cu_skip_flag(cu);
}
m_CABACEstimator->pred_mode(cu);
m_CABACEstimator->cu_pred_data(cu);
// Encode Coefficients
CUCtx cuCtx;
cuCtx.isDQPCoded = true;
cuCtx.isChromaQpAdjCoded = true;
m_CABACEstimator->cu_residual(cu, partitioner, cuCtx);
tempCS->fracBits = m_CABACEstimator->getEstFracBits();
tempCS->cost = m_cRdCost.calcRdCost(tempCS->fracBits, tempCS->dist);
xEncodeDontSplit(*tempCS, partitioner);
xCheckDQP(*tempCS, partitioner);
if (m_pcEncCfg->m_EDO)
{
xCalDebCost(*tempCS, partitioner);
}
DTRACE_MODE_COST(*tempCS, m_cRdCost.getLambda(true));
xCheckBestMode(tempCS, bestCS, partitioner, encTestMode, m_pcEncCfg->m_EDO);
STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
}
void EncCu::xUpdateAfterCtuRC( const Slice* slice, const int numberOfWrittenBits, const int ctuRsAddr )
{
if ( m_pcEncCfg->m_RCTargetBitrate == 0 )
{
return;
}
double actualLambda = m_cRdCost.getLambda();
if ( m_rcMutex ) m_rcMutex->lock();
slice->pic->encRCPic->updateAfterCTU( ctuRsAddr, numberOfWrittenBits, actualLambda );
if ( m_rcMutex ) m_rcMutex->unlock();
return;
}
void EncCu::xCheckDQP( CodingStructure& cs, Partitioner& partitioner, bool bKeepCtx )
{
if( !cs.pps->useDQP )
{
return;
}
if (partitioner.isSepTree(cs) && isChroma(partitioner.chType))
{
return;
}
if( !partitioner.currQgEnable() ) // do not consider split or leaf/not leaf QG condition (checked by caller)
{
return;
}
CodingUnit* cuFirst = cs.getCU( partitioner.chType, partitioner.treeType );
CHECK( bKeepCtx && cs.cus.size() <= 1 && partitioner.getImplicitSplit( cs ) == CU_DONT_SPLIT, "bKeepCtx should only be set in split case" );
CHECK( !bKeepCtx && cs.cus.size() > 1, "bKeepCtx should never be set for non-split case" );
CHECK( !cuFirst, "No CU available" );
bool hasResidual = false;
for( const auto &cu : cs.cus )
{
//not include the chroma CU because chroma CU is decided based on corresponding luma QP and deltaQP is not signaled at chroma CU
if( cu->rootCbf && !isChroma( cu->chType ))
{
hasResidual = true;
break;
}
}
int predQP = CU::predictQP( *cuFirst, cs.prevQP[partitioner.chType] );
if( hasResidual )
{
TempCtx ctxTemp( m_CtxCache );
if( !bKeepCtx ) ctxTemp = SubCtx( Ctx::DeltaQP, m_CABACEstimator->getCtx() );
m_CABACEstimator->resetBits();
m_CABACEstimator->cu_qp_delta( *cuFirst, predQP, cuFirst->qp );
cs.fracBits += m_CABACEstimator->getEstFracBits(); // dQP bits
cs.cost = m_cRdCost.calcRdCost(cs.fracBits, cs.dist);
if( !bKeepCtx ) m_CABACEstimator->getCtx() = SubCtx( Ctx::DeltaQP, ctxTemp );
// NOTE: reset QPs for CUs without residuals up to first coded CU
for( const auto &cu : cs.cus )
{
//not include the chroma CU because chroma CU is decided based on corresponding luma QP and deltaQP is not signaled at chroma CU
if( cu->rootCbf && !isChroma( cu->chType ))
{
break;
}
cu->qp = predQP;
}
}
else
{
// No residuals: reset CU QP to predicted value
for( const auto &cu : cs.cus )
{
cu->qp = predQP;
}
}
}
void EncCu::xCheckRDCostMerge( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, EncTestMode& encTestMode )
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_INTER_MRG, tempCS, partitioner.chType );
const Slice &slice = *tempCS->slice;
const SPS& sps = *tempCS->sps;
CHECK( slice.sliceType == VVENC_I_SLICE, "Merge modes not available for I-slices" );
tempCS->initStructData( encTestMode.qp );
MergeCtx mergeCtx;
bool affineMrgAvail =!((m_pcEncCfg->m_Affine > 1) && (bestCS->slice->TLayer > 3) && (!m_pcEncCfg->m_SbTMVP))
&& (m_pcEncCfg->m_Affine || sps.SbtMvp) && m_pcEncCfg->m_maxNumAffineMergeCand
&& !(bestCS->area.lumaSize().width < 8 || bestCS->area.lumaSize().height < 8);
AffineMergeCtx affineMergeCtx;
MergeCtx mrgCtx;
if (sps.SbtMvp)
{
Size bufSize = g_miScaling.scale(tempCS->area.lumaSize());
mergeCtx.subPuMvpMiBuf = MotionBuf(m_subPuMiBuf, bufSize);
mrgCtx.subPuMvpMiBuf = MotionBuf(m_subPuMiBuf, bufSize);
affineMergeCtx.mrgCtx = &mrgCtx;
}
m_mergeBestSATDCost = MAX_DOUBLE;
bool mrgTempBufSet = false;
PelUnitBuf* globSortedPelBuf[MRG_MAX_NUM_CANDS];
bool mmvdCandInserted = false;
PelUnitBuf acMergeTmpBuffer[MRG_MAX_NUM_CANDS];
{
// first get merge candidates
CodingUnit cu( tempCS->area );
cu.cs = tempCS;
cu.predMode = MODE_INTER;
cu.slice = tempCS->slice;
cu.tileIdx = 0;
CU::getInterMergeCandidates(cu, mergeCtx, 0 );
CU::getInterMMVDMergeCandidates(cu, mergeCtx);
if (affineMrgAvail)
{
cu.regularMergeFlag = false;
cu.affine = true;
CU::getAffineMergeCand(cu, affineMergeCtx);
cu.affine = false;
if (affineMergeCtx.numValidMergeCand <= 0)
{
affineMrgAvail = false;
}
}
cu.regularMergeFlag = true;
}
bool candHasNoResidual[MRG_MAX_NUM_CANDS + MMVD_ADD_NUM] = { false };
bool bestIsSkip = false;
bool bestIsMMVDSkip = true;
unsigned uiNumMrgSATDCand = mergeCtx.numValidMergeCand + MMVD_ADD_NUM;
static_vector<ModeInfo, MRG_MAX_NUM_CANDS + MMVD_ADD_NUM> RdModeList;
const int candNum = mergeCtx.numValidMergeCand + (sps.MMVD ? std::min<int>(MMVD_BASE_MV_NUM, mergeCtx.numValidMergeCand) * MMVD_MAX_REFINE_NUM : 0);
for (int i = 0; i < candNum; i++)
{
if (i < mergeCtx.numValidMergeCand)
{
RdModeList.push_back(ModeInfo(i, true, false, false, false, false));
}
else
{
RdModeList.push_back(ModeInfo(std::min(MMVD_ADD_NUM, i - mergeCtx.numValidMergeCand), false, true, false, false, false));
}
}
bool fastCIIP = m_pcEncCfg->m_CIIP>1;
bool testCIIP = sps.CIIP && (bestCS->area.lwidth() * bestCS->area.lheight() >= 64 && bestCS->area.lwidth() < MAX_CU_SIZE && bestCS->area.lheight() < MAX_CU_SIZE);
testCIIP &= (!fastCIIP) || !m_modeCtrl.getBlkInfo( tempCS->area ).isSkip; //5
int numCiipIntra = 0;
const ReshapeData& reshapeData = tempCS->picture->reshapeData;
PelUnitBuf ciipBuf = m_aTmpStorageLCU[1].getCompactBuf( tempCS->area );
m_SortedPelUnitBufs.reset();
const uint16_t merge_ctx_size = Ctx::MergeFlag.size() + Ctx::RegularMergeFlag.size() + Ctx::MergeIdx.size() + Ctx::MmvdFlag.size() + Ctx::MmvdMergeIdx.size() + Ctx::MmvdStepMvpIdx.size() + Ctx::SubblockMergeFlag.size() + Ctx::AffMergeIdx.size() + Ctx::CiipFlag.size();
const TempCtx ctxStartIntraCtx( m_CtxCache, SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), m_CABACEstimator->getCtx()) );
int numCiiPExtraTests = fastCIIP ? 0 : 1;
if( m_pcEncCfg->m_useFastMrg || testCIIP )
{
uiNumMrgSATDCand = NUM_MRG_SATD_CAND + (testCIIP ? numCiiPExtraTests : 0);
if (slice.sps->IBC)
{
ComprCUCtx cuECtx = *m_modeCtrl.comprCUCtx;
bestIsSkip = m_modeCtrl.getBlkInfo(tempCS->area).isSkip && cuECtx.bestCU;
}
else
{
bestIsSkip = !testCIIP && m_modeCtrl.getBlkInfo( tempCS->area ).isSkip;
}
bestIsMMVDSkip = m_modeCtrl.getBlkInfo(tempCS->area).isMMVDSkip;
if (affineMrgAvail)
{
bestIsSkip = false;
}
static_vector<double, MRG_MAX_NUM_CANDS + MMVD_ADD_NUM> candCostList;
Distortion uiSadBestForQPA = MAX_DISTORTION;
// 1. Pass: get SATD-cost for selected candidates and reduce their count
if( !bestIsSkip )
{
const UnitArea localUnitArea(tempCS->area.chromaFormat, Area(0, 0, tempCS->area.Y().width, tempCS->area.Y().height));
m_SortedPelUnitBufs.prepare(localUnitArea, uiNumMrgSATDCand+4);
mrgTempBufSet = true;
RdModeList.clear();
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), ctxStartIntraCtx);
CodingUnit &cu = tempCS->addCU( tempCS->area, partitioner.chType );
const double sqrtLambdaForFirstPassIntra = m_cRdCost.getMotionLambda() * FRAC_BITS_SCALE;
partitioner.setCUData( cu );
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.skip = false;
cu.mmvdSkip = false;
cu.geo = false;
cu.predMode = MODE_INTER;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.affine = false;
//cu.emtFlag is set below
cu.initPuData();
const DFunc dfunc = encTestMode.lossless || tempCS->slice->disableSATDForRd ? DF_SAD : DF_HAD;
DistParam distParam = m_cRdCost.setDistParam(tempCS->getOrgBuf(COMP_Y), m_SortedPelUnitBufs.getTestBuf(COMP_Y), sps.bitDepths[ CH_L ], dfunc);
bool sameMV[ MRG_MAX_NUM_CANDS ] = { false, };
if (m_pcEncCfg->m_useFastMrg == 2)
{
for (int m = 0; m < mergeCtx.numValidMergeCand - 1; m++)
{
if( sameMV[m] == false)
{
for (int n = m + 1; n < mergeCtx.numValidMergeCand; n++)
{
if( (mergeCtx.mvFieldNeighbours[(m << 1) + 0].mv == mergeCtx.mvFieldNeighbours[(n << 1) + 0].mv)
&& (mergeCtx.mvFieldNeighbours[(m << 1) + 1].mv == mergeCtx.mvFieldNeighbours[(n << 1) + 1].mv))
{
sameMV[n] = true;
}
}
}
}
}
Mv* cu_mvdL0SubPuBackup = cu.mvdL0SubPu; //we have to restore this later
for( uint32_t uiMergeCand = 0; uiMergeCand < mergeCtx.numValidMergeCand; uiMergeCand++ )
{
if (sameMV[uiMergeCand])
{
continue;
}
mergeCtx.setMergeInfo( cu, uiMergeCand );
CU::spanMotionInfo( cu, mergeCtx );
cu.mvRefine = true;
cu.mvdL0SubPu = m_refinedMvdL0[uiMergeCand]; // set an alternative storage for sub mvs
acMergeTmpBuffer[uiMergeCand] = m_acMergeTmpBuffer[uiMergeCand].getBuf(localUnitArea);
bool BioOrDmvr = m_cInterSearch.motionCompensation(cu, m_SortedPelUnitBufs.getTestBuf(), REF_PIC_LIST_X, &(acMergeTmpBuffer[uiMergeCand]) );
cu.mvRefine = false;
if( mergeCtx.interDirNeighbours[uiMergeCand] == 3 && mergeCtx.mrgTypeNeighbours[uiMergeCand] == MRG_TYPE_DEFAULT_N )
{
mergeCtx.mvFieldNeighbours[2*uiMergeCand].mv = cu.mv[0][0];
mergeCtx.mvFieldNeighbours[2*uiMergeCand+1].mv = cu.mv[1][0];
}
distParam.cur.buf = m_SortedPelUnitBufs.getTestBuf().Y().buf;
Distortion uiSad = distParam.distFunc(distParam);
uint64_t fracBits = xCalcPuMeBits(cu);
//restore ctx
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), ctxStartIntraCtx);
if (uiSadBestForQPA > uiSad) { uiSadBestForQPA = uiSad; }
double cost = (double)uiSad + (double)fracBits * sqrtLambdaForFirstPassIntra;
int insertPos = -1;
updateCandList(ModeInfo(uiMergeCand, true, false, false, BioOrDmvr, false), cost, RdModeList, candCostList, uiNumMrgSATDCand, &insertPos);
m_SortedPelUnitBufs.insert( insertPos, (int)RdModeList.size() );
if (m_pcEncCfg->m_useFastMrg != 2)
{
CHECK(std::min(uiMergeCand + 1, uiNumMrgSATDCand) != RdModeList.size(), "");
}
}
cu.mvdL0SubPu = cu_mvdL0SubPuBackup; // restore original stoarge
if (testCIIP)
{
unsigned numCiipInitialCand = std::min(NUM_MRG_SATD_CAND-1+numCiiPExtraTests, (const int)RdModeList.size());
//save trhe original order
uint32_t sortedMergeCand[4];
bool BioOrDmvr[4];
int numCiipTests = 0;
for (uint32_t mergeCounter = 0; mergeCounter < numCiipInitialCand; mergeCounter++)
{
if (!sameMV[mergeCounter] && ( m_pcEncCfg->m_CIIP != 3 || !RdModeList[mergeCounter].isBioOrDmvr ) )
{
globSortedPelBuf[RdModeList[mergeCounter].mergeCand] = m_SortedPelUnitBufs.getBufFromSortedList( mergeCounter );
sortedMergeCand[numCiipTests] = RdModeList[mergeCounter].mergeCand;
BioOrDmvr[numCiipTests] = RdModeList[mergeCounter].isBioOrDmvr;
numCiipTests++;
}
}
if( numCiipTests )
{
cu.ciip = true;
// generate intrainter Y prediction
cu.intraDir[0] = PLANAR_IDX;
m_cIntraSearch.initIntraPatternChType(cu, cu.Y());
m_cIntraSearch.predIntraAng(COMP_Y, ciipBuf.Y(), cu);
numCiipIntra = m_cIntraSearch.getNumIntraCiip( cu );
// save the to-be-tested merge candidates
for (uint32_t mergeCounter = 0; mergeCounter < numCiipTests; mergeCounter++)
{
uint32_t mergeCand = sortedMergeCand[mergeCounter];
// estimate merge bits
mergeCtx.setMergeInfo(cu, mergeCand);
PelUnitBuf testBuf = m_SortedPelUnitBufs.getTestBuf();
if( BioOrDmvr[mergeCounter] ) // recalc
{
cu.mvRefine = false;
cu.mcControl = 0;
m_cInterSearch.motionCompensation(cu, testBuf);
}
else if( cu.BcwIdx != BCW_DEFAULT )
{
testBuf.copyFrom( acMergeTmpBuffer[mergeCand] );
}
else
{
testBuf.copyFrom( *globSortedPelBuf[mergeCand] );
}
if( slice.lmcsEnabled && reshapeData.getCTUFlag() )
{
testBuf.Y().rspSignal( reshapeData.getFwdLUT());
}
testBuf.Y().weightCiip( ciipBuf.Y(), numCiipIntra );
// calculate cost
if( slice.lmcsEnabled && reshapeData.getCTUFlag() )
{
PelBuf tmpLmcs = m_aTmpStorageLCU[0].getCompactBuf( cu.Y() );
tmpLmcs.rspSignal( testBuf.Y(), reshapeData.getInvLUT());
distParam.cur = tmpLmcs;
}
else
{
distParam.cur = testBuf.Y();
}
Distortion sadValue = distParam.distFunc(distParam);
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), ctxStartIntraCtx);
cu.regularMergeFlag = false;
uint64_t fracBits = xCalcPuMeBits(cu);
if (uiSadBestForQPA > sadValue) { uiSadBestForQPA = sadValue; }
double cost = (double)sadValue + (double)fracBits * sqrtLambdaForFirstPassIntra;
int insertPos = -1;
updateCandList(ModeInfo(mergeCand, false, false, true, false, false), cost, RdModeList, candCostList, uiNumMrgSATDCand, &insertPos);
if( insertPos > -1 )
{
m_SortedPelUnitBufs.getTestBuf().copyFrom( testBuf );
m_SortedPelUnitBufs.insert( insertPos, uiNumMrgSATDCand+4 ); // add 4 to prevent best RdCandidates being reused as testbuf
}
else if (fastCIIP) //3
{
break;
}
}
cu.ciip = false;
}
}
bool testMMVD = true;
if (m_pcEncCfg->m_useFastMrg == 2)
{
uiNumMrgSATDCand = (unsigned)RdModeList.size();
testMMVD = (RdModeList.size() > 1);
}
if (cu.cs->sps->MMVD && testMMVD)
{
cu.mmvdSkip = true;
cu.regularMergeFlag = true;
int tempNum = (mergeCtx.numValidMergeCand > 1) ? MMVD_ADD_NUM : MMVD_ADD_NUM >> 1;
int bestDir = 0;
double bestCostMerge = candCostList[uiNumMrgSATDCand - 1];
double bestCostOffset = MAX_DOUBLE;
bool doMMVD = true;
int shiftCandStart = 0;
if (m_pcEncCfg->m_MMVD == 4)
{
if (RdModeList[0].mergeCand > 1 && RdModeList[1].mergeCand > 1)
{
doMMVD = false;
}
else if (!(RdModeList[0].mergeCand < 2 && RdModeList[1].mergeCand < 2))
{
int shiftCand = RdModeList[0].mergeCand < 2 ? RdModeList[0].mergeCand : RdModeList[1].mergeCand;
if (shiftCand)
{
shiftCandStart = MMVD_MAX_REFINE_NUM;
}
else
{
tempNum = MMVD_MAX_REFINE_NUM;
}
}
}
for (uint32_t mmvdMergeCand = shiftCandStart; (mmvdMergeCand < tempNum) && doMMVD; mmvdMergeCand++)
{
if (m_pcEncCfg->m_MMVD > 1)
{
int checkMMVD = xCheckMMVDCand(mmvdMergeCand, bestDir, tempNum, bestCostOffset, bestCostMerge, candCostList[uiNumMrgSATDCand - 1]);
if (checkMMVD)
{
if (checkMMVD == 2)
{
break;
}
continue;
}
}
int baseIdx = mmvdMergeCand / MMVD_MAX_REFINE_NUM;
int refineStep = (mmvdMergeCand - (baseIdx * MMVD_MAX_REFINE_NUM)) / 4;
if (refineStep >= m_pcEncCfg->m_MmvdDisNum )
{
continue;
}
mergeCtx.setMmvdMergeCandiInfo(cu, mmvdMergeCand);
CU::spanMotionInfo(cu, mergeCtx);
cu.mvRefine = true;
cu.mcControl = (refineStep > 2) || (m_pcEncCfg->m_MMVD > 1) ? 3 : 0;
CHECK(!cu.mmvdMergeFlag, "MMVD merge should be set");
// Don't do chroma MC here
m_cInterSearch.motionCompensation(cu, m_SortedPelUnitBufs.getTestBuf(), REF_PIC_LIST_X);
cu.mcControl = 0;
cu.mvRefine = false;
distParam.cur.buf = m_SortedPelUnitBufs.getTestBuf().Y().buf;
Distortion uiSad = distParam.distFunc(distParam);
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), ctxStartIntraCtx);
uint64_t fracBits = xCalcPuMeBits(cu);
if (uiSadBestForQPA > uiSad) { uiSadBestForQPA = uiSad; }
double cost = (double)uiSad + (double)fracBits * sqrtLambdaForFirstPassIntra;
if (m_pcEncCfg->m_MMVD > 1 && bestCostOffset > cost)
{
bestCostOffset = cost;
int CandCur = mmvdMergeCand - MMVD_MAX_REFINE_NUM*baseIdx;
if (CandCur < 4)
{
bestDir = CandCur;
}
}
int insertPos = -1;
updateCandList(ModeInfo(mmvdMergeCand, false, true, false, false, false), cost, RdModeList, candCostList, uiNumMrgSATDCand, &insertPos);
mmvdCandInserted |= insertPos>-1;
m_SortedPelUnitBufs.insert(insertPos, (int)RdModeList.size());
}
}
if (affineMrgAvail)
{
mmvdCandInserted |=xCheckSATDCostAffineMerge(tempCS, cu, affineMergeCtx, mrgCtx, m_SortedPelUnitBufs, uiNumMrgSATDCand, RdModeList, candCostList, distParam, ctxStartIntraCtx, merge_ctx_size);
}
// Try to limit number of candidates using SATD-costs
uiNumMrgSATDCand = (m_pcEncCfg->m_useFastMrg == 2) ? (unsigned)candCostList.size() : uiNumMrgSATDCand;
for( uint32_t i = 1; i < uiNumMrgSATDCand; i++ )
{
if( candCostList[i] > MRG_FAST_RATIO * candCostList[0] )
{
uiNumMrgSATDCand = i;
break;
}
}
m_mergeBestSATDCost = candCostList[0];
if (testCIIP && isChromaEnabled(cu.cs->pcv->chrFormat) && cu.chromaSize().width != 2 )
{
for (uint32_t mergeCnt = 0; mergeCnt < uiNumMrgSATDCand; mergeCnt++)
{
if (RdModeList[mergeCnt].isCIIP)
{
cu.intraDir[0] = PLANAR_IDX;
cu.intraDir[1] = DM_CHROMA_IDX;
cu.ciip = true;
m_cIntraSearch.initIntraPatternChType(cu, cu.Cb());
m_cIntraSearch.predIntraAng(COMP_Cb, ciipBuf.Cb(), cu);
m_cIntraSearch.initIntraPatternChType(cu, cu.Cr());
m_cIntraSearch.predIntraAng(COMP_Cr, ciipBuf.Cr(), cu);
cu.ciip = false;
break;
}
}
}
tempCS->initStructData( encTestMode.qp );
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), ctxStartIntraCtx);
}
else
{
if (m_pcEncCfg->m_useFastMrg != 2)
{
if (bestIsMMVDSkip)
{
uiNumMrgSATDCand = mergeCtx.numValidMergeCand + ((mergeCtx.numValidMergeCand > 1) ? MMVD_ADD_NUM : MMVD_ADD_NUM >> 1);
}
else
{
uiNumMrgSATDCand = mergeCtx.numValidMergeCand;
}
}
}
if ((m_pcEncCfg->m_usePerceptQPATempFiltISlice == 2) && (uiSadBestForQPA < MAX_DISTORTION) && (slice.TLayer == 0) // non-Intra key-frame
&& (m_pcEncCfg->m_usePerceptQPA) && partitioner.currQgEnable() && (partitioner.currSubdiv == 0)) // CTU-level luma quantization group
{
const Picture* pic = slice.pic;
const uint32_t rsAddr = getCtuAddr (partitioner.currQgPos, *pic->cs->pcv);
const int pumpReducQP = BitAllocation::getCtuPumpingReducingQP (&slice, tempCS->getOrgBuf (COMP_Y), uiSadBestForQPA, *m_globalCtuQpVector, rsAddr, m_pcEncCfg->m_QP);
if (pumpReducQP != 0) // subtract QP offset, reduces Intra-period pumping or overcoding
{
encTestMode.qp = Clip3 (0, MAX_QP, encTestMode.qp - pumpReducQP);
tempCS->currQP[partitioner.chType] = tempCS->baseQP =
bestCS->currQP[partitioner.chType] = bestCS->baseQP = Clip3 (0, MAX_QP, tempCS->baseQP - pumpReducQP);
updateLambda (slice, pic->ctuQpaLambda[rsAddr], pic->ctuAdaptedQP[rsAddr], tempCS->baseQP, true);
}
}
}
uiNumMrgSATDCand = std::min(int(uiNumMrgSATDCand), int(RdModeList.size()));
uint32_t iteration = (encTestMode.lossless) ? 1 : 2;
double bestEndCost = MAX_DOUBLE;
bool isTestSkipMerge[MRG_MAX_NUM_CANDS] = {false}; // record if the merge candidate has tried skip mode
for (uint32_t uiNoResidualPass = 0; uiNoResidualPass < iteration; ++uiNoResidualPass)
{
for( uint32_t uiMrgHADIdx = 0; uiMrgHADIdx < uiNumMrgSATDCand; uiMrgHADIdx++ )
{
uint32_t uiMergeCand = RdModeList[uiMrgHADIdx].mergeCand;
if (uiNoResidualPass != 0 && RdModeList[uiMrgHADIdx].isCIIP) // intrainter does not support skip mode
{
if (isTestSkipMerge[uiMergeCand])
{
continue;
}
}
if (((uiNoResidualPass != 0) && candHasNoResidual[uiMrgHADIdx])
|| ( (uiNoResidualPass == 0) && bestIsSkip ) )
{
continue;
}
// first get merge candidates
CodingUnit &cu = tempCS->addCU( tempCS->area, partitioner.chType );
partitioner.setCUData( cu );
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.skip = false;
cu.mmvdSkip = false;
cu.geo = false;
cu.predMode = MODE_INTER;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.affine = false;
cu.initPuData();
if (uiNoResidualPass == 0 && RdModeList[uiMrgHADIdx].isCIIP)
{
cu.mmvdSkip = false;
mergeCtx.setMergeInfo(cu, uiMergeCand);
cu.ciip = true;
cu.regularMergeFlag = false;
cu.intraDir[0] = PLANAR_IDX;
cu.intraDir[1] = DM_CHROMA_IDX;
}
else if (RdModeList[uiMrgHADIdx].isMMVD)
{
cu.mmvdSkip = true;
cu.regularMergeFlag = true;
cu.ciip = false;
mergeCtx.setMmvdMergeCandiInfo(cu, uiMergeCand);
}
else if (RdModeList[uiMrgHADIdx].isAffine)
{
// continue;
CHECK(uiMergeCand >= affineMergeCtx.numValidMergeCand, "");
cu.mmvdSkip = false;
cu.regularMergeFlag = false;
cu.ciip = false;
cu.affine = true;
cu.imv = 0;
cu.mergeFlag = true;
cu.mergeIdx = uiMergeCand;
cu.interDir = affineMergeCtx.interDirNeighbours[uiMergeCand];
cu.affineType = affineMergeCtx.affineType[uiMergeCand];
cu.BcwIdx = affineMergeCtx.BcwIdx[uiMergeCand];
cu.mergeType = affineMergeCtx.mergeType[uiMergeCand];
if (cu.mergeType == MRG_TYPE_SUBPU_ATMVP)
{
cu.refIdx[0] = affineMergeCtx.mvFieldNeighbours[(uiMergeCand << 1) + 0][0].refIdx;
cu.refIdx[1] = affineMergeCtx.mvFieldNeighbours[(uiMergeCand << 1) + 1][0].refIdx;
CU::spanMotionInfo(cu, mrgCtx);
}
else
{
CU::setAllAffineMvField(cu, affineMergeCtx.mvFieldNeighbours[(uiMergeCand << 1) + 0], REF_PIC_LIST_0);
CU::setAllAffineMvField(cu, affineMergeCtx.mvFieldNeighbours[(uiMergeCand << 1) + 1], REF_PIC_LIST_1);
CU::spanMotionInfo(cu);
}
}
else
{
cu.mmvdSkip = false;
cu.regularMergeFlag = true;
cu.ciip = false;
mergeCtx.setMergeInfo(cu, uiMergeCand);
}
if (!RdModeList[uiMrgHADIdx].isAffine)
{
CU::spanMotionInfo( cu, mergeCtx );
}
if (!cu.affine && cu.refIdx[0] >= 0 && cu.refIdx[1] >= 0 && (cu.lwidth() + cu.lheight() == 12))
{
tempCS->initStructData(encTestMode.qp);
continue;
}
if( mrgTempBufSet )
{
if( CU::checkDMVRCondition( cu ) )
{
int num = 0;
for( int i = 0; i < ( cu.lheight() ); i += DMVR_SUBCU_SIZE )
{
for( int j = 0; j < ( cu.lwidth() ); j += DMVR_SUBCU_SIZE )
{
cu.mvdL0SubPu[num] = m_refinedMvdL0[uiMergeCand][num];
num++;
}
}
}
if (cu.ciip)
{
PelUnitBuf predBuf = tempCS->getPredBuf();
predBuf.copyFrom( *m_SortedPelUnitBufs.getBufFromSortedList( uiMrgHADIdx ));
if (isChromaEnabled(cu.chromaFormat) && cu.chromaSize().width > 2 )
{
predBuf.Cb().weightCiip( ciipBuf.Cb(), numCiipIntra);
predBuf.Cr().weightCiip( ciipBuf.Cr(), numCiipIntra);
}
}
else
{
if (RdModeList[uiMrgHADIdx].isMMVD)
{
cu.mcControl = 0;
m_cInterSearch.motionCompensation(cu, tempCS->getPredBuf() );
}
else if( RdModeList[uiMrgHADIdx].isCIIP )
{
if( mmvdCandInserted )
{
cu.mcControl = 0;
cu.mvRefine = true;
m_cInterSearch.motionCompensation(cu, tempCS->getPredBuf() );
cu.mvRefine = false;
}
else
{
tempCS->getPredBuf().copyFrom( *globSortedPelBuf[uiMergeCand]);
}
}
else if (RdModeList[uiMrgHADIdx].isAffine)
{
PelUnitBuf* sortedListBuf = m_SortedPelUnitBufs.getBufFromSortedList(uiMrgHADIdx);
if (sortedListBuf)
{
tempCS->getPredBuf().Y().copyFrom(sortedListBuf->Y()); // Copy Luma Only
cu.mcControl = 4;
m_cInterSearch.motionCompensation(cu, tempCS->getPredBuf(), REF_PIC_LIST_X);
cu.mcControl = 0;
}
else
{
m_cInterSearch.motionCompensation(cu, tempCS->getPredBuf());
}
}
else
{
PelUnitBuf* sortedListBuf = m_SortedPelUnitBufs.getBufFromSortedList(uiMrgHADIdx);
CHECK(!sortedListBuf, "Buffer failed");
tempCS->getPredBuf().copyFrom(*sortedListBuf);
}
}
}
else
{
cu.mvRefine = true;
m_cInterSearch.motionCompensation( cu, tempCS->getPredBuf() );
cu.mvRefine = false;
}
if (!cu.mmvdSkip && !cu.ciip && !cu.affine && uiNoResidualPass != 0)
{
CHECK(uiMergeCand >= mergeCtx.numValidMergeCand, "out of normal merge");
isTestSkipMerge[uiMergeCand] = true;
}
xEncodeInterResidual( tempCS, bestCS, partitioner, encTestMode, uiNoResidualPass, uiNoResidualPass == 0 ? &candHasNoResidual[uiMrgHADIdx] : NULL );
if (m_pcEncCfg->m_useFastMrg == 2)
{
if( cu.ciip && bestCS->cost == MAX_DOUBLE && uiMrgHADIdx+1 == uiNumMrgSATDCand )
{
uiNumMrgSATDCand = (unsigned)RdModeList.size();
}
if (uiMrgHADIdx > 0 && tempCS->cost >= bestEndCost && !cu.ciip)
{
uiMrgHADIdx = uiNumMrgSATDCand;
tempCS->initStructData(encTestMode.qp);
continue;
}
if (uiNoResidualPass == 0 && tempCS->cost < bestEndCost)
{
bestEndCost = tempCS->cost;
}
}
if( m_pcEncCfg->m_useFastDecisionForMerge && !bestIsSkip && !cu.ciip)
{
bestIsSkip = !bestCS->cus.empty() && bestCS->getCU( partitioner.chType, partitioner.treeType )->rootCbf == 0;
}
tempCS->initStructData( encTestMode.qp );
}// end loop uiMrgHADIdx
}
STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
}
void EncCu::xCheckRDCostMergeGeo(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode &encTestMode)
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_INTER_MRG, tempCS, partitioner.chType );
const Slice &slice = *tempCS->slice;
if ((m_pcEncCfg->m_Geo > 1) && (slice.TLayer <= 1))
{
return;
}
tempCS->initStructData(encTestMode.qp);
MergeCtx mergeCtx;
const SPS &sps = *tempCS->sps;
if (sps.SbtMvp)
{
Size bufSize = g_miScaling.scale(tempCS->area.lumaSize());
mergeCtx.subPuMvpMiBuf = MotionBuf(m_subPuMiBuf, bufSize);
}
CodingUnit &cu = tempCS->addCU(tempCS->area, pm.chType);
pm.setCUData(cu);
cu.predMode = MODE_INTER;
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.qp = encTestMode.qp;
cu.affine = false;
cu.mtsFlag = false;
cu.BcwIdx = BCW_DEFAULT;
cu.geo = true;
cu.imv = 0;
cu.mmvdSkip = false;
cu.skip = false;
cu.mipFlag = false;
cu.bdpcmM[CH_L] = 0;
cu.initPuData();
cu.mergeFlag = true;
cu.regularMergeFlag = false;
CU::getGeoMergeCandidates(cu, mergeCtx);
GeoComboCostList comboList;
int bitsCandTB = floorLog2(GEO_NUM_PARTITION_MODE);
PelUnitBuf geoCombinations[GEO_MAX_TRY_WEIGHTED_SAD];
DistParam distParam;
const UnitArea localUnitArea(tempCS->area.chromaFormat, Area(0, 0, tempCS->area.Y().width, tempCS->area.Y().height));
const double sqrtLambdaForFirstPass = m_cRdCost.getMotionLambda();
uint8_t maxNumMergeCandidates = cu.cs->sps->maxNumGeoCand;
m_SortedPelUnitBufs.prepare(localUnitArea, GEO_MAX_TRY_WEIGHTED_SATD );
DistParam distParamWholeBlk;
m_cRdCost.setDistParam(distParamWholeBlk, tempCS->getOrgBuf().Y(), m_SortedPelUnitBufs.getTestBuf().Y().buf, m_SortedPelUnitBufs.getTestBuf().Y().stride, sps.bitDepths[CH_L], COMP_Y);
Distortion bestWholeBlkSad = MAX_UINT64;
double bestWholeBlkCost = MAX_DOUBLE;
Distortion sadWholeBlk[ GEO_MAX_NUM_UNI_CANDS];
if (m_pcEncCfg->m_Geo == 3)
{
maxNumMergeCandidates = maxNumMergeCandidates > 1 ? ((maxNumMergeCandidates >> 1) + 1) : maxNumMergeCandidates;
}
int PermitCandidates = maxNumMergeCandidates-1;
{
// NOTE: Diagnostic is disabled due to a GCC bug (7.4.0).
// GCC is trying to optimize the loop and complains about the possible exceeding of array bounds
#if FIX_FOR_TEMPORARY_COMPILER_ISSUES_ENABLED && defined( __GNUC__ )
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
#endif
int pocMrg[ GEO_MAX_NUM_UNI_CANDS];
Mv MrgMv [ GEO_MAX_NUM_UNI_CANDS];
for (uint8_t mergeCand = 0; mergeCand < maxNumMergeCandidates; mergeCand++)
{
int MrgList = mergeCtx.mvFieldNeighbours[(mergeCand << 1) + 0].refIdx == -1 ? 1 : 0;
RefPicList eList = (MrgList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
int MrgrefIdx = mergeCtx.mvFieldNeighbours[(mergeCand << 1) + MrgList].refIdx;
pocMrg[mergeCand] = tempCS->slice->getRefPic(eList, MrgrefIdx)->getPOC();
MrgMv[mergeCand] = mergeCtx.mvFieldNeighbours[(mergeCand << 1) + MrgList].mv;
if (mergeCand)
{
for (int i = 0; i < mergeCand; i++)
{
if (pocMrg[mergeCand] == pocMrg[i] && MrgMv[mergeCand] == MrgMv[i])
{
PermitCandidates--;
break;
}
}
}
}
#if FIX_FOR_TEMPORARY_COMPILER_ISSUES_ENABLED && defined( __GNUC__ )
#pragma GCC diagnostic pop
#endif
}
if (PermitCandidates<=0)
{
return;
}
bool sameMV[MRG_MAX_NUM_CANDS] = { false, };
if (m_pcEncCfg->m_Geo > 1)
{
for (int m = 0; m < maxNumMergeCandidates; m++)
{
if (sameMV[m] == false)
{
for (int n = m + 1; n < maxNumMergeCandidates; n++)
{
if( (mergeCtx.mvFieldNeighbours[(m << 1) + 0].mv == mergeCtx.mvFieldNeighbours[(n << 1) + 0].mv)
&& (mergeCtx.mvFieldNeighbours[(m << 1) + 1].mv == mergeCtx.mvFieldNeighbours[(n << 1) + 1].mv))
{
sameMV[n] = true;
}
}
}
}
}
PelUnitBuf mcBuf[MAX_TMP_BUFS];
PelBuf sadBuf[MAX_TMP_BUFS];
for( int i = 0; i < maxNumMergeCandidates; i++)
{
mcBuf[i] = m_aTmpStorageLCU[i].getCompactBuf( cu );
sadBuf[i] = m_SortedPelUnitBufs.getBufFromSortedList(i)->Y();
}
{
const ClpRng& lclpRng = cu.slice->clpRngs[COMP_Y];
const unsigned rshift = std::max<int>(2, (IF_INTERNAL_PREC - lclpRng.bd));
const int offset = (1 << (rshift - 1)) + IF_INTERNAL_OFFS;
const int numSamples = cu.lwidth() * cu.lheight();
for (uint8_t mergeCand = 0; mergeCand < maxNumMergeCandidates; mergeCand++)
{
if (sameMV[mergeCand] )
{
continue;
}
mergeCtx.setMergeInfo(cu, mergeCand);
CU::spanMotionInfo(cu, mergeCtx);
m_cInterSearch.motionCompensation(cu, mcBuf[mergeCand], REF_PIC_LIST_X); //new
g_pelBufOP.roundGeo( mcBuf[mergeCand].Y().buf, sadBuf[mergeCand].buf, numSamples, rshift, offset, lclpRng);
distParamWholeBlk.cur.buf = sadBuf[mergeCand].buf;
sadWholeBlk[mergeCand] = distParamWholeBlk.distFunc(distParamWholeBlk);
if (sadWholeBlk[mergeCand] < bestWholeBlkSad)
{
bestWholeBlkSad = sadWholeBlk[mergeCand];
int bitsCand = mergeCand + 1;
bestWholeBlkCost = (double) bestWholeBlkSad + (double) bitsCand * sqrtLambdaForFirstPass;
}
}
}
int wIdx = floorLog2(cu.lwidth()) - GEO_MIN_CU_LOG2;
int hIdx = floorLog2(cu.lheight()) - GEO_MIN_CU_LOG2;
for (int splitDir = 0; splitDir < GEO_NUM_PARTITION_MODE;)
{
int maskStride = 0, maskStride2 = 0;
int stepX = 1;
Pel *SADmask;
int16_t angle = g_GeoParams[splitDir][0];
if (g_angle2mirror[angle] == 2)
{
maskStride = -GEO_WEIGHT_MASK_SIZE;
maskStride2 = -(int) cu.lwidth();
SADmask = &g_globalGeoEncSADmask[g_angle2mask[g_GeoParams[splitDir][0]]]
[(GEO_WEIGHT_MASK_SIZE - 1 - g_weightOffset[hIdx][wIdx][splitDir][1])
* GEO_WEIGHT_MASK_SIZE + g_weightOffset[hIdx][wIdx][splitDir][0]];
}
else if (g_angle2mirror[angle] == 1)
{
stepX = -1;
maskStride2 = cu.lwidth();
maskStride = GEO_WEIGHT_MASK_SIZE;
SADmask = &g_globalGeoEncSADmask[g_angle2mask[g_GeoParams[splitDir][0]]]
[g_weightOffset[hIdx][wIdx][splitDir][1] * GEO_WEIGHT_MASK_SIZE
+ (GEO_WEIGHT_MASK_SIZE - 1 - g_weightOffset[hIdx][wIdx][splitDir][0])];
}
else
{
maskStride = GEO_WEIGHT_MASK_SIZE;
maskStride2 = -(int) cu.lwidth();
SADmask = &g_globalGeoEncSADmask[g_angle2mask[g_GeoParams[splitDir][0]]]
[g_weightOffset[hIdx][wIdx][splitDir][1] * GEO_WEIGHT_MASK_SIZE
+ g_weightOffset[hIdx][wIdx][splitDir][0]];
}
Distortion sadSmall = 0, sadLarge = 0;
m_cRdCost.setDistParamGeo(distParam, tempCS->getOrgBuf().Y(), sadBuf[0].buf, sadBuf[0].stride, SADmask, maskStride, stepX, maskStride2, sps.bitDepths[CH_L], COMP_Y);
for (uint8_t mergeCand = 0; mergeCand < maxNumMergeCandidates; mergeCand++)
{
if( sameMV[mergeCand] )
{
continue;
}
int bitsCand = mergeCand + 1;
distParam.cur.buf = sadBuf[mergeCand].buf;
sadLarge = distParam.distFunc(distParam);
m_GeoCostList.insert(splitDir, 0, mergeCand, (double) sadLarge + (double) bitsCand * sqrtLambdaForFirstPass);
sadSmall = sadWholeBlk[mergeCand] - sadLarge;
m_GeoCostList.insert(splitDir, 1, mergeCand, (double) sadSmall + (double) bitsCand * sqrtLambdaForFirstPass);
}
if (m_pcEncCfg->m_Geo == 3)
{
if (splitDir == 1)
{
splitDir += 7;
}
else if( (splitDir == 35)||((splitDir + 1) % 4))
{
splitDir++;
}
else
{
splitDir += 5;
}
}
else
{
splitDir++;
}
}
for (int splitDir = 0; splitDir < GEO_NUM_PARTITION_MODE; )
{
for (int GeoMotionIdx = 0; GeoMotionIdx < maxNumMergeCandidates * (maxNumMergeCandidates - 1); GeoMotionIdx++)
{
unsigned int mergeCand0 = m_GeoModeTest[GeoMotionIdx][0];
unsigned int mergeCand1 = m_GeoModeTest[GeoMotionIdx][1];
if( sameMV[mergeCand0] || sameMV[mergeCand1] )
{
continue;
}
double tempCost = m_GeoCostList.singleDistList[0][splitDir][mergeCand0].cost
+ m_GeoCostList.singleDistList[1][splitDir][mergeCand1].cost;
if (tempCost > bestWholeBlkCost)
{
continue;
}
tempCost = tempCost + (double) bitsCandTB * sqrtLambdaForFirstPass;
comboList.list.push_back(GeoMergeCombo(splitDir, mergeCand0, mergeCand1, tempCost));
}
if (m_pcEncCfg->m_Geo == 3)
{
if (splitDir == 1)
{
splitDir += 7;
}
else if ((splitDir == 35) || ((splitDir + 1) % 4))
{
splitDir++;
}
else
{
splitDir += 5;
}
}
else
{
splitDir++;
}
}
if (comboList.list.empty())
{
return;
}
comboList.sortByCost();
bool geocandHasNoResidual[GEO_MAX_TRY_WEIGHTED_SAD] = { false };
bool bestIsSkip = false;
int geoNumCobo = (int) comboList.list.size();
static_vector<uint8_t, GEO_MAX_TRY_WEIGHTED_SAD> geoRdModeList;
static_vector<double, GEO_MAX_TRY_WEIGHTED_SAD> geocandCostList;
const DFunc dfunc = encTestMode.lossless || tempCS->slice->disableSATDForRd ? DF_SAD : DF_HAD;//new
DistParam distParamSAD2 = m_cRdCost.setDistParam( tempCS->getOrgBuf(COMP_Y), m_SortedPelUnitBufs.getTestBuf(COMP_Y), sps.bitDepths[CH_L], dfunc);
int geoNumMrgSATDCand = std::min(GEO_MAX_TRY_WEIGHTED_SATD, geoNumCobo);
const ClpRngs &clpRngs = cu.slice->clpRngs;
const int EndGeo = std::min(geoNumCobo, ((m_pcEncCfg->m_Geo > 1) ? 10 : GEO_MAX_TRY_WEIGHTED_SAD));
for (uint8_t candidateIdx = 0; candidateIdx < EndGeo; candidateIdx++)
{
int splitDir = comboList.list[candidateIdx].splitDir;
int mergeCand0 = comboList.list[candidateIdx].mergeIdx0;
int mergeCand1 = comboList.list[candidateIdx].mergeIdx1;
geoCombinations[candidateIdx] = m_SortedPelUnitBufs.getTestBuf();
m_cInterSearch.weightedGeoBlk(clpRngs, cu, splitDir, CH_L, geoCombinations[candidateIdx], mcBuf[mergeCand0], mcBuf[mergeCand1]);
distParamSAD2.cur = geoCombinations[candidateIdx].Y();
Distortion sad = distParamSAD2.distFunc(distParamSAD2);
int mvBits = 2;
mergeCand1 -= mergeCand1 < mergeCand0 ? 0 : 1;
mvBits += mergeCand0;
mvBits += mergeCand1;
double updateCost = (double) sad + (double) (bitsCandTB + mvBits) * sqrtLambdaForFirstPass;
comboList.list[candidateIdx].cost = updateCost;
if ((m_pcEncCfg->m_Geo > 1) && candidateIdx)
{
if (updateCost > MRG_FAST_RATIO * geocandCostList[0] || updateCost > m_mergeBestSATDCost || updateCost > m_AFFBestSATDCost)
{
geoNumMrgSATDCand = (int)geoRdModeList.size();
break;
}
}
int insertPos = -1;
updateCandList(candidateIdx, updateCost, geoRdModeList, geocandCostList, geoNumMrgSATDCand, &insertPos);
m_SortedPelUnitBufs.insert( insertPos, geoNumMrgSATDCand );
}
for (uint8_t i = 0; i < geoNumMrgSATDCand; i++)
{
if (geocandCostList[i] > MRG_FAST_RATIO * geocandCostList[0] || geocandCostList[i] > m_mergeBestSATDCost
|| geocandCostList[i] > m_AFFBestSATDCost)
{
geoNumMrgSATDCand = i;
break;
}
}
if (m_pcEncCfg->m_Geo > 1)
{
geoNumMrgSATDCand = geoNumMrgSATDCand > 2 ? 2 : geoNumMrgSATDCand;
}
for (uint8_t i = 0; i < geoNumMrgSATDCand && isChromaEnabled(cu.chromaFormat); i++)
{
const uint8_t candidateIdx = geoRdModeList[i];
const GeoMergeCombo& ge = comboList.list[candidateIdx];
m_cInterSearch.weightedGeoBlk(clpRngs, cu, ge.splitDir, CH_C, geoCombinations[candidateIdx], mcBuf[ge.mergeIdx0], mcBuf[ge.mergeIdx1]);
}
tempCS->initStructData(encTestMode.qp);
uint8_t iteration;
uint8_t iterationBegin = 0;
iteration = 2;
for (uint8_t noResidualPass = iterationBegin; noResidualPass < iteration; ++noResidualPass)
{
for (uint8_t mrgHADIdx = 0; mrgHADIdx < geoNumMrgSATDCand; mrgHADIdx++)
{
uint8_t candidateIdx = geoRdModeList[mrgHADIdx];
if (((noResidualPass != 0) && geocandHasNoResidual[candidateIdx]) || ((noResidualPass == 0) && bestIsSkip))
{
continue;
}
if ((m_pcEncCfg->m_Geo > 1) && mrgHADIdx && !bestCS->getCU(pm.chType, pm.treeType)->geo)
{
continue;
}
CodingUnit &cu = tempCS->addCU(tempCS->area, pm.chType);
pm.setCUData(cu);
cu.predMode = MODE_INTER;
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.qp = encTestMode.qp;
cu.affine = false;
cu.mtsFlag = false;
cu.BcwIdx = BCW_DEFAULT;
cu.geo = true;
cu.imv = 0;
cu.mmvdSkip = false;
cu.skip = false;
cu.mipFlag = false;
cu.bdpcmM[CH_L] = 0;
cu.initPuData();
cu.mergeFlag = true;
cu.regularMergeFlag = false;
cu.geoSplitDir = comboList.list[candidateIdx].splitDir;
cu.geoMergeIdx0 = comboList.list[candidateIdx].mergeIdx0;
cu.geoMergeIdx1 = comboList.list[candidateIdx].mergeIdx1;
cu.mmvdMergeFlag = false;
cu.mmvdMergeIdx = MAX_UINT;
CU::spanGeoMotionInfo(cu, mergeCtx, cu.geoSplitDir, cu.geoMergeIdx0, cu.geoMergeIdx1);
tempCS->getPredBuf().copyFrom(geoCombinations[candidateIdx]);
xEncodeInterResidual(tempCS, bestCS, pm, encTestMode, noResidualPass,
(noResidualPass == 0 ? &geocandHasNoResidual[candidateIdx] : NULL));
if (m_pcEncCfg->m_useFastDecisionForMerge && !bestIsSkip)
{
bestIsSkip = bestCS->getCU(pm.chType, pm.treeType)->rootCbf == 0;
}
tempCS->initStructData(encTestMode.qp);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// ibc merge/skip mode check
void EncCu::xCheckRDCostIBCModeMerge2Nx2N(CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& partitioner, const EncTestMode& encTestMode)
{
assert(partitioner.chType != CH_C); // chroma IBC is derived
if (tempCS->area.lwidth() == 128 || tempCS->area.lheight() == 128) // disable IBC mode larger than 64x64
{
return;
}
if ((m_pcEncCfg->m_IBCFastMethod > 1) && !bestCS->slice->isIntra() && (bestCS->cus.size() != 0))
{
if (bestCS->getCU(partitioner.chType, partitioner.treeType)->skip)
{
return;
}
}
const SPS& sps = *tempCS->sps;
tempCS->initStructData(encTestMode.qp);
MergeCtx mergeCtx;
if (sps.SbtMvp)
{
Size bufSize = g_miScaling.scale(tempCS->area.lumaSize());
mergeCtx.subPuMvpMiBuf = MotionBuf(m_subPuMiBuf, bufSize);
}
{
// first get merge candidates
CodingUnit cu(tempCS->area);
cu.cs = tempCS;
cu.predMode = MODE_IBC;
cu.slice = tempCS->slice;
cu.tileIdx = tempCS->pps->getTileIdx(tempCS->area.lumaPos());
cu.initPuData();
cu.cs = tempCS;
cu.mmvdSkip = false;
cu.mmvdMergeFlag = false;
cu.regularMergeFlag = false;
cu.geo = false;
CU::getIBCMergeCandidates(cu, mergeCtx);
}
int candHasNoResidual[MRG_MAX_NUM_CANDS];
for (unsigned int ui = 0; ui < mergeCtx.numValidMergeCand; ui++)
{
candHasNoResidual[ui] = 0;
}
bool bestIsSkip = false;
unsigned numMrgSATDCand = mergeCtx.numValidMergeCand;
static_vector<unsigned, MRG_MAX_NUM_CANDS> RdModeList(MRG_MAX_NUM_CANDS);
for (unsigned i = 0; i < MRG_MAX_NUM_CANDS; i++)
{
RdModeList[i] = i;
}
//{
static_vector<double, MRG_MAX_NUM_CANDS> candCostList(MRG_MAX_NUM_CANDS, MAX_DOUBLE);
// 1. Pass: get SATD-cost for selected candidates and reduce their count
{
const double sqrtLambdaForFirstPass = m_cRdCost.getMotionLambda();
CodingUnit& cu = tempCS->addCU(CS::getArea(*tempCS, tempCS->area, partitioner.chType,partitioner.treeType), partitioner.chType);
partitioner.setCUData(cu);
cu.slice = tempCS->slice;
cu.tileIdx = tempCS->pps->getTileIdx(tempCS->area.lumaPos());
cu.skip = false;
cu.predMode = MODE_IBC;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.mmvdSkip = false;
cu.geo = false;
DistParam distParam;
cu.initPuData();
cu.mmvdMergeFlag = false;
cu.regularMergeFlag = false;
Picture* refPic = cu.slice->pic;
const UnitArea localUnitArea(tempCS->area.chromaFormat, Area(cu.blocks[COMP_Y].x, cu.blocks[COMP_Y].y, tempCS->area.Y().width, tempCS->area.Y().height));
const CompArea& compArea = localUnitArea.block(COMP_Y);
const CPelBuf refBuf = refPic->getRecoBuf(compArea);
const Pel* piRefSrch = refBuf.buf;
const ReshapeData& reshapeData = cu.cs->picture->reshapeData;
if (cu.cs->slice->lmcsEnabled && reshapeData.getCTUFlag())
{
PelBuf tmpLmcs = m_aTmpStorageLCU[0].getCompactBuf(cu.Y());
tmpLmcs.rspSignal(tempCS->getOrgBuf().Y(), reshapeData.getFwdLUT());
distParam = m_cRdCost.setDistParam( tmpLmcs, refBuf, sps.bitDepths[CH_L], DF_HAD);
}
else
{
distParam = m_cRdCost.setDistParam(tempCS->getOrgBuf(COMP_Y), refBuf, sps.bitDepths[CH_L], DF_HAD);
}
int refStride = refBuf.stride;
int numValidBv = mergeCtx.numValidMergeCand;
for (unsigned int mergeCand = 0; mergeCand < mergeCtx.numValidMergeCand; mergeCand++)
{
mergeCtx.setMergeInfo(cu, mergeCand); // set bv info in merge mode
const int cuPelX = cu.Y().x;
const int cuPelY = cu.Y().y;
int roiWidth = cu.lwidth();
int roiHeight = cu.lheight();
const int picWidth = cu.cs->slice->pps->picWidthInLumaSamples;
const int picHeight = cu.cs->slice->pps->picHeightInLumaSamples;
const unsigned int lcuWidth = cu.cs->slice->sps->CTUSize;
int xPred = cu.bv.hor;
int yPred = cu.bv.ver;
if (!m_cInterSearch.searchBvIBC(cu, cuPelX, cuPelY, roiWidth, roiHeight, picWidth, picHeight, xPred, yPred, lcuWidth)) // not valid bv derived
{
numValidBv--;
continue;
}
CU::spanMotionInfo(cu, mergeCtx);
distParam.cur.buf = piRefSrch + refStride * yPred + xPred;
Distortion sad = distParam.distFunc(distParam);
unsigned int bitsCand = mergeCand + 1;
if (mergeCand == tempCS->sps->maxNumIBCMergeCand - 1)
{
bitsCand--;
}
double cost = (double)sad + (double)bitsCand * sqrtLambdaForFirstPass;
updateCandList(mergeCand, cost, RdModeList, candCostList
, numMrgSATDCand);
}
// Try to limit number of candidates using SATD-costs
if (numValidBv)
{
numMrgSATDCand = numValidBv;
for (unsigned int i = 1; i < numValidBv; i++)
{
if (candCostList[i] > MRG_FAST_RATIO * candCostList[0])
{
numMrgSATDCand = i;
break;
}
}
}
else
{
tempCS->dist = 0;
tempCS->fracBits = 0;
tempCS->cost = MAX_DOUBLE;
tempCS->costDbOffset = 0;
tempCS->initStructData(encTestMode.qp);
return;
}
tempCS->initStructData(encTestMode.qp);
}
//}
const unsigned int iteration = 2;
// m_bestModeUpdated = tempCS->cost = bestCS->cost = false;
// 2. Pass: check candidates using full RD test
for (unsigned int numResidualPass = 0; numResidualPass < iteration; numResidualPass++)
{
for (unsigned int mrgHADIdx = 0; mrgHADIdx < numMrgSATDCand; mrgHADIdx++)
{
unsigned int mergeCand = RdModeList[mrgHADIdx];
if (!(numResidualPass == 1 && candHasNoResidual[mergeCand] == 1))
{
if (!(bestIsSkip && (numResidualPass == 0)))
{
{
// first get merge candidates
CodingUnit& cu = tempCS->addCU(CS::getArea(*tempCS, tempCS->area, (const ChannelType)partitioner.chType,partitioner.treeType), (const ChannelType)partitioner.chType);
partitioner.setCUData(cu);
cu.slice = tempCS->slice;
cu.tileIdx = tempCS->pps->getTileIdx(tempCS->area.lumaPos());
cu.skip = false;
cu.predMode = MODE_IBC;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.sbtInfo = 0;
cu.initPuData();
cu.intraDir[0] = DC_IDX; // set intra pred for ibc block
cu.intraDir[1] = PLANAR_IDX; // set intra pred for ibc block
cu.mmvdSkip = false;
cu.mmvdMergeFlag = false;
cu.regularMergeFlag = false;
cu.geo = false;
mergeCtx.setMergeInfo(cu, mergeCand);
CU::spanMotionInfo(cu, mergeCtx);
assert(mergeCtx.mrgTypeNeighbours[mergeCand] == MRG_TYPE_IBC);
const bool chroma = !CU::isSepTree(cu);
// MC
cu.mcControl = chroma ? 0: 2;
m_cInterSearch.motionCompensationIBC(cu, tempCS->getPredBuf());
m_CABACEstimator->getCtx() = m_CurrCtx->start;
m_cInterSearch.encodeResAndCalcRdInterCU(*tempCS, partitioner, (numResidualPass != 0));
cu.mcControl = 0;
xEncodeDontSplit(*tempCS, partitioner);
xCheckDQP(*tempCS, partitioner);
xCheckBestMode(tempCS, bestCS, partitioner, encTestMode);
tempCS->initStructData(encTestMode.qp);
}
if (m_pcEncCfg->m_useFastDecisionForMerge && !bestIsSkip)
{
if (bestCS->getCU(partitioner.chType, partitioner.treeType) == NULL)
bestIsSkip = 0;
else
bestIsSkip = bestCS->getCU(partitioner.chType, partitioner.treeType)->rootCbf == 0;
}
}
}
}
}
if (m_pcEncCfg->m_EDO && bestCS->cost != MAX_DOUBLE)
{
xCalDebCost(*bestCS, partitioner);
}
}
void EncCu::xCheckRDCostIBCMode(CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& partitioner,
const EncTestMode& encTestMode)
{
if (tempCS->area.lwidth() == 128 || tempCS->area.lheight() == 128) // disable IBC mode larger than 64x64
{
return;
}
if ((m_pcEncCfg->m_IBCFastMethod > 1) && !bestCS->slice->isIntra() && (bestCS->cus.size() != 0))
{
if (bestCS->getCU(partitioner.chType, partitioner.treeType)->skip)
{
return;
}
}
tempCS->initStructData(encTestMode.qp);
CodingUnit& cu = tempCS->addCU(CS::getArea(*tempCS, tempCS->area, partitioner.chType, partitioner.treeType), partitioner.chType);
partitioner.setCUData(cu);
cu.slice = tempCS->slice;
cu.tileIdx = tempCS->pps->getTileIdx(tempCS->area.lumaPos());
cu.skip = false;
cu.predMode = MODE_IBC;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.initPuData();
cu.imv = 0;
cu.sbtInfo = 0;
cu.mmvdSkip = false;
cu.mmvdMergeFlag = false;
cu.regularMergeFlag = false;
cu.intraDir[0] = DC_IDX; // set intra pred for ibc block
cu.intraDir[1] = PLANAR_IDX; // set intra pred for ibc block
cu.interDir = 1; // use list 0 for IBC mode
cu.refIdx[REF_PIC_LIST_0] = MAX_NUM_REF; // last idx in the list
bool bValid = m_cInterSearch.predIBCSearch(cu, partitioner);
if (bValid)
{
CU::spanMotionInfo(cu);
const bool chroma = !CU::isSepTree(cu);
// MC
cu.mcControl = chroma ? 0 : 2;
m_cInterSearch.motionCompensationIBC(cu, tempCS->getPredBuf());
m_cInterSearch.encodeResAndCalcRdInterCU(*tempCS, partitioner, false);
cu.mcControl = 0;
xEncodeDontSplit(*tempCS, partitioner);
xCheckDQP(*tempCS, partitioner);
if (m_pcEncCfg->m_EDO )
{
xCalDebCost(*tempCS, partitioner);
}
xCheckBestMode(tempCS, bestCS, partitioner, encTestMode);
} // bValid
else
{
tempCS->dist = 0;
tempCS->fracBits = 0;
tempCS->cost = MAX_DOUBLE;
tempCS->costDbOffset = 0;
}
}
void EncCu::xCheckRDCostInter( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode )
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_INTER_MVD_SEARCH, tempCS, partitioner.chType );
tempCS->initStructData( encTestMode.qp );
m_cInterSearch.setAffineModeSelected( false );
m_cInterSearch.resetBufferedUniMotions();
int bcwLoopNum = (tempCS->slice->isInterB() ? BCW_NUM : 1);
bcwLoopNum = (tempCS->sps->BCW ? bcwLoopNum : 1);
if( tempCS->area.lwidth() * tempCS->area.lheight() < BCW_SIZE_CONSTRAINT )
{
bcwLoopNum = 1;
}
double curBestCost = bestCS->cost;
double equBcwCost = MAX_DOUBLE;
for( int bcwLoopIdx = 0; bcwLoopIdx < bcwLoopNum; bcwLoopIdx++ )
{
if( m_pcEncCfg->m_BCW == 2 )
{
bool isBestInter = m_modeCtrl.getBlkInfo( bestCS->area ).isInter;
uint8_t bestBcwIdx = m_modeCtrl.getBlkInfo( bestCS->area).BcwIdx;
if( isBestInter && g_BcwSearchOrder[bcwLoopIdx] != BCW_DEFAULT && g_BcwSearchOrder[bcwLoopIdx] != bestBcwIdx )
{
continue;
}
}
if( !tempCS->slice->checkLDC )
{
if( bcwLoopIdx != 0 && bcwLoopIdx != 3 && bcwLoopIdx != 4 )
{
continue;
}
}
CodingUnit &cu = tempCS->addCU( tempCS->area, partitioner.chType );
partitioner.setCUData( cu );
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.skip = false;
cu.mmvdSkip = false;
cu.predMode = MODE_INTER;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.initPuData();
cu.BcwIdx = g_BcwSearchOrder[bcwLoopIdx];
uint8_t bcwIdx = cu.BcwIdx;
bool testBcw = (bcwIdx != BCW_DEFAULT);
bool StopInterRes = (m_pcEncCfg->m_FastInferMerge >> 3) & 1;
StopInterRes &= bestCS->slice->TLayer > (log2(m_pcEncCfg->m_GOPSize) - (m_pcEncCfg->m_FastInferMerge & 7));
double bestCostInter = StopInterRes ? m_mergeBestSATDCost : MAX_DOUBLE;
bool stopTest = m_cInterSearch.predInterSearch(cu, partitioner, bestCostInter);
if (StopInterRes && (bestCostInter != m_mergeBestSATDCost))
{
int L = (cu.slice->TLayer <= 2) ? 0 : (cu.slice->TLayer - 2);
if ((bestCostInter > MRG_FAST_RATIOMYV[L] * m_mergeBestSATDCost))
{
stopTest = true;
}
}
if( !stopTest )
{
bcwIdx = CU::getValidBcwIdx(cu);
stopTest = testBcw && bcwIdx == BCW_DEFAULT;
}
if( stopTest )
{
tempCS->initStructData(encTestMode.qp);
continue;
}
CHECK(!(testBcw || (!testBcw && bcwIdx == BCW_DEFAULT)), " !( bTestBcw || (!bTestBcw && bcwIdx == BCW_DEFAULT ) )");
xEncodeInterResidual(tempCS, bestCS, partitioner, encTestMode, 0, 0, &equBcwCost);
if( bcwIdx == BCW_DEFAULT )
{
m_cInterSearch.setAffineModeSelected( bestCS->cus.front()->affine && !bestCS->cus.front()->mergeFlag );
}
tempCS->initStructData(encTestMode.qp);
double skipTH = MAX_DOUBLE;
skipTH = (m_pcEncCfg->m_BCW == 2 ? 1.05 : MAX_DOUBLE);
if( equBcwCost > curBestCost * skipTH )
{
break;
}
if( m_pcEncCfg->m_BCW == 2 )
{
if( ( cu.interDir != 3 && testBcw == 0 && m_pcEncCfg->m_IntraPeriod == -1 )
|| ( g_BcwSearchOrder[bcwLoopIdx] == BCW_DEFAULT && xIsBcwSkip( cu ) ) )
{
break;
}
}
}
STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
}
void EncCu::xCheckRDCostInterIMV(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode)
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_INTER_MVD_SEARCH_IMV, tempCS, partitioner.chType );
bool Test_AMVR = m_pcEncCfg->m_AMVRspeed ? true: false;
if (m_pcEncCfg->m_AMVRspeed > 2 && m_pcEncCfg->m_AMVRspeed < 5 && bestCS->getCU(partitioner.chType, partitioner.treeType)->skip)
{
Test_AMVR = false;
}
else if (m_pcEncCfg->m_AMVRspeed > 4 && bestCS->getCU(partitioner.chType, partitioner.treeType)->mergeFlag && !bestCS->getCU(partitioner.chType, partitioner.treeType)->ciip)
{
Test_AMVR = false;
}
bool Do_Limit = (m_pcEncCfg->m_AMVRspeed == 4 || m_pcEncCfg->m_AMVRspeed == 6) ? true : false;
bool Do_OnceRes = (m_pcEncCfg->m_AMVRspeed == 7) ? true : false;
if( Test_AMVR )
{
double Fpel_cost = m_pcEncCfg->m_AMVRspeed == 1 ? MAX_DOUBLE*0.5 : MAX_DOUBLE;
double costCurStart = m_pcEncCfg->m_AMVRspeed == 1 ? m_modeCtrl.comprCUCtx->bestCostNoImv : bestCS->cost;
double costCur = MAX_DOUBLE;
double bestCostIMV = MAX_DOUBLE;
if (Do_OnceRes)
{
costCurStart = xCalcDistortion(bestCS, partitioner.chType, bestCS->sps->bitDepths[CH_L], 0);
Fpel_cost = costCurStart;
tempCS->initSubStructure(*m_pTempCS2, partitioner.chType, partitioner.currArea(), false);
}
CodingStructure *tempCSbest = m_pTempCS2;
m_cInterSearch.setAffineModeSelected( false );
m_cInterSearch.resetBufferedUniMotions();
int bcwLoopNum = (tempCS->slice->isInterB() ? BCW_NUM : 1);
bcwLoopNum = (tempCS->sps->BCW ? bcwLoopNum : 1);
if( tempCS->area.lwidth() * tempCS->area.lheight() < BCW_SIZE_CONSTRAINT )
{
bcwLoopNum = 1;
}
for (int i = 1; i <= IMV_HPEL; i++)
{
double curBestCost = bestCS->cost;
double equBcwCost = MAX_DOUBLE;
for( int bcwLoopIdx = 0; bcwLoopIdx < bcwLoopNum; bcwLoopIdx++ )
{
if( m_pcEncCfg->m_BCW == 2 )
{
bool isBestInter = m_modeCtrl.getBlkInfo( bestCS->area ).isInter;
uint8_t bestBcwIdx = m_modeCtrl.getBlkInfo( bestCS->area).BcwIdx;
if( isBestInter && g_BcwSearchOrder[bcwLoopIdx] != BCW_DEFAULT && g_BcwSearchOrder[bcwLoopIdx] != bestBcwIdx )
{
continue;
}
if( tempCS->slice->checkLDC && g_BcwSearchOrder[bcwLoopIdx] != BCW_DEFAULT
&& (m_bestBcwIdx[0] >= 0 && g_BcwSearchOrder[bcwLoopIdx] != m_bestBcwIdx[0])
&& (m_bestBcwIdx[1] >= 0 && g_BcwSearchOrder[bcwLoopIdx] != m_bestBcwIdx[1]))
{
continue;
}
}
if( !tempCS->slice->checkLDC )
{
if( bcwLoopIdx != 0 && bcwLoopIdx != 3 && bcwLoopIdx != 4 )
{
continue;
}
}
bool testBcw;
uint8_t bcwIdx;
bool isEqualUni = false;
if (i > IMV_FPEL)
{
bool nextimv = false;
double stopCost = i == IMV_HPEL ? 1.25 : 1.06;
if (Fpel_cost > stopCost * costCurStart)
{
nextimv = true;
}
if ( m_pcEncCfg->m_AMVRspeed == 1 )
{
costCurStart = bestCS->cost;
}
if (nextimv)
{
continue;
}
}
bool Do_Search = Do_OnceRes ? false : true;
if (Do_Limit)
{
Do_Search = i == IMV_FPEL ? true : false;
if (i == IMV_HPEL)
{
if (bestCS->slice->TLayer > 3)
{
continue;
}
if (bestCS->getCU(partitioner.chType, partitioner.treeType)->imv != 0)
{
Do_Search = true; //do_est
}
}
}
tempCS->initStructData(encTestMode.qp);
if (!Do_Search)
{
tempCS->copyStructure(*bestCS, partitioner.chType, TREE_D);
}
tempCS->dist = 0;
tempCS->fracBits = 0;
tempCS->cost = MAX_DOUBLE;
CodingUnit &cu = (Do_Search) ? tempCS->addCU(tempCS->area, partitioner.chType) : *tempCS->getCU(partitioner.chType, partitioner.treeType);
if (Do_Search)
{
partitioner.setCUData(cu);
cu.slice = tempCS->slice;
cu.tileIdx = 0;
cu.skip = false;
cu.mmvdSkip = false;
cu.predMode = MODE_INTER;
cu.chromaQpAdj = m_cuChromaQpOffsetIdxPlus1;
cu.qp = encTestMode.qp;
cu.initPuData();
cu.imv = i;
cu.BcwIdx = g_BcwSearchOrder[bcwLoopIdx];
bcwIdx = cu.BcwIdx;
testBcw = (bcwIdx != BCW_DEFAULT);
cu.interDir = 10;
double bestCostInter = MAX_DOUBLE;
m_cInterSearch.predInterSearch(cu, partitioner, bestCostInter);
if ( cu.interDir <= 3 )
{
bcwIdx = CU::getValidBcwIdx(cu);
}
else
{
continue;
}
if( testBcw && bcwIdx == BCW_DEFAULT ) // Enabled Bcw but the search results is uni.
{
continue;
}
CHECK(!(testBcw || (!testBcw && bcwIdx == BCW_DEFAULT)), " !( bTestBcw || (!bTestBcw && bcwIdx == BCW_DEFAULT ) )");
if( m_pcEncCfg->m_BCW == 2 )
{
if( cu.interDir != 3 && testBcw == 0 )
{
isEqualUni = true;
}
}
if (!CU::hasSubCUNonZeroMVd(cu))
{
continue;
}
}
else
{
cu.smvdMode = 0;
cu.affine = false;
cu.imv = i ;
CU::resetMVDandMV2Int(cu);
if (!CU::hasSubCUNonZeroMVd(cu))
{
continue;
}
cu.BcwIdx = g_BcwSearchOrder[bcwLoopIdx];
cu.mvRefine = true;
m_cInterSearch.motionCompensation(cu, tempCS->getPredBuf() );
cu.mvRefine = false;
}
if( Do_OnceRes )
{
costCur = xCalcDistortion(tempCS, partitioner.chType, tempCS->sps->bitDepths[CH_L], cu.imv );
if (costCur < bestCostIMV)
{
bestCostIMV = costCur;
tempCSbest->getPredBuf().copyFrom(tempCS->getPredBuf());
tempCSbest->clearCUs();
tempCSbest->clearTUs();
tempCSbest->copyStructure(*tempCS, partitioner.chType, TREE_D);
}
if (i > IMV_FPEL)
{
costCurStart = costCurStart > costCur ? costCur : costCurStart;
}
}
else
{
xEncodeInterResidual(tempCS, bestCS, partitioner, encTestMode, 0, 0, &equBcwCost);
costCur = tempCS->cost;
if (i > IMV_FPEL)
{
costCurStart = bestCS->cost;
}
}
if (i == IMV_FPEL)
{
Fpel_cost = costCur;
}
double skipTH = MAX_DOUBLE;
skipTH = (m_pcEncCfg->m_BCW == 2 ? 1.05 : MAX_DOUBLE);
if( equBcwCost > curBestCost * skipTH )
{
break;
}
if( m_pcEncCfg->m_BCW == 2 )
{
if( isEqualUni == true && m_pcEncCfg->m_IntraPeriod == -1 )
{
break;
}
if( g_BcwSearchOrder[bcwLoopIdx] == BCW_DEFAULT && xIsBcwSkip( cu ) )
{
break;
}
}
}
}
if (Do_OnceRes && (bestCostIMV != MAX_DOUBLE))
{
CodingStructure* CSCandBest = tempCSbest;
tempCS->initStructData(bestCS->currQP[partitioner.chType]);
tempCS->copyStructure(*CSCandBest, partitioner.chType, TREE_D);
tempCS->getPredBuf().copyFrom(tempCSbest->getPredBuf());
tempCS->dist = 0;
tempCS->fracBits = 0;
tempCS->cost = MAX_DOUBLE;
xEncodeInterResidual(tempCS, bestCS, partitioner, encTestMode, 0, 0, NULL);
}
tempCS->initStructData(encTestMode.qp);
}
STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_MODES_TESTED][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_MODES_TESTED][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
}
void EncCu::xCalDebCost( CodingStructure &cs, Partitioner &partitioner )
{
PROFILER_SCOPE_AND_STAGE_EXT( 1, g_timeProfiler, P_DEBLOCK_FILTER, &cs, partitioner.chType );
if ( cs.slice->deblockingFilterDisable )
{
return;
}
const ChromaFormat format = cs.area.chromaFormat;
CodingUnit* cu = cs.getCU(partitioner.chType, partitioner.treeType);
const Position lumaPos = cu->Y().valid() ? cu->Y().pos() : recalcPosition( format, cu->chType, CH_L, cu->blocks[cu->chType].pos() );
bool topEdgeAvai = lumaPos.y > 0 && ((lumaPos.y % 4) == 0);
bool leftEdgeAvai = lumaPos.x > 0 && ((lumaPos.x % 4) == 0);
if( ! ( topEdgeAvai || leftEdgeAvai ))
{
return;
}
ComponentID compStr = ( CU::isSepTree(*cu) && !isLuma( partitioner.chType ) ) ? COMP_Cb : COMP_Y;
ComponentID compEnd = (( CU::isSepTree(*cu) && isLuma( partitioner.chType )) || cu->chromaFormat == VVENC_CHROMA_400 ) ? COMP_Y : COMP_Cr;
const UnitArea currCsArea = clipArea( CS::getArea( cs, cs.area, partitioner.chType, partitioner.treeType ), *cs.picture );
PelStorage& picDbBuf = m_dbBuffer; //th we could reduce the buffer size and do some relocate
//deblock neighbour pixels
const Size lumaSize = cu->Y().valid() ? cu->Y().size() : recalcSize( format, cu->chType, CH_L, cu->blocks[cu->chType].size() );
int verOffset = lumaPos.y > 7 ? 8 : 4;
int horOffset = lumaPos.x > 7 ? 8 : 4;
LoopFilter::calcFilterStrengths( *cu, true );
if( m_pcEncCfg->m_EDO == 2 && CS::isDualITree( cs ) && isLuma( partitioner.chType ) )
{
m_cLoopFilter.getMaxFilterLength( *cu, verOffset, horOffset );
if( 0== (verOffset + horOffset) )
{
return;
}
topEdgeAvai &= verOffset != 0;
leftEdgeAvai &= horOffset != 0;
}
const UnitArea areaTop = UnitArea( format, Area( lumaPos.x, lumaPos.y - verOffset, lumaSize.width, verOffset ) );
const UnitArea areaLeft = UnitArea( format, Area( lumaPos.x - horOffset, lumaPos.y, horOffset, lumaSize.height ) );
for ( int compIdx = compStr; compIdx <= compEnd; compIdx++ )
{
ComponentID compId = (ComponentID)compIdx;
//Copy current CU's reco to Deblock Pic Buffer
const ReshapeData& reshapeData = cs.picture->reshapeData;
const CompArea& compArea = currCsArea.block( compId );
CompArea locArea = compArea;
locArea.x -= cu->blocks[compIdx].x;
locArea.y -= cu->blocks[compIdx].y;
PelBuf dbReco = picDbBuf.getBuf( locArea );
if (cs.slice->lmcsEnabled && isLuma(compId) )
{
if ((!cs.sps->LFNST) && (!cs.sps->MTS) && (!cs.sps->ISP)&& reshapeData.getCTUFlag())
{
PelBuf rspReco = cs.getRspRecoBuf();
dbReco.copyFrom( rspReco );
}
else
{
PelBuf reco = cs.getRecoBuf( compId );
dbReco.rspSignal( reco, reshapeData.getInvLUT() );
}
}
else
{
PelBuf reco = cs.getRecoBuf( compId );
dbReco.copyFrom( reco );
}
//left neighbour
if ( leftEdgeAvai )
{
const CompArea& compArea = areaLeft.block(compId);
CompArea locArea = compArea;
locArea.x -= cu->blocks[compIdx].x;
locArea.y -= cu->blocks[compIdx].y;
PelBuf dbReco = picDbBuf.getBuf( locArea );
if (cs.slice->lmcsEnabled && isLuma(compId))
{
dbReco.rspSignal( cs.picture->getRecoBuf( compArea ), reshapeData.getInvLUT() );
}
else
{
dbReco.copyFrom( cs.picture->getRecoBuf( compArea ) );
}
}
//top neighbour
if ( topEdgeAvai )
{
const CompArea& compArea = areaTop.block( compId );
CompArea locArea = compArea;
locArea.x -= cu->blocks[compIdx].x;
locArea.y -= cu->blocks[compIdx].y;
PelBuf dbReco = picDbBuf.getBuf( locArea );
if (cs.slice->lmcsEnabled && isLuma(compId))
{
dbReco.rspSignal( cs.picture->getRecoBuf( compArea ), reshapeData.getInvLUT() );
}
else
{
dbReco.copyFrom( cs.picture->getRecoBuf( compArea ) );
}
}
}
ChannelType dbChType = CU::isSepTree(*cu) ? partitioner.chType : MAX_NUM_CH;
CHECK( CU::isSepTree(*cu) && !cu->Y().valid() && partitioner.chType == CH_L, "xxx" );
if( cu->Y() .valid() ) m_cLoopFilter.setOrigin( CH_L, cu->lumaPos() );
if( cu->chromaFormat != VVENC_CHROMA_400 && cu->Cb().valid() ) m_cLoopFilter.setOrigin( CH_C, cu->chromaPos() );
//deblock
if( leftEdgeAvai )
{
m_cLoopFilter.loopFilterCu( *cu, dbChType, EDGE_VER, m_dbBuffer );
}
if( topEdgeAvai )
{
m_cLoopFilter.loopFilterCu( *cu, dbChType, EDGE_HOR, m_dbBuffer );
}
//calculate difference between DB_before_SSE and DB_after_SSE for neighbouring CUs
Distortion distBeforeDb = 0, distAfterDb = 0, distCur = 0;
for (int compIdx = compStr; compIdx <= compEnd; compIdx++)
{
ComponentID compId = (ComponentID)compIdx;
{
CompArea compArea = currCsArea.block( compId );
CompArea locArea = compArea;
locArea.x -= cu->blocks[compIdx].x;
locArea.y -= cu->blocks[compIdx].y;
CPelBuf reco = picDbBuf.getBuf( locArea );
CPelBuf org = cs.getOrgBuf( compId );
distCur += xGetDistortionDb( cs, org, reco, compArea, false );
}
if ( leftEdgeAvai )
{
const CompArea& compArea = areaLeft.block( compId );
CompArea locArea = compArea;
locArea.x -= cu->blocks[compIdx].x;
locArea.y -= cu->blocks[compIdx].y;
CPelBuf org = cs.picture->getOrigBuf( compArea );
if ( cs.picture->getFilteredOrigBuffer().valid() )
{
org = cs.picture->getRspOrigBuf( compArea );
}
CPelBuf reco = cs.picture->getRecoBuf( compArea );
CPelBuf recoDb = picDbBuf.getBuf( locArea );
distBeforeDb += xGetDistortionDb( cs, org, reco, compArea, true );
distAfterDb += xGetDistortionDb( cs, org, recoDb, compArea, false );
}
if ( topEdgeAvai )
{
const CompArea& compArea = areaTop.block( compId );
CompArea locArea = compArea;
locArea.x -= cu->blocks[compIdx].x;
locArea.y -= cu->blocks[compIdx].y;
CPelBuf org = cs.picture->getOrigBuf( compArea );
if ( cs.picture->getFilteredOrigBuffer().valid() )
{
org = cs.picture->getRspOrigBuf( compArea );
}
CPelBuf reco = cs.picture->getRecoBuf( compArea );
CPelBuf recoDb = picDbBuf.getBuf( locArea );
distBeforeDb += xGetDistortionDb( cs, org, reco, compArea, true );
distAfterDb += xGetDistortionDb( cs, org, recoDb, compArea, false );
}
}
//updated cost
int64_t distTmp = distCur - cs.dist + distAfterDb - distBeforeDb;
cs.costDbOffset = distTmp < 0 ? -m_cRdCost.calcRdCost( 0, -distTmp ) : m_cRdCost.calcRdCost( 0, distTmp );
}
Distortion EncCu::xGetDistortionDb(CodingStructure &cs, CPelBuf& org, CPelBuf& reco, const CompArea& compArea, bool beforeDb)
{
Distortion dist;
const ReshapeData& reshapeData = cs.picture->reshapeData;
const ComponentID compID = compArea.compID;
if( (cs.slice->lmcsEnabled && reshapeData.getCTUFlag()) || m_pcEncCfg->m_lumaLevelToDeltaQPEnabled)
{
if ( compID == COMP_Y && !m_pcEncCfg->m_lumaLevelToDeltaQPEnabled)
{
CPelBuf tmpReco;
if( beforeDb )
{
PelBuf tmpLmcs = m_aTmpStorageLCU[0].getCompactBuf( compArea );
tmpLmcs.rspSignal( reco, reshapeData.getInvLUT() );
tmpReco = tmpLmcs;
}
else
{
tmpReco = reco;
}
dist = m_cRdCost.getDistPart( org, tmpReco, cs.sps->bitDepths[CH_L], compID, DF_SSE_WTD, &org );
}
else if( m_pcEncCfg->m_EDO == 2)
{
// use the correct luma area to scale chroma
const int csx = getComponentScaleX( compID, cs.area.chromaFormat );
const int csy = getComponentScaleY( compID, cs.area.chromaFormat );
CompArea lumaArea = CompArea( COMP_Y, cs.area.chromaFormat, Area( compArea.x << csx, compArea.y << csy, compArea.width << csx, compArea.height << csy), true);
CPelBuf orgLuma = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getRspOrigBuf( lumaArea ): cs.picture->getOrigBuf( lumaArea );
dist = m_cRdCost.getDistPart( org, reco, cs.sps->bitDepths[toChannelType( compID )], compID, DF_SSE_WTD, &orgLuma );
}
else
{
const int csx = getComponentScaleX( compID, cs.area.chromaFormat );
const int csy = getComponentScaleY( compID, cs.area.chromaFormat );
CompArea lumaArea = compArea.compID ? CompArea( COMP_Y, cs.area.chromaFormat, Area( compArea.x << csx, compArea.y << csy, compArea.width << csx, compArea.height << csy), true) : cs.area.blocks[COMP_Y];
CPelBuf orgLuma = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getRspOrigBuf( lumaArea ): cs.picture->getOrigBuf( lumaArea );
// CPelBuf orgLuma = cs.picture->getFilteredOrigBuffer().valid() ? cs.picture->getRspOrigBuf( cs.area.blocks[COMP_Y] ): cs.picture->getOrigBuf( cs.area.blocks[COMP_Y] );
dist = m_cRdCost.getDistPart( org, reco, cs.sps->bitDepths[toChannelType( compID )], compID, DF_SSE_WTD, &orgLuma );
}
return dist;
}
if ( cs.slice->lmcsEnabled && cs.slice->isIntra() && compID == COMP_Y && !beforeDb ) //intra slice
{
PelBuf tmpLmcs = m_aTmpStorageLCU[0].getCompactBuf( compArea );
tmpLmcs.rspSignal( reco, reshapeData.getFwdLUT() );
dist = m_cRdCost.getDistPart( org, tmpLmcs, cs.sps->bitDepths[CH_L], compID, DF_SSE );
return dist;
}
dist = m_cRdCost.getDistPart(org, reco, cs.sps->bitDepths[toChannelType(compID)], compID, DF_SSE);
return dist;
}
bool checkValidMvs( const CodingUnit& cu)
{
// clang-format off
const int affineShiftTab[3] =
{
MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER,
MV_PRECISION_INTERNAL - MV_PRECISION_SIXTEENTH,
MV_PRECISION_INTERNAL - MV_PRECISION_INT
};
const int normalShiftTab[NUM_IMV_MODES] =
{
MV_PRECISION_INTERNAL - MV_PRECISION_QUARTER,
MV_PRECISION_INTERNAL - MV_PRECISION_INT,
MV_PRECISION_INTERNAL - MV_PRECISION_4PEL,
MV_PRECISION_INTERNAL - MV_PRECISION_HALF,
};
// clang-format on
int mvShift;
for (int refList = 0; refList < NUM_REF_PIC_LIST_01; refList++)
{
if (cu.refIdx[refList] >= 0)
{
if (!cu.affine)
{
mvShift = normalShiftTab[cu.imv];
Mv signaledmvd(cu.mvd[refList][0].hor >> mvShift, cu.mvd[refList][0].ver >> mvShift);
if (!((signaledmvd.hor >= MVD_MIN) && (signaledmvd.hor <= MVD_MAX)) || !((signaledmvd.ver >= MVD_MIN) && (signaledmvd.ver <= MVD_MAX)))
return false;
}
else
{
for (int ctrlP = 1 + (cu.affineType == AFFINEMODEL_6PARAM); ctrlP >= 0; ctrlP--)
{
mvShift = affineShiftTab[cu.imv];
Mv signaledmvd(cu.mvd[refList][ctrlP].hor >> mvShift, cu.mvd[refList][ctrlP].ver >> mvShift);
if (!((signaledmvd.hor >= MVD_MIN) && (signaledmvd.hor <= MVD_MAX)) || !((signaledmvd.ver >= MVD_MIN) && (signaledmvd.ver <= MVD_MAX)))
return false;;
}
}
}
}
// avoid MV exceeding 18-bit dynamic range
const int maxMv = 1 << 17;
if (!cu.affine && !cu.mergeFlag)
{
if ((cu.refIdx[0] >= 0 && (cu.mv[0][0].getAbsHor() >= maxMv || cu.mv[0][0].getAbsVer() >= maxMv))
|| (cu.refIdx[1] >= 0 && (cu.mv[1][0].getAbsHor() >= maxMv || cu.mv[1][0].getAbsVer() >= maxMv)))
{
return false;
}
}
if (cu.affine && !cu.mergeFlag)
{
for (int refList = 0; refList < NUM_REF_PIC_LIST_01; refList++)
{
if (cu.refIdx[refList] >= 0)
{
for (int ctrlP = 1 + (cu.affineType == AFFINEMODEL_6PARAM); ctrlP >= 0; ctrlP--)
{
if (cu.mv[refList][ctrlP].getAbsHor() >= maxMv || cu.mv[refList][ctrlP].getAbsVer() >= maxMv)
{
return false;
}
}
}
}
}
return true;
}
void EncCu::xEncodeInterResidual( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode, int residualPass, bool* bestHasNonResi, double* equBcwCost )
{
if( residualPass == 1 && encTestMode.lossless )
{
return;
}
CodingUnit* cu = tempCS->getCU( partitioner.chType, partitioner.treeType );
double bestCostInternal = MAX_DOUBLE;
if( ! checkValidMvs(*cu))
return;
double currBestCost = MAX_DOUBLE;
// For SBT
double bestCost = bestCS->cost;
double bestCostBegin = bestCS->cost;
const CodingUnit* prevBestCU = bestCS->getCU( partitioner.chType, partitioner.treeType );
uint8_t prevBestSbt = ( prevBestCU == nullptr ) ? 0 : prevBestCU->sbtInfo;
Distortion sbtOffDist = 0;
bool sbtOffRootCbf = 0;
double sbtOffCost = MAX_DOUBLE;
uint8_t currBestSbt = 0;
uint8_t histBestSbt = MAX_UCHAR;
Distortion curPuSse = MAX_DISTORTION;
uint8_t numRDOTried = 0;
bool doPreAnalyzeResi = false;
const bool mtsAllowed = tempCS->sps->MTSInter && partitioner.currArea().lwidth() <= MTS_INTER_MAX_CU_SIZE && partitioner.currArea().lheight() <= MTS_INTER_MAX_CU_SIZE;
uint8_t sbtAllowed = CU::checkAllowedSbt(*cu);
if( tempCS->pps->picWidthInLumaSamples < (uint32_t)SBT_FAST64_WIDTH_THRESHOLD || m_pcEncCfg->m_SBT>1)
{
sbtAllowed = ((cu->lwidth() > 32 || cu->lheight() > 32)) ? 0 : sbtAllowed;
}
if( sbtAllowed )
{
//SBT resolution-dependent fast algorithm: not try size-64 SBT in RDO for low-resolution sequences (now resolution below HD)
doPreAnalyzeResi = ( sbtAllowed || mtsAllowed ) && residualPass == 0;
m_cInterSearch.getBestSbt( tempCS, cu, histBestSbt, curPuSse, sbtAllowed, doPreAnalyzeResi, mtsAllowed );
}
cu->skip = false;
cu->sbtInfo = 0;
const bool skipResidual = residualPass == 1;
if( skipResidual || histBestSbt == MAX_UCHAR || !CU::isSbtMode( histBestSbt ) )
{
m_cInterSearch.encodeResAndCalcRdInterCU( *tempCS, partitioner, skipResidual );
xEncodeDontSplit( *tempCS, partitioner );
xCheckDQP( *tempCS, partitioner );
if( NULL != bestHasNonResi && (bestCostInternal > tempCS->cost) )
{
bestCostInternal = tempCS->cost;
if (!(cu->ciip))
*bestHasNonResi = !cu->rootCbf;
}
if (cu->rootCbf == false)
{
if (cu->ciip)
{
tempCS->cost = MAX_DOUBLE;
tempCS->costDbOffset = 0;
return;
}
}
currBestCost = tempCS->cost;
if( sbtAllowed )
{
sbtOffCost = tempCS->cost;
sbtOffDist = tempCS->dist;
sbtOffRootCbf = cu->rootCbf;
currBestSbt = cu->firstTU->mtsIdx[COMP_Y] > MTS_SKIP ? SBT_OFF_MTS : SBT_OFF_DCT;
numRDOTried += mtsAllowed ? 2 : 1;
}
DTRACE_MODE_COST( *tempCS, m_cRdCost.getLambda( true ) );
xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_RD_TESTS][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_RD_TESTS][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
}
if( sbtAllowed && (m_pcEncCfg->m_SBT == 1 || sbtOffRootCbf))
{
bool swapped = false; // avoid unwanted data copy
uint8_t numSbtRdo = CU::numSbtModeRdo( sbtAllowed );
//early termination if all SBT modes are not allowed
//normative
if( !sbtAllowed || skipResidual )
{
numSbtRdo = 0;
}
//fast algorithm
if( ( histBestSbt != MAX_UCHAR && !CU::isSbtMode( histBestSbt ) ) || m_cInterSearch.getSkipSbtAll() )
{
numSbtRdo = 0;
}
if( bestCost != MAX_DOUBLE && sbtOffCost != MAX_DOUBLE )
{
double th = 1.07;
if( !( prevBestSbt == 0 || m_sbtCostSave[0] == MAX_DOUBLE ) )
{
assert( m_sbtCostSave[1] <= m_sbtCostSave[0] );
th *= ( m_sbtCostSave[0] / m_sbtCostSave[1] );
}
if( sbtOffCost > bestCost * th )
{
numSbtRdo = 0;
}
}
if( !sbtOffRootCbf && sbtOffCost != MAX_DOUBLE )
{
double th = Clip3( 0.05, 0.55, ( 27 - cu->qp ) * 0.02 + 0.35 );
if( sbtOffCost < m_cRdCost.calcRdCost( ( cu->lwidth() * cu->lheight() ) << SCALE_BITS, 0 ) * th )
{
numSbtRdo = 0;
}
}
if( histBestSbt != MAX_UCHAR && numSbtRdo != 0 )
{
numSbtRdo = 1;
m_cInterSearch.initSbtRdoOrder( CU::getSbtMode( CU::getSbtIdx( histBestSbt ), CU::getSbtPos( histBestSbt ) ) );
}
for( int sbtModeIdx = 0; sbtModeIdx < numSbtRdo; sbtModeIdx++ )
{
uint8_t sbtMode = m_cInterSearch.getSbtRdoOrder( sbtModeIdx );
uint8_t sbtIdx = CU::getSbtIdxFromSbtMode( sbtMode );
uint8_t sbtPos = CU::getSbtPosFromSbtMode( sbtMode );
//fast algorithm (early skip, save & load)
if( histBestSbt == MAX_UCHAR )
{
uint8_t skipCode = m_cInterSearch.skipSbtByRDCost( cu->lwidth(), cu->lheight(), cu->mtDepth, sbtIdx, sbtPos, bestCS->cost, sbtOffDist, sbtOffCost, sbtOffRootCbf );
if( skipCode != MAX_UCHAR )
{
continue;
}
if( sbtModeIdx > 0 )
{
uint8_t prevSbtMode = m_cInterSearch.getSbtRdoOrder( sbtModeIdx - 1 );
//make sure the prevSbtMode is the same size as the current SBT mode (otherwise the estimated dist may not be comparable)
if( CU::isSameSbtSize( prevSbtMode, sbtMode ) )
{
Distortion currEstDist = m_cInterSearch.getEstDistSbt( sbtMode );
Distortion prevEstDist = m_cInterSearch.getEstDistSbt( prevSbtMode );
if( currEstDist > prevEstDist * 1.15 )
{
continue;
}
}
}
}
//init tempCS and TU
if( bestCost == bestCS->cost ) //The first EMT pass didn't become the bestCS, so we clear the TUs generated
{
tempCS->clearTUs();
}
else if( !swapped )
{
tempCS->initStructData( encTestMode.qp );
tempCS->copyStructure( *bestCS, partitioner.chType, partitioner.treeType );
tempCS->getPredBuf().copyFrom( bestCS->getPredBuf() );
bestCost = bestCS->cost;
cu = tempCS->getCU( partitioner.chType, partitioner.treeType );
swapped = true;
}
else
{
tempCS->clearTUs();
bestCost = bestCS->cost;
cu = tempCS->getCU( partitioner.chType, partitioner.treeType );
}
//we need to restart the distortion for the new tempCS, the bit count and the cost
tempCS->dist = 0;
tempCS->fracBits = 0;
tempCS->cost = MAX_DOUBLE;
cu->skip = false;
//set SBT info
cu->sbtInfo = (sbtPos << 4) + sbtIdx;
//try residual coding
m_cInterSearch.encodeResAndCalcRdInterCU( *tempCS, partitioner, skipResidual );
numRDOTried++;
xEncodeDontSplit( *tempCS, partitioner );
xCheckDQP( *tempCS, partitioner );
if( NULL != bestHasNonResi && ( bestCostInternal > tempCS->cost ) )
{
bestCostInternal = tempCS->cost;
if( !( cu->ciip ) )
*bestHasNonResi = !cu->rootCbf;
}
if( tempCS->cost < currBestCost )
{
currBestSbt = cu->sbtInfo;
currBestCost = tempCS->cost;
}
else if( m_pcEncCfg->m_SBT > 2 )
{
sbtModeIdx = numSbtRdo;
}
DTRACE_MODE_COST( *tempCS, m_cRdCost.getLambda( true ) );
xCheckBestMode( tempCS, bestCS, partitioner, encTestMode );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L, g_cuCounters1D[CU_RD_TESTS][0][!tempCS->slice->isIntra() + tempCS->slice->depth] );
STAT_COUNT_CU_MODES( partitioner.chType == CH_L && !tempCS->slice->isIntra(), g_cuCounters2D[CU_RD_TESTS][Log2( tempCS->area.lheight() )][Log2( tempCS->area.lwidth() )] );
}
if( bestCostBegin != bestCS->cost )
{
m_sbtCostSave[0] = sbtOffCost;
m_sbtCostSave[1] = currBestCost;
}
if( histBestSbt == MAX_UCHAR && doPreAnalyzeResi && numRDOTried > 1 )
{
auto slsSbt = static_cast<CacheBlkInfoCtrl&>( m_modeCtrl );
int slShift = 4 + std::min( Log2( cu->lwidth() ) + Log2( cu->lheight() ), 9 );
slsSbt.saveBestSbt( cu->cs->area, (uint32_t)( curPuSse >> slShift ), currBestSbt );
}
if( ETM_INTER_ME == encTestMode.type )
{
if( equBcwCost != NULL )
{
if( tempCS->cost < ( *equBcwCost ) && cu->BcwIdx == BCW_DEFAULT )
{
( *equBcwCost ) = tempCS->cost;
}
}
else
{
CHECK( equBcwCost == NULL, "equBcwCost == NULL" );
}
if( tempCS->slice->checkLDC && !cu->imv && cu->BcwIdx != BCW_DEFAULT && tempCS->cost < m_bestBcwCost[1] )
{
if( tempCS->cost < m_bestBcwCost[0] )
{
m_bestBcwCost[1] = m_bestBcwCost[0];
m_bestBcwCost[0] = tempCS->cost;
m_bestBcwIdx[1] = m_bestBcwIdx[0];
m_bestBcwIdx[0] = cu->BcwIdx;
}
else
{
m_bestBcwCost[1] = tempCS->cost;
m_bestBcwIdx[1] = cu->BcwIdx;
}
}
}
}
tempCS->cost = currBestCost;
}
void EncCu::xEncodeDontSplit( CodingStructure &cs, Partitioner &partitioner )
{
m_CABACEstimator->resetBits();
m_CABACEstimator->split_cu_mode( CU_DONT_SPLIT, cs, partitioner );
if( partitioner.treeType == TREE_C )
CHECK( m_CABACEstimator->getEstFracBits() != 0, "must be 0 bit" );
cs.fracBits += m_CABACEstimator->getEstFracBits(); // split bits
cs.cost = m_cRdCost.calcRdCost( cs.fracBits, cs.dist );
}
void EncCu::xReuseCachedResult( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner )
{
EncTestMode cachedMode;
if( ! m_modeCtrl.setCsFrom( *tempCS, cachedMode, partitioner ) )
{
THROW( "Should never happen!" );
}
CodingUnit& cu = *tempCS->cus.front();
partitioner.setCUData( cu );
if( CU::isIntra( cu ) )
{
xReconIntraQT( cu );
}
else
{
xDeriveCUMV( cu );
xReconInter( cu );
}
m_CABACEstimator->getCtx() = m_CurrCtx->start;
m_CABACEstimator->resetBits();
CUCtx cuCtx;
cuCtx.isDQPCoded = true;
cuCtx.isChromaQpAdjCoded = true;
m_CABACEstimator->coding_unit( cu, partitioner, cuCtx );
tempCS->fracBits = m_CABACEstimator->getEstFracBits();
tempCS->cost = m_cRdCost.calcRdCost( tempCS->fracBits, tempCS->dist );
xEncodeDontSplit( *tempCS, partitioner );
xCheckDQP ( *tempCS, partitioner );
xCheckBestMode ( tempCS, bestCS, partitioner, cachedMode, m_pcEncCfg->m_EDO );
}
bool EncCu::xCheckSATDCostAffineMerge(CodingStructure*& tempCS, CodingUnit& cu, AffineMergeCtx affineMergeCtx, MergeCtx& mrgCtx, SortedPelUnitBufs<SORTED_BUFS>& sortedPelBuffer
, unsigned& uiNumMrgSATDCand, static_vector<ModeInfo, MRG_MAX_NUM_CANDS + MMVD_ADD_NUM>& RdModeList, static_vector<double, MRG_MAX_NUM_CANDS + MMVD_ADD_NUM>& candCostList, DistParam distParam, const TempCtx& ctxStart, uint16_t merge_ctx_size)
{
bool mmvdCandInserted = false;
cu.mmvdSkip = false;
cu.geo = false;
cu.affine = true;
cu.mergeFlag = true;
cu.ciip = false;
cu.mmvdMergeFlag = false;
cu.regularMergeFlag = false;
const double sqrtLambdaForFirstPassIntra = m_cRdCost.getMotionLambda() * FRAC_BITS_SCALE;
bool sameMV[MRG_MAX_NUM_CANDS] = { false, };
if (m_pcEncCfg->m_Affine > 1)
{
for (int m = 0; m < affineMergeCtx.numValidMergeCand; m++)
{
if ((tempCS->slice->TLayer > 3) && (affineMergeCtx.mergeType[m] != MRG_TYPE_SUBPU_ATMVP))
{
sameMV[m] = m != 0;
}
else if (sameMV[m + 1] == false)
{
for (int n = m + 1; n < affineMergeCtx.numValidMergeCand; n++)
{
if ((affineMergeCtx.mvFieldNeighbours[(m << 1) + 0]->mv == affineMergeCtx.mvFieldNeighbours[(n << 1) + 0]->mv)
&& (affineMergeCtx.mvFieldNeighbours[(m << 1) + 1]->mv == affineMergeCtx.mvFieldNeighbours[(n << 1) + 1]->mv))
{
sameMV[n] = true;
}
}
}
}
}
int insertPos = -1;
for (uint32_t uiAffMergeCand = 0; uiAffMergeCand < affineMergeCtx.numValidMergeCand; uiAffMergeCand++)
{
if ((m_pcEncCfg->m_Affine > 1) && sameMV[uiAffMergeCand])
{
continue;
}
// set merge information
cu.interDir = affineMergeCtx.interDirNeighbours[uiAffMergeCand];
cu.mergeIdx = uiAffMergeCand;
cu.affineType = affineMergeCtx.affineType[uiAffMergeCand];
cu.BcwIdx = affineMergeCtx.BcwIdx[uiAffMergeCand];
cu.mv[0]->setZero();
cu.mv[1]->setZero();
cu.imv = 0;
cu.mergeType = affineMergeCtx.mergeType[uiAffMergeCand];
if (cu.mergeType == MRG_TYPE_SUBPU_ATMVP)
{
cu.refIdx[0] = affineMergeCtx.mvFieldNeighbours[(uiAffMergeCand << 1) + 0][0].refIdx;
cu.refIdx[1] = affineMergeCtx.mvFieldNeighbours[(uiAffMergeCand << 1) + 1][0].refIdx;
CU::spanMotionInfo(cu, mrgCtx);
}
else
{
CU::setAllAffineMvField(cu, affineMergeCtx.mvFieldNeighbours[(uiAffMergeCand << 1) + 0], REF_PIC_LIST_0);
CU::setAllAffineMvField(cu, affineMergeCtx.mvFieldNeighbours[(uiAffMergeCand << 1) + 1], REF_PIC_LIST_1);
CU::spanMotionInfo(cu);
}
distParam.cur.buf = sortedPelBuffer.getTestBuf().Y().buf;
cu.mcControl = 2;
m_cInterSearch.motionCompensation(cu, sortedPelBuffer.getTestBuf(), REF_PIC_LIST_X);
cu.mcControl = 0;
Distortion uiSad = distParam.distFunc(distParam);
m_CABACEstimator->getCtx() = SubCtx(CtxSet(Ctx::MergeFlag(), merge_ctx_size), ctxStart);
uint64_t fracBits = xCalcPuMeBits(cu);
double cost = (double)uiSad + (double)fracBits * sqrtLambdaForFirstPassIntra;
insertPos = -1;
updateCandList(ModeInfo(uiAffMergeCand, false, false, false, false, true), cost, RdModeList, candCostList, uiNumMrgSATDCand, &insertPos);
mmvdCandInserted |= insertPos > -1;
sortedPelBuffer.insert(insertPos, (int)RdModeList.size());
}
cu.regularMergeFlag = true;
cu.affine = false;
return mmvdCandInserted;
}
uint64_t EncCu::xCalcPuMeBits(const CodingUnit& cu)
{
assert(cu.mergeFlag);
assert(!CU::isIBC(cu));
m_CABACEstimator->resetBits();
m_CABACEstimator->merge_flag(cu);
if (cu.mergeFlag)
{
m_CABACEstimator->merge_data(cu);
}
return m_CABACEstimator->getEstFracBits();
}
double EncCu::xCalcDistortion(CodingStructure *&cur_CS, ChannelType chType, int BitDepth, int imv)
{
const auto currDist1 = m_cRdCost.getDistPart(cur_CS->getOrgBuf( COMP_Y ), cur_CS->getPredBuf( COMP_Y ), BitDepth, COMP_Y, DF_HAD);
unsigned int uiMvBits = 0;
unsigned imvShift = imv == IMV_HPEL ? 1 : (imv << 1);
const CodingUnit& cu = *cur_CS->getCU( chType, TREE_D);
if (cu.interDir != 2)
{
uiMvBits += m_cRdCost.getBitsOfVectorWithPredictor(cu.mvd[0][0].hor, cu.mvd[0][0].ver, imvShift + MV_FRACTIONAL_BITS_DIFF);
}
if (cu.interDir != 1)
{
uiMvBits += m_cRdCost.getBitsOfVectorWithPredictor(cu.mvd[1][0].hor, cu.mvd[1][0].ver, imvShift + MV_FRACTIONAL_BITS_DIFF);
}
return (double(currDist1) + (double)m_cRdCost.getCost(uiMvBits));
}
int EncCu::xCheckMMVDCand(uint32_t& mmvdMergeCand, int& bestDir, int tempNum, double& bestCostOffset, double& bestCostMerge, double bestCostList )
{
int baseIdx = mmvdMergeCand / MMVD_MAX_REFINE_NUM;
int CandCur = mmvdMergeCand - MMVD_MAX_REFINE_NUM*baseIdx;
if (m_pcEncCfg->m_MMVD > 2)
{
if (CandCur % 4 == 0)
{
if ((bestCostOffset >= bestCostMerge) && (CandCur >= 4))
{
if (mmvdMergeCand > MMVD_MAX_REFINE_NUM)
{
return 2;
}
else
{
mmvdMergeCand = MMVD_MAX_REFINE_NUM;
if (tempNum == mmvdMergeCand)
{
return 2;
}
}
}
//reset
bestCostOffset = MAX_DOUBLE;
bestCostMerge = bestCostList;
}
}
if (mmvdMergeCand == MMVD_MAX_REFINE_NUM)
{
bestDir = 0;
}
if (CandCur >= 4)
{
if (CandCur % 4 != bestDir)
{
return 1;
}
}
return 0;
}
} // namespace vvenc
//! \}
| 36.461158 | 270 | 0.627911 | [
"vector"
] |
ba544fb66bfed19f93f105865affc083f003c8b6 | 735 | cpp | C++ | cpp/9869.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 9 | 2021-01-15T13:36:39.000Z | 2022-02-23T03:44:46.000Z | cpp/9869.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | 1 | 2021-07-31T17:11:26.000Z | 2021-08-02T01:01:03.000Z | cpp/9869.cpp | jinhan814/BOJ | 47d2a89a2602144eb08459cabac04d036c758577 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
using pii = pair<int, int>;
struct UnionFind {
vector<int> par;
UnionFind(int n) : par(n) { iota(par.begin(), par.end(), 0); }
int Find(int x) { return x == par[x] ? x : par[x] = Find(par[x]); }
void Union(int a, int b) { a = Find(a), b = Find(b); if (a > b) swap(a, b); par[b] = a; }
};
int main() {
fastio;
int n, ans = 0; cin >> n;
vector<pii> v(n);
for (int i = 0; i < n; i++) cin >> v[i].first >> v[i].second;
sort(v.rbegin(), v.rend());
UnionFind UF(10'001);
for (auto& [a, b] : v) {
int t = UF.Find(b);
if (t) ans += b, UF.Union(t, t - 1);
}
cout << ans << '\n';
} | 27.222222 | 93 | 0.504762 | [
"vector"
] |
ba5b8ec63e148bb26f52f5d8282f4ef6ac3a040f | 5,903 | cpp | C++ | src/sdk/hl2_csgo/game/server/swarm/asw_mine.cpp | newcommerdontblame/ionlib | 47ca829009e1529f62b2134aa6c0df8673864cf3 | [
"MIT"
] | 51 | 2016-03-18T01:48:07.000Z | 2022-03-21T20:02:02.000Z | src/game/server/swarm/asw_mine.cpp | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | null | null | null | src/game/server/swarm/asw_mine.cpp | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | 26 | 2016-03-17T21:20:37.000Z | 2022-03-24T10:21:30.000Z | #include "cbase.h"
#include "asw_mine.h"
#include "Sprite.h"
#include "SpriteTrail.h"
#include "soundent.h"
#include "te_effect_dispatch.h"
#include "IEffects.h"
#include "weapon_flaregun.h"
#include "decals.h"
#include "ai_basenpc.h"
#include "asw_marine.h"
#include "asw_firewall_piece.h"
#include "asw_marine_skills.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define ASW_MINE_MODEL "models/items/Mine/mine.mdl"
#define ASW_MINE_EXPLODE_TIME 0.6f
ConVar asw_debug_mine("asw_debug_mine", "0", FCVAR_CHEAT, "Turn on debug messages for Incendiary Mines");
LINK_ENTITY_TO_CLASS( asw_mine, CASW_Mine );
BEGIN_DATADESC( CASW_Mine )
DEFINE_FUNCTION( MineTouch ),
DEFINE_FUNCTION( MineThink ),
DEFINE_FIELD( m_bPrimed, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bMineTriggered, FIELD_BOOLEAN ),
DEFINE_FIELD( m_fForcePrimeTime, FIELD_FLOAT ),
END_DATADESC()
IMPLEMENT_SERVERCLASS_ST( CASW_Mine, DT_ASW_Mine )
SendPropBool( SENDINFO( m_bMineTriggered ) ),
END_SEND_TABLE()
CASW_Mine::CASW_Mine()
{
m_flDurationScale = 1.0f;
m_iExtraFires = 0;
}
CASW_Mine::~CASW_Mine( void )
{
}
void CASW_Mine::Spawn( void )
{
Precache( );
SetModel( ASW_MINE_MODEL );
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_SOLID || FSOLID_TRIGGER);
SetMoveType( MOVETYPE_FLYGRAVITY );
m_takedamage = DAMAGE_NO;
m_bPrimed = false;
AddEffects( EF_NOSHADOW|EF_NORECEIVESHADOW );
m_fForcePrimeTime = gpGlobals->curtime + 5.0f;
SetThink( &CASW_Mine::MineThink );
SetNextThink( gpGlobals->curtime + 0.1f );
SetTouch( &CASW_Mine::MineTouch );
}
unsigned int CASW_Mine::PhysicsSolidMaskForEntity( void ) const
{
return MASK_NPCSOLID;
}
void CASW_Mine::MineThink( void )
{
if (m_bMineTriggered)
{
Explode();
}
// if we've stopped moving, prime ourselves
else if (!m_bPrimed && (GetAbsVelocity().Length() < 1.0f || gpGlobals->curtime > m_fForcePrimeTime))
{
Prime();
}
else
{
SetNextThink( gpGlobals->curtime + 0.1f );
}
}
void CASW_Mine::Explode()
{
if (asw_debug_mine.GetBool())
Msg("OMG MINE ASPLODE!\n");
CASW_Firewall_Piece* pFirewall = (CASW_Firewall_Piece *)CreateEntityByName( "asw_firewall_piece" );
if (pFirewall)
{
pFirewall->SetAbsAngles( GetAbsAngles() );
if (GetOwnerEntity())
Msg("Creating firewall with owner %s\n", GetOwnerEntity()->GetClassname());
pFirewall->SetOwnerEntity(GetOwnerEntity());
pFirewall->SetAbsOrigin( GetAbsOrigin() );
CASW_Marine *pMarine = dynamic_cast<CASW_Marine*>(GetOwnerEntity());
if (!pMarine)
{
pFirewall->SetSideFire( 3 + m_iExtraFires , 3+ m_iExtraFires );
}
else
{
int iSideFires = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_MINES_FIRES) + m_iExtraFires;
float fDuration = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_MINES_DURATION);
pFirewall->SetSideFire(iSideFires,iSideFires);
pFirewall->SetDuration(fDuration * m_flDurationScale);
}
pFirewall->m_hCreatorWeapon = m_hCreatorWeapon;
pFirewall->Spawn();
pFirewall->SetAbsVelocity( vec3_origin );
}
EmitSound("ASW_Mine.Explode");
UTIL_Remove( this );
}
void CASW_Mine::Precache( void )
{
PrecacheModel( ASW_MINE_MODEL );
PrecacheScriptSound("ASW_Mine.Lay");
PrecacheScriptSound("ASW_Mine.Flash");
PrecacheScriptSound("ASW_Mine.Explode");
BaseClass::Precache();
}
CASW_Mine* CASW_Mine::ASW_Mine_Create( const Vector &position, const QAngle &angles, const Vector &velocity, const AngularImpulse &angVelocity, CBaseEntity *pOwner, CBaseEntity *pCreatorWeapon )
{
CASW_Mine *pMine = (CASW_Mine*)CreateEntityByName( "asw_mine" );
pMine->SetAbsAngles( angles );
pMine->Spawn();
pMine->SetOwnerEntity( pOwner );
UTIL_SetOrigin( pMine, position );
pMine->SetAbsVelocity( velocity );
pMine->m_hCreatorWeapon.Set( pCreatorWeapon );
return pMine;
}
void CASW_Mine::MineTouch( CBaseEntity *pOther )
{
Assert( pOther );
if (pOther->entindex() != 0 && asw_debug_mine.GetBool())
Msg("Touched by %s\n", pOther->GetClassname());
if (!m_bMineTriggered && m_bPrimed)
{
// if other is an alien, trigger the mine
if (ValidMineTarget(pOther))
{
// Ensure clear path to the target
trace_t tr;
UTIL_TraceLine( GetAbsOrigin(), pOther->WorldSpaceCenter(), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
if ( tr.fraction >= 1.0f || tr.m_pEnt == pOther )
{
if (asw_debug_mine.GetBool())
Msg("Mine triggered!\n");
m_bMineTriggered = true;
EmitSound("ASW_Mine.Flash");
SetNextThink( gpGlobals->curtime + ASW_MINE_EXPLODE_TIME );
}
}
}
// Slow down
Vector vecNewVelocity = GetAbsVelocity();
vecNewVelocity.x *= 0.8f;
vecNewVelocity.y *= 0.8f;
SetAbsVelocity( vecNewVelocity );
}
// set the mine up for exploding
void CASW_Mine::Prime()
{
if (asw_debug_mine.GetBool())
Msg("Mine primed!\n");
EmitSound("ASW_Mine.Lay");
SetSolid( SOLID_BBOX );
float boxWidth = 150;
UTIL_SetSize(this, Vector(-boxWidth,-boxWidth,-boxWidth),Vector(boxWidth,boxWidth,boxWidth * 2));
SetCollisionGroup( ASW_COLLISION_GROUP_PASSABLE );
CollisionProp()->UseTriggerBounds( true, 24 );
AddSolidFlags(FSOLID_TRIGGER);
AddSolidFlags(FSOLID_NOT_SOLID);
SetTouch( &CASW_Mine::MineTouch );
m_bPrimed = true;
// attach to whatever we're standing on
CBaseEntity *pGround = GetGroundEntity();
if ( pGround && !pGround->IsWorld() )
{
if (asw_debug_mine.GetBool())
Msg( "Parenting mine to %s\n", GetGroundEntity()->GetClassname() );
SetParent( GetGroundEntity() );
SetMoveType( MOVETYPE_NONE );
}
}
bool CASW_Mine::ValidMineTarget(CBaseEntity *pOther)
{
CASW_Marine* pMarine = CASW_Marine::AsMarine( pOther );
if (pMarine)
return false;
CAI_BaseNPC* pNPC = dynamic_cast<CAI_BaseNPC*>(pOther);
if (pNPC)
return true;
return false;
}
void CASW_Mine::StopLoopingSounds()
{
BaseClass::StopLoopingSounds();
} | 26.59009 | 194 | 0.734203 | [
"vector"
] |
ba6082347006dd0bf664cc5682ac9cef1a4966f9 | 497 | cc | C++ | factory-wrapped-object/hello.cc | juxiangwu/electron-node-addons | a271b600427a29daa3aac7ef4b77b4a4d3c09d6f | [
"Apache-2.0"
] | 2 | 2020-07-07T05:49:49.000Z | 2020-12-11T09:49:50.000Z | factory-wrapped-object/hello.cc | juxiangwu/electron-node-addons | a271b600427a29daa3aac7ef4b77b4a4d3c09d6f | [
"Apache-2.0"
] | null | null | null | factory-wrapped-object/hello.cc | juxiangwu/electron-node-addons | a271b600427a29daa3aac7ef4b77b4a4d3c09d6f | [
"Apache-2.0"
] | null | null | null | #include <node.h>
#include "myobject.h"
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
MyObject::NewInstance(args);
}
void InitAll(Local<Object> exports, Local<Object> module) {
MyObject::Init(exports->GetIsolate());
NODE_SET_METHOD(module, "exports", CreateObject);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
} // namespace demo | 19.88 | 60 | 0.746479 | [
"object"
] |
ba6130506ffb4c35079c0e9805ba81ddcb3f2c05 | 92 | cc | C++ | Part-III/Ch16/16.1.5/16.26.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | 1 | 2021-09-23T13:13:12.000Z | 2021-09-23T13:13:12.000Z | Part-III/Ch16/16.1.5/16.26.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | Part-III/Ch16/16.1.5/16.26.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | #include <vector>
using std::vector;
class NoDefault {};
template class vector<NoDefault>; | 15.333333 | 33 | 0.75 | [
"vector"
] |
ba63c2985d4b53fc75a1b7a9c4797fadf92f4125 | 5,594 | cc | C++ | libcef/common/command_line_impl.cc | emclient/cef | 84117f2d1be1ce54513290d835c4dcb79da750d4 | [
"BSD-3-Clause"
] | null | null | null | libcef/common/command_line_impl.cc | emclient/cef | 84117f2d1be1ce54513290d835c4dcb79da750d4 | [
"BSD-3-Clause"
] | null | null | null | libcef/common/command_line_impl.cc | emclient/cef | 84117f2d1be1ce54513290d835c4dcb79da750d4 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Embedded Framework 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 "libcef/common/command_line_impl.h"
#include "base/files/file_path.h"
#include "base/logging.h"
CefCommandLineImpl::CefCommandLineImpl(base::CommandLine* value,
bool will_delete,
bool read_only)
: CefValueBase<CefCommandLine, base::CommandLine>(
value,
nullptr,
will_delete ? kOwnerWillDelete : kOwnerNoDelete,
read_only,
nullptr) {}
bool CefCommandLineImpl::IsValid() {
return !detached();
}
bool CefCommandLineImpl::IsReadOnly() {
return read_only();
}
CefRefPtr<CefCommandLine> CefCommandLineImpl::Copy() {
CEF_VALUE_VERIFY_RETURN(false, nullptr);
return new CefCommandLineImpl(new base::CommandLine(const_value().argv()),
true, false);
}
void CefCommandLineImpl::InitFromArgv(int argc, const char* const* argv) {
#if !defined(OS_WIN)
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->InitFromArgv(argc, argv);
#else
NOTREACHED() << "method not supported on this platform";
#endif
}
void CefCommandLineImpl::InitFromString(const CefString& command_line) {
#if defined(OS_WIN)
CEF_VALUE_VERIFY_RETURN_VOID(true);
const std::wstring& str16 = command_line;
mutable_value()->ParseFromString(str16);
#else
NOTREACHED() << "method not supported on this platform";
#endif
}
void CefCommandLineImpl::Reset() {
CEF_VALUE_VERIFY_RETURN_VOID(true);
base::CommandLine::StringVector argv;
argv.push_back(mutable_value()->GetProgram().value());
mutable_value()->InitFromArgv(argv);
const base::CommandLine::SwitchMap& map = mutable_value()->GetSwitches();
const_cast<base::CommandLine::SwitchMap*>(&map)->clear();
}
void CefCommandLineImpl::GetArgv(std::vector<CefString>& argv) {
CEF_VALUE_VERIFY_RETURN_VOID(false);
const base::CommandLine::StringVector& cmd_argv = const_value().argv();
base::CommandLine::StringVector::const_iterator it = cmd_argv.begin();
for (; it != cmd_argv.end(); ++it)
argv.push_back(*it);
}
CefString CefCommandLineImpl::GetCommandLineString() {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().GetCommandLineString();
}
CefString CefCommandLineImpl::GetProgram() {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().GetProgram().value();
}
void CefCommandLineImpl::SetProgram(const CefString& program) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->SetProgram(base::FilePath(program));
}
bool CefCommandLineImpl::HasSwitches() {
CEF_VALUE_VERIFY_RETURN(false, false);
return (const_value().GetSwitches().size() > 0);
}
bool CefCommandLineImpl::HasSwitch(const CefString& name) {
CEF_VALUE_VERIFY_RETURN(false, false);
return const_value().HasSwitch(name.ToString());
}
CefString CefCommandLineImpl::GetSwitchValue(const CefString& name) {
CEF_VALUE_VERIFY_RETURN(false, CefString());
return const_value().GetSwitchValueNative(name.ToString());
}
void CefCommandLineImpl::GetSwitches(SwitchMap& switches) {
CEF_VALUE_VERIFY_RETURN_VOID(false);
const base::CommandLine::SwitchMap& map = const_value().GetSwitches();
base::CommandLine::SwitchMap::const_iterator it = map.begin();
for (; it != map.end(); ++it)
switches.insert(std::make_pair(it->first, it->second));
}
void CefCommandLineImpl::AppendSwitch(const CefString& name) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
mutable_value()->AppendSwitch(name.ToString());
}
void CefCommandLineImpl::AppendSwitchWithValue(const CefString& name,
const CefString& value) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
#if defined(OS_WIN)
mutable_value()->AppendSwitchNative(name.ToString(), value.ToWString());
#else
mutable_value()->AppendSwitchNative(name.ToString(), value.ToString());
#endif
}
bool CefCommandLineImpl::HasArguments() {
CEF_VALUE_VERIFY_RETURN(false, false);
return (const_value().GetArgs().size() > 0);
}
void CefCommandLineImpl::GetArguments(ArgumentList& arguments) {
CEF_VALUE_VERIFY_RETURN_VOID(false);
const base::CommandLine::StringVector& vec = const_value().GetArgs();
base::CommandLine::StringVector::const_iterator it = vec.begin();
for (; it != vec.end(); ++it)
arguments.push_back(*it);
}
void CefCommandLineImpl::AppendArgument(const CefString& argument) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
#if defined(OS_WIN)
mutable_value()->AppendArgNative(argument.ToWString());
#else
mutable_value()->AppendArgNative(argument.ToString());
#endif
}
void CefCommandLineImpl::PrependWrapper(const CefString& wrapper) {
CEF_VALUE_VERIFY_RETURN_VOID(true);
#if defined(OS_WIN)
mutable_value()->PrependWrapper(wrapper.ToWString());
#else
mutable_value()->PrependWrapper(wrapper.ToString());
#endif
}
// CefCommandLine implementation.
// static
CefRefPtr<CefCommandLine> CefCommandLine::CreateCommandLine() {
return new CefCommandLineImpl(
new base::CommandLine(base::CommandLine::NO_PROGRAM), true, false);
}
// static
CefRefPtr<CefCommandLine> CefCommandLine::GetGlobalCommandLine() {
// Uses a singleton reference object.
static CefRefPtr<CefCommandLineImpl> commandLinePtr;
if (!commandLinePtr.get()) {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line)
commandLinePtr = new CefCommandLineImpl(command_line, false, true);
}
return commandLinePtr.get();
}
| 32.149425 | 77 | 0.730247 | [
"object",
"vector"
] |
ba646cbf3ec863f0187edc178cf5935bbe6c3af0 | 8,684 | cpp | C++ | src/vk/buffer.cpp | wroblewskipawel/vulkan_sandbox | 8ff02cb07ef4357705f36d44200da0d1fd570469 | [
"MIT"
] | null | null | null | src/vk/buffer.cpp | wroblewskipawel/vulkan_sandbox | 8ff02cb07ef4357705f36d44200da0d1fd570469 | [
"MIT"
] | null | null | null | src/vk/buffer.cpp | wroblewskipawel/vulkan_sandbox | 8ff02cb07ef4357705f36d44200da0d1fd570469 | [
"MIT"
] | null | null | null | #include "vk/buffer.h"
#include <cstring>
#include "vk/context.h"
namespace vks {
StagingBuffer::StagingBuffer(Device& device, VkDeviceSize size)
: device{device}, m_size{size} {
VkBufferCreateInfo buffer_info{};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.queueFamilyIndexCount = 1;
buffer_info.pQueueFamilyIndices = &device.info().queue_families.transfer;
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
buffer_info.size = m_size;
buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
if (vkCreateBuffer(*device, &buffer_info, nullptr, &m_buffer) !=
VK_SUCCESS) {
throw std::runtime_error("Failed to create staging buffer");
}
VkMemoryRequirements requirements{};
vkGetBufferMemoryRequirements(*device, m_buffer, &requirements);
VkMemoryAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = requirements.size;
alloc_info.memoryTypeIndex = device.getMemoryIndex(
requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
if (vkAllocateMemory(*device, &alloc_info, nullptr, &m_memory) !=
VK_SUCCESS) {
throw std::runtime_error("Failed to allocate staging buffer memory");
}
vkBindBufferMemory(*device, m_buffer, m_memory, 0);
VkCommandPoolCreateInfo pool_info{};
pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_info.queueFamilyIndex = device.info().queue_families.transfer;
pool_info.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
if (vkCreateCommandPool(*device, &pool_info, nullptr, &m_pool) !=
VK_SUCCESS) {
throw std::runtime_error(
"Failed to create staging buffer transfer command pool");
}
VkFenceCreateInfo fence_info{};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
if (vkCreateFence(*device, &fence_info, nullptr, &m_copy_fence) !=
VK_SUCCESS) {
throw std::runtime_error("Failed to create staging buffer fence");
};
};
StagingBuffer::~StagingBuffer() {
vkDestroyBuffer(*device, m_buffer, nullptr);
vkFreeMemory(*device, m_memory, nullptr);
vkDestroyFence(*device, m_copy_fence, nullptr);
vkDestroyCommandPool(*device, m_pool, nullptr);
}
VkCommandBuffer StagingBuffer::beginTransferCommand() {
VkCommandBufferAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
alloc_info.commandPool = m_pool;
alloc_info.commandBufferCount = 1;
alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
VkCommandBuffer command;
if (vkAllocateCommandBuffers(*device, &alloc_info, &command) !=
VK_SUCCESS) {
throw std::runtime_error(
"Failed to alloacte staging buffer transfer command buffer");
}
VkCommandBufferBeginInfo begin_info{};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
if (vkBeginCommandBuffer(command, &begin_info) != VK_SUCCESS) {
throw std::runtime_error(
"Failed to begin recording staging buffer transfer command");
}
return command;
}
void StagingBuffer::endTransferCommand(VkCommandBuffer command) {
if (vkEndCommandBuffer(command) != VK_SUCCESS) {
throw std::runtime_error(
"Failed to record staging buffer transfer command");
};
VkSubmitInfo submit_info{};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command;
if (vkQueueSubmit(device.queues.transfer, 1, &submit_info, m_copy_fence) !=
VK_SUCCESS) {
throw std::runtime_error(
"Failed to submit staging buffer transfer command");
}
waitFence();
vkFreeCommandBuffers(*device, m_pool, 1, &command);
}
void StagingBuffer::copyBuffer(Buffer& dst, VkDeviceSize offset,
const void* src, VkDeviceSize size) {
if (size > m_size) {
throw std::runtime_error(
"Not enough memory allocated for staging buffer");
}
if (dst.size() < offset + size) {
throw std::runtime_error("Invalid destination buffer offset");
}
void* map{};
vkMapMemory(*device, m_memory, 0, size, 0, &map);
std::memcpy(map, src, size);
vkUnmapMemory(*device, m_memory);
auto command = beginTransferCommand();
VkBufferCopy region{};
region.dstOffset = offset;
region.srcOffset = 0;
region.size = size;
vkCmdCopyBuffer(command, m_buffer, *dst, 1, ®ion);
endTransferCommand(command);
}
void StagingBuffer::copyImage(Image2D& dst, const std::vector<uint8_t>& src) {
if (src.size() > m_size) {
throw std::runtime_error(
"Not enough memory allocated for staging buffer");
}
void* map{};
vkMapMemory(*device, m_memory, 0, src.size(), 0, &map);
std::memcpy(map, src.data(), src.size());
vkUnmapMemory(*device, m_memory);
auto command = beginTransferCommand();
VkImageMemoryBarrier barier{};
barier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barier.image = *dst;
barier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barier.subresourceRange.baseArrayLayer = 0;
barier.subresourceRange.baseMipLevel = 0;
barier.subresourceRange.layerCount = 1;
barier.subresourceRange.levelCount = 1;
barier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
barier.srcAccessMask = 0;
barier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(command, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0,
nullptr, 1, &barier);
VkBufferImageCopy region{};
region.bufferImageHeight = dst.width();
region.bufferRowLength = dst.height();
region.bufferOffset = 0;
region.imageExtent = {dst.width(), dst.height(), 1};
region.imageOffset = {0, 0, 0};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
vkCmdCopyBufferToImage(command, m_buffer, *dst,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
barier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
barier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barier.dstAccessMask = 0;
vkCmdPipelineBarrier(command, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0,
nullptr, 1, &barier);
endTransferCommand(command);
}
void StagingBuffer::waitFence() {
if (vkWaitForFences(*device, 1, &m_copy_fence, VK_TRUE, UINT64_MAX) !=
VK_SUCCESS) {
throw std::runtime_error("Staging buffer fence timeout");
};
vkResetFences(*device, 1, &m_copy_fence);
}
Buffer::Buffer(Device& device, VkDeviceSize size, VkBufferUsageFlags usage,
const std::vector<uint32_t>& queue_families)
: device{device}, m_size{size} {
VkBufferCreateInfo buffer_info{};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.usage = usage;
buffer_info.size = m_size;
buffer_info.queueFamilyIndexCount = queue_families.size();
buffer_info.pQueueFamilyIndices = queue_families.data();
buffer_info.sharingMode = queue_families.size() != 1
? VK_SHARING_MODE_CONCURRENT
: VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(*device, &buffer_info, nullptr, &m_buffer) !=
VK_SUCCESS) {
throw std::runtime_error("Failed to create buffer");
}
}
Buffer::~Buffer() {
if (m_buffer != VK_NULL_HANDLE) {
vkDestroyBuffer(*device, m_buffer, nullptr);
}
}
void Buffer::bindMemory(VkDeviceMemory memory, VkDeviceSize offset) {
if (vkBindBufferMemory(*device, m_buffer, memory, offset) != VK_SUCCESS) {
throw std::runtime_error("Failed to bind buffer memory");
}
}
VkMemoryRequirements Buffer::memoryRequirements() const {
VkMemoryRequirements requirements{};
vkGetBufferMemoryRequirements(*device, m_buffer, &requirements);
return requirements;
}
} // namespace vks | 37.270386 | 80 | 0.700253 | [
"vector"
] |
ba677f72dbb6397306c7b220be792b7943861954 | 7,949 | cc | C++ | chrome/browser/sync/test/integration/single_client_workspace_desk_sync_test.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/sync/test/integration/single_client_workspace_desk_sync_test.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-03-13T10:32:53.000Z | 2019-03-13T11:05:30.000Z | chrome/browser/sync/test/integration/single_client_workspace_desk_sync_test.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/desk_template.h"
#include "base/guid.h"
#include "base/test/bind.h"
#include "base/test/simple_test_clock.h"
#include "chrome/browser/sync/desk_sync_service_factory.h"
#include "chrome/browser/sync/test/integration/sync_consent_optional_sync_test.h"
#include "chrome/browser/sync/test/integration/sync_integration_test_util.h"
#include "chrome/browser/sync/test/integration/sync_service_impl_harness.h"
#include "chrome/browser/sync/test/integration/workspace_desk_helper.h"
#include "chrome/browser/ui/browser.h"
#include "components/desks_storage/core/desk_model.h"
#include "components/desks_storage/core/desk_sync_service.h"
#include "components/sync/base/time.h"
#include "components/sync/protocol/entity_specifics.pb.h"
#include "components/sync/protocol/workspace_desk_specifics.pb.h"
#include "content/public/test/browser_test.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace {
using ash::DeskTemplate;
using desks_storage::DeskModel;
using desks_storage::DeskSyncService;
using sync_pb::WorkspaceDeskSpecifics;
constexpr char kUuidFormat[] = "9e186d5a-502e-49ce-9ee1-00000000000%d";
constexpr char kNameFormat[] = "template %d";
WorkspaceDeskSpecifics CreateWorkspaceDeskSpecifics(int templateIndex,
base::Time created_time) {
WorkspaceDeskSpecifics specifics;
specifics.set_uuid(base::StringPrintf(kUuidFormat, templateIndex));
specifics.set_name(base::StringPrintf(kNameFormat, templateIndex));
specifics.set_created_time_usec(
created_time.ToDeltaSinceWindowsEpoch().InMicroseconds());
return specifics;
}
// Desk Sync is a Chrome OS sync type.
// Therefore this class should subclass from SyncConsentOptionalSyncTest.
class SingleClientWorkspaceDeskSyncTest : public SyncConsentOptionalSyncTest {
public:
SingleClientWorkspaceDeskSyncTest()
: SyncConsentOptionalSyncTest(SINGLE_CLIENT) {
kTestUuid1_ =
base::GUID::ParseCaseInsensitive(base::StringPrintf(kUuidFormat, 1));
}
SingleClientWorkspaceDeskSyncTest(const SingleClientWorkspaceDeskSyncTest&) =
delete;
SingleClientWorkspaceDeskSyncTest& operator=(
const SingleClientWorkspaceDeskSyncTest&) = delete;
~SingleClientWorkspaceDeskSyncTest() override = default;
base::Time AdvanceAndGetTime(base::TimeDelta delta = base::Milliseconds(10)) {
clock_.Advance(delta);
return clock_.Now();
}
void DisableDeskSync() {
syncer::SyncService* service = GetSyncService(0);
if (chromeos::features::IsSyncSettingsCategorizationEnabled()) {
// Disable all OS types, including the desk sync type.
service->GetUserSettings()->SetSelectedOsTypes(
/*sync_all_os_types=*/false, syncer::UserSelectableOsTypeSet());
} else {
// Disable all user types, including the desk sync type.
service->GetUserSettings()->SetSelectedTypes(
/*sync_everything=*/false, syncer::UserSelectableTypeSet());
}
GetClient(0)->AwaitSyncSetupCompletion();
}
base::GUID kTestUuid1_;
private:
base::SimpleTestClock clock_;
};
IN_PROC_BROWSER_TEST_F(SingleClientWorkspaceDeskSyncTest,
DisablingOsSyncFeatureDisablesDataType) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
syncer::SyncService* service = GetSyncService(0);
syncer::SyncUserSettings* settings = service->GetUserSettings();
EXPECT_TRUE(settings->IsOsSyncFeatureEnabled());
EXPECT_TRUE(service->GetActiveDataTypes().Has(syncer::WORKSPACE_DESK));
settings->SetOsSyncFeatureEnabled(false);
EXPECT_FALSE(settings->IsOsSyncFeatureEnabled());
EXPECT_FALSE(service->GetActiveDataTypes().Has(syncer::WORKSPACE_DESK));
}
IN_PROC_BROWSER_TEST_F(SingleClientWorkspaceDeskSyncTest,
DownloadDeskTemplateWhenSyncEnabled) {
// Inject a test desk template to Sync.
sync_pb::EntitySpecifics specifics;
WorkspaceDeskSpecifics* desk = specifics.mutable_workspace_desk();
desk->CopyFrom(CreateWorkspaceDeskSpecifics(1, AdvanceAndGetTime()));
fake_server_->InjectEntity(
syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
"non_unique_name", kTestUuid1_.AsLowercaseString(), specifics,
/*creation_time=*/syncer::TimeToProtoTime(AdvanceAndGetTime()),
/*last_modified_time=*/syncer::TimeToProtoTime(AdvanceAndGetTime())));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
syncer::SyncService* sync_service = GetSyncService(0);
syncer::SyncUserSettings* settings = sync_service->GetUserSettings();
ASSERT_TRUE(settings->IsOsSyncFeatureEnabled());
ASSERT_TRUE(sync_service->GetActiveDataTypes().Has(syncer::WORKSPACE_DESK));
// Check the test desk template is downloaded.
EXPECT_TRUE(
workspace_desk_helper::DeskUuidChecker(
DeskSyncServiceFactory::GetForProfile(GetProfile(0)), kTestUuid1_)
.Wait());
}
IN_PROC_BROWSER_TEST_F(SingleClientWorkspaceDeskSyncTest, IsReady) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
EXPECT_TRUE(workspace_desk_helper::DeskModelReadyChecker(
DeskSyncServiceFactory::GetForProfile(GetProfile(0)))
.Wait());
}
IN_PROC_BROWSER_TEST_F(SingleClientWorkspaceDeskSyncTest, DeleteDeskTemplate) {
sync_pb::EntitySpecifics specifics;
WorkspaceDeskSpecifics* desk = specifics.mutable_workspace_desk();
desk->CopyFrom(CreateWorkspaceDeskSpecifics(1, AdvanceAndGetTime()));
fake_server_->InjectEntity(
syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting(
"non_unique_name", kTestUuid1_.AsLowercaseString(), specifics,
/*creation_time=*/syncer::TimeToProtoTime(AdvanceAndGetTime()),
/*last_modified_time=*/syncer::TimeToProtoTime(AdvanceAndGetTime())));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(
workspace_desk_helper::DeskUuidChecker(
DeskSyncServiceFactory::GetForProfile(GetProfile(0)), kTestUuid1_)
.Wait());
desks_storage::DeskModel* model =
DeskSyncServiceFactory::GetForProfile(GetProfile(0))->GetDeskModel();
// Delete template 1.
base::RunLoop loop;
model->DeleteEntry(
kTestUuid1_.AsLowercaseString(),
base::BindLambdaForTesting([&](DeskModel::DeleteEntryStatus status) {
EXPECT_EQ(DeskModel::DeleteEntryStatus::kOk, status);
loop.Quit();
}));
loop.Run();
EXPECT_TRUE(
workspace_desk_helper::DeskUuidDeletedChecker(
DeskSyncServiceFactory::GetForProfile(GetProfile(0)), kTestUuid1_)
.Wait());
}
IN_PROC_BROWSER_TEST_F(SingleClientWorkspaceDeskSyncTest,
ShouldAllowAddTemplateLocallyWhenSyncIsDisabled) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
DisableDeskSync();
EXPECT_FALSE(
GetSyncService(0)->GetActiveDataTypes().Has(syncer::WORKSPACE_DESK));
desks_storage::DeskModel* model =
DeskSyncServiceFactory::GetForProfile(GetProfile(0))->GetDeskModel();
ASSERT_FALSE(model->IsSyncing());
base::RunLoop loop;
model->AddOrUpdateEntry(
std::make_unique<DeskTemplate>(kTestUuid1_.AsLowercaseString(),
"template 1", AdvanceAndGetTime()),
base::BindLambdaForTesting([&](DeskModel::AddOrUpdateEntryStatus status) {
EXPECT_EQ(DeskModel::AddOrUpdateEntryStatus::kOk, status);
loop.Quit();
}));
loop.Run();
DeskSyncService* service =
DeskSyncServiceFactory::GetForProfile(GetProfile(0));
// Check the test desk template is added.
EXPECT_TRUE(
workspace_desk_helper::DeskUuidChecker(service, kTestUuid1_).Wait());
// There should be exactly one desk template.
EXPECT_EQ(1u, service->GetDeskModel()->GetEntryCount());
}
} // namespace
| 37.672986 | 81 | 0.741351 | [
"model"
] |
ba67f11c32a17dad152ba86e495b65b7aaa8013f | 8,539 | cpp | C++ | Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPoolResolver.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-12T14:13:45.000Z | 2022-03-12T14:13:45.000Z | Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPoolResolver.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Gems/Atom/RHI/Vulkan/Code/Source/RHI/BufferPoolResolver.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <RHI/Buffer.h>
#include <RHI/BufferPool.h>
#include <RHI/BufferPoolResolver.h>
#include <RHI/MemoryView.h>
#include <RHI/Conversion.h>
#include <algorithm>
namespace AZ
{
namespace Vulkan
{
BufferPoolResolver::BufferPoolResolver(Device& device, [[maybe_unused]] const RHI::BufferPoolDescriptor& descriptor)
: ResourcePoolResolver(device)
{
}
void* BufferPoolResolver::MapBuffer(const RHI::BufferMapRequest& request)
{
AZ_Assert(request.m_byteCount > 0, "ByteCount of request is null");
auto* buffer = static_cast<Buffer*>(request.m_buffer);
RHI::Ptr<Buffer> stagingBuffer = m_device.AcquireStagingBuffer(request.m_byteCount);
if (stagingBuffer)
{
m_uploadPacketsLock.lock();
m_uploadPackets.emplace_back();
BufferUploadPacket& uploadRequest = m_uploadPackets.back();
m_uploadPacketsLock.unlock();
uploadRequest.m_attachmentBuffer = buffer;
uploadRequest.m_byteOffset = request.m_byteOffset;
uploadRequest.m_stagingBuffer = stagingBuffer;
uploadRequest.m_byteSize = request.m_byteCount;
return stagingBuffer->GetBufferMemoryView()->Map(RHI::HostMemoryAccess::Write);
}
return nullptr;
}
void BufferPoolResolver::Compile(const RHI::HardwareQueueClass hardwareClass)
{
auto supportedQueuePipelineStages = m_device.GetCommandQueueContext().GetCommandQueue(hardwareClass).GetSupportedPipelineStages();
VkBufferMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.pNext = nullptr;
for (BufferUploadPacket& packet : m_uploadPackets)
{
packet.m_stagingBuffer->GetBufferMemoryView()->Unmap(RHI::HostMemoryAccess::Write);
// Filter stages and access flags
VkPipelineStageFlags bufferPipelineFlags = RHI::FilterBits(GetResourcePipelineStateFlags(packet.m_attachmentBuffer->GetDescriptor().m_bindFlags), supportedQueuePipelineStages);
VkAccessFlags bufferAccessFlags = RHI::FilterBits(GetResourceAccessFlags(packet.m_attachmentBuffer->GetDescriptor().m_bindFlags), GetSupportedAccessFlags(bufferPipelineFlags));
const BufferMemoryView* destBufferMemoryView = packet.m_attachmentBuffer->GetBufferMemoryView();
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.buffer = destBufferMemoryView->GetNativeBuffer();
barrier.offset = destBufferMemoryView->GetOffset() + packet.m_byteOffset;
barrier.size = packet.m_byteSize;
{
barrier.srcAccessMask = bufferAccessFlags;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
m_prologueBarriers.emplace_back();
BarrierInfo& barrierInfo = m_prologueBarriers.back();
barrierInfo.m_srcStageMask = bufferPipelineFlags;
barrierInfo.m_dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
barrierInfo.m_barrier = barrier;
}
{
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = bufferAccessFlags;
m_epilogueBarriers.emplace_back();
BarrierInfo& barrierInfo = m_epilogueBarriers.back();
barrierInfo.m_srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
barrierInfo.m_dstStageMask = bufferPipelineFlags;
barrierInfo.m_barrier = barrier;
}
}
}
void BufferPoolResolver::Resolve(CommandList& commandList)
{
auto& device = static_cast<Device&>(commandList.GetDevice());
VkBufferCopy bufCopy{};
for (const BufferUploadPacket& packet : m_uploadPackets)
{
Buffer* stagingBuffer = packet.m_stagingBuffer.get();
Buffer* destBuffer = packet.m_attachmentBuffer;
AZ_Assert(stagingBuffer, "Staging Buffer is null.");
AZ_Assert(destBuffer, "Attachment Buffer is null.");
RHI::CopyBufferDescriptor copyDescriptor;
copyDescriptor.m_sourceBuffer = stagingBuffer;
copyDescriptor.m_sourceOffset = 0;
copyDescriptor.m_destinationBuffer = destBuffer;
copyDescriptor.m_destinationOffset = static_cast<uint32_t>(packet.m_byteOffset);
copyDescriptor.m_size = static_cast<uint32_t>(packet.m_byteSize);
commandList.Submit(RHI::CopyItem(copyDescriptor));
device.QueueForRelease(stagingBuffer);
}
}
void BufferPoolResolver::Deactivate()
{
m_uploadPackets.clear();
m_epilogueBarriers.clear();
m_prologueBarriers.clear();
}
template<class T, class Predicate>
void EraseResourceFromList(AZStd::vector<T>& list, const Predicate& predicate)
{
list.erase(AZStd::remove_if(list.begin(), list.end(), predicate), list.end());
}
void BufferPoolResolver::OnResourceShutdown(const RHI::Resource& resource)
{
AZStd::lock_guard<AZStd::mutex> lock(m_uploadPacketsLock);
const Buffer* buffer = static_cast<const Buffer*>(&resource);
auto eraseBeginIt = std::stable_partition(
m_uploadPackets.begin(),
m_uploadPackets.end(),
[&buffer](const BufferUploadPacket& packet)
{
// We want the elements to erase at the back of the vector
// so we can easily erase them by resizing the vector.
return packet.m_attachmentBuffer != buffer;
}
);
for (auto it = eraseBeginIt; it != m_uploadPackets.end(); ++it)
{
it->m_stagingBuffer->GetBufferMemoryView()->Unmap(RHI::HostMemoryAccess::Write);
}
m_uploadPackets.resize(AZStd::distance(m_uploadPackets.begin(), eraseBeginIt));
auto predicateBarriers = [&buffer](const BarrierInfo& barrierInfo)
{
const BufferMemoryView* bufferView = buffer->GetBufferMemoryView();
if (barrierInfo.m_barrier.buffer != bufferView->GetNativeBuffer())
{
return false;
}
VkDeviceSize barrierBegin = barrierInfo.m_barrier.offset;
VkDeviceSize barrierEnd = barrierBegin + barrierInfo.m_barrier.size;
VkDeviceSize bufferBegin = bufferView->GetOffset();
VkDeviceSize bufferEnd = bufferBegin + bufferView->GetSize();
return barrierBegin < bufferEnd && bufferBegin < barrierEnd;
};
EraseResourceFromList(m_prologueBarriers, predicateBarriers);
EraseResourceFromList(m_epilogueBarriers, predicateBarriers);
}
void BufferPoolResolver::QueuePrologueTransitionBarriers(CommandList& commandList)
{
EmmitBarriers(commandList, m_prologueBarriers);
}
void BufferPoolResolver::QueueEpilogueTransitionBarriers(CommandList& commandList)
{
EmmitBarriers(commandList, m_epilogueBarriers);
}
void BufferPoolResolver::EmmitBarriers(CommandList& commandList, const AZStd::vector<BarrierInfo>& barriers) const
{
for (const BarrierInfo& barrierInfo : barriers)
{
vkCmdPipelineBarrier(
commandList.GetNativeCommandBuffer(),
barrierInfo.m_srcStageMask,
barrierInfo.m_dstStageMask,
0,
0,
nullptr,
1,
&barrierInfo.m_barrier,
0,
nullptr);
}
}
}
}
| 42.909548 | 192 | 0.608034 | [
"vector",
"3d"
] |
ba6c9ce89a8969bba822102278d7c9888339afca | 5,879 | cpp | C++ | export/release/windows/obj/src/Control.cpp | Plain-bot/BEAR-SRC | e817b352446c29e01ca6dd314a9c76edd41aa43e | [
"Apache-2.0"
] | null | null | null | export/release/windows/obj/src/Control.cpp | Plain-bot/BEAR-SRC | e817b352446c29e01ca6dd314a9c76edd41aa43e | [
"Apache-2.0"
] | null | null | null | export/release/windows/obj/src/Control.cpp | Plain-bot/BEAR-SRC | e817b352446c29e01ca6dd314a9c76edd41aa43e | [
"Apache-2.0"
] | null | null | null | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_Control
#include <Control.h>
#endif
::Control Control_obj::ACCEPT;
::Control Control_obj::BACK;
::Control Control_obj::NOTE_DOWN;
::Control Control_obj::NOTE_LEFT;
::Control Control_obj::NOTE_RIGHT;
::Control Control_obj::NOTE_UP;
::Control Control_obj::PAUSE;
::Control Control_obj::RESET;
::Control Control_obj::UI_DOWN;
::Control Control_obj::UI_LEFT;
::Control Control_obj::UI_RIGHT;
::Control Control_obj::UI_UP;
bool Control_obj::__GetStatic(const ::String &inName, ::Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
if (inName==HX_("ACCEPT",08,3f,89,bd)) { outValue = Control_obj::ACCEPT; return true; }
if (inName==HX_("BACK",27,a2,d1,2b)) { outValue = Control_obj::BACK; return true; }
if (inName==HX_("NOTE_DOWN",0f,ef,09,08)) { outValue = Control_obj::NOTE_DOWN; return true; }
if (inName==HX_("NOTE_LEFT",b4,fe,4b,0d)) { outValue = Control_obj::NOTE_LEFT; return true; }
if (inName==HX_("NOTE_RIGHT",6f,ec,3f,0c)) { outValue = Control_obj::NOTE_RIGHT; return true; }
if (inName==HX_("NOTE_UP",c8,83,48,cd)) { outValue = Control_obj::NOTE_UP; return true; }
if (inName==HX_("PAUSE",d6,0e,46,3b)) { outValue = Control_obj::PAUSE; return true; }
if (inName==HX_("RESET",af,81,b6,64)) { outValue = Control_obj::RESET; return true; }
if (inName==HX_("UI_DOWN",6d,a1,ed,de)) { outValue = Control_obj::UI_DOWN; return true; }
if (inName==HX_("UI_LEFT",12,b1,2f,e4)) { outValue = Control_obj::UI_LEFT; return true; }
if (inName==HX_("UI_RIGHT",51,4c,98,3c)) { outValue = Control_obj::UI_RIGHT; return true; }
if (inName==HX_("UI_UP",a6,42,98,21)) { outValue = Control_obj::UI_UP; return true; }
return super::__GetStatic(inName, outValue, inCallProp);
}
HX_DEFINE_CREATE_ENUM(Control_obj)
int Control_obj::__FindIndex(::String inName)
{
if (inName==HX_("ACCEPT",08,3f,89,bd)) return 9;
if (inName==HX_("BACK",27,a2,d1,2b)) return 10;
if (inName==HX_("NOTE_DOWN",0f,ef,09,08)) return 7;
if (inName==HX_("NOTE_LEFT",b4,fe,4b,0d)) return 5;
if (inName==HX_("NOTE_RIGHT",6f,ec,3f,0c)) return 6;
if (inName==HX_("NOTE_UP",c8,83,48,cd)) return 4;
if (inName==HX_("PAUSE",d6,0e,46,3b)) return 11;
if (inName==HX_("RESET",af,81,b6,64)) return 8;
if (inName==HX_("UI_DOWN",6d,a1,ed,de)) return 3;
if (inName==HX_("UI_LEFT",12,b1,2f,e4)) return 1;
if (inName==HX_("UI_RIGHT",51,4c,98,3c)) return 2;
if (inName==HX_("UI_UP",a6,42,98,21)) return 0;
return super::__FindIndex(inName);
}
int Control_obj::__FindArgCount(::String inName)
{
if (inName==HX_("ACCEPT",08,3f,89,bd)) return 0;
if (inName==HX_("BACK",27,a2,d1,2b)) return 0;
if (inName==HX_("NOTE_DOWN",0f,ef,09,08)) return 0;
if (inName==HX_("NOTE_LEFT",b4,fe,4b,0d)) return 0;
if (inName==HX_("NOTE_RIGHT",6f,ec,3f,0c)) return 0;
if (inName==HX_("NOTE_UP",c8,83,48,cd)) return 0;
if (inName==HX_("PAUSE",d6,0e,46,3b)) return 0;
if (inName==HX_("RESET",af,81,b6,64)) return 0;
if (inName==HX_("UI_DOWN",6d,a1,ed,de)) return 0;
if (inName==HX_("UI_LEFT",12,b1,2f,e4)) return 0;
if (inName==HX_("UI_RIGHT",51,4c,98,3c)) return 0;
if (inName==HX_("UI_UP",a6,42,98,21)) return 0;
return super::__FindArgCount(inName);
}
::hx::Val Control_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
if (inName==HX_("ACCEPT",08,3f,89,bd)) return ACCEPT;
if (inName==HX_("BACK",27,a2,d1,2b)) return BACK;
if (inName==HX_("NOTE_DOWN",0f,ef,09,08)) return NOTE_DOWN;
if (inName==HX_("NOTE_LEFT",b4,fe,4b,0d)) return NOTE_LEFT;
if (inName==HX_("NOTE_RIGHT",6f,ec,3f,0c)) return NOTE_RIGHT;
if (inName==HX_("NOTE_UP",c8,83,48,cd)) return NOTE_UP;
if (inName==HX_("PAUSE",d6,0e,46,3b)) return PAUSE;
if (inName==HX_("RESET",af,81,b6,64)) return RESET;
if (inName==HX_("UI_DOWN",6d,a1,ed,de)) return UI_DOWN;
if (inName==HX_("UI_LEFT",12,b1,2f,e4)) return UI_LEFT;
if (inName==HX_("UI_RIGHT",51,4c,98,3c)) return UI_RIGHT;
if (inName==HX_("UI_UP",a6,42,98,21)) return UI_UP;
return super::__Field(inName,inCallProp);
}
static ::String Control_obj_sStaticFields[] = {
HX_("UI_UP",a6,42,98,21),
HX_("UI_LEFT",12,b1,2f,e4),
HX_("UI_RIGHT",51,4c,98,3c),
HX_("UI_DOWN",6d,a1,ed,de),
HX_("NOTE_UP",c8,83,48,cd),
HX_("NOTE_LEFT",b4,fe,4b,0d),
HX_("NOTE_RIGHT",6f,ec,3f,0c),
HX_("NOTE_DOWN",0f,ef,09,08),
HX_("RESET",af,81,b6,64),
HX_("ACCEPT",08,3f,89,bd),
HX_("BACK",27,a2,d1,2b),
HX_("PAUSE",d6,0e,46,3b),
::String(null())
};
::hx::Class Control_obj::__mClass;
Dynamic __Create_Control_obj() { return new Control_obj; }
void Control_obj::__register()
{
::hx::Static(__mClass) = ::hx::_hx_RegisterClass(HX_("Control",3d,93,d2,e6), ::hx::TCanCast< Control_obj >,Control_obj_sStaticFields,0,
&__Create_Control_obj, &__Create,
&super::__SGetClass(), &CreateControl_obj, 0
#ifdef HXCPP_VISIT_ALLOCS
, 0
#endif
#ifdef HXCPP_SCRIPTABLE
, 0
#endif
);
__mClass->mGetStaticField = &Control_obj::__GetStatic;
}
void Control_obj::__boot()
{
ACCEPT = ::hx::CreateConstEnum< Control_obj >(HX_("ACCEPT",08,3f,89,bd),9);
BACK = ::hx::CreateConstEnum< Control_obj >(HX_("BACK",27,a2,d1,2b),10);
NOTE_DOWN = ::hx::CreateConstEnum< Control_obj >(HX_("NOTE_DOWN",0f,ef,09,08),7);
NOTE_LEFT = ::hx::CreateConstEnum< Control_obj >(HX_("NOTE_LEFT",b4,fe,4b,0d),5);
NOTE_RIGHT = ::hx::CreateConstEnum< Control_obj >(HX_("NOTE_RIGHT",6f,ec,3f,0c),6);
NOTE_UP = ::hx::CreateConstEnum< Control_obj >(HX_("NOTE_UP",c8,83,48,cd),4);
PAUSE = ::hx::CreateConstEnum< Control_obj >(HX_("PAUSE",d6,0e,46,3b),11);
RESET = ::hx::CreateConstEnum< Control_obj >(HX_("RESET",af,81,b6,64),8);
UI_DOWN = ::hx::CreateConstEnum< Control_obj >(HX_("UI_DOWN",6d,a1,ed,de),3);
UI_LEFT = ::hx::CreateConstEnum< Control_obj >(HX_("UI_LEFT",12,b1,2f,e4),1);
UI_RIGHT = ::hx::CreateConstEnum< Control_obj >(HX_("UI_RIGHT",51,4c,98,3c),2);
UI_UP = ::hx::CreateConstEnum< Control_obj >(HX_("UI_UP",a6,42,98,21),0);
}
| 37.929032 | 135 | 0.689233 | [
"3d"
] |
ba6ed1e18f0eabbabf86fa3a5df79111fd73560c | 2,513 | cpp | C++ | Vectors.cpp | sidd5sci/Vectors | 6451ea3d9acaf0c81af994e90ff22f3995044a8a | [
"Apache-2.0"
] | null | null | null | Vectors.cpp | sidd5sci/Vectors | 6451ea3d9acaf0c81af994e90ff22f3995044a8a | [
"Apache-2.0"
] | null | null | null | Vectors.cpp | sidd5sci/Vectors | 6451ea3d9acaf0c81af994e90ff22f3995044a8a | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 Siddhartha singh sidd5sci@gmail.com
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<cmath>
class Vector {
protected float x;
protected float y;
protected float z;
/*
* initilize the vector
*/
public Vector(int x, int y,int z) {
this.x = x;
this.y = y;
this.z = z;
}
/*
* Add two vector
*/
public void add(Vector vector) {
this.x += vector.x;
this.y += vector.y;
this.z += vector.z;
}
/*
* substract two vectors
*/
public void sub(Vector vector) {
this.x -= vector.x;
this.y -= vector.y;
this.z -= vector.z;
}
/*
* multiply two vectors
*/
public void mul(Vector vector) {
this.x *= vector.x;
this.y *= vector.y;
this.z *= vector.z;
}
/*
* Divide two vectors
*/
public void div(Vector vector) {
this.x /= vector.x;
this.y /= vector.y;
this.z /= vector.z;
}
/*
* dot product of the two vectors
*/
public float dot(Vector vector){
float x = (this.x *vector.x)-(this.z*vector.y);
float y = this.y *vector.y;
return x+y;
}
/*
* Return the vector by multiplying the two vectors
*/
public Vector cross(Vector vector){
float x = (vctr.y*self.z - vctr.z*self.y)
float y = (vctr.x*self.z - vctr.z*self.x)
float z = (vctr.x*self.y - vctr.y*self.x)
Vector v = new Vector(x,y);
return v;
}
/*
* calculate the magnitude of the vector and return it
*/
public float calMag(){
return math.sqrt((this.x*this.x)+(this.y*this.y)+(this.z*this.z));
}
/*
* Normalise the vector
*/
public void normalise(){
this.x /= this.calMag();
this.y /= this.calMag();
this.z /= this.calMag();
}
};
| 24.398058 | 75 | 0.54238 | [
"vector"
] |
ba6ef10f830d44dd52ac01eca51f1034f4bb8947 | 13,470 | cpp | C++ | Source/Voxel/Private/VoxelRender/Renderers/VoxelRendererClusteredMeshHandler.cpp | RobertBiehl/VoxelPlugin | 49abc94261b3d93c9d8fe392a3731b6d09100941 | [
"MIT"
] | null | null | null | Source/Voxel/Private/VoxelRender/Renderers/VoxelRendererClusteredMeshHandler.cpp | RobertBiehl/VoxelPlugin | 49abc94261b3d93c9d8fe392a3731b6d09100941 | [
"MIT"
] | null | null | null | Source/Voxel/Private/VoxelRender/Renderers/VoxelRendererClusteredMeshHandler.cpp | RobertBiehl/VoxelPlugin | 49abc94261b3d93c9d8fe392a3731b6d09100941 | [
"MIT"
] | null | null | null | // Copyright 2020 Phyronnaz
#include "VoxelRendererClusteredMeshHandler.h"
#include "VoxelRender/IVoxelRenderer.h"
#include "VoxelRender/VoxelProceduralMeshComponent.h"
#include "VoxelRender/VoxelChunkMaterials.h"
#include "VoxelRender/VoxelChunkMesh.h"
#include "VoxelRender/VoxelProcMeshBuffers.h"
#include "VoxelDebug/VoxelDebugManager.h"
#include "VoxelThreadingUtilities.h"
#include "IVoxelPool.h"
#include "VoxelAsyncWork.h"
#include "Async/Async.h"
class FVoxelClusteredMeshMergeWork : public FVoxelAsyncWork
{
public:
static FVoxelClusteredMeshMergeWork* Create(
FVoxelRendererClusteredMeshHandler& Handler,
FVoxelRendererClusteredMeshHandler::FClusterRef ClusterRef)
{
auto* Cluster = Handler.GetCluster(ClusterRef);
check(Cluster);
return new FVoxelClusteredMeshMergeWork(
ClusterRef,
Cluster->Position,
Handler,
Cluster->UpdateIndex.ToSharedRef(),
Cluster->ChunkMeshesToBuild);
}
private:
const FVoxelRendererClusteredMeshHandler::FClusterRef ClusterRef;
const FIntVector Position;
const FVoxelRendererSettingsBase RendererSettings;
const TVoxelWeakPtr<FVoxelRendererClusteredMeshHandler> Handler;
const TMap<uint64, TVoxelSharedPtr<const FVoxelChunkMeshesToBuild>> MeshesToBuild;
const TVoxelSharedRef<FThreadSafeCounter> UpdateIndexPtr;
const int32 UpdateIndex;
FVoxelClusteredMeshMergeWork(
FVoxelRendererClusteredMeshHandler::FClusterRef ClusterRef,
const FIntVector& Position,
FVoxelRendererClusteredMeshHandler& Handler,
const TVoxelSharedRef<FThreadSafeCounter>& UpdateIndexPtr,
const TMap<uint64, TVoxelSharedPtr<const FVoxelChunkMeshesToBuild>>& MeshesToBuild)
: FVoxelAsyncWork(STATIC_FNAME("FVoxelClusteredMeshMergeWork"), 1e9, true)
, ClusterRef(ClusterRef)
, Position(Position)
, RendererSettings(static_cast<const FVoxelRendererSettingsBase&>(Handler.Renderer.Settings))
, Handler(StaticCastVoxelSharedRef<FVoxelRendererClusteredMeshHandler>(Handler.AsShared()))
, MeshesToBuild(MeshesToBuild)
, UpdateIndexPtr(UpdateIndexPtr)
, UpdateIndex(UpdateIndexPtr->GetValue())
{
}
~FVoxelClusteredMeshMergeWork() = default;
virtual uint32 GetPriority() const override
{
return 0;
}
virtual void DoWork() override
{
if (UpdateIndexPtr->GetValue() > UpdateIndex)
{
// Canceled
return;
}
FVoxelChunkMeshesToBuild RealMap;
for (auto& ChunkIt : MeshesToBuild)
{
// Key is ChunkId = useless here
for (auto& MeshIt : *ChunkIt.Value)
{
auto& MeshMap = RealMap.FindOrAdd(MeshIt.Key);
for (auto& SectionIt : MeshIt.Value)
{
MeshMap.FindOrAdd(SectionIt.Key).Append(SectionIt.Value);
}
}
}
auto BuiltMeshes = FVoxelRenderUtilities::BuildMeshes_AnyThread(RealMap, RendererSettings, Position, *UpdateIndexPtr, UpdateIndex);
if (!BuiltMeshes.IsValid())
{
// Canceled
return;
}
auto HandlerPinned = Handler.Pin();
if (HandlerPinned.IsValid())
{
// Queue callback
HandlerPinned->MeshMergeCallback(ClusterRef, UpdateIndex, MoveTemp(BuiltMeshes));
FVoxelUtilities::DeleteOnGameThread_AnyThread(HandlerPinned);
}
}
};
FVoxelRendererClusteredMeshHandler::~FVoxelRendererClusteredMeshHandler()
{
FlushBuiltDataQueue();
FlushActionQueue(MAX_dbl);
ensure(ChunkInfos.Num() == 0);
ensure(Clusters.Num() == 0);
}
IVoxelRendererMeshHandler::FChunkId FVoxelRendererClusteredMeshHandler::AddChunkImpl(int32 LOD, const FIntVector& Position)
{
return ChunkInfos.Add(FChunkInfo::Create(LOD, Position));
}
void FVoxelRendererClusteredMeshHandler::ApplyAction(const FAction& Action)
{
VOXEL_FUNCTION_COUNTER();
const FChunkId ChunkId{ Action.ChunkId };
switch (Action.Action)
{
case EAction::UpdateChunk:
{
check(Action.UpdateChunk().InitialCall.MainChunk);
const auto& MainChunk = *Action.UpdateChunk().InitialCall.MainChunk;
const auto* TransitionChunk = Action.UpdateChunk().InitialCall.TransitionChunk;
// This should never happen, as the chunk should be removed instead
ensure(!MainChunk.IsEmpty() || (TransitionChunk && !TransitionChunk->IsEmpty()));
auto& ChunkInfo = ChunkInfos[ChunkId];
if (!ChunkInfo.ClusterId.IsValid())
{
const FClusterRef ClusterRef = FindOrCreateCluster(ChunkInfo.LOD, ChunkInfo.Position);
ChunkInfo.ClusterId = ClusterRef.ClusterId;
Clusters[ChunkInfo.ClusterId].NumChunks++;
}
auto& Cluster = Clusters[ChunkInfo.ClusterId];
if (!Cluster.Materials.IsValid())
{
Cluster.Materials = MakeShared<FVoxelChunkMaterials>();
}
if (!Cluster.UpdateIndex.IsValid())
{
Cluster.UpdateIndex = MakeVoxelShared<FThreadSafeCounter>();
}
// Cancel any previous build task
// Note: we do not clear the built data, as it could still be used
// The added cost of applying the update is probably worth it compared to stalling the entire queue waiting for an update
Cluster.UpdateIndex->Increment();
// Find the meshes to build (= copying & merging mesh buffers to proc mesh buffers)
FVoxelChunkMeshesToBuild MeshesToBuild = FVoxelRenderUtilities::GetMeshesToBuild(
ChunkInfo.LOD,
ChunkInfo.Position,
Renderer.Settings,
Action.UpdateChunk().InitialCall.ChunkSettings,
*Cluster.Materials,
MainChunk,
TransitionChunk,
Renderer.OnMaterialInstanceCreated,
{});
Cluster.ChunkMeshesToBuild.FindOrAdd(ChunkInfo.UniqueId) = MakeVoxelShared<FVoxelChunkMeshesToBuild>(MoveTemp(MeshesToBuild));
// Start a task to asynchronously build them
auto* Task = FVoxelClusteredMeshMergeWork::Create(*this, { ChunkInfo.ClusterId, Cluster.UniqueId });
Renderer.Settings.Pool->QueueTask(EVoxelTaskType::MeshMerge, Task);
FAction NewAction;
NewAction.Action = EAction::UpdateChunk;
NewAction.ChunkId = Action.ChunkId;
NewAction.UpdateChunk().AfterCall.UpdateIndex = Cluster.UpdateIndex->GetValue();
NewAction.UpdateChunk().AfterCall.DistanceFieldVolumeData = Action.UpdateChunk().InitialCall.MainChunk->GetDistanceFieldVolumeData();
ActionQueue.Enqueue(NewAction);
break;
}
case EAction::RemoveChunk:
{
auto& ChunkInfo = ChunkInfos[Action.ChunkId];
if (!ChunkInfo.ClusterId.IsValid())
{
// No cluster = no mesh, just remove it
ChunkInfos.RemoveAt(Action.ChunkId);
return;
}
// For remove, we trigger an update
// and then queue a remove action
auto& Cluster = Clusters[ChunkInfo.ClusterId];
// Cancel any previous build task
// Note: we do not clear the built data, as it could still be used
// The added cost of applying the update is probably worth it compared to stalling the entire queue waiting for an update
Cluster.UpdateIndex->Increment();
ensure(Cluster.ChunkMeshesToBuild.Remove(ChunkInfo.UniqueId) == 1); // We must have some mesh
// Start a task to asynchronously build them
auto* Task = FVoxelClusteredMeshMergeWork::Create(*this, { ChunkInfo.ClusterId, Cluster.UniqueId });
Renderer.Settings.Pool->QueueTask(EVoxelTaskType::MeshMerge, Task);
FAction NewAction;
NewAction.Action = EAction::UpdateChunk;
NewAction.ChunkId = Action.ChunkId;
NewAction.UpdateChunk().AfterCall.UpdateIndex = Cluster.UpdateIndex->GetValue();
NewAction.UpdateChunk().AfterCall.DistanceFieldVolumeData = nullptr;
ActionQueue.Enqueue(NewAction);
// Enqueue remove as well
ActionQueue.Enqueue(Action);
}
case EAction::SetTransitionsMaskForSurfaceNets:
{
break;
}
case EAction::DitherChunk:
case EAction::ResetDithering:
// These 2 should be done by an UpdateChunk
case EAction::HideChunk:
case EAction::ShowChunk:
default: ensure(false);
}
}
void FVoxelRendererClusteredMeshHandler::ClearChunkMaterials()
{
for (auto& Cluster : Clusters)
{
if (Cluster.Materials.IsValid())
{
Cluster.Materials->Reset();
}
}
}
void FVoxelRendererClusteredMeshHandler::Tick(double MaxTime)
{
VOXEL_FUNCTION_COUNTER();
IVoxelRendererMeshHandler::Tick(MaxTime);
FlushBuiltDataQueue();
FlushActionQueue(MaxTime);
Renderer.Settings.DebugManager->ReportMeshActionQueueNum(ActionQueue.Num());
}
FVoxelRendererClusteredMeshHandler::FClusterRef FVoxelRendererClusteredMeshHandler::FindOrCreateCluster(
int32 LOD,
const FIntVector& Position)
{
const int32 Divisor = FMath::Clamp<uint64>(uint64(Renderer.Settings.ChunksClustersSize) << LOD, 1, MAX_int32);
const FIntVector Key = FVoxelUtilities::DivideFloor(Position, Divisor);
auto& ClusterRef = ClustersMap[LOD].FindOrAdd(Key);
if (!GetCluster(ClusterRef))
{
ClusterRef.ClusterId = Clusters.Add(FCluster::Create(LOD, Key * Divisor));
ClusterRef.UniqueId = Clusters[ClusterRef.ClusterId].UniqueId;
}
check(GetCluster(ClusterRef));
return ClusterRef;
}
void FVoxelRendererClusteredMeshHandler::FlushBuiltDataQueue()
{
VOXEL_FUNCTION_COUNTER();
// Copy built data from async task callbacks to the chunk infos
// Should be fast enough to not require checking the time
FBuildCallback Callback;
while (CallbackQueue.Dequeue(Callback))
{
auto& BuiltData = Callback.BuiltData;
if (!ensure(BuiltData.BuiltMeshes.IsValid())) continue;
auto* Cluster = GetCluster(Callback.ClusterRef);
if (Cluster && BuiltData.UpdateIndex >= Cluster->UpdateIndex->GetValue())
{
// Not outdated
ensure(BuiltData.UpdateIndex == Cluster->UpdateIndex->GetValue());
Cluster->BuiltData = MoveTemp(BuiltData);
}
}
}
void FVoxelRendererClusteredMeshHandler::FlushActionQueue(double MaxTime)
{
VOXEL_FUNCTION_COUNTER();
FAction Action;
// Peek: if UpdateChunk isn't ready yet we don't want to pop the action
while (ActionQueue.Peek(Action) && FPlatformTime::Seconds() < MaxTime)
{
auto& ChunkInfo = ChunkInfos[Action.ChunkId];
if (IsDestroying() && Action.Action != EAction::RemoveChunk)
{
ActionQueue.Pop();
continue;
}
switch (Action.Action)
{
case EAction::UpdateChunk:
{
if (!ensure(ChunkInfo.ClusterId.IsValid())) continue; // Not possible if UpdateChunk was called
auto& Cluster = Clusters[ChunkInfo.ClusterId];
const int32 WantedUpdateIndex = Action.UpdateChunk().AfterCall.UpdateIndex;
if (Cluster.MeshUpdateIndex >= WantedUpdateIndex)
{
// Already updated
// This happens when a previous UpdateChunk used the built data we triggered
break;
}
if (WantedUpdateIndex > Cluster.BuiltData.UpdateIndex)
{
// Not built yet, wait
if (Cluster.BuiltData.UpdateIndex != -1)
{
// Stored built data is outdated, clear it to save memory
ensure(Cluster.BuiltData.BuiltMeshes.IsValid());
Cluster.BuiltData.BuiltMeshes.Reset();
Cluster.BuiltData.UpdateIndex = -1;
}
return;
}
// Move to clear the built data value
const auto BuiltMeshes = MoveTemp(Cluster.BuiltData.BuiltMeshes);
Cluster.MeshUpdateIndex = Cluster.BuiltData.UpdateIndex;
Cluster.BuiltData.UpdateIndex = -1;
if (!ensure(BuiltMeshes.IsValid())) continue;
int32 MeshIndex = 0;
CleanUp(Cluster.Meshes);
// Apply built meshes
for (auto& BuiltMesh : *BuiltMeshes)
{
const FVoxelMeshConfig& MeshConfig = BuiltMesh.Key;
if (Cluster.Meshes.Num() <= MeshIndex)
{
// Not enough meshes to render the built mesh, allocate new ones
auto* NewMesh = GetNewMesh(Action.ChunkId, Cluster.Position, Cluster.LOD);
if (!ensure(NewMesh)) return;
Cluster.Meshes.Add(NewMesh);
}
auto& Mesh = *Cluster.Meshes[MeshIndex];
MeshConfig.ApplyTo(Mesh);
Mesh.SetDistanceFieldData(nullptr);
Mesh.ClearSections(EVoxelProcMeshSectionUpdate::DelayUpdate);
for (auto& Section : BuiltMesh.Value)
{
Mesh.AddProcMeshSection(Section.Key, MoveTemp(Section.Value), EVoxelProcMeshSectionUpdate::DelayUpdate);
}
Mesh.FinishSectionsUpdates();
MeshIndex++;
}
// Clear unused meshes
for (; MeshIndex < Cluster.Meshes.Num(); MeshIndex++)
{
auto& Mesh = *Cluster.Meshes[MeshIndex];
Mesh.SetDistanceFieldData(nullptr);
Mesh.ClearSections(EVoxelProcMeshSectionUpdate::UpdateNow);
}
// Handle distance fields
const auto& DistanceFieldVolumeData = Action.UpdateChunk().AfterCall.DistanceFieldVolumeData;
if (DistanceFieldVolumeData.IsValid())
{
#if 0
// Use the first mesh to hold the distance field data
// We should always have at least one mesh, else the chunk should have been removed instead of updated
if (ensure(Cluster.Meshes.Num() > 0))
{
Cluster.Meshes[0]->SetDistanceFieldData(DistanceFieldVolumeData);
}
#endif
// TODO: No distance fields with merging = on
}
break;
}
case EAction::RemoveChunk:
{
if (ChunkInfo.ClusterId.IsValid())
{
auto& Cluster = Clusters[ChunkInfo.ClusterId];
Cluster.NumChunks--;
ensure(Cluster.NumChunks >= 0);
if (Cluster.NumChunks == 0)
{
for (auto& Mesh : CleanUp(Cluster.Meshes))
{
RemoveMesh(*Mesh);
}
Clusters.RemoveAt(ChunkInfo.ClusterId);
}
}
ChunkInfos.RemoveAt(Action.ChunkId);
break;
}
case EAction::ShowChunk:
case EAction::HideChunk:
case EAction::SetTransitionsMaskForSurfaceNets:
case EAction::DitherChunk:
case EAction::ResetDithering:
default: ensure(false);
}
if (CVarLogActionQueue.GetValueOnGameThread() != 0)
{
LOG_VOXEL(Log, TEXT("ActionQueue: LOD: %d; %s; Position: %s"), ChunkInfo.LOD, *Action.ToString(), *ChunkInfo.Position.ToString());
}
ActionQueue.Pop();
}
}
void FVoxelRendererClusteredMeshHandler::MeshMergeCallback(FClusterRef ClusterRef, int32 UpdateIndex, TUniquePtr<FVoxelBuiltChunkMeshes> BuiltMeshes)
{
CallbackQueue.Enqueue({ ClusterRef, FClusterBuiltData{ UpdateIndex, MoveTemp(BuiltMeshes) } });
} | 30.965517 | 149 | 0.746696 | [
"mesh",
"render"
] |
ba71fa6140a68d30347b4a7ccbe78c02928fa5f6 | 2,335 | cpp | C++ | test/structure/container/binary_heap_test.cpp | plamenko/altruct | e16fc162043933fbe282fe01a44e0c908df4f612 | [
"MIT"
] | 66 | 2016-10-18T20:37:09.000Z | 2021-11-28T09:56:41.000Z | test/structure/container/binary_heap_test.cpp | plamenko/altruct | e16fc162043933fbe282fe01a44e0c908df4f612 | [
"MIT"
] | null | null | null | test/structure/container/binary_heap_test.cpp | plamenko/altruct | e16fc162043933fbe282fe01a44e0c908df4f612 | [
"MIT"
] | 4 | 2018-02-11T17:56:03.000Z | 2019-01-18T15:41:15.000Z | #include "altruct/structure/container/binary_heap.h"
#include "altruct/algorithm/collections/collections.h"
#include "altruct/io/iostream_overloads.h"
#include "gtest/gtest.h"
using namespace std;
using namespace altruct::container;
using namespace altruct::collections;
namespace {
template<typename T>
void verify_structure(const binary_heap<T>& bh, const vector<T>& v) {
for (size_t i = bh.size() - 1; i > 0; i--) {
EXPECT_FALSE(bh.cmp(bh.v[i], bh.v[(i - 1) / 2])) << "incorrect parent-child order";
}
EXPECT_EQ(sorted(v), sorted(bh.v));
}
}
TEST(binary_heap_test, constructor) {
vector<int> v1(100); for (int& a : v1) a = rand() % 10;
vector<int> v2(110); for (int& a : v2) a = rand() % 1000000000;
binary_heap<int>bh1(v1); verify_structure(bh1, v1);
binary_heap<int>bh2(v2); verify_structure(bh2, v2);
EXPECT_EQ(100, bh1.size());
EXPECT_EQ(110, bh2.size());
}
TEST(binary_heap_test, insert) {
vector<int> v1;
binary_heap<int>bh1;
for (int i = 0; i < 100; i++) {
int a = rand() % 10;
v1.push_back(a);
bh1.insert(a);
}
verify_structure(bh1, v1);
}
TEST(binary_heap_test, pop_front) {
vector<int> v1(100); for (int& a : v1) a = rand() % 10;
binary_heap<int>bh1(v1);
vector<int> s1;
for (; bh1.size() > 0; bh1.pop_front()) {
s1.push_back(bh1.front());
}
EXPECT_EQ(sorted(v1), s1);
}
TEST(binary_heap_test, sort) {
vector<int> v1(100); for (int& a : v1) a = rand() % 10;
binary_heap<int> bh1(v1);
bh1.sort();
EXPECT_EQ(sorted(v1), bh1.v);
}
TEST(binary_heap_test, test_perf) {
return; // disable by default
vector<int> va(10000000);
for (int& a : va) a = rand() % 10;
auto T0 = clock();
binary_heap<int> bh(va);
bh.sort();
auto dT0 = clock() - T0;
printf("%0.3lf s\n", dT0/double(CLOCKS_PER_SEC));
// mod10 1448 ms
// any 3723 ms
auto T1 = clock();
sort(va.begin(), va.end());
auto dT1 = clock() - T1;
printf("%0.3lf s\n", dT1/double(CLOCKS_PER_SEC));
// mod10 162 ms
// any 815 ms
if (bh.v != va) {
printf("ERROR\n");
//cout << va << endl;
//cout << bh.v << endl;
}
}
| 27.151163 | 96 | 0.5606 | [
"vector"
] |
ba740017c24c839f042cd710fccbc0162e79e345 | 8,158 | cpp | C++ | Source/Falcor/Scene/Material/StandardMaterial.cpp | mistralk/Falcor | 49621cc8484bdd5887886b191c2dbde91693ec6a | [
"BSD-3-Clause"
] | null | null | null | Source/Falcor/Scene/Material/StandardMaterial.cpp | mistralk/Falcor | 49621cc8484bdd5887886b191c2dbde91693ec6a | [
"BSD-3-Clause"
] | null | null | null | Source/Falcor/Scene/Material/StandardMaterial.cpp | mistralk/Falcor | 49621cc8484bdd5887886b191c2dbde91693ec6a | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
# Copyright (c) 2015-21, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************/
#include "stdafx.h"
#include "StandardMaterial.h"
namespace Falcor
{
StandardMaterial::SharedPtr StandardMaterial::create(const std::string& name, ShadingModel shadingModel)
{
return SharedPtr(new StandardMaterial(name, shadingModel));
}
StandardMaterial::StandardMaterial(const std::string& name, ShadingModel shadingModel)
: BasicMaterial(name, MaterialType::Standard)
{
setShadingModel(shadingModel);
bool specGloss = getShadingModel() == ShadingModel::SpecGloss;
// Setup additional texture slots.
mTextureSlotInfo[(uint32_t)TextureSlot::BaseColor] = { specGloss ? "diffuse" : "baseColor", TextureChannelFlags::RGBA, true };
mTextureSlotInfo[(uint32_t)TextureSlot::Specular] = specGloss ? TextureSlotInfo{ "specular", TextureChannelFlags::RGBA, true } : TextureSlotInfo{ "spec", TextureChannelFlags::Green | TextureChannelFlags::Blue, false };
mTextureSlotInfo[(uint32_t)TextureSlot::Normal] = { "normal", TextureChannelFlags::RGB, false };
mTextureSlotInfo[(uint32_t)TextureSlot::Emissive] = { "emissive", TextureChannelFlags::RGB, true };
mTextureSlotInfo[(uint32_t)TextureSlot::Transmission] = { "transmission", TextureChannelFlags::RGB, true };
}
bool StandardMaterial::renderUI(Gui::Widgets& widget)
{
widget.text("Shading model: " + to_string(getShadingModel()));
// Render the base class UI first.
bool changed = BasicMaterial::renderUI(widget);
// We're re-using the material's update flags here to track changes.
// Cache the previous flag so we can restore it before returning.
UpdateFlags prevUpdates = mUpdates;
mUpdates = UpdateFlags::None;
if (auto pTexture = getEmissiveTexture())
{
widget.text("Emissive color: " + pTexture->getSourceFilename());
widget.text("Texture info: " + std::to_string(pTexture->getWidth()) + "x" + std::to_string(pTexture->getHeight()) + " (" + to_string(pTexture->getFormat()) + ")");
widget.image("Emissive color", pTexture, float2(100.f));
if (widget.button("Remove texture##Emissive")) setEmissiveTexture(nullptr);
}
else
{
float3 emissiveColor = getEmissiveColor();
if (widget.var("Emissive color", emissiveColor, 0.f, 1.f, 0.01f)) setEmissiveColor(emissiveColor);
}
float emissiveFactor = getEmissiveFactor();
if (widget.var("Emissive factor", emissiveFactor, 0.f, std::numeric_limits<float>::max(), 0.01f)) setEmissiveFactor(emissiveFactor);
// Restore update flags.
changed |= mUpdates != UpdateFlags::None;
markUpdates(prevUpdates | mUpdates);
return changed;
}
void StandardMaterial::renderSpecularUI(Gui::Widgets& widget)
{
if (getShadingModel() == ShadingModel::MetalRough)
{
float roughness = getRoughness();
if (widget.var("Roughness", roughness, 0.f, 1.f, 0.01f)) setRoughness(roughness);
float metallic = getMetallic();
if (widget.var("Metallic", metallic, 0.f, 1.f, 0.01f)) setMetallic(metallic);
}
}
void StandardMaterial::setShadingModel(ShadingModel model)
{
checkArgument(model == ShadingModel::MetalRough || model == ShadingModel::SpecGloss, "'model' must be MetalRough or SpecGloss");
if (getShadingModel() != model)
{
mData.setShadingModel(model);
markUpdates(UpdateFlags::DataChanged);
}
}
void StandardMaterial::setRoughness(float roughness)
{
if (getShadingModel() != ShadingModel::MetalRough)
{
logWarning("Ignoring setRoughness(). Material '{}' does not use the metallic/roughness shading model.", mName);
return;
}
if (mData.specular[1] != (float16_t)roughness)
{
mData.specular[1] = (float16_t)roughness;
markUpdates(UpdateFlags::DataChanged);
}
}
void StandardMaterial::setMetallic(float metallic)
{
if (getShadingModel() != ShadingModel::MetalRough)
{
logWarning("Ignoring setMetallic(). Material '{}' does not use the metallic/roughness shading model.", mName);
return;
}
if (mData.specular[2] != (float16_t)metallic)
{
mData.specular[2] = (float16_t)metallic;
markUpdates(UpdateFlags::DataChanged);
}
}
void StandardMaterial::setEmissiveColor(const float3& color)
{
if (mData.emissive != (float16_t3)color)
{
mData.emissive = (float16_t3)color;
markUpdates(UpdateFlags::DataChanged);
updateEmissiveFlag();
}
}
void StandardMaterial::setEmissiveFactor(float factor)
{
if (mData.emissiveFactor != factor)
{
mData.emissiveFactor = factor;
markUpdates(UpdateFlags::DataChanged);
updateEmissiveFlag();
}
}
FALCOR_SCRIPT_BINDING(StandardMaterial)
{
FALCOR_SCRIPT_BINDING_DEPENDENCY(BasicMaterial)
pybind11::enum_<ShadingModel> shadingModel(m, "ShadingModel");
shadingModel.value("MetalRough", ShadingModel::MetalRough);
shadingModel.value("SpecGloss", ShadingModel::SpecGloss);
pybind11::class_<StandardMaterial, BasicMaterial, StandardMaterial::SharedPtr> material(m, "StandardMaterial");
material.def(pybind11::init(&StandardMaterial::create), "name"_a = "", "model"_a = ShadingModel::MetalRough);
material.def_property("roughness", &StandardMaterial::getRoughness, &StandardMaterial::setRoughness);
material.def_property("metallic", &StandardMaterial::getMetallic, &StandardMaterial::setMetallic);
material.def_property("emissiveColor", &StandardMaterial::getEmissiveColor, &StandardMaterial::setEmissiveColor);
material.def_property("emissiveFactor", &StandardMaterial::getEmissiveFactor, &StandardMaterial::setEmissiveFactor);
material.def_property_readonly("shadingModel", &StandardMaterial::getShadingModel);
// Register alias Material -> StandardMaterial to allow deprecated script syntax.
// TODO: Remove workaround when all scripts have been updated to create StandardMaterial directly.
m.attr("Material") = m.attr("StandardMaterial"); // PYTHONDEPRECATED
}
}
| 44.824176 | 226 | 0.664624 | [
"render",
"model"
] |
ba76e5f9bcb27f79a85e9dc562a439f3274f1b3d | 10,074 | cpp | C++ | rclcpp/src/rclcpp/subscription_base.cpp | devrite/rclcpp | d5f3d35fbe3127e30d4ee9d40f57c42584eeb830 | [
"Apache-2.0"
] | 2 | 2021-01-28T12:29:28.000Z | 2021-06-14T08:26:33.000Z | rclcpp/src/rclcpp/subscription_base.cpp | devrite/rclcpp | d5f3d35fbe3127e30d4ee9d40f57c42584eeb830 | [
"Apache-2.0"
] | null | null | null | rclcpp/src/rclcpp/subscription_base.cpp | devrite/rclcpp | d5f3d35fbe3127e30d4ee9d40f57c42584eeb830 | [
"Apache-2.0"
] | 3 | 2021-09-07T12:09:45.000Z | 2021-10-06T02:39:56.000Z | // Copyright 2015 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.
#include "rclcpp/subscription_base.hpp"
#include <cstdio>
#include <memory>
#include <string>
#include <vector>
#include "rclcpp/exceptions.hpp"
#include "rclcpp/expand_topic_or_service_name.hpp"
#include "rclcpp/experimental/intra_process_manager.hpp"
#include "rclcpp/logging.hpp"
#include "rclcpp/node_interfaces/node_base_interface.hpp"
#include "rclcpp/qos_event.hpp"
#include "rmw/error_handling.h"
#include "rmw/rmw.h"
using rclcpp::SubscriptionBase;
SubscriptionBase::SubscriptionBase(
rclcpp::node_interfaces::NodeBaseInterface * node_base,
const rosidl_message_type_support_t & type_support_handle,
const std::string & topic_name,
const rcl_subscription_options_t & subscription_options,
bool is_serialized)
: node_base_(node_base),
node_handle_(node_base_->get_shared_rcl_node_handle()),
use_intra_process_(false),
intra_process_subscription_id_(0),
type_support_(type_support_handle),
is_serialized_(is_serialized)
{
auto custom_deletor = [node_handle = this->node_handle_](rcl_subscription_t * rcl_subs)
{
if (rcl_subscription_fini(rcl_subs, node_handle.get()) != RCL_RET_OK) {
RCLCPP_ERROR(
rclcpp::get_node_logger(node_handle.get()).get_child("rclcpp"),
"Error in destruction of rcl subscription handle: %s",
rcl_get_error_string().str);
rcl_reset_error();
}
delete rcl_subs;
};
subscription_handle_ = std::shared_ptr<rcl_subscription_t>(
new rcl_subscription_t, custom_deletor);
*subscription_handle_.get() = rcl_get_zero_initialized_subscription();
rcl_ret_t ret = rcl_subscription_init(
subscription_handle_.get(),
node_handle_.get(),
&type_support_handle,
topic_name.c_str(),
&subscription_options);
if (ret != RCL_RET_OK) {
if (ret == RCL_RET_TOPIC_NAME_INVALID) {
auto rcl_node_handle = node_handle_.get();
// this will throw on any validation problem
rcl_reset_error();
expand_topic_or_service_name(
topic_name,
rcl_node_get_name(rcl_node_handle),
rcl_node_get_namespace(rcl_node_handle));
}
rclcpp::exceptions::throw_from_rcl_error(ret, "could not create subscription");
}
}
SubscriptionBase::~SubscriptionBase()
{
if (!use_intra_process_) {
return;
}
auto ipm = weak_ipm_.lock();
if (!ipm) {
// TODO(ivanpauno): should this raise an error?
RCLCPP_WARN(
rclcpp::get_logger("rclcpp"),
"Intra process manager died before than a subscription.");
return;
}
ipm->remove_subscription(intra_process_subscription_id_);
}
const char *
SubscriptionBase::get_topic_name() const
{
return rcl_subscription_get_topic_name(subscription_handle_.get());
}
std::shared_ptr<rcl_subscription_t>
SubscriptionBase::get_subscription_handle()
{
return subscription_handle_;
}
std::shared_ptr<const rcl_subscription_t>
SubscriptionBase::get_subscription_handle() const
{
return subscription_handle_;
}
const std::vector<std::shared_ptr<rclcpp::QOSEventHandlerBase>> &
SubscriptionBase::get_event_handlers() const
{
return event_handlers_;
}
rclcpp::QoS
SubscriptionBase::get_actual_qos() const
{
const rmw_qos_profile_t * qos = rcl_subscription_get_actual_qos(subscription_handle_.get());
if (!qos) {
auto msg = std::string("failed to get qos settings: ") + rcl_get_error_string().str;
rcl_reset_error();
throw std::runtime_error(msg);
}
return rclcpp::QoS(rclcpp::QoSInitialization::from_rmw(*qos), *qos);
}
bool
SubscriptionBase::take_type_erased(void * message_out, rclcpp::MessageInfo & message_info_out)
{
rcl_ret_t ret = rcl_take(
this->get_subscription_handle().get(),
message_out,
&message_info_out.get_rmw_message_info(),
nullptr // rmw_subscription_allocation_t is unused here
);
if (RCL_RET_SUBSCRIPTION_TAKE_FAILED == ret) {
return false;
} else if (RCL_RET_OK != ret) {
rclcpp::exceptions::throw_from_rcl_error(ret);
}
if (
matches_any_intra_process_publishers(&message_info_out.get_rmw_message_info().publisher_gid))
{
// In this case, the message will be delivered via intra-process and
// we should ignore this copy of the message.
return false;
}
return true;
}
bool
SubscriptionBase::take_serialized(
rclcpp::SerializedMessage & message_out,
rclcpp::MessageInfo & message_info_out)
{
rcl_ret_t ret = rcl_take_serialized_message(
this->get_subscription_handle().get(),
&message_out.get_rcl_serialized_message(),
&message_info_out.get_rmw_message_info(),
nullptr);
if (RCL_RET_SUBSCRIPTION_TAKE_FAILED == ret) {
return false;
} else if (RCL_RET_OK != ret) {
rclcpp::exceptions::throw_from_rcl_error(ret);
}
return true;
}
const rosidl_message_type_support_t &
SubscriptionBase::get_message_type_support_handle() const
{
return type_support_;
}
bool
SubscriptionBase::is_serialized() const
{
return is_serialized_;
}
size_t
SubscriptionBase::get_publisher_count() const
{
size_t inter_process_publisher_count = 0;
rmw_ret_t status = rcl_subscription_get_publisher_count(
subscription_handle_.get(),
&inter_process_publisher_count);
if (RCL_RET_OK != status) {
rclcpp::exceptions::throw_from_rcl_error(status, "failed to get get publisher count");
}
return inter_process_publisher_count;
}
void
SubscriptionBase::setup_intra_process(
uint64_t intra_process_subscription_id,
IntraProcessManagerWeakPtr weak_ipm)
{
intra_process_subscription_id_ = intra_process_subscription_id;
weak_ipm_ = weak_ipm;
use_intra_process_ = true;
}
bool
SubscriptionBase::can_loan_messages() const
{
return rcl_subscription_can_loan_messages(subscription_handle_.get());
}
rclcpp::Waitable::SharedPtr
SubscriptionBase::get_intra_process_waitable() const
{
// If not using intra process, shortcut to nullptr.
if (!use_intra_process_) {
return nullptr;
}
// Get the intra process manager.
auto ipm = weak_ipm_.lock();
if (!ipm) {
throw std::runtime_error(
"SubscriptionBase::get_intra_process_waitable() called "
"after destruction of intra process manager");
}
// Use the id to retrieve the subscription intra-process from the intra-process manager.
return ipm->get_subscription_intra_process(intra_process_subscription_id_);
}
void
SubscriptionBase::default_incompatible_qos_callback(
rclcpp::QOSRequestedIncompatibleQoSInfo & event) const
{
std::string policy_name = qos_policy_name_from_kind(event.last_policy_kind);
RCLCPP_WARN(
rclcpp::get_logger(rcl_node_get_logger_name(node_handle_.get())),
"New publisher discovered on topic '%s', offering incompatible QoS. "
"No messages will be sent to it. "
"Last incompatible policy: %s",
get_topic_name(),
policy_name.c_str());
}
bool
SubscriptionBase::matches_any_intra_process_publishers(const rmw_gid_t * sender_gid) const
{
if (!use_intra_process_) {
return false;
}
auto ipm = weak_ipm_.lock();
if (!ipm) {
throw std::runtime_error(
"intra process publisher check called "
"after destruction of intra process manager");
}
return ipm->matches_any_publishers(sender_gid);
}
bool
SubscriptionBase::exchange_in_use_by_wait_set_state(
void * pointer_to_subscription_part,
bool in_use_state)
{
if (nullptr == pointer_to_subscription_part) {
throw std::invalid_argument("pointer_to_subscription_part is unexpectedly nullptr");
}
if (this == pointer_to_subscription_part) {
return subscription_in_use_by_wait_set_.exchange(in_use_state);
}
if (get_intra_process_waitable().get() == pointer_to_subscription_part) {
return intra_process_subscription_waitable_in_use_by_wait_set_.exchange(in_use_state);
}
for (const auto & qos_event : event_handlers_) {
if (qos_event.get() == pointer_to_subscription_part) {
return qos_events_in_use_by_wait_set_[qos_event.get()].exchange(in_use_state);
}
}
throw std::runtime_error("given pointer_to_subscription_part does not match any part");
}
std::vector<rclcpp::NetworkFlowEndpoint> SubscriptionBase::get_network_flow_endpoints() const
{
rcutils_allocator_t allocator = rcutils_get_default_allocator();
rcl_network_flow_endpoint_array_t network_flow_endpoint_array =
rcl_get_zero_initialized_network_flow_endpoint_array();
rcl_ret_t ret = rcl_subscription_get_network_flow_endpoints(
subscription_handle_.get(), &allocator, &network_flow_endpoint_array);
if (RCL_RET_OK != ret) {
auto error_msg = std::string("Error obtaining network flows of subscription: ") +
rcl_get_error_string().str;
rcl_reset_error();
if (RCL_RET_OK !=
rcl_network_flow_endpoint_array_fini(&network_flow_endpoint_array))
{
error_msg += std::string(". Also error cleaning up network flow array: ") +
rcl_get_error_string().str;
rcl_reset_error();
}
rclcpp::exceptions::throw_from_rcl_error(ret, error_msg);
}
std::vector<rclcpp::NetworkFlowEndpoint> network_flow_endpoint_vector;
for (size_t i = 0; i < network_flow_endpoint_array.size; ++i) {
network_flow_endpoint_vector.push_back(
rclcpp::NetworkFlowEndpoint(
network_flow_endpoint_array.
network_flow_endpoint[i]));
}
ret = rcl_network_flow_endpoint_array_fini(&network_flow_endpoint_array);
if (RCL_RET_OK != ret) {
rclcpp::exceptions::throw_from_rcl_error(ret, "error cleaning up network flow array");
}
return network_flow_endpoint_vector;
}
| 30.713415 | 97 | 0.749454 | [
"vector"
] |
ba7879232081c60c692ba8bece714d686719290f | 2,730 | cpp | C++ | src/shogun/structure/MulticlassSOLabels.cpp | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | src/shogun/structure/MulticlassSOLabels.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | src/shogun/structure/MulticlassSOLabels.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* 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.
*
* Written (W) 2013 Thoralf Klein
* Written (W) 2012 Fernando José Iglesias García
* Copyright (C) 2012 Fernando José Iglesias García
*/
#include <shogun/structure/MulticlassSOLabels.h>
using namespace shogun;
CMulticlassSOLabels::CMulticlassSOLabels()
: CStructuredLabels(), m_labels_vector(16)
{
init();
}
CMulticlassSOLabels::CMulticlassSOLabels(int32_t num_labels)
: CStructuredLabels(), m_labels_vector(num_labels)
{
init();
}
CMulticlassSOLabels::CMulticlassSOLabels(SGVector< float64_t > const src)
: CStructuredLabels(src.vlen), m_labels_vector(src.vlen)
{
init();
m_num_classes = SGVector< float64_t >::max(src.vector, src.vlen) + 1;
m_labels_vector.resize_vector(src.vlen);
for ( int32_t i = 0 ; i < src.vlen ; ++i )
{
if ( src[i] < 0 || src[i] >= m_num_classes )
SG_ERROR("Found label out of {0, 1, 2, ..., num_classes-1}")
else
add_label( new CRealNumber(src[i]) );
}
//TODO check that every class has at least one example
}
CMulticlassSOLabels::~CMulticlassSOLabels()
{
}
CStructuredData* CMulticlassSOLabels::get_label(int32_t idx)
{
// ensure_valid("CMulticlassSOLabels::get_label(int32_t)");
if ( idx < 0 || idx >= get_num_labels() )
SG_ERROR("Index must be inside [0, num_labels-1]\n")
return (CStructuredData*) new CRealNumber(m_labels_vector[idx]);
}
void CMulticlassSOLabels::add_label(CStructuredData* label)
{
SG_REF(label);
float64_t value = CRealNumber::obtain_from_generic(label)->value;
SG_UNREF(label);
//ensure_valid_sdt(label);
if (m_num_labels_set >= m_labels_vector.vlen)
{
m_labels_vector.resize_vector(m_num_labels_set + 16);
}
m_labels_vector[m_num_labels_set] = value;
m_num_labels_set++;
}
bool CMulticlassSOLabels::set_label(int32_t idx, CStructuredData* label)
{
SG_REF(label);
float64_t value = CRealNumber::obtain_from_generic(label)->value;
SG_UNREF(label);
// ensure_valid_sdt(label);
int32_t real_idx = m_subset_stack->subset_idx_conversion(idx);
if ( real_idx < get_num_labels() )
{
m_labels_vector[real_idx] = value;
return true;
}
else
{
return false;
}
}
int32_t CMulticlassSOLabels::get_num_labels() const
{
return m_num_labels_set;
}
void CMulticlassSOLabels::init()
{
SG_ADD(&m_num_classes, "m_num_classes", "The number of classes",
MS_NOT_AVAILABLE);
SG_ADD(&m_num_labels_set, "m_num_labels_set", "The number of assigned labels",
MS_NOT_AVAILABLE);
m_num_classes = 0;
m_num_labels_set = 0;
}
| 24.375 | 79 | 0.727473 | [
"vector"
] |
ba8c40832804f6b4fdd4bcd1c3f77c1fa14fdfff | 12,599 | cpp | C++ | proxygen/lib/http/codec/compress/experimental/interop/QPACKInterop.cpp | rohitm17/proxygen | efdf2800afa8fe6e969bcd5eede78aa5b96aec82 | [
"BSD-3-Clause"
] | null | null | null | proxygen/lib/http/codec/compress/experimental/interop/QPACKInterop.cpp | rohitm17/proxygen | efdf2800afa8fe6e969bcd5eede78aa5b96aec82 | [
"BSD-3-Clause"
] | null | null | null | proxygen/lib/http/codec/compress/experimental/interop/QPACKInterop.cpp | rohitm17/proxygen | efdf2800afa8fe6e969bcd5eede78aa5b96aec82 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <folly/File.h>
#include <folly/FileUtil.h>
#include <folly/init/Init.h>
#include <folly/io/Cursor.h>
#include <folly/portability/GFlags.h>
#include <proxygen/lib/http/codec/compress/QPACKCodec.h>
#include <proxygen/lib/http/codec/compress/experimental/simulator/CompressionUtils.h>
#include <proxygen/lib/http/codec/compress/experimental/simulator/SimStreamingCallback.h>
#include <proxygen/lib/http/codec/compress/test/HTTPArchive.h>
#include <fstream>
using namespace proxygen;
using namespace proxygen::compress;
using namespace folly;
using namespace folly::io;
DEFINE_string(output, "compress.out", "Output file for encoding");
DEFINE_string(input, "compress.in", "Input file for decoding");
DEFINE_string(har, "", "HAR file to compress or compare");
DEFINE_string(mode, "encode", "<encode|decode>");
DEFINE_bool(ack, true, "Encoder assumes immediate ack of all frames");
DEFINE_int32(table_size, 4096, "Dynamic table size");
DEFINE_int32(max_blocking, 100, "Max blocking streams");
DEFINE_bool(public, false, "Public HAR file");
namespace {
void writeFrame(folly::io::QueueAppender& appender,
uint64_t streamId,
std::unique_ptr<folly::IOBuf> buf) {
appender.writeBE<uint64_t>(streamId);
appender.writeBE<uint32_t>(buf->computeChainDataLength());
appender.insert(std::move(buf));
}
void encodeBlocks(QPACKCodec& decoder,
std::vector<std::vector<compress::Header>>& blocks) {
uint64_t streamId = 1;
QPACKCodec encoder;
encoder.setMaxVulnerable(FLAGS_max_blocking);
encoder.setEncoderHeaderTableSize(FLAGS_table_size);
folly::File outputF(FLAGS_output, O_CREAT | O_RDWR | O_TRUNC);
IOBufQueue outbuf;
QueueAppender appender(&outbuf, 1000);
uint64_t bytesIn = 0;
uint64_t bytesOut = 0;
for (auto& block : blocks) {
auto result = encoder.encode(block, streamId);
// always write stream before control to test decoder blocking
SimStreamingCallback cb(streamId, nullptr);
if (result.stream) {
decoder.decodeStreaming(streamId, result.stream->clone(),
result.stream->computeChainDataLength(),
&cb);
writeFrame(appender, streamId, std::move(result.stream));
if (FLAGS_ack && cb.acknowledge) {
encoder.decodeDecoderStream(decoder.encodeHeaderAck(streamId));
}
}
if (result.control) {
decoder.decodeEncoderStream(result.control->clone());
writeFrame(appender, 0, std::move(result.control));
if (FLAGS_ack) {
// There can be ICI when the decoder is non-blocking
auto res = decoder.encodeInsertCountInc();
if (res) {
encoder.decodeDecoderStream(std::move(res));
}
}
}
bytesIn += encoder.getEncodedSize().uncompressed;
auto out = outbuf.move();
auto iov = out->getIov();
bytesOut += writevFull(outputF.fd(), iov.data(), iov.size());
streamId++;
}
LOG(INFO) << "Encoded " << (streamId - 1) << " streams. Bytes in="
<< bytesIn << " Bytes out=" << bytesOut << " Ratio="
<< int32_t(100 * (1 - (bytesOut / double(bytesIn))));
}
void encodeHar(QPACKCodec& decoder, const proxygen::HTTPArchive& har) {
std::vector<std::vector<compress::Header>> blocks;
std::vector<std::vector<std::string>> cookies{har.requests.size()};
uint32_t i = 0;
for (auto& req : har.requests) {
blocks.emplace_back(prepareMessageForCompression(req, cookies[i++]));
}
encodeBlocks(decoder, blocks);
}
class Reader {
std::string filename;
public:
explicit Reader(const std::string& fname)
: filename(fname) {}
virtual ~Reader() {}
virtual ssize_t read() {
ssize_t rc = -1;
folly::IOBufQueue inbuf{folly::IOBufQueue::cacheChainLength()};
folly::File inputF(filename, O_RDONLY);
do {
auto pre = inbuf.preallocate(4096, 4096);
rc = readNoInt(inputF.fd(), pre.first, pre.second);
if (rc < 0) {
LOG(ERROR) << "Read failed on " << FLAGS_input;
return 1;
}
inbuf.postallocate(rc);
onIngress(inbuf);
} while (rc != 0);
if (!inbuf.empty()) {
LOG(ERROR) << "Premature end of file";
return 1;
}
return rc;
}
virtual void onIngress(folly::IOBufQueue& inbuf) = 0;
};
class CompressedReader : public Reader {
enum { HEADER, DATA } state{HEADER};
uint64_t streamId{0};
uint32_t length{0};
std::function<void(uint64_t, uint32_t,
std::unique_ptr<folly::IOBuf>)> callback;
public:
explicit CompressedReader(
std::function<void(uint64_t, uint32_t,
std::unique_ptr<folly::IOBuf>)> cb)
: Reader(FLAGS_input),
callback(cb) {}
void onIngress(folly::IOBufQueue& inbuf) override {
while (true) {
if (state == HEADER) {
if (inbuf.chainLength() < (sizeof(uint64_t) + sizeof(uint32_t))) {
return;
}
Cursor c(inbuf.front());
streamId = c.readBE<uint64_t>();
length = c.readBE<uint32_t>();
inbuf.trimStart(sizeof(uint64_t) + sizeof(uint32_t));
state = DATA;
}
if (state == DATA) {
if (inbuf.chainLength() < length) {
return;
}
auto buf = inbuf.split(length);
callback(streamId, length, std::move(buf));
state = HEADER;
}
}
}
};
int decodeAndVerify(QPACKCodec& decoder, const proxygen::HTTPArchive& har) {
std::map<uint64_t, SimStreamingCallback> streams;
CompressedReader creader(
[&] (uint64_t streamId, uint32_t length,
std::unique_ptr<folly::IOBuf> buf) {
if (streamId == 0) {
CHECK_EQ(decoder.decodeEncoderStream(std::move(buf)),
HPACK::DecodeError::NONE);
} else {
auto res = streams.emplace(std::piecewise_construct,
std::forward_as_tuple(streamId),
std::forward_as_tuple(streamId, nullptr,
FLAGS_public));
decoder.decodeStreaming(
streamId, std::move(buf), length, &res.first->second);
}
});
if (creader.read()) {
return 1;
}
size_t i = 0;
for (const auto& req : streams) {
if (req.second.error != HPACK::DecodeError::NONE) {
LOG(ERROR) << "request=" << req.first
<< " failed to decode error=" << req.second.error;
return 1;
}
if (!(req.second.msg == har.requests[i])) {
LOG(ERROR) << "requests are not equal, got=" << req.second.msg
<< " expected=" << har.requests[i];
}
i++;
}
LOG(INFO) << "Verified " << i << " streams.";
return 0;
}
class QIFCallback : public HPACK::StreamingCallback {
public:
QIFCallback(uint64_t id_, std::ofstream& of_) :
id(id_),
of(of_) {}
void onHeader(const HPACKHeaderName& name,
const folly::fbstring& value) override {
if (first) {
of << "# stream " << id << std::endl;
first = false;
}
of << name.get() << "\t" << value << std::endl;
}
void onHeadersComplete(HTTPHeaderSize /*decodedSize*/,
bool /*acknowledge*/) override {
of << std::endl;
complete = true;
}
void onDecodeError(HPACK::DecodeError decodeError) override {
LOG(FATAL) << "Decode error with stream=" << id << " err=" << decodeError;
}
uint64_t id{0};
std::ofstream& of;
bool first{true};
bool complete{false};
};
int decodeToQIF(QPACKCodec& decoder) {
std::ofstream of(FLAGS_output, std::ofstream::trunc);
std::map<uint64_t, QIFCallback> streams;
uint64_t encoderStreamBytes = 0;
CompressedReader creader(
[&] (uint64_t streamId, uint32_t length,
std::unique_ptr<folly::IOBuf> buf) {
if (streamId == 0) {
CHECK_EQ(decoder.decodeEncoderStream(std::move(buf)),
HPACK::DecodeError::NONE);
encoderStreamBytes += length;
} else {
auto res = streams.emplace(std::piecewise_construct,
std::forward_as_tuple(streamId),
std::forward_as_tuple(streamId, of));
decoder.decodeStreaming(
streamId, std::move(buf), length, &res.first->second);
}
});
if (creader.read()) {
return 1;
}
for (const auto& stream : streams) {
CHECK(stream.second.complete) << "Stream " << stream.first <<
" didn't complete";
}
LOG(INFO) << "encoderStreamBytes=" << encoderStreamBytes;
return 0;
}
int interopHAR(QPACKCodec& decoder) {
std::unique_ptr<HTTPArchive> har = (FLAGS_public) ?
HTTPArchive::fromPublicFile(FLAGS_har) :
HTTPArchive::fromFile(FLAGS_har);
if (!har) {
LOG(ERROR) << "Failed to read har file='" << FLAGS_har << "'";
return 1;
}
if (FLAGS_mode == "encode") {
encodeHar(decoder, *har);
} else if (FLAGS_mode == "decode") {
return decodeAndVerify(decoder, *har);
} else {
LOG(ERROR) << "Usage" << std::endl;
return 1;
}
return 0;
}
struct QIFReader : public Reader {
std::vector<std::string> strings;
std::vector<std::vector<Header>> blocks{1};
enum { LINESTART, COMMENT, NAME, VALUE, EOL } state_{LINESTART};
bool seenR{false};
QIFReader()
: Reader(FLAGS_input) {
strings.reserve(32768);
}
ssize_t read() override {
ssize_t rc = Reader::read();
if (rc != 0) {
return rc;
}
CHECK(blocks.back().empty());
blocks.pop_back();
return 0;
}
static bool iseol(uint8_t ch) {
return ch == '\r' || ch == '\n';
}
void onIngress(folly::IOBufQueue& input) override {
Cursor c(input.front());
while (!c.isAtEnd()) {
switch (state_) {
case LINESTART:
{
seenR = false;
auto p = c.peek();
switch (p.first[0]) {
case '#':
state_ = COMMENT;
break;
case '\r':
case '\n':
if (!blocks.back().empty()) {
blocks.emplace_back();
}
state_ = EOL;
break;
default:
state_ = NAME;
strings.emplace_back();
}
break;
}
case COMMENT:
c.skipWhile([] (uint8_t ch) {
return !iseol(ch);
});
if (!c.isAtEnd()) {
state_ = EOL;
}
break;
case EOL:
{
auto p = c.peek();
if (p.first[0] == '\n') {
c.skip(1);
state_ = LINESTART;
} else if (seenR) { // \r followed by anything but \n -> mac newline
state_ = LINESTART;
} else if (p.first[0] == '\r') {
c.skip(1);
seenR = true;
}
break;
}
case NAME:
strings.back() += c.readWhile([] (uint8_t ch) {
return ch != '\t';
});
if (!c.isAtEnd()) {
c.skip(1);
state_ = VALUE;
strings.emplace_back();
}
break;
case VALUE:
strings.back() += c.readWhile([] (uint8_t ch) {
return !iseol(ch);
});
if (!c.isAtEnd()) {
CHECK_GE(strings.size(), 2);
blocks.back().emplace_back(
compress::Header::makeHeaderForTest(
*(strings.rbegin() + 1), *strings.rbegin()));
state_ = EOL;
}
break;
}
}
input.move();
}
};
int interopQIF(QPACKCodec& decoder) {
if (FLAGS_mode == "encode") {
QIFReader reader;
if (reader.read() != 0) {
LOG(ERROR) << "Failed to read QIF file='" << FLAGS_input << "'";
return 1;
}
encodeBlocks(decoder, reader.blocks);
} else if (FLAGS_mode == "decode") {
decodeToQIF(decoder);
} else {
LOG(ERROR) << "Usage" << std::endl;
return 1;
}
return 0;
}
}
int main(int argc, char** argv) {
folly::init(&argc, &argv, true);
QPACKCodec decoder;
decoder.setMaxBlocking(FLAGS_max_blocking);
decoder.setDecoderHeaderTableMaxSize(FLAGS_table_size);
if (!FLAGS_har.empty()) {
return interopHAR(decoder);
} else {
return interopQIF(decoder);
}
}
| 29.926366 | 89 | 0.577189 | [
"vector"
] |
ba8dd5ee031cd14a5a7429ecd79683dc7937b69d | 27,932 | cpp | C++ | PhysX-3.2.4_PC_SDK_Core/Samples/SampleBase/RenderPhysX3Debug.cpp | JayStilla/AIEPhysics | d3e45c1bbe44987a96ed12781ef9781fba06bcfa | [
"MIT"
] | null | null | null | PhysX-3.2.4_PC_SDK_Core/Samples/SampleBase/RenderPhysX3Debug.cpp | JayStilla/AIEPhysics | d3e45c1bbe44987a96ed12781ef9781fba06bcfa | [
"MIT"
] | null | null | null | PhysX-3.2.4_PC_SDK_Core/Samples/SampleBase/RenderPhysX3Debug.cpp | JayStilla/AIEPhysics | d3e45c1bbe44987a96ed12781ef9781fba06bcfa | [
"MIT"
] | null | null | null | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "RenderPhysX3Debug.h"
#include "RendererColor.h"
#include "common/PxRenderBuffer.h"
#include "foundation/PxSimpleTypes.h"
#include "SampleCamera.h"
#include "geometry/PxConvexMesh.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxBoxGeometry.h"
#include "PsUtilities.h"
#include "PsPrintString.h"
using namespace physx;
using namespace SampleRenderer;
using namespace SampleFramework;
RenderPhysX3Debug::RenderPhysX3Debug(Renderer& renderer, SampleAssetManager& assetmanager) :
SamplePointDebugRender (renderer, assetmanager),
SampleLineDebugRender (renderer, assetmanager),
SampleTriangleDebugRender (renderer, assetmanager)
{
}
RenderPhysX3Debug::~RenderPhysX3Debug()
{
}
void RenderPhysX3Debug::update(const PxRenderBuffer& debugRenderable)
{
// Points
const PxU32 numPoints = debugRenderable.getNbPoints();
if(numPoints)
{
const PxDebugPoint* PX_RESTRICT points = debugRenderable.getPoints();
checkResizePoint(numPoints);
for(PxU32 i=0; i<numPoints; i++)
{
const PxDebugPoint& point = points[i];
addPoint(point.pos, RendererColor(point.color));
}
}
// Lines
const PxU32 numLines = debugRenderable.getNbLines();
if(numLines)
{
const PxDebugLine* PX_RESTRICT lines = debugRenderable.getLines();
checkResizeLine(numLines * 2);
for(PxU32 i=0; i<numLines; i++)
{
const PxDebugLine& line = lines[i];
addLine(line.pos0, line.pos1, RendererColor(line.color0));
}
}
// Triangles
const PxU32 numTriangles = debugRenderable.getNbTriangles();
if(numTriangles)
{
const PxDebugTriangle* PX_RESTRICT triangles = debugRenderable.getTriangles();
checkResizeTriangle(numTriangles * 3);
for(PxU32 i=0; i<numTriangles; i++)
{
const PxDebugTriangle& triangle = triangles[i];
addTriangle(triangle.pos0, triangle.pos1, triangle.pos2, RendererColor(triangle.color0));
}
}
}
void RenderPhysX3Debug::update(const PxRenderBuffer& debugRenderable, const Camera& camera)
{
// Points
const PxU32 numPoints = debugRenderable.getNbPoints();
if(numPoints)
{
const PxDebugPoint* PX_RESTRICT points = debugRenderable.getPoints();
checkResizePoint(numPoints);
for(PxU32 i=0; i<numPoints; i++)
{
const PxDebugPoint& point = points[i];
addPoint(point.pos, RendererColor(point.color));
}
}
// Lines
const PxU32 numLines = debugRenderable.getNbLines();
if(numLines)
{
const PxDebugLine* PX_RESTRICT lines = debugRenderable.getLines();
checkResizeLine(numLines * 2);
PxU32 nbVisible = 0;
for(PxU32 i=0; i<numLines; i++)
{
const PxDebugLine& line = lines[i];
PxBounds3 b;
b.minimum.x = PxMin(line.pos0.x, line.pos1.x);
b.minimum.y = PxMin(line.pos0.y, line.pos1.y);
b.minimum.z = PxMin(line.pos0.z, line.pos1.z);
b.maximum.x = PxMax(line.pos0.x, line.pos1.x);
b.maximum.y = PxMax(line.pos0.y, line.pos1.y);
b.maximum.z = PxMax(line.pos0.z, line.pos1.z);
if(camera.cull(b)==PLANEAABB_EXCLUSION)
continue;
addLine(line.pos0, line.pos1, RendererColor(line.color0));
nbVisible++;
}
shdfnd::printFormatted("%f\n", float(nbVisible)/float(numLines));
}
// Triangles
const PxU32 numTriangles = debugRenderable.getNbTriangles();
if(numTriangles)
{
const PxDebugTriangle* PX_RESTRICT triangles = debugRenderable.getTriangles();
checkResizeTriangle(numTriangles * 3);
for(PxU32 i=0; i<numTriangles; i++)
{
const PxDebugTriangle& triangle = triangles[i];
addTriangle(triangle.pos0, triangle.pos1, triangle.pos2, RendererColor(triangle.color0));
}
}
}
void RenderPhysX3Debug::queueForRender()
{
queueForRenderPoint();
queueForRenderLine();
queueForRenderTriangle();
}
void RenderPhysX3Debug::clear()
{
clearPoint();
clearLine();
clearTriangle();
}
///////////////////////////////////////////////////////////////////////////////
#define NB_CIRCLE_PTS 20
void RenderPhysX3Debug::addBox(const PxVec3* pts, const RendererColor& color, PxU32 renderFlags)
{
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
const PxU8 indices[] = {
0, 1, 1, 2, 2, 3, 3, 0,
7, 6, 6, 5, 5, 4, 4, 7,
1, 5, 6, 2,
3, 7, 4, 0
};
for(PxU32 i=0;i<12;i++)
addLine(pts[indices[i*2]], pts[indices[i*2+1]], color);
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
const PxU8 indices[] = {
0,2,1, 0,3,2,
1,6,5, 1,2,6,
5,7,4, 5,6,7,
4,3,0, 4,7,3,
3,6,2, 3,7,6,
5,0,1, 5,4,0
};
for(PxU32 i=0;i<12;i++)
addTriangle(pts[indices[i*3+0]], pts[indices[i*3+1]], pts[indices[i*3+2]], color);
}
}
void RenderPhysX3Debug::addCircle(PxU32 nbPts, const PxVec3* pts, const RendererColor& color, const PxVec3& offset)
{
for(PxU32 i=0;i<nbPts;i++)
{
const PxU32 j = (i+1) % nbPts;
addLine(pts[i]+offset, pts[j]+offset, color);
}
}
void RenderPhysX3Debug::addAABB(const PxBounds3& box, const RendererColor& color, PxU32 renderFlags)
{
const PxVec3& min = box.minimum;
const PxVec3& max = box.maximum;
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
// Generate 8 corners of the bbox
PxVec3 pts[8];
pts[0] = PxVec3(min.x, min.y, min.z);
pts[1] = PxVec3(max.x, min.y, min.z);
pts[2] = PxVec3(max.x, max.y, min.z);
pts[3] = PxVec3(min.x, max.y, min.z);
pts[4] = PxVec3(min.x, min.y, max.z);
pts[5] = PxVec3(max.x, min.y, max.z);
pts[6] = PxVec3(max.x, max.y, max.z);
pts[7] = PxVec3(min.x, max.y, max.z);
addBox(pts, color, renderFlags);
}
void RenderPhysX3Debug::addBox(const PxBoxGeometry& bg, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
addOBB(tr.p, bg.halfExtents, PxMat33(tr.q), color, renderFlags);
}
void RenderPhysX3Debug::addOBB(const PxVec3& boxCenter, const PxVec3& boxExtents, const PxMat33& boxRot, const RendererColor& color, PxU32 renderFlags)
{
PxVec3 Axis0 = boxRot.column0;
PxVec3 Axis1 = boxRot.column1;
PxVec3 Axis2 = boxRot.column2;
// "Rotated extents"
Axis0 *= boxExtents.x;
Axis1 *= boxExtents.y;
Axis2 *= boxExtents.z;
// 7+------+6 0 = ---
// /| /| 1 = +--
// / | / | 2 = ++-
// / 4+---/--+5 3 = -+-
// 3+------+2 / y z 4 = --+
// | / | / | / 5 = +-+
// |/ |/ |/ 6 = +++
// 0+------+1 *---x 7 = -++
// Original code: 24 vector ops
/* pts[0] = mCenter - Axis0 - Axis1 - Axis2;
pts[1] = mCenter + Axis0 - Axis1 - Axis2;
pts[2] = mCenter + Axis0 + Axis1 - Axis2;
pts[3] = mCenter - Axis0 + Axis1 - Axis2;
pts[4] = mCenter - Axis0 - Axis1 + Axis2;
pts[5] = mCenter + Axis0 - Axis1 + Axis2;
pts[6] = mCenter + Axis0 + Axis1 + Axis2;
pts[7] = mCenter - Axis0 + Axis1 + Axis2;*/
// Rewritten: 12 vector ops
PxVec3 pts[8];
pts[0] = pts[3] = pts[4] = pts[7] = boxCenter - Axis0;
pts[1] = pts[2] = pts[5] = pts[6] = boxCenter + Axis0;
PxVec3 Tmp = Axis1 + Axis2;
pts[0] -= Tmp;
pts[1] -= Tmp;
pts[6] += Tmp;
pts[7] += Tmp;
Tmp = Axis1 - Axis2;
pts[2] += Tmp;
pts[3] += Tmp;
pts[4] -= Tmp;
pts[5] -= Tmp;
addBox(pts, color, renderFlags);
}
enum Orientation
{
ORIENTATION_XY,
ORIENTATION_XZ,
ORIENTATION_YZ,
ORIENTATION_FORCE_DWORD = 0x7fffffff
};
static bool generatePolygon(PxU32 nbVerts, PxVec3* verts, Orientation orientation, float amplitude, float phase, const PxTransform* transform=NULL)
{
if(!nbVerts || !verts)
return false;
const float step = PxTwoPi/float(nbVerts);
for(PxU32 i=0;i<nbVerts;i++)
{
const float angle = phase + float(i) * step;
const float y = sinf(angle) * amplitude;
const float x = cosf(angle) * amplitude;
if(orientation==ORIENTATION_XY) { verts[i] = PxVec3(x, y, 0.0f); }
else if(orientation==ORIENTATION_XZ) { verts[i] = PxVec3(x, 0.0f, y); }
else if(orientation==ORIENTATION_YZ) { verts[i] = PxVec3(0.0f, x, y); }
if(transform)
verts[i] = transform->transform(verts[i]);
}
return true;
}
// PT: this comes from RendererCapsuleShape.cpp. Maybe we could grab the data from there instead of duplicating. But it protects us from external changes.
static const PxVec3 gCapsuleVertices[] =
{
PxVec3(0.0000f, -2.0000f, -0.0000f),
PxVec3(0.3827f, -1.9239f, -0.0000f),
PxVec3(0.2706f, -1.9239f, 0.2706f),
PxVec3(-0.0000f, -1.9239f, 0.3827f),
PxVec3(-0.2706f, -1.9239f, 0.2706f),
PxVec3(-0.3827f, -1.9239f, -0.0000f),
PxVec3(-0.2706f, -1.9239f, -0.2706f),
PxVec3(0.0000f, -1.9239f, -0.3827f),
PxVec3(0.2706f, -1.9239f, -0.2706f),
PxVec3(0.7071f, -1.7071f, -0.0000f),
PxVec3(0.5000f, -1.7071f, 0.5000f),
PxVec3(-0.0000f, -1.7071f, 0.7071f),
PxVec3(-0.5000f, -1.7071f, 0.5000f),
PxVec3(-0.7071f, -1.7071f, -0.0000f),
PxVec3(-0.5000f, -1.7071f, -0.5000f),
PxVec3(0.0000f, -1.7071f, -0.7071f),
PxVec3(0.5000f, -1.7071f, -0.5000f),
PxVec3(0.9239f, -1.3827f, -0.0000f),
PxVec3(0.6533f, -1.3827f, 0.6533f),
PxVec3(-0.0000f, -1.3827f, 0.9239f),
PxVec3(-0.6533f, -1.3827f, 0.6533f),
PxVec3(-0.9239f, -1.3827f, -0.0000f),
PxVec3(-0.6533f, -1.3827f, -0.6533f),
PxVec3(0.0000f, -1.3827f, -0.9239f),
PxVec3(0.6533f, -1.3827f, -0.6533f),
PxVec3(1.0000f, -1.0000f, -0.0000f),
PxVec3(0.7071f, -1.0000f, 0.7071f),
PxVec3(-0.0000f, -1.0000f, 1.0000f),
PxVec3(-0.7071f, -1.0000f, 0.7071f),
PxVec3(-1.0000f, -1.0000f, -0.0000f),
PxVec3(-0.7071f, -1.0000f, -0.7071f),
PxVec3(0.0000f, -1.0000f, -1.0000f),
PxVec3(0.7071f, -1.0000f, -0.7071f),
PxVec3(1.0000f, 1.0000f, 0.0000f),
PxVec3(0.7071f, 1.0000f, 0.7071f),
PxVec3(-0.0000f, 1.0000f, 1.0000f),
PxVec3(-0.7071f, 1.0000f, 0.7071f),
PxVec3(-1.0000f, 1.0000f, -0.0000f),
PxVec3(-0.7071f, 1.0000f, -0.7071f),
PxVec3(0.0000f, 1.0000f, -1.0000f),
PxVec3(0.7071f, 1.0000f, -0.7071f),
PxVec3(0.9239f, 1.3827f, 0.0000f),
PxVec3(0.6533f, 1.3827f, 0.6533f),
PxVec3(-0.0000f, 1.3827f, 0.9239f),
PxVec3(-0.6533f, 1.3827f, 0.6533f),
PxVec3(-0.9239f, 1.3827f, -0.0000f),
PxVec3(-0.6533f, 1.3827f, -0.6533f),
PxVec3(0.0000f, 1.3827f, -0.9239f),
PxVec3(0.6533f, 1.3827f, -0.6533f),
PxVec3(0.7071f, 1.7071f, 0.0000f),
PxVec3(0.5000f, 1.7071f, 0.5000f),
PxVec3(-0.0000f, 1.7071f, 0.7071f),
PxVec3(-0.5000f, 1.7071f, 0.5000f),
PxVec3(-0.7071f, 1.7071f, 0.0000f),
PxVec3(-0.5000f, 1.7071f, -0.5000f),
PxVec3(0.0000f, 1.7071f, -0.7071f),
PxVec3(0.5000f, 1.7071f, -0.5000f),
PxVec3(0.3827f, 1.9239f, 0.0000f),
PxVec3(0.2706f, 1.9239f, 0.2706f),
PxVec3(-0.0000f, 1.9239f, 0.3827f),
PxVec3(-0.2706f, 1.9239f, 0.2706f),
PxVec3(-0.3827f, 1.9239f, 0.0000f),
PxVec3(-0.2706f, 1.9239f, -0.2706f),
PxVec3(0.0000f, 1.9239f, -0.3827f),
PxVec3(0.2706f, 1.9239f, -0.2706f),
PxVec3(0.0000f, 2.0000f, 0.0000f),
};
static const PxU8 gCapsuleIndices[] =
{
1, 0, 2, 2, 0, 3, 3, 0, 4, 4, 0, 5, 5, 0, 6, 6, 0, 7, 7, 0, 8,
8, 0, 1, 9, 1, 10, 10, 1, 2, 10, 2, 11, 11, 2, 3, 11, 3, 12,
12, 3, 4, 12, 4, 13, 13, 4, 5, 13, 5, 14, 14, 5, 6, 14, 6, 15,
15, 6, 7, 15, 7, 16, 16, 7, 8, 16, 8, 9, 9, 8, 1, 17, 9, 18,
18, 9, 10, 18, 10, 19, 19, 10, 11, 19, 11, 20, 20, 11, 12, 20, 12, 21,
21, 12, 13, 21, 13, 22, 22, 13, 14, 22, 14, 23, 23, 14, 15, 23, 15, 24,
24, 15, 16, 24, 16, 17, 17, 16, 9, 25, 17, 26, 26, 17, 18, 26, 18, 27,
27, 18, 19, 27, 19, 28, 28, 19, 20, 28, 20, 29, 29, 20, 21, 29, 21, 30,
30, 21, 22, 30, 22, 31, 31, 22, 23, 31, 23, 32, 32, 23, 24, 32, 24, 25,
25, 24, 17, 33, 25, 34, 34, 25, 26, 34, 26, 35, 35, 26, 27, 35, 27, 36,
36, 27, 28, 36, 28, 37, 37, 28, 29, 37, 29, 38, 38, 29, 30, 38, 30, 39,
39, 30, 31, 39, 31, 40, 40, 31, 32, 40, 32, 33, 33, 32, 25, 41, 33, 42,
42, 33, 34, 42, 34, 43, 43, 34, 35, 43, 35, 44, 44, 35, 36, 44, 36, 45,
45, 36, 37, 45, 37, 46, 46, 37, 38, 46, 38, 47, 47, 38, 39, 47, 39, 48,
48, 39, 40, 48, 40, 41, 41, 40, 33, 49, 41, 50, 50, 41, 42, 50, 42, 51,
51, 42, 43, 51, 43, 52, 52, 43, 44, 52, 44, 53, 53, 44, 45, 53, 45, 54,
54, 45, 46, 54, 46, 55, 55, 46, 47, 55, 47, 56, 56, 47, 48, 56, 48, 49,
49, 48, 41, 57, 49, 58, 58, 49, 50, 58, 50, 59, 59, 50, 51, 59, 51, 60,
60, 51, 52, 60, 52, 61, 61, 52, 53, 61, 53, 62, 62, 53, 54, 62, 54, 63,
63, 54, 55, 63, 55, 64, 64, 55, 56, 64, 56, 57, 57, 56, 49, 65, 57, 58,
65, 58, 59, 65, 59, 60, 65, 60, 61, 65, 61, 62, 65, 62, 63, 65, 63, 64,
65, 64, 57,
};
static const PxU32 gNumCapsuleIndices = PX_ARRAY_SIZE(gCapsuleIndices);
static PX_FORCE_INLINE void fixCapsuleVertex(PxVec3& p, PxF32 radius, PxF32 halfHeight)
{
const PxF32 sign = p.y > 0 ? 1.0f : -1.0f;
p.y -= sign;
p *= radius;
p.y += halfHeight*sign;
}
void RenderPhysX3Debug::addSphere(const PxSphereGeometry& sg, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
addSphere(tr.p, sg.radius, color, renderFlags);
}
void RenderPhysX3Debug::addSphere(const PxVec3& sphereCenter, float sphereRadius, const RendererColor& color, PxU32 renderFlags)
{
const PxU32 nbVerts = NB_CIRCLE_PTS;
PxVec3 pts[NB_CIRCLE_PTS];
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
generatePolygon(nbVerts, pts, ORIENTATION_XY, sphereRadius, 0.0f);
addCircle(nbVerts, pts, color, sphereCenter);
generatePolygon(nbVerts, pts, ORIENTATION_XZ, sphereRadius, 0.0f);
addCircle(nbVerts, pts, color, sphereCenter);
generatePolygon(nbVerts, pts, ORIENTATION_YZ, sphereRadius, 0.0f);
addCircle(nbVerts, pts, color, sphereCenter);
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
const PxF32 halfHeight = 0.0f;
for(PxU32 i=0;i<gNumCapsuleIndices/3;i++)
{
const PxU32 i0 = gCapsuleIndices[i*3+0];
const PxU32 i1 = gCapsuleIndices[i*3+1];
const PxU32 i2 = gCapsuleIndices[i*3+2];
PxVec3 v0 = gCapsuleVertices[i0];
PxVec3 v1 = gCapsuleVertices[i1];
PxVec3 v2 = gCapsuleVertices[i2];
fixCapsuleVertex(v0, sphereRadius, halfHeight);
fixCapsuleVertex(v1, sphereRadius, halfHeight);
fixCapsuleVertex(v2, sphereRadius, halfHeight);
addTriangle(v0+sphereCenter, v1+sphereCenter, v2+sphereCenter, color);
}
}
}
#define MAX_TEMP_VERTEX_BUFFER 400
// creaet triangle strip of spheres
static bool generateSphere(PxU32 nbSeg, PxU32& nbVerts, PxVec3* verts, PxVec3* normals)
{
PxVec3 tempVertexBuffer[MAX_TEMP_VERTEX_BUFFER];
PxVec3 tempNormalBuffer[MAX_TEMP_VERTEX_BUFFER];
int halfSeg = nbSeg / 2;
int nSeg = halfSeg * 2;
if (((nSeg+1) * (nSeg+1)) > MAX_TEMP_VERTEX_BUFFER)
return false;
const float stepTheta = PxTwoPi / float(nSeg);
const float stepPhi = PxPi / float(nSeg);
// compute sphere vertices on the temporary buffer
nbVerts = 0;
for (int i = 0; i <= nSeg; i++)
{
const float theta = float(i) * stepTheta;
const float cosi = cos(theta);
const float sini = sin(theta);
for (int j = -halfSeg; j <= halfSeg; j++)
{
const float phi = float(j) * stepPhi;
const float sinj = sin( phi);
const float cosj = cos( phi);
const float y = cosj * cosi;
const float x = sinj;
const float z = cosj * sini;
tempVertexBuffer[nbVerts] = PxVec3(x,y,z);
tempNormalBuffer[nbVerts] = PxVec3(x,y,z).getNormalized();
nbVerts++;
}
}
nbVerts = 0;
// now create triangle soup data
for (int i = 0; i < nSeg; i++)
{
for (int j = 0; j < nSeg; j++)
{
// add one triangle
verts[nbVerts] = tempVertexBuffer[ (nSeg+1) * i + j];
normals[nbVerts] = tempNormalBuffer[ (nSeg+1) * i + j];
nbVerts++;
verts[nbVerts] = tempVertexBuffer[ (nSeg+1) * i + j+1];
normals[nbVerts] = tempNormalBuffer[ (nSeg+1) * i + j+1];
nbVerts++;
verts[nbVerts] = tempVertexBuffer[ (nSeg+1) * (i+1) + j+1];
normals[nbVerts] = tempNormalBuffer[ (nSeg+1) * (i+1) + j+1];
nbVerts++;
// add another triangle
verts[nbVerts] = tempVertexBuffer[ (nSeg+1) * i + j];
normals[nbVerts] = tempNormalBuffer[ (nSeg+1) * i + j];
nbVerts++;
verts[nbVerts] = tempVertexBuffer[ (nSeg+1) * (i+1) + j+1];
normals[nbVerts] = tempNormalBuffer[ (nSeg+1) * (i+1) + j+1];
nbVerts++;
verts[nbVerts] = tempVertexBuffer[ (nSeg+1) * (i+1) + j];
normals[nbVerts] = tempNormalBuffer[ (nSeg+1) * (i+1) + j];
nbVerts++;
}
}
return true;
}
void RenderPhysX3Debug::addSphereExt(const PxVec3& sphereCenter, float sphereRadius, const RendererColor& color, PxU32 renderFlags)
{
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
const PxU32 nbVerts = NB_CIRCLE_PTS;
PxVec3 pts[NB_CIRCLE_PTS];
generatePolygon(nbVerts, pts, ORIENTATION_XY, sphereRadius, 0.0f);
addCircle(nbVerts, pts, color, sphereCenter);
generatePolygon(nbVerts, pts, ORIENTATION_XZ, sphereRadius, 0.0f);
addCircle(nbVerts, pts, color, sphereCenter);
generatePolygon(nbVerts, pts, ORIENTATION_YZ, sphereRadius, 0.0f);
addCircle(nbVerts, pts, color, sphereCenter);
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
static bool initDone = false;
static PxU32 nbVerts;
static PxVec3 verts[MAX_TEMP_VERTEX_BUFFER*6];
static PxVec3 normals[MAX_TEMP_VERTEX_BUFFER*6];
if (!initDone)
{
generateSphere(16, nbVerts, verts, normals);
initDone = true;
}
PxU32 i = 0;
while ( i < nbVerts )
{
addTriangle( sphereCenter + sphereRadius * verts[i], sphereCenter + sphereRadius * verts[i+1], sphereCenter + sphereRadius * verts[i+2],
normals[i], normals[i+1], normals[i+2], color);
i += 3;
}
}
}
#undef MAX_TEMP_VERTEX_BUFFFER
static inline PxU32 minArgument(const PxVec3 &v)
{
PxU32 j = 0;
if ( v[j] > v[1]) j = 1;
if ( v[j] > v[2]) j = 2;
return j;
}
static inline PxVec3 abs(const PxVec3 &v)
{
return PxVec3( ::abs(v.x), ::abs(v.y), ::abs(v.z));
}
void RenderPhysX3Debug::addConeExt(float r0, float r1, const PxVec3& p0, const PxVec3& p1 , const RendererColor& color, PxU32 renderFlags)
{
PxVec3 axis = p1 - p0;
PxReal length = axis.magnitude();
PxReal rdiff = r0 - r1;
PxReal sinAngle = rdiff / length;
PxReal x0 = r0 * sinAngle;
PxReal x1 = r1 * sinAngle;
PxVec3 center = 0.5f * (p0 + p1);
if (length < fabs(rdiff))
return;
PxReal r0p = sqrt(r0 * r0 - x0 * x0);
PxReal r1p = sqrt(r1 * r1 - x1 * x1);
if (length == 0.0f)
axis = PxVec3(1,0,0);
else
axis.normalize();
PxVec3 axis1(0.0f);
axis1[minArgument(abs(axis))] = 1.0f;
axis1 = axis1.cross(axis);
axis1.normalize();
PxVec3 axis2 = axis.cross(axis1);
axis2.normalize();
PxMat44 m;
m.column0 = PxVec4(axis, 0.0f);
m.column1 = PxVec4(axis1, 0.0f);
m.column2 = PxVec4(axis2, 0.0f);
m.column3 = PxVec4(center, 1.0f);
PxTransform tr(m);
#define NUM_CONE_VERTS 72
const PxU32 nbVerts = NUM_CONE_VERTS;
PxVec3 pts0[NUM_CONE_VERTS] ;
PxVec3 pts1[NUM_CONE_VERTS];
PxVec3 normals[NUM_CONE_VERTS] ;
const float step = PxTwoPi / float(nbVerts);
for (PxU32 i = 0; i < nbVerts; i++)
{
const float angle = float(i) * step;
const float x = cosf(angle);
const float y = sinf(angle);
PxVec3 p = PxVec3(0.0f, x, y);
pts0[i] = tr.transform(r0p * p + PxVec3(-0.5f * length + x0,0,0));
pts1[i] = tr.transform(r1p * p + PxVec3(0.5f * length + x1, 0, 0));
normals[i] = tr.q.rotate(p.getNormalized());
normals[i] = x0 * axis + r0p * normals[i];
normals[i].normalize();
}
#undef NUM_CONE_VERTS
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
for(PxU32 i=0;i<nbVerts;i++)
{
addLine(pts1[i], pts0[i], color);
}
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
for(PxU32 i=0;i<nbVerts;i++)
{
const PxU32 j = (i+1) % nbVerts;
addTriangle(pts0[i], pts1[j], pts0[j], normals[i], normals[j], normals[j], color);
addTriangle(pts0[i], pts1[i], pts1[j], normals[i], normals[i], normals[j], color);
}
}
}
void RenderPhysX3Debug::addCone(float radius, float height, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
const PxU32 nbVerts = NB_CIRCLE_PTS;
PxVec3 pts[NB_CIRCLE_PTS];
generatePolygon(nbVerts, pts, ORIENTATION_XZ, radius, 0.0f, &tr);
const PxVec3 tip = tr.transform(PxVec3(0.0f, height, 0.0f));
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
addCircle(nbVerts, pts, color, PxVec3(0));
for(PxU32 i=0;i<nbVerts;i++)
{
addLine(tip, pts[i], color); // side of the cone
addLine(tr.p, pts[i], color); // base disk of the cone
}
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
for(PxU32 i=0;i<nbVerts;i++)
{
const PxU32 j = (i+1) % nbVerts;
addTriangle(tip, pts[i], pts[j], color);
addTriangle(tr.p, pts[i], pts[j], color);
}
}
}
void RenderPhysX3Debug::addCylinder(float radius, float height, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
const PxU32 nbVerts = NB_CIRCLE_PTS;
PxVec3 pts[NB_CIRCLE_PTS];
generatePolygon(nbVerts, pts, ORIENTATION_XZ, radius, 0.0f, &tr);
PxTransform tr2 = tr;
tr2.p = tr.transform(PxVec3(0.0f, height, 0.0f));
PxVec3 pts2[NB_CIRCLE_PTS];
generatePolygon(nbVerts, pts2, ORIENTATION_XZ, radius, 0.0f, &tr2);
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
for(PxU32 i=0;i<nbVerts;i++)
{
const PxU32 j = (i+1) % nbVerts;
addLine(pts[i], pts[j], color); // circle
addLine(pts2[i], pts2[j], color); // circle
}
for(PxU32 i=0;i<nbVerts;i++)
{
addLine(pts[i], pts2[i], color); // side
addLine(tr.p, pts[i], color); // disk
addLine(tr2.p, pts2[i], color); // disk
}
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
for(PxU32 i=0;i<nbVerts;i++)
{
const PxU32 j = (i+1) % nbVerts;
addTriangle(tr.p, pts[i], pts[j], color);
addTriangle(tr2.p, pts2[i], pts2[j], color);
addTriangle(pts[i], pts[j], pts2[j], color);
addTriangle(pts[i], pts2[j], pts2[i], color);
}
}
}
void RenderPhysX3Debug::addStar(const PxVec3& p, const float size, const RendererColor& color )
{
const PxVec3 up(0.f, size, 0.f);
const PxVec3 right(size, 0.f, 0.f);
const PxVec3 forwards(0.f, 0.f, size);
addLine(p + up, p - up, color);
addLine(p + right, p - right, color);
addLine(p + forwards, p - forwards, color);
}
void RenderPhysX3Debug::addCapsule(const PxCapsuleGeometry& cg, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
PxTransform pose = PxTransform(PxVec3(0.f), PxQuat(PxPi/2, PxVec3(0,0,1)));
pose = tr * pose;
PxVec3 p0(0, -cg.halfHeight, 0);
PxVec3 p1(0, cg.halfHeight, 0);
p0 = pose.transform(p0);
p1 = pose.transform(p1);
pose.p = p0;
/*PxTransform pose = PxTransform(PxVec3(0.f), PxQuat(PxPi/2, PxVec3(0,0,1)));
pose = tr * pose;*/
//const PxReal height = cg.halfHeight;
//const PxVec3 p0 = tr.p - PxVec3(0, height, 0);
//const PxVec3 p1 = tr.p + PxVec3(0, height, 0);
addCapsule(p0, p1, cg.radius, 2*cg.halfHeight, pose, color, renderFlags);
}
void RenderPhysX3Debug::addCapsule(const PxVec3& p0, const PxVec3& p1, const float radius, const float height, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
addSphere(p0, radius, color, renderFlags);
addSphere(p1, radius, color, renderFlags);
addCylinder(radius, height, tr, color, renderFlags);
}
void RenderPhysX3Debug::addRectangle(float width, float length, const PxTransform& tr, const RendererColor& color)
{
PxMat33 m33 = PxMat33(tr.q);
PxVec3 Axis1 = m33.column1;
PxVec3 Axis2 = m33.column2;
Axis1 *= length;
Axis2 *= width;
PxVec3 pts[4];
pts[0] = tr.p + Axis1 + Axis2 ;
pts[1] = tr.p - Axis1 + Axis2 ;
pts[2] = tr.p - Axis1 - Axis2 ;
pts[3] = tr.p + Axis1 - Axis2 ;
addTriangle(pts[0], pts[1], pts[2], color);
addTriangle(pts[0], pts[2], pts[3], color);
}
void RenderPhysX3Debug::addGeometry(const PxGeometry& geom, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
switch(geom.getType())
{
case PxGeometryType::eBOX:
{
addBox(static_cast<const PxBoxGeometry&>(geom), tr, color, renderFlags);
}
break;
case PxGeometryType::eSPHERE:
{
addSphere(static_cast<const PxSphereGeometry&>(geom), tr, color, renderFlags);
}
break;
case PxGeometryType::eCAPSULE:
{
addCapsule(static_cast<const PxCapsuleGeometry&>(geom), tr, color, renderFlags);
}
break;
case PxGeometryType::eCONVEXMESH:
{
addConvex(static_cast<const PxConvexMeshGeometry&>(geom), tr, color, renderFlags);
}
break;
case PxGeometryType::ePLANE:
case PxGeometryType::eTRIANGLEMESH:
case PxGeometryType::eHEIGHTFIELD:
default:
{
PX_ASSERT(!"Not supported!");
break;
}
}
}
void RenderPhysX3Debug::addConvex(const PxConvexMeshGeometry& cg, const PxTransform& tr, const RendererColor& color, PxU32 renderFlags)
{
const PxConvexMesh& mesh = *cg.convexMesh;
const PxMat33 rot = PxMat33(tr.q) * cg.scale.toMat33();
// PT: you can't use PxTransform with a non-uniform scaling
const PxMat44 globalPose(rot, tr.p);
const PxU32 polygonCount = mesh.getNbPolygons();
const PxU8* indexBuffer = mesh.getIndexBuffer();
const PxVec3* vertexBuffer = mesh.getVertices();
if(renderFlags & RENDER_DEBUG_WIREFRAME)
{
for(PxU32 i=0; i<polygonCount; i++)
{
PxHullPolygon data;
mesh.getPolygonData(i, data);
const PxU32 vertexCount = data.mNbVerts;
PxU32 i0 = indexBuffer[vertexCount-1];
PxU32 i1 = *indexBuffer++;
addLine(globalPose.transform(vertexBuffer[i0]), globalPose.transform(vertexBuffer[i1]), color);
for(PxU32 j=1; j<vertexCount; j++)
{
i0 = indexBuffer[-1];
i1 = *indexBuffer++;
addLine(globalPose.transform(vertexBuffer[i0]), globalPose.transform(vertexBuffer[i1]), color);
}
}
}
if(renderFlags & RENDER_DEBUG_SOLID)
{
for(PxU32 i=0; i<polygonCount; i++)
{
PxHullPolygon data;
mesh.getPolygonData(i, data);
const PxU32 vertexCount = data.mNbVerts;
const PxVec3& v0 = vertexBuffer[indexBuffer[0]];
for(PxU32 j=0; j<vertexCount-2; j++)
{
const PxVec3& v1 = vertexBuffer[indexBuffer[j+1]];
const PxVec3& v2 = vertexBuffer[indexBuffer[j+2]];
addTriangle(globalPose.transform(v0), globalPose.transform(v1), globalPose.transform(v2), color);
}
indexBuffer += vertexCount;
}
}
}
void RenderPhysX3Debug::addArrow(const PxVec3& posA, const PxVec3& posB, const RendererColor& color)
{
const PxVec3 t0 = (posB - posA).getNormalized();
const PxVec3 a = PxAbs(t0.x)<0.707f ? PxVec3(1,0,0): PxVec3(0,1,0);
const PxVec3 t1 = t0.cross(a).getNormalized();
const PxVec3 t2 = t0.cross(t1).getNormalized();
addLine(posA, posB, color);
addLine(posB, posB - t0*0.15 + t1 * 0.15, color);
addLine(posB, posB - t0*0.15 - t1 * 0.15, color);
addLine(posB, posB - t0*0.15 + t2 * 0.15, color);
addLine(posB, posB - t0*0.15 - t2 * 0.15, color);
}
| 30.229437 | 180 | 0.660569 | [
"mesh",
"geometry",
"vector",
"transform"
] |
ba8f1693b34b51aa384bab8236c96aed8380bf06 | 1,480 | c++ | C++ | tempCodeRunnerFile.c++ | Sambitcr-7/DSA-C- | f3c80f54fa6160a99f39a934f330cdf40711de50 | [
"Apache-2.0"
] | null | null | null | tempCodeRunnerFile.c++ | Sambitcr-7/DSA-C- | f3c80f54fa6160a99f39a934f330cdf40711de50 | [
"Apache-2.0"
] | null | null | null | tempCodeRunnerFile.c++ | Sambitcr-7/DSA-C- | f3c80f54fa6160a99f39a934f330cdf40711de50 | [
"Apache-2.0"
] | null | null | null | #include"bits/stdc++.h"
using namespace std;
#define vi vector<int>
#define vvi vector<vi>
#define pii pair<int,int>
#define vii vector<pii>
#define rep(i,a,b) for(int i=a; i<b; i++)
#define ff first
#define ss second
#define setBits(x) builtin_popcount(x)
const int N = 1e3+2 ;
// int dp[N][N];
// int lcs(string &s1, string &s2, int n , int m)
// {
// if(n == 0 || m == 0)
// return 0;
// if(dp[n][m] !=-1)
// return dp[n][m];
// if(s1[n-1] == s2[m-1])
// dp[n] [m] = 1 + lcs(s1,s2,n-1,m-1);
// else
// {
// dp[n][m] = max(lcs(s1,s2,n,m-1), lcs(s1,s2,n-1,m));
// }
// return dp[n][m];
// }
signed main()
{
// rep(i,0,N)
// {
// rep(j,0,N)
// dp[i][j] = -1;
// }
// string s1, s2;
// cin >> s1>>s2;
// int n = s1.size(), m = s2.size();
// cout << lcs(s1,s2,n,m) <<endl;
string s1, s2;
cin >> s1 >> s2;
int n = s1.size(), m = s2.size();
vvi dp(n+1, vi(m+1, -1));
rep(i,0,n+1)
{
rep(j,0,m+1)
{
if(i == 0 || j == 0)
{
dp[i][j] = 0;
continue;
}
if(s1[i-1] == s2[j-1])
dp[i][j] = 1 + dp[i-1][j-1];
else
{
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
cout << dp[n][m] << endl;
return 0;
} | 18.271605 | 63 | 0.371622 | [
"vector"
] |
ba8f319c1bfafdb336c74e60ac7c71ce8de3f1a1 | 960 | cpp | C++ | modules/sksg/src/SkSGGeometryNode.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | modules/sksg/src/SkSGGeometryNode.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | modules/sksg/src/SkSGGeometryNode.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* 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 "modules/sksg/include/SkSGGeometryNode.h"
#include "include/core/SkPath.h"
namespace sksg {
// Geometry nodes don't generate damage on their own, but via their aggregation ancestor Draw nodes.
GeometryNode::GeometryNode() : INHERITED(kBubbleDamage_Trait) {}
void GeometryNode::clip(SkCanvas* canvas, bool aa) const {
SkASSERT(!this->hasInval());
this->onClip(canvas, aa);
}
void GeometryNode::draw(SkCanvas* canvas, const SkPaint& paint) const {
SkASSERT(!this->hasInval());
this->onDraw(canvas, paint);
}
bool GeometryNode::contains(const SkPoint& p) const {
SkASSERT(!this->hasInval());
return this->bounds().contains(p.x(), p.y()) ? this->onContains(p) : false;
}
SkPath GeometryNode::asPath() const {
SkASSERT(!this->hasInval());
return this->onAsPath();
}
} // namespace sksg
| 25.263158 | 100 | 0.709375 | [
"geometry"
] |
ba91a0495746b7ab4458cb4b2ba72a536d4026af | 10,137 | tcc | C++ | libiop/relations/r1cs.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/relations/r1cs.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/relations/r1cs.tcc | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | /** @file
*****************************************************************************
Declaration of interfaces for:
- a R1CS constraint,
- a R1CS variable assignment, and
- a R1CS constraint system.
See r1cs.hpp .
*****************************************************************************
* @author This file is adapted from libsnark, developed by SCIPR Lab
* and contributors
* (see AUTHORS for libsnark and here for libiop).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBIOP_RELATIONS_R1CS_TCC_
#define LIBIOP_RELATIONS_R1CS_TCC_
#include <algorithm>
#include <cassert>
#include <set>
#include <libff/common/utils.hpp>
namespace libiop {
template<typename FieldT>
r1cs_constraint<FieldT>::r1cs_constraint(const linear_combination<FieldT> &a,
const linear_combination<FieldT> &b,
const linear_combination<FieldT> &c) :
a_(a), b_(b), c_(c)
{
}
template<typename FieldT>
r1cs_constraint<FieldT>::r1cs_constraint(const std::initializer_list<linear_combination<FieldT> > &A,
const std::initializer_list<linear_combination<FieldT> > &B,
const std::initializer_list<linear_combination<FieldT> > &C)
{
for (auto lc_A : A)
{
a_.terms.insert(a_.terms.end(), lc_A.terms.begin(), lc_A.terms.end());
}
for (auto lc_B : B)
{
b_.terms.insert(b_.terms.end(), lc_B.terms.begin(), lc_B.terms.end());
}
for (auto lc_C : C)
{
c_.terms.insert(c_.terms.end(), lc_C.terms.begin(), lc_C.terms.end());
}
}
template<typename FieldT>
bool r1cs_constraint<FieldT>::operator==(const r1cs_constraint<FieldT> &other) const
{
return (this->a_ == other.a_ &&
this->b_ == other.b_ &&
this->c_ == other.c_);
}
template<typename FieldT>
size_t r1cs_constraint_system<FieldT>::num_inputs() const
{
return primary_input_size_;
}
template<typename FieldT>
size_t r1cs_constraint_system<FieldT>::num_variables() const
{
return primary_input_size_ + auxiliary_input_size_;
}
template<typename FieldT>
size_t r1cs_constraint_system<FieldT>::num_constraints() const
{
return constraints_.size();
}
template<typename FieldT>
bool r1cs_constraint_system<FieldT>::is_valid() const
{
if (this->num_inputs() > this->num_variables()) return false;
for (size_t c = 0; c < constraints_.size(); ++c)
{
if (!(constraints_[c].a_.is_valid(this->num_variables()) &&
constraints_[c].b_.is_valid(this->num_variables()) &&
constraints_[c].c_.is_valid(this->num_variables())))
{
return false;
}
}
return true;
}
template<typename FieldT>
void dump_r1cs_constraint(const r1cs_constraint<FieldT> &constraint,
const r1cs_variable_assignment<FieldT> &full_variable_assignment,
const std::map<size_t, std::string> &variable_annotations)
{
printf("terms for a:\n"); constraint.a_.print_with_assignment(full_variable_assignment, variable_annotations);
printf("terms for b:\n"); constraint.b_.print_with_assignment(full_variable_assignment, variable_annotations);
printf("terms for c:\n"); constraint.c_.print_with_assignment(full_variable_assignment, variable_annotations);
}
template<typename FieldT>
bool r1cs_constraint_system<FieldT>::is_satisfied(const r1cs_primary_input<FieldT> &primary_input,
const r1cs_auxiliary_input<FieldT> &auxiliary_input) const
{
assert(primary_input.size() == num_inputs());
assert(primary_input.size() + auxiliary_input.size() == num_variables());
const r1cs_variable_assignment<FieldT> full_variable_assignment =
variable_assignment_from_inputs(primary_input, auxiliary_input);
return this->is_satisfied(full_variable_assignment);
}
template<typename FieldT>
bool r1cs_constraint_system<FieldT>::is_satisfied(const r1cs_variable_assignment<FieldT> &full_variable_assignment) const
{
for (size_t c = 0; c < constraints_.size(); ++c)
{
const FieldT ares = constraints_[c].a_.evaluate(full_variable_assignment);
const FieldT bres = constraints_[c].b_.evaluate(full_variable_assignment);
const FieldT cres = constraints_[c].c_.evaluate(full_variable_assignment);
if (!(ares*bres == cres))
{
#ifdef DEBUG
auto it = constraint_annotations_.find(c);
printf("constraint %zu (%s) unsatisfied\n", c, (it == constraint_annotations_.end() ? "no annotation" : it->second.c_str()));
printf("<a,(1,x)> = "); ares.print();
printf("<b,(1,x)> = "); bres.print();
printf("<c,(1,x)> = "); cres.print();
printf("constraint was:\n");
dump_r1cs_constraint(constraints_[c], full_variable_assignment, variable_annotations_);
#endif // DEBUG
return false;
}
}
return true;
}
template<typename FieldT>
void r1cs_constraint_system<FieldT>::add_constraint(const r1cs_constraint<FieldT> &c)
{
constraints_.emplace_back(c);
}
template<typename FieldT>
void r1cs_constraint_system<FieldT>::add_constraint(const r1cs_constraint<FieldT> &c, const std::string &annotation)
{
#ifdef DEBUG
constraint_annotations_[constraints_.size()] = annotation;
#else
libff::UNUSED(annotation);
#endif
constraints_.emplace_back(c);
}
template<typename FieldT>
bool r1cs_constraint_system<FieldT>::operator==(const r1cs_constraint_system<FieldT> &other) const
{
return (this->constraints_ == other.constraints_ &&
this->primary_input_size_ == other.primary_input_size_ &&
this->auxiliary_input_size_ == other.auxiliary_input_size_);
}
template<typename FieldT>
naive_sparse_matrix<FieldT> r1cs_constraint_system<FieldT>::A_matrix() const
{
naive_sparse_matrix<FieldT> matrix;
for (std::size_t i = 0; i < this->num_constraints(); ++i)
{
const r1cs_constraint<FieldT> &constraint = this->constraints_[i];
std::vector<linear_term<FieldT>> terms = constraint.a_.terms;
std::map<std::size_t, FieldT> values;
for (std::size_t j = 0; j < terms.size(); ++j)
{
values.insert(std::pair<std::size_t, FieldT>(terms[j].index_, terms[j].coeff_));
}
matrix.push_back(std::move(values));
}
return matrix;
}
template<typename FieldT>
naive_sparse_matrix<FieldT> r1cs_constraint_system<FieldT>::B_matrix() const
{
naive_sparse_matrix<FieldT> matrix;
for (std::size_t i = 0; i < this->num_constraints(); ++i)
{
const r1cs_constraint<FieldT> &constraint = this->constraints_[i];
std::vector<linear_term<FieldT>> terms = constraint.b_.terms;
std::map<std::size_t, FieldT> values;
for (std::size_t j = 0; j < terms.size(); ++j)
{
values.insert(std::pair<std::size_t, FieldT>(terms[j].index_, terms[j].coeff_));
}
matrix.push_back(std::move(values));
}
return matrix;
}
template<typename FieldT>
naive_sparse_matrix<FieldT> r1cs_constraint_system<FieldT>::C_matrix() const
{
naive_sparse_matrix<FieldT> matrix;
for (std::size_t i = 0; i < this->num_constraints(); ++i)
{
const r1cs_constraint<FieldT> &constraint = this->constraints_[i];
std::vector<linear_term<FieldT>> terms = constraint.c_.terms;
std::map<std::size_t, FieldT> values;
for (std::size_t j = 0; j < terms.size(); ++j)
{
values.insert(std::pair<std::size_t, FieldT>(terms[j].index_, terms[j].coeff_));
}
matrix.push_back(std::move(values));
}
return matrix;
}
template<typename FieldT>
void r1cs_constraint_system<FieldT>::create_Az_Bz_Cz_from_variable_assignment(
const r1cs_variable_assignment<FieldT> &variable_assignment,
std::vector<FieldT> &Az_out,
std::vector<FieldT> &Bz_out,
std::vector<FieldT> &Cz_out) const
{
/** This assumes variable assignment z is structured as (1, v, w). */
for (size_t i = 0; i < this->constraints_.size(); ++i)
{
FieldT Az_i = FieldT::zero();
for (auto < : this->constraints_[i].a_.terms)
{
Az_i += variable_assignment[lt.index_] * lt.coeff_;
}
Az_out.emplace_back(Az_i);
FieldT Bz_i = FieldT::zero();
for (auto < : this->constraints_[i].b_.terms)
{
Bz_i += variable_assignment[lt.index_] * lt.coeff_;
}
Bz_out.emplace_back(Bz_i);
FieldT Cz_i = FieldT::zero();
for (auto < : this->constraints_[i].c_.terms)
{
Cz_i += variable_assignment[lt.index_] * lt.coeff_;
}
Cz_out.emplace_back(Cz_i);
}
}
template<typename FieldT>
std::size_t r1cs_constraint_system<FieldT>::size_in_bytes() const
{
std::size_t num_terms = 0;
for (auto &C : this->constraints_)
{
num_terms += (C.a_.terms.size() +
C.b_.terms.size() +
C.c_.terms.size());
}
/*
Assume that the most efficient representation spends:
- 3 bits per constraint (to delineate A, B, and C)
- libff::log2(num_variables) + |FieldT| bits per term
*/
const std::size_t size_in_bits = 3 * this->num_constraints() +
num_terms * (libff::log2(this->num_variables()) + 8*sizeof(FieldT));
return size_in_bits / 8;
}
template<typename FieldT>
r1cs_variable_assignment<FieldT> variable_assignment_from_inputs(const r1cs_primary_input<FieldT> &primary_input,
const r1cs_auxiliary_input<FieldT> &auxiliary_input)
{
r1cs_variable_assignment<FieldT> full_variable_assignment = primary_input;
full_variable_assignment.insert(full_variable_assignment.end(), auxiliary_input.begin(), auxiliary_input.end());
return full_variable_assignment;
}
} // libiop
#endif // LIBIOP_RELATIONS_R1CS_TCC_
| 33.455446 | 137 | 0.637072 | [
"vector"
] |
ba924cb9cc0e0e17543614b871998b4ae1c0292a | 1,195 | cpp | C++ | src/pipeline/node/XLinkIn.cpp | diablodale/depthai-core | 9f5d0861c07fea580c652f435c7e1422473ae079 | [
"MIT"
] | null | null | null | src/pipeline/node/XLinkIn.cpp | diablodale/depthai-core | 9f5d0861c07fea580c652f435c7e1422473ae079 | [
"MIT"
] | null | null | null | src/pipeline/node/XLinkIn.cpp | diablodale/depthai-core | 9f5d0861c07fea580c652f435c7e1422473ae079 | [
"MIT"
] | null | null | null | #include "depthai/pipeline/node/XLinkIn.hpp"
namespace dai {
namespace node {
XLinkIn::XLinkIn(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId) : Node(par, nodeId) {}
std::string XLinkIn::getName() const {
return "XLinkIn";
}
std::vector<Node::Input> XLinkIn::getInputs() {
return {};
}
std::vector<Node::Output> XLinkIn::getOutputs() {
return {out};
}
nlohmann::json XLinkIn::getProperties() {
nlohmann::json j;
nlohmann::to_json(j, properties);
return j;
}
std::shared_ptr<Node> XLinkIn::clone() {
return std::make_shared<std::decay<decltype(*this)>::type>(*this);
}
void XLinkIn::setStreamName(const std::string& name) {
properties.streamName = name;
}
void XLinkIn::setMaxDataSize(std::uint32_t maxDataSize) {
properties.maxDataSize = maxDataSize;
}
void XLinkIn::setNumFrames(std::uint32_t numFrames) {
properties.numFrames = numFrames;
}
std::string XLinkIn::getStreamName() const {
return properties.streamName;
}
std::uint32_t XLinkIn::getMaxDataSize() const {
return properties.maxDataSize;
}
std::uint32_t XLinkIn::getNumFrames() const {
return properties.numFrames;
}
} // namespace node
} // namespace dai
| 21.339286 | 97 | 0.702929 | [
"vector"
] |
ba9a3a18c2780667327568b6b16291e873741c39 | 5,969 | cc | C++ | tensorflow/contrib/tensor_forest/core/ops/training_ops_test.cc | waitingkuo/tensorflow | ce3572a08b9ecfa5c8dd94921c2011f37b58e608 | [
"Apache-2.0"
] | 1 | 2019-05-17T03:23:15.000Z | 2019-05-17T03:23:15.000Z | tensorflow/contrib/tensor_forest/core/ops/training_ops_test.cc | waitingkuo/tensorflow | ce3572a08b9ecfa5c8dd94921c2011f37b58e608 | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/tensor_forest/core/ops/training_ops_test.cc | waitingkuo/tensorflow | ce3572a08b9ecfa5c8dd94921c2011f37b58e608 | [
"Apache-2.0"
] | 1 | 2016-08-22T11:33:35.000Z | 2016-08-22T11:33:35.000Z | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (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.
==============================================================================*/
// TODO(cwhipkey): iwyu
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference_testutil.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
TEST(TrainingOpsTest, UpdateFertileSlots_ShapeFn) {
ShapeInferenceTestOp op("UpdateFertileSlots");
INFER_OK(op, "?;?;?;?;?;?;?", "[2,?];[?];[?]");
}
TEST(TrainingOpsTest, ScatterAddNdim_ShapeFn) {
ShapeInferenceTestOp op("ScatterAddNdim");
INFER_OK(op, "?;?;?", "");
}
TEST(TrainingOpsTest, GrowTree_ShapeFn) {
ShapeInferenceTestOp op("GrowTree");
INFER_OK(op, "?;?;?;?;?;?", "[?];[?,2];[?];[1]");
}
TEST(TrainingOpsTest, FinishedNodes_ShapeFn) {
ShapeInferenceTestOp op("FinishedNodes");
INFER_OK(op, "?;?;?;?;?;?;?;?", "[?];[?]");
}
TEST(TrainingOpsTest, BestSplits_ShapeFn) {
ShapeInferenceTestOp op("BestSplits");
INFER_OK(op, "?;?;?;?;?;?", "[?]");
INFER_OK(op, "[?];?;?;?;?;?", "[d0_0]");
INFER_OK(op, "[1];?;?;?;?;?", "[d0_0]");
INFER_ERROR("Shape must be rank 1 but is rank 2", op, "[1,2];?;?;?;?;?");
}
TEST(TrainingOpsTest, SampleInputs_ShapeFn) {
ShapeInferenceTestOp op("SampleInputs");
// input[6].dim(1) determines dims in the output.
INFER_OK(op, "?;?;?;?;?;?;?;?", "[?];[?,?];[?,?]");
INFER_OK(op, "?;?;?;?;?;?;[?,?];?", "[?];[?,d6_1];[?,d6_1]");
INFER_OK(op, "?;?;?;?;?;?;[1,2];?", "[?];[?,d6_1];[?,d6_1]");
INFER_ERROR("Shape must be rank 2 but is rank 3", op,
"?;?;?;?;?;?;[1,2,3];?");
}
TEST(TrainingOpsTest, CountExtremelyRandomStats_ShapeFn) {
ShapeInferenceTestOp op("CountExtremelyRandomStats");
TF_ASSERT_OK(NodeDefBuilder("test", "CountExtremelyRandomStats")
.Input("input_data", 0, DT_FLOAT)
.Input("sparse_input_indices", 1, DT_INT64)
.Input("sparse_input_values", 2, DT_FLOAT)
.Input("sparse_input_shape", 3, DT_INT64)
.Input("input_spec", 4, DT_INT32)
.Input("input_labels", 5, DT_FLOAT)
.Input("input_weights", 6, DT_FLOAT)
.Input("tree", 7, DT_INT32)
.Input("tree_thresholds", 8, DT_FLOAT)
.Input("node_to_accumulator", 9, DT_INT32)
.Input("candidate_split_features", 10, DT_INT32)
.Input("candidate_split_thresholds", 11, DT_FLOAT)
.Input("birth_epochs", 12, DT_INT32)
.Input("current_epoch", 13, DT_INT32)
.Attr("num_classes", 10)
.Attr("regression", false)
.Finalize(&op.node_def));
// num_points = 2, num_nodes = 4, regression = false, num_classes = 10
// num_nodes = 4
INFER_OK(op, "[2,3];?;?;?;?;?;?;[4];?;?;?;?;?;?",
"[d7_0,10];[d7_0,10];[?,3];[?];[0];[?,2];[?];[0];[d0_0]");
TF_ASSERT_OK(NodeDefBuilder("test", "CountExtremelyRandomStats")
.Input("input_data", 0, DT_FLOAT)
.Input("sparse_input_indices", 1, DT_INT64)
.Input("sparse_input_values", 2, DT_FLOAT)
.Input("sparse_input_shape", 3, DT_INT64)
.Input("input_spec", 4, DT_INT32)
.Input("input_labels", 5, DT_FLOAT)
.Input("input_weights", 6, DT_FLOAT)
.Input("tree", 7, DT_INT32)
.Input("tree_thresholds", 8, DT_FLOAT)
.Input("node_to_accumulator", 9, DT_INT32)
.Input("candidate_split_features", 10, DT_INT32)
.Input("candidate_split_thresholds", 11, DT_FLOAT)
.Input("birth_epochs", 12, DT_INT32)
.Input("current_epoch", 13, DT_INT32)
.Attr("num_classes", 10)
.Attr("regression", true)
.Finalize(&op.node_def));
// num_points = 2, num_nodes = 4, regression = false, num_classes = 10
// num_nodes = 4
INFER_OK(
op, "[2,3];?;?;?;?;?;?;[4];?;?;?;?;?;?",
"[d7_0,10];[d7_0,10];[?,2];[?,10];[?,10];[?,1];[?,10];[?,10];[d0_0]");
// Sparse shape known and > 1, so num_points is unknown
INFER_OK(op, "[2,3];?;?;[10,11];?;?;?;[4];?;?;?;?;?;?",
"[d7_0,10];[d7_0,10];[?,2];[?,10];[?,10];[?,1];[?,10];[?,10];[?]");
}
TEST(TrainingOpsTest, TreePredictions_ShapeFn) {
ShapeInferenceTestOp op("TreePredictions");
TF_ASSERT_OK(NodeDefBuilder("test", "TreePredictions")
.Input("a", 0, DT_FLOAT)
.Input("b", 1, DT_INT64)
.Input("c", 2, DT_FLOAT)
.Input("d", 3, DT_INT64)
.Input("e", 4, DT_INT32)
.Input("f", 5, DT_INT32)
.Input("g", 6, DT_FLOAT)
.Input("h", 7, DT_FLOAT)
.Attr("valid_leaf_threshold", 0.5)
.Finalize(&op.node_def));
// num_points = 2, num_classes = 10, sparse shape not known
INFER_OK(op, "[2,3];?;?;?;?;?;?;[1,10]", "[d0_0,9]");
// num_points = 2, num_classes = 10, sparse shape rank known and > 1
INFER_OK(op, "[2,3];?;?;[10,11];?;?;?;[1,10]", "[?,9]");
}
} // namespace tensorflow
| 41.451389 | 80 | 0.551516 | [
"shape"
] |
ba9ed6e30372db09884a7501e6f3f9d36077ef9e | 9,893 | cpp | C++ | intern/ghost/intern/GHOST_EventPrinter.cpp | juangea/B28_boneMaster | 6be9d19951ed460829d379aa90953b14a9f281f2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 3 | 2019-09-16T10:29:19.000Z | 2022-02-11T14:43:18.000Z | intern/ghost/intern/GHOST_EventPrinter.cpp | juangea/B28_boneMaster | 6be9d19951ed460829d379aa90953b14a9f281f2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | intern/ghost/intern/GHOST_EventPrinter.cpp | juangea/B28_boneMaster | 6be9d19951ed460829d379aa90953b14a9f281f2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2019-09-05T05:11:15.000Z | 2019-09-05T05:11:15.000Z | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*/
/** \file
* \ingroup GHOST
* Declaration of GHOST_EventPrinter class.
*/
#include "GHOST_EventPrinter.h"
#include <iostream>
#include "GHOST_EventKey.h"
#include "GHOST_EventDragnDrop.h"
#include "GHOST_Debug.h"
#include <stdio.h>
bool GHOST_EventPrinter::processEvent(GHOST_IEvent *event)
{
bool handled = true;
GHOST_ASSERT(event, "event==0");
if (event->getType() == GHOST_kEventWindowUpdate)
return false;
std::cout << "\nGHOST_EventPrinter::processEvent, time: " << (GHOST_TInt32)event->getTime()
<< ", type: ";
switch (event->getType()) {
case GHOST_kEventUnknown:
std::cout << "GHOST_kEventUnknown";
handled = false;
break;
case GHOST_kEventButtonUp: {
GHOST_TEventButtonData *buttonData =
(GHOST_TEventButtonData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventCursorButtonUp, button: " << buttonData->button;
} break;
case GHOST_kEventButtonDown: {
GHOST_TEventButtonData *buttonData =
(GHOST_TEventButtonData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventButtonDown, button: " << buttonData->button;
} break;
case GHOST_kEventWheel: {
GHOST_TEventWheelData *wheelData =
(GHOST_TEventWheelData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventWheel, z: " << wheelData->z;
} break;
case GHOST_kEventCursorMove: {
GHOST_TEventCursorData *cursorData =
(GHOST_TEventCursorData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventCursorMove, (x,y): (" << cursorData->x << "," << cursorData->y
<< ")";
} break;
case GHOST_kEventKeyUp: {
GHOST_TEventKeyData *keyData = (GHOST_TEventKeyData *)((GHOST_IEvent *)event)->getData();
char str[32] = {'\0'};
getKeyString(keyData->key, str);
std::cout << "GHOST_kEventKeyUp, key: " << str;
} break;
case GHOST_kEventKeyDown: {
GHOST_TEventKeyData *keyData = (GHOST_TEventKeyData *)((GHOST_IEvent *)event)->getData();
char str[32] = {'\0'};
getKeyString(keyData->key, str);
std::cout << "GHOST_kEventKeyDown, key: " << str;
} break;
case GHOST_kEventDraggingEntered: {
GHOST_TEventDragnDropData *dragnDropData =
(GHOST_TEventDragnDropData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventDraggingEntered, dragged object type : "
<< dragnDropData->dataType;
std::cout << " mouse at x=" << dragnDropData->x << " y=" << dragnDropData->y;
} break;
case GHOST_kEventDraggingUpdated: {
GHOST_TEventDragnDropData *dragnDropData =
(GHOST_TEventDragnDropData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventDraggingUpdated, dragged object type : "
<< dragnDropData->dataType;
std::cout << " mouse at x=" << dragnDropData->x << " y=" << dragnDropData->y;
} break;
case GHOST_kEventDraggingExited: {
GHOST_TEventDragnDropData *dragnDropData =
(GHOST_TEventDragnDropData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventDraggingExited, dragged object type : " << dragnDropData->dataType;
} break;
case GHOST_kEventDraggingDropDone: {
GHOST_TEventDragnDropData *dragnDropData =
(GHOST_TEventDragnDropData *)((GHOST_IEvent *)event)->getData();
std::cout << "GHOST_kEventDraggingDropDone,";
std::cout << " mouse at x=" << dragnDropData->x << " y=" << dragnDropData->y;
switch (dragnDropData->dataType) {
case GHOST_kDragnDropTypeString:
std::cout << " type : GHOST_kDragnDropTypeString,";
std::cout << "\n String received = " << (char *)dragnDropData->data;
break;
case GHOST_kDragnDropTypeFilenames: {
GHOST_TStringArray *strArray = (GHOST_TStringArray *)dragnDropData->data;
int i;
std::cout << " type : GHOST_kDragnDropTypeFilenames,";
std::cout << "\n Received " << strArray->count << " filename"
<< (strArray->count > 1 ? "s:" : ":");
for (i = 0; i < strArray->count; i++)
std::cout << "\n File[" << i << "] : " << strArray->strings[i];
} break;
default:
break;
}
} break;
case GHOST_kEventOpenMainFile: {
GHOST_TEventDataPtr eventData = ((GHOST_IEvent *)event)->getData();
if (eventData)
std::cout << "GHOST_kEventOpenMainFile for path : " << (char *)eventData;
else
std::cout << "GHOST_kEventOpenMainFile with no path specified!!";
} break;
case GHOST_kEventQuitRequest:
std::cout << "GHOST_kEventQuitRequest";
break;
case GHOST_kEventWindowClose:
std::cout << "GHOST_kEventWindowClose";
break;
case GHOST_kEventWindowActivate:
std::cout << "GHOST_kEventWindowActivate";
break;
case GHOST_kEventWindowDeactivate:
std::cout << "GHOST_kEventWindowDeactivate";
break;
case GHOST_kEventWindowUpdate:
std::cout << "GHOST_kEventWindowUpdate";
break;
case GHOST_kEventWindowSize:
std::cout << "GHOST_kEventWindowSize";
break;
default:
std::cout << "not found";
handled = false;
break;
}
std::cout.flush();
return handled;
}
void GHOST_EventPrinter::getKeyString(GHOST_TKey key, char str[32]) const
{
if ((key >= GHOST_kKeyComma) && (key <= GHOST_kKeyRightBracket)) {
sprintf(str, "%c", (char)key);
}
else if ((key >= GHOST_kKeyNumpad0) && (key <= GHOST_kKeyNumpad9)) {
sprintf(str, "Numpad %d", (key - GHOST_kKeyNumpad0));
}
else if ((key >= GHOST_kKeyF1) && (key <= GHOST_kKeyF24)) {
sprintf(str, "F%d", key - GHOST_kKeyF1 + 1);
}
else {
const char *tstr = NULL;
switch (key) {
case GHOST_kKeyBackSpace:
tstr = "BackSpace";
break;
case GHOST_kKeyTab:
tstr = "Tab";
break;
case GHOST_kKeyLinefeed:
tstr = "Linefeed";
break;
case GHOST_kKeyClear:
tstr = "Clear";
break;
case GHOST_kKeyEnter:
tstr = "Enter";
break;
case GHOST_kKeyEsc:
tstr = "Esc";
break;
case GHOST_kKeySpace:
tstr = "Space";
break;
case GHOST_kKeyQuote:
tstr = "Quote";
break;
case GHOST_kKeyBackslash:
tstr = "\\";
break;
case GHOST_kKeyAccentGrave:
tstr = "`";
break;
case GHOST_kKeyLeftShift:
tstr = "LeftShift";
break;
case GHOST_kKeyRightShift:
tstr = "RightShift";
break;
case GHOST_kKeyLeftControl:
tstr = "LeftControl";
break;
case GHOST_kKeyRightControl:
tstr = "RightControl";
break;
case GHOST_kKeyLeftAlt:
tstr = "LeftAlt";
break;
case GHOST_kKeyRightAlt:
tstr = "RightAlt";
break;
case GHOST_kKeyOS:
tstr = "OS";
break;
case GHOST_kKeyGrLess:
// PC german!
tstr = "GrLess";
break;
case GHOST_kKeyCapsLock:
tstr = "CapsLock";
break;
case GHOST_kKeyNumLock:
tstr = "NumLock";
break;
case GHOST_kKeyScrollLock:
tstr = "ScrollLock";
break;
case GHOST_kKeyLeftArrow:
tstr = "LeftArrow";
break;
case GHOST_kKeyRightArrow:
tstr = "RightArrow";
break;
case GHOST_kKeyUpArrow:
tstr = "UpArrow";
break;
case GHOST_kKeyDownArrow:
tstr = "DownArrow";
break;
case GHOST_kKeyPrintScreen:
tstr = "PrintScreen";
break;
case GHOST_kKeyPause:
tstr = "Pause";
break;
case GHOST_kKeyInsert:
tstr = "Insert";
break;
case GHOST_kKeyDelete:
tstr = "Delete";
break;
case GHOST_kKeyHome:
tstr = "Home";
break;
case GHOST_kKeyEnd:
tstr = "End";
break;
case GHOST_kKeyUpPage:
tstr = "UpPage";
break;
case GHOST_kKeyDownPage:
tstr = "DownPage";
break;
case GHOST_kKeyNumpadPeriod:
tstr = "NumpadPeriod";
break;
case GHOST_kKeyNumpadEnter:
tstr = "NumpadEnter";
break;
case GHOST_kKeyNumpadPlus:
tstr = "NumpadPlus";
break;
case GHOST_kKeyNumpadMinus:
tstr = "NumpadMinus";
break;
case GHOST_kKeyNumpadAsterisk:
tstr = "NumpadAsterisk";
break;
case GHOST_kKeyNumpadSlash:
tstr = "NumpadSlash";
break;
case GHOST_kKeyMediaPlay:
tstr = "MediaPlayPause";
break;
case GHOST_kKeyMediaStop:
tstr = "MediaStop";
break;
case GHOST_kKeyMediaFirst:
tstr = "MediaFirst";
break;
case GHOST_kKeyMediaLast:
tstr = "MediaLast";
break;
default:
tstr = "unknown";
break;
}
sprintf(str, "%s", tstr);
}
}
| 30.533951 | 99 | 0.601739 | [
"object"
] |
ba9f020df8ea78ebbc363ea828d2b1297e3a0ec1 | 48,922 | cpp | C++ | legacy/btmux-gluereimpl/funmath.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-07-09T17:37:42.000Z | 2020-07-09T17:37:42.000Z | legacy/btmux-gluereimpl/funmath.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | legacy/btmux-gluereimpl/funmath.cpp | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-11-07T00:02:47.000Z | 2020-11-07T00:02:47.000Z | // funmath.cpp -- MUX math function handlers.
//
// $Id: funmath.cpp,v 1.3 2005/07/14 04:40:54 rmg Exp $
//
// MUX 2.4
// Copyright (C) 1998 through 2005 Solid Vertical Domains, Ltd. All
// rights not explicitly given are reserved.
//
#include "copyright.h"
#include "autoconf.h"
#include "config.h"
#include "externs.h"
#include <float.h>
#include <limits.h>
#include <math.h>
#include "functions.h"
#include "funmath.h"
#include "sha1.h"
#ifdef HAVE_IEEE_FP_FORMAT
const char *mux_FPStrings[] = { "+Inf", "-Inf", "Ind", "NaN", "0", "0", "0", "0" };
#define MUX_FPGROUP_PASS 0x00 // Pass-through to printf
#define MUX_FPGROUP_ZERO 0x10 // Force to be zero.
#define MUX_FPGROUP_PINF 0x20 // "+Inf"
#define MUX_FPGROUP_NINF 0x30 // "-Inf"
#define MUX_FPGROUP_IND 0x40 // "Ind"
#define MUX_FPGROUP_NAN 0x50 // "NaN"
#define MUX_FPGROUP(x) ((x) & 0xF0)
// mux_fpclass returns an integer that is one of the following:
//
#define MUX_FPCLASS_PINF (MUX_FPGROUP_PINF|0) // Positive infinity (+INF)
#define MUX_FPCLASS_NINF (MUX_FPGROUP_NINF|1) // Negative infinity (-INF)
#define MUX_FPCLASS_QNAN (MUX_FPGROUP_IND |2) // Quiet NAN (Indefinite)
#define MUX_FPCLASS_SNAN (MUX_FPGROUP_NAN |3) // Signaling NAN
#define MUX_FPCLASS_ND (MUX_FPGROUP_ZERO|4) // Negative denormalized
#define MUX_FPCLASS_NZ (MUX_FPGROUP_ZERO|5) // Negative zero (-0)
#define MUX_FPCLASS_PZ (MUX_FPGROUP_ZERO|6) // Positive zero (+0)
#define MUX_FPCLASS_PD (MUX_FPGROUP_ZERO|7) // Positive denormalized
#define MUX_FPCLASS_PN (MUX_FPGROUP_PASS|8) // Positive normalized non-zero
#define MUX_FPCLASS_NN (MUX_FPGROUP_PASS|9) // Negative normalized non-zero
#define MUX_FPCLASS(x) ((x) & 0x0F)
#ifdef WIN32
#define IEEE_MASK_SIGN 0x8000000000000000ui64
#define IEEE_MASK_EXPONENT 0x7FF0000000000000ui64
#define IEEE_MASK_MANTISSA 0x000FFFFFFFFFFFFFui64
#define IEEE_MASK_QNAN 0x0008000000000000ui64
#else
#define IEEE_MASK_SIGN 0x8000000000000000ull
#define IEEE_MASK_EXPONENT 0x7FF0000000000000ull
#define IEEE_MASK_MANTISSA 0x000FFFFFFFFFFFFFull
#define IEEE_MASK_QNAN 0x0008000000000000ull
#endif
#define ARBITRARY_NUMBER 1
#define IEEE_MAKE_TABLESIZE 5
typedef union
{
INT64 i64;
double d;
} SpecialFloatUnion;
// We return a Quiet NAN when a Signalling NAN is requested because
// any operation on a Signalling NAN will result in a Quiet NAN anyway.
// MUX doesn't catch SIGFPE, but if it did, a Signalling NAN would
// generate a SIGFPE.
//
SpecialFloatUnion SpecialFloatTable[IEEE_MAKE_TABLESIZE] =
{
{ 0 }, // Unused.
{ IEEE_MASK_EXPONENT | IEEE_MASK_QNAN | ARBITRARY_NUMBER },
{ IEEE_MASK_EXPONENT | IEEE_MASK_QNAN | ARBITRARY_NUMBER },
{ IEEE_MASK_EXPONENT },
{ IEEE_MASK_EXPONENT | IEEE_MASK_SIGN }
};
double MakeSpecialFloat(int iWhich)
{
return SpecialFloatTable[iWhich].d;
}
static int mux_fpclass(double result)
{
UINT64 i64;
*((double *)&i64) = result;
if ((i64 & IEEE_MASK_EXPONENT) == 0)
{
if (i64 & IEEE_MASK_MANTISSA)
{
if (i64 & IEEE_MASK_SIGN) return MUX_FPCLASS_ND;
else return MUX_FPCLASS_PD;
}
else
{
if (i64 & IEEE_MASK_SIGN) return MUX_FPCLASS_NZ;
else return MUX_FPCLASS_PZ;
}
}
else if ((i64 & IEEE_MASK_EXPONENT) == IEEE_MASK_EXPONENT)
{
if (i64 & IEEE_MASK_MANTISSA)
{
if (i64 & IEEE_MASK_QNAN) return MUX_FPCLASS_QNAN;
else return MUX_FPCLASS_SNAN;
}
else
{
if (i64 & IEEE_MASK_SIGN) return MUX_FPCLASS_NINF;
else return MUX_FPCLASS_PINF;
}
}
else
{
if (i64 & IEEE_MASK_SIGN) return MUX_FPCLASS_NN;
else return MUX_FPCLASS_PN;
}
}
#endif // HAVE_IEEE_FP_FORMAT
static double AddWithError(double& err, double a, double b)
{
double sum = a+b;
err = b-(sum-a);
return sum;
}
// Typically, we are within 1ulp of an exact answer, find the shortest answer
// within that 1 ulp (that is, within 0, +ulp, and -ulp).
//
static double NearestPretty(double R)
{
char *rve = NULL;
int decpt;
int bNegative;
const int mode = 0;
double ulpR = ulp(R);
double R0 = R-ulpR;
double R1 = R+ulpR;
// R.
//
char *p = mux_dtoa(R, mode, 50, &decpt, &bNegative, &rve);
int nDigits = rve - p;
// R-ulp(R)
//
p = mux_dtoa(R0, mode, 50, &decpt, &bNegative, &rve);
if (rve - p < nDigits)
{
nDigits = rve - p;
R = R0;
}
// R+ulp(R)
//
p = mux_dtoa(R1, mode, 50, &decpt, &bNegative, &rve);
if (rve - p < nDigits)
{
nDigits = rve - p;
R = R1;
}
return R;
}
// Compare for decreasing order by absolute value.
//
static int DCL_CDECL f_comp_abs(const void *s1, const void *s2)
{
double a = fabs(*(double *)s1);
double b = fabs(*(double *)s2);
if (a > b)
{
return -1;
}
else if (a < b)
{
return 1;
}
return 0;
}
// Double compensation method. Extended by Priest from Knuth and Kahan.
//
// Error of sum is less than 2*epsilon or 1 ulp except for very large n.
// Return the result that yields the shortest number of base-10 digits.
//
static double AddDoubles(int n, double pd[])
{
qsort(pd, n, sizeof(double), f_comp_abs);
double sum = 0.0;
if (0 < n)
{
sum = pd[0];
double sum_err = 0.0;
int i;
for (i = 1; i < n; i++)
{
double addend_err;
double addend = AddWithError(addend_err, sum_err, pd[i]);
double sum1_err;
double sum1 = AddWithError(sum1_err, sum, addend);
sum = AddWithError(sum_err, sum1, addend_err + sum1_err);
}
}
return NearestPretty(sum);
}
/* ---------------------------------------------------------------------------
* fval: copy the floating point value into a buffer and make it presentable
*/
static void fval(char *buff, char **bufc, double result)
{
// Get double val into buffer.
//
#ifdef HAVE_IEEE_FP_FORMAT
int fpc = mux_fpclass(result);
if (MUX_FPGROUP(fpc) == MUX_FPGROUP_PASS)
{
#endif // HAVE_IEEE_FP_FORMAT
double rIntegerPart;
double rFractionalPart = modf(result, &rIntegerPart);
if ( 0.0 == rFractionalPart
&& LONG_MIN <= rIntegerPart
&& rIntegerPart <= LONG_MAX)
{
long i = (long)rIntegerPart;
safe_ltoa(i, buff, bufc);
}
else
{
safe_str(mux_ftoa(result, false, 0), buff, bufc);
}
#ifdef HAVE_IEEE_FP_FORMAT
}
else
{
safe_str(mux_FPStrings[MUX_FPCLASS(fpc)], buff, bufc);
}
#endif // HAVE_IEEE_FP_FORMAT
}
static const long nMaximums[10] =
{
0, 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999
};
static double g_aDoubles[(LBUF_SIZE+1)/2];
FUNCTION(fun_add)
{
int i;
for (i = 0; i < nfargs; i++)
{
int nDigits;
long nMaxValue = 0;
if ( !is_integer(fargs[i], &nDigits)
|| nDigits > 9
|| (nMaxValue += nMaximums[nDigits]) > 999999999L)
{
// Do it the slow way.
//
for (int j = 0; j < nfargs; j++)
{
g_aDoubles[j] = mux_atof(fargs[j]);
}
fval(buff, bufc, AddDoubles(nfargs, g_aDoubles));
return;
}
}
// We can do it the fast way.
//
long sum = 0;
for (i = 0; i < nfargs; i++)
{
sum += mux_atol(fargs[i]);
}
safe_ltoa(sum, buff, bufc);
}
FUNCTION(fun_ladd)
{
int n = 0;
if (0 < nfargs)
{
SEP sep;
if (!OPTIONAL_DELIM(2, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
char *cp = trim_space_sep(fargs[0], &sep);
while (cp)
{
char *curr = split_token(&cp, &sep);
g_aDoubles[n++] = mux_atof(curr);
}
}
fval(buff, bufc, AddDoubles(n, g_aDoubles));
}
/////////////////////////////////////////////////////////////////
// Function : iadd(Arg[0], Arg[1],..,Arg[n])
//
// Written by : Chris Rouse (Seraphim) 04/04/2000
/////////////////////////////////////////////////////////////////
FUNCTION(fun_iadd)
{
INT64 sum = 0;
for (int i = 0; i < nfargs; i++)
{
sum += mux_atoi64(fargs[i]);
}
safe_i64toa(sum, buff, bufc);
}
FUNCTION(fun_sub)
{
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
int iResult;
iResult = mux_atol(fargs[0]) - mux_atol(fargs[1]);
safe_ltoa(iResult, buff, bufc);
}
else
{
g_aDoubles[0] = mux_atof(fargs[0]);
g_aDoubles[1] = -mux_atof(fargs[1]);
fval(buff, bufc, AddDoubles(2, g_aDoubles));
}
}
/////////////////////////////////////////////////////////////////
// Function : isub(Arg[0], Arg[1])
//
// Written by : Chris Rouse (Seraphim) 04/04/2000
/////////////////////////////////////////////////////////////////
FUNCTION(fun_isub)
{
INT64 diff = mux_atoi64(fargs[0]) - mux_atoi64(fargs[1]);
safe_i64toa(diff, buff, bufc);
}
FUNCTION(fun_mul)
{
double prod = 1.0;
for (int i = 0; i < nfargs; i++)
{
prod *= mux_atof(fargs[i]);
}
fval(buff, bufc, NearestPretty(prod));
}
/////////////////////////////////////////////////////////////////
// Function : imul(Arg[0], Arg[1], ... , Arg[n])
//
// Written by : Chris Rouse (Seraphim) 04/04/2000
/////////////////////////////////////////////////////////////////
FUNCTION(fun_imul)
{
INT64 prod = 1;
for (int i = 0; i < nfargs; i++)
{
prod *= mux_atoi64(fargs[i]);
}
safe_i64toa(prod, buff, bufc);
}
FUNCTION(fun_gt)
{
bool bResult = false;
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
bResult = (mux_atol(fargs[0]) > mux_atol(fargs[1]));
}
else
{
bResult = (mux_atof(fargs[0]) > mux_atof(fargs[1]));
}
safe_bool(bResult, buff, bufc);
}
FUNCTION(fun_gte)
{
bool bResult = false;
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
bResult = (mux_atol(fargs[0]) >= mux_atol(fargs[1]));
}
else
{
bResult = (mux_atof(fargs[0]) >= mux_atof(fargs[1]));
}
safe_bool(bResult, buff, bufc);
}
FUNCTION(fun_lt)
{
bool bResult = false;
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
bResult = (mux_atol(fargs[0]) < mux_atol(fargs[1]));
}
else
{
bResult = (mux_atof(fargs[0]) < mux_atof(fargs[1]));
}
safe_bool(bResult, buff, bufc);
}
FUNCTION(fun_lte)
{
bool bResult = false;
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
bResult = (mux_atol(fargs[0]) <= mux_atol(fargs[1]));
}
else
{
bResult = (mux_atof(fargs[0]) <= mux_atof(fargs[1]));
}
safe_bool(bResult, buff, bufc);
}
FUNCTION(fun_eq)
{
bool bResult = false;
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
bResult = (mux_atol(fargs[0]) == mux_atol(fargs[1]));
}
else
{
bResult = ( strcmp(fargs[0], fargs[1]) == 0
|| mux_atof(fargs[0]) == mux_atof(fargs[1]));
}
safe_bool(bResult, buff, bufc);
}
FUNCTION(fun_neq)
{
bool bResult = false;
int nDigits;
if ( is_integer(fargs[0], &nDigits)
&& nDigits <= 9
&& is_integer(fargs[1], &nDigits)
&& nDigits <= 9)
{
bResult = (mux_atol(fargs[0]) != mux_atol(fargs[1]));
}
else
{
bResult = ( strcmp(fargs[0], fargs[1]) != 0
&& mux_atof(fargs[0]) != mux_atof(fargs[1]));
}
safe_bool(bResult, buff, bufc);
}
/*
* ---------------------------------------------------------------------------
* * fun_max, fun_min: Return maximum (minimum) value.
*/
FUNCTION(fun_max)
{
double maximum = 0.0;
for (int i = 0; i < nfargs; i++)
{
double tval = mux_atof(fargs[i]);
if ( i == 0
|| tval > maximum)
{
maximum = tval;
}
}
fval(buff, bufc, maximum);
}
FUNCTION(fun_min)
{
double minimum = 0.0;
for (int i = 0; i < nfargs; i++)
{
double tval = mux_atof(fargs[i]);
if ( i == 0
|| tval < minimum)
{
minimum = tval;
}
}
fval(buff, bufc, minimum);
}
/* ---------------------------------------------------------------------------
* fun_sign: Returns -1, 0, or 1 based on the the sign of its argument.
*/
FUNCTION(fun_sign)
{
double num = mux_atof(fargs[0]);
if (num < 0)
{
safe_str("-1", buff, bufc);
}
else
{
safe_bool(num > 0, buff, bufc);
}
}
// fun_isign: Returns -1, 0, or 1 based on the the sign of its argument.
//
FUNCTION(fun_isign)
{
INT64 num = mux_atoi64(fargs[0]);
if (num < 0)
{
safe_str("-1", buff, bufc);
}
else
{
safe_bool(num > 0, buff, bufc);
}
}
// shl() and shr() borrowed from PennMUSH 1.50
//
FUNCTION(fun_shl)
{
if ( is_integer(fargs[0], NULL)
&& is_integer(fargs[1], NULL))
{
safe_i64toa(mux_atoi64(fargs[0]) << mux_atol(fargs[1]), buff, bufc);
}
else
{
safe_str("#-1 ARGUMENTS MUST BE INTEGERS", buff, bufc);
}
}
FUNCTION(fun_shr)
{
if ( is_integer(fargs[0], NULL)
&& is_integer(fargs[1], NULL))
{
safe_i64toa(mux_atoi64(fargs[0]) >> mux_atol(fargs[1]), buff, bufc);
}
else
{
safe_str("#-1 ARGUMENTS MUST BE INTEGERS", buff, bufc);
}
}
FUNCTION(fun_inc)
{
if (nfargs == 1)
{
safe_i64toa(mux_atoi64(fargs[0]) + 1, buff, bufc);
}
else
{
safe_chr('1', buff, bufc);
}
}
FUNCTION(fun_dec)
{
if (nfargs == 1)
{
safe_i64toa(mux_atoi64(fargs[0]) - 1, buff, bufc);
}
else
{
safe_str("-1", buff, bufc);
}
}
FUNCTION(fun_trunc)
{
double rArg = mux_atof(fargs[0]);
double rIntegerPart;
double rFractionalPart;
mux_FPRestore();
rFractionalPart = modf(rArg, &rIntegerPart);
mux_FPSet();
#ifdef HAVE_IEEE_FP_FORMAT
int fpc = mux_fpclass(rIntegerPart);
if (MUX_FPGROUP(fpc) == MUX_FPGROUP_PASS)
{
#endif // HAVE_IEEE_FP_FORMAT
safe_tprintf_str(buff, bufc, "%.0f", rIntegerPart);
#ifdef HAVE_IEEE_FP_FORMAT
}
else
{
safe_str(mux_FPStrings[MUX_FPCLASS(fpc)], buff, bufc);
}
#endif // HAVE_IEEE_FP_FORMAT
}
FUNCTION(fun_fdiv)
{
double bot = mux_atof(fargs[1]);
double top = mux_atof(fargs[0]);
#ifndef HAVE_IEEE_FP_SNAN
if (bot == 0.0)
{
if (top > 0.0)
{
safe_str("+Inf", buff, bufc);
}
else if (top < 0.0)
{
safe_str("-Inf", buff, bufc);
}
else
{
safe_str("Ind", buff, bufc);
}
}
else
{
fval(buff, bufc, top/bot);
}
#else
fval(buff, bufc, top/bot);
#endif
}
FUNCTION(fun_idiv)
{
INT64 bot, top;
bot = mux_atoi64(fargs[1]);
if (bot == 0)
{
safe_str("#-1 DIVIDE BY ZERO", buff, bufc);
}
else
{
top = mux_atoi64(fargs[0]);
top = i64Division(top, bot);
safe_i64toa(top, buff, bufc);
}
}
FUNCTION(fun_floordiv)
{
INT64 bot, top;
bot = mux_atoi64(fargs[1]);
if (bot == 0)
{
safe_str("#-1 DIVIDE BY ZERO", buff, bufc);
}
else
{
top = mux_atoi64(fargs[0]);
top = i64FloorDivision(top, bot);
safe_i64toa(top, buff, bufc);
}
}
FUNCTION(fun_mod)
{
INT64 bot, top;
bot = mux_atoi64(fargs[1]);
if (bot == 0)
{
bot = 1;
}
top = mux_atoi64(fargs[0]);
top = i64Mod(top, bot);
safe_i64toa(top, buff, bufc);
}
FUNCTION(fun_remainder)
{
INT64 bot, top;
bot = mux_atoi64(fargs[1]);
if (bot == 0)
{
bot = 1;
}
top = mux_atoi64(fargs[0]);
top = i64Remainder(top, bot);
safe_i64toa(top, buff, bufc);
}
/* ---------------------------------------------------------------------------
* fun_abs: Returns the absolute value of its argument.
*/
FUNCTION(fun_abs)
{
double num = mux_atof(fargs[0]);
if (num == 0.0)
{
safe_chr('0', buff, bufc);
}
else if (num < 0.0)
{
fval(buff, bufc, -num);
}
else
{
fval(buff, bufc, num);
}
}
// fun_iabs: Returns the absolute value of its argument.
//
FUNCTION(fun_iabs)
{
INT64 num = mux_atoi64(fargs[0]);
if (num == 0)
{
safe_chr('0', buff, bufc);
}
else if (num < 0)
{
safe_i64toa(-num, buff, bufc);
}
else
{
safe_i64toa(num, buff, bufc);
}
}
FUNCTION(fun_dist2d)
{
double d;
double sum;
d = mux_atof(fargs[0]) - mux_atof(fargs[2]);
sum = d * d;
d = mux_atof(fargs[1]) - mux_atof(fargs[3]);
sum += d * d;
mux_FPRestore();
double result = sqrt(sum);
mux_FPSet();
fval(buff, bufc, result);
}
FUNCTION(fun_dist3d)
{
double d;
double sum;
d = mux_atof(fargs[0]) - mux_atof(fargs[3]);
sum = d * d;
d = mux_atof(fargs[1]) - mux_atof(fargs[4]);
sum += d * d;
d = mux_atof(fargs[2]) - mux_atof(fargs[5]);
sum += d * d;
mux_FPRestore();
double result = sqrt(sum);
mux_FPSet();
fval(buff, bufc, result);
}
//------------------------------------------------------------------------
// Vector functions: VADD, VSUB, VMUL, VCROSS, VMAG, VUNIT, VDIM
// Vectors are space-separated numbers.
//
#define VADD_F 0
#define VSUB_F 1
#define VMUL_F 2
#define VDOT_F 3
#define VCROSS_F 4
static void handle_vectors
(
char *vecarg1, char *vecarg2, char *buff, char **bufc, SEP *psep,
SEP *posep, int flag
)
{
char *v1[(LBUF_SIZE+1)/2], *v2[(LBUF_SIZE+1)/2];
double scalar;
int n, m, i;
// Split the list up, or return if the list is empty.
//
if (!vecarg1 || !*vecarg1 || !vecarg2 || !*vecarg2)
{
return;
}
n = list2arr(v1, (LBUF_SIZE+1)/2, vecarg1, psep);
m = list2arr(v2, (LBUF_SIZE+1)/2, vecarg2, psep);
// vmul() and vadd() accepts a scalar in the first or second arg,
// but everything else has to be same-dimensional.
//
if ( n != m
&& !( ( flag == VMUL_F
|| flag == VADD_F
|| flag == VSUB_F)
&& ( n == 1
|| m == 1)))
{
safe_str("#-1 VECTORS MUST BE SAME DIMENSIONS", buff, bufc);
return;
}
switch (flag)
{
case VADD_F:
// If n or m is 1, this is scalar addition.
// otherwise, add element-wise.
//
if (n == 1)
{
scalar = mux_atof(v1[0]);
for (i = 0; i < m; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v2[i]) + scalar);
}
n = m;
}
else if (m == 1)
{
scalar = mux_atof(v2[0]);
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v1[i]) + scalar);
}
}
else
{
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v1[i]) + mux_atof(v2[i]));
}
}
break;
case VSUB_F:
if (n == 1)
{
// This is a scalar minus a vector.
//
scalar = mux_atof(v1[0]);
for (i = 0; i < m; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, scalar - mux_atof(v2[i]));
}
}
else if (m == 1)
{
// This is a vector minus a scalar.
//
scalar = mux_atof(v2[0]);
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v1[i]) - scalar);
}
}
else
{
// This is a vector minus a vector.
//
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v1[i]) - mux_atof(v2[i]));
}
}
break;
case VMUL_F:
// If n or m is 1, this is scalar multiplication.
// otherwise, multiply elementwise.
//
if (n == 1)
{
scalar = mux_atof(v1[0]);
for (i = 0; i < m; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v2[i]) * scalar);
}
}
else if (m == 1)
{
scalar = mux_atof(v2[0]);
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v1[i]) * scalar);
}
}
else
{
// Vector element-wise product.
//
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(posep, buff, bufc);
}
fval(buff, bufc, mux_atof(v1[i]) * mux_atof(v2[i]));
}
}
break;
case VDOT_F:
scalar = 0.0;
for (i = 0; i < n; i++)
{
scalar += mux_atof(v1[i]) * mux_atof(v2[i]);
}
fval(buff, bufc, scalar);
break;
case VCROSS_F:
// cross product: (a,b,c) x (d,e,f) = (bf - ce, cd - af, ae - bd)
//
// Or in other words:
//
// | a b c |
// det | d e f | = i(bf-ce) + j(cd-af) + k(ae-bd)
// | i j k |
//
// where i, j, and k are unit vectors in the x, y, and z
// cartisian coordinate space and are understood when expressed
// in vector form.
//
if (n != 3)
{
safe_str("#-1 VECTORS MUST BE DIMENSION OF 3", buff, bufc);
}
else
{
double a[2][3];
for (i = 0; i < 3; i++)
{
a[0][i] = mux_atof(v1[i]);
a[1][i] = mux_atof(v2[i]);
}
fval(buff, bufc, (a[0][1] * a[1][2]) - (a[0][2] * a[1][1]));
print_sep(posep, buff, bufc);
fval(buff, bufc, (a[0][2] * a[1][0]) - (a[0][0] * a[1][2]));
print_sep(posep, buff, bufc);
fval(buff, bufc, (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]));
}
break;
default:
// If we reached this, we're in trouble.
//
safe_str("#-1 UNIMPLEMENTED", buff, bufc);
}
}
FUNCTION(fun_vadd)
{
SEP sep;
if (!OPTIONAL_DELIM(3, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
SEP osep = sep;
if (!OPTIONAL_DELIM(4, osep, DELIM_NULL|DELIM_CRLF|DELIM_STRING|DELIM_INIT))
{
return;
}
handle_vectors(fargs[0], fargs[1], buff, bufc, &sep, &osep, VADD_F);
}
FUNCTION(fun_vsub)
{
SEP sep;
if (!OPTIONAL_DELIM(3, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
SEP osep = sep;
if (!OPTIONAL_DELIM(4, osep, DELIM_NULL|DELIM_CRLF|DELIM_STRING|DELIM_INIT))
{
return;
}
handle_vectors(fargs[0], fargs[1], buff, bufc, &sep, &osep, VSUB_F);
}
FUNCTION(fun_vmul)
{
SEP sep;
if (!OPTIONAL_DELIM(3, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
SEP osep = sep;
if (!OPTIONAL_DELIM(4, osep, DELIM_NULL|DELIM_CRLF|DELIM_STRING|DELIM_INIT))
{
return;
}
handle_vectors(fargs[0], fargs[1], buff, bufc, &sep, &osep, VMUL_F);
}
FUNCTION(fun_vdot)
{
// dot product: (a,b,c) . (d,e,f) = ad + be + cf
//
SEP sep;
if (!OPTIONAL_DELIM(3, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
SEP osep = sep;
if (!OPTIONAL_DELIM(4, osep, DELIM_NULL|DELIM_CRLF|DELIM_STRING|DELIM_INIT))
{
return;
}
handle_vectors(fargs[0], fargs[1], buff, bufc, &sep, &osep, VDOT_F);
}
FUNCTION(fun_vcross)
{
// cross product: (a,b,c) x (d,e,f) = (bf - ce, cd - af, ae - bd)
//
SEP sep;
if (!OPTIONAL_DELIM(3, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
SEP osep = sep;
if (!OPTIONAL_DELIM(4, osep, DELIM_NULL|DELIM_CRLF|DELIM_STRING|DELIM_INIT))
{
return;
}
handle_vectors(fargs[0], fargs[1], buff, bufc, &sep, &osep, VCROSS_F);
}
FUNCTION(fun_vmag)
{
SEP sep;
if (!OPTIONAL_DELIM(2, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
char *v1[LBUF_SIZE];
int n, i;
double tmp, res = 0.0;
// Split the list up, or return if the list is empty.
//
if (!fargs[0] || !*fargs[0])
{
return;
}
n = list2arr(v1, LBUF_SIZE, fargs[0], &sep);
// Calculate the magnitude.
//
for (i = 0; i < n; i++)
{
tmp = mux_atof(v1[i]);
res += tmp * tmp;
}
if (res > 0)
{
mux_FPRestore();
double result = sqrt(res);
mux_FPSet();
fval(buff, bufc, result);
}
else
{
safe_chr('0', buff, bufc);
}
}
FUNCTION(fun_vunit)
{
SEP sep;
if (!OPTIONAL_DELIM(2, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
char *v1[LBUF_SIZE];
int n, i;
double tmp, res = 0.0;
// Split the list up, or return if the list is empty.
//
if (!fargs[0] || !*fargs[0])
{
return;
}
n = list2arr(v1, LBUF_SIZE, fargs[0], &sep);
// Calculate the magnitude.
//
for (i = 0; i < n; i++)
{
tmp = mux_atof(v1[i]);
res += tmp * tmp;
}
if (res <= 0)
{
safe_str("#-1 CAN'T MAKE UNIT VECTOR FROM ZERO-LENGTH VECTOR",
buff, bufc);
return;
}
for (i = 0; i < n; i++)
{
if (i != 0)
{
print_sep(&sep, buff, bufc);
}
mux_FPRestore();
double result = sqrt(res);
mux_FPSet();
fval(buff, bufc, mux_atof(v1[i]) / result);
}
}
FUNCTION(fun_floor)
{
mux_FPRestore();
double r = floor(mux_atof(fargs[0]));
mux_FPSet();
#ifdef HAVE_IEEE_FP_FORMAT
int fpc = mux_fpclass(r);
if (MUX_FPGROUP(fpc) == MUX_FPGROUP_PASS)
{
#endif // HAVE_IEEE_FP_FORMAT
safe_tprintf_str(buff, bufc, "%.0f", r);
#ifdef HAVE_IEEE_FP_FORMAT
}
else
{
safe_str(mux_FPStrings[MUX_FPCLASS(fpc)], buff, bufc);
}
#endif // HAVE_IEEE_FP_FORMAT
}
FUNCTION(fun_ceil)
{
mux_FPRestore();
double r = ceil(mux_atof(fargs[0]));
mux_FPSet();
#ifdef HAVE_IEEE_FP_FORMAT
int fpc = mux_fpclass(r);
if (MUX_FPGROUP(fpc) == MUX_FPGROUP_PASS)
{
#endif // HAVE_IEEE_FP_FORMAT
safe_tprintf_str(buff, bufc, "%.0f", r);
#ifdef HAVE_IEEE_FP_FORMAT
}
else
{
safe_str(mux_FPStrings[MUX_FPCLASS(fpc)], buff, bufc);
}
#endif // HAVE_IEEE_FP_FORMAT
}
FUNCTION(fun_round)
{
double r = mux_atof(fargs[0]);
#ifdef HAVE_IEEE_FP_FORMAT
int fpc = mux_fpclass(r);
if ( MUX_FPGROUP(fpc) == MUX_FPGROUP_PASS
|| MUX_FPGROUP(fpc) == MUX_FPGROUP_ZERO)
{
if (MUX_FPGROUP(fpc) == MUX_FPGROUP_ZERO)
{
r = 0.0;
}
#endif // HAVE_IEEE_FP_FORMAT
int frac = mux_atol(fargs[1]);
safe_str(mux_ftoa(r, true, frac), buff, bufc);
#ifdef HAVE_IEEE_FP_FORMAT
}
else
{
safe_str(mux_FPStrings[MUX_FPCLASS(fpc)], buff, bufc);
}
#endif // HAVE_IEEE_FP_FORMAT
}
FUNCTION(fun_pi)
{
safe_str("3.141592653589793", buff, bufc);
}
FUNCTION(fun_e)
{
safe_str("2.718281828459045", buff, bufc);
}
static double ConvertRDG2R(double d, const char *szUnits)
{
switch (mux_tolower(szUnits[0]))
{
case 'd':
// Degrees to Radians.
//
d *= 0.017453292519943295;
break;
case 'g':
// Gradians to Radians.
//
d *= 0.015707963267948967;
break;
}
return d;
}
static double ConvertR2RDG(double d, const char *szUnits)
{
switch (mux_tolower(szUnits[0]))
{
case 'd':
// Radians to Degrees.
//
d *= 57.29577951308232;
break;
case 'g':
// Radians to Gradians.
//
d *= 63.66197723675813;
break;
}
return d;
}
FUNCTION(fun_ctu)
{
double val = mux_atof(fargs[0]);
val = ConvertRDG2R(val, fargs[1]);
val = ConvertR2RDG(val, fargs[2]);
fval(buff, bufc, val);
}
FUNCTION(fun_sin)
{
double d = mux_atof(fargs[0]);
if (nfargs == 2)
{
d = ConvertRDG2R(d, fargs[1]);
}
mux_FPRestore();
d = sin(d);
mux_FPSet();
fval(buff, bufc, d);
}
FUNCTION(fun_cos)
{
double d = mux_atof(fargs[0]);
if (nfargs == 2)
{
d = ConvertRDG2R(d, fargs[1]);
}
mux_FPRestore();
d = cos(d);
mux_FPSet();
fval(buff, bufc, d);
}
FUNCTION(fun_tan)
{
double d = mux_atof(fargs[0]);
if (nfargs == 2)
{
d = ConvertRDG2R(d, fargs[1]);
}
mux_FPRestore();
d = tan(d);
mux_FPSet();
fval(buff, bufc, d);
}
FUNCTION(fun_asin)
{
double val = mux_atof(fargs[0]);
#ifndef HAVE_IEEE_FP_SNAN
if ((val < -1.0) || (val > 1.0))
{
safe_str("Ind", buff, bufc);
return;
}
#endif
mux_FPRestore();
val = asin(val);
mux_FPSet();
if (nfargs == 2)
{
val = ConvertR2RDG(val, fargs[1]);
}
fval(buff, bufc, val);
}
FUNCTION(fun_acos)
{
double val = mux_atof(fargs[0]);
#ifndef HAVE_IEEE_FP_SNAN
if ((val < -1.0) || (val > 1.0))
{
safe_str("Ind", buff, bufc);
return;
}
#endif
mux_FPRestore();
val = acos(val);
mux_FPSet();
if (nfargs == 2)
{
val = ConvertR2RDG(val, fargs[1]);
}
fval(buff, bufc, val);
}
FUNCTION(fun_atan)
{
double val = mux_atof(fargs[0]);
mux_FPRestore();
val = atan(val);
mux_FPSet();
if (nfargs == 2)
{
val = ConvertR2RDG(val, fargs[1]);
}
fval(buff, bufc, val);
}
FUNCTION(fun_exp)
{
double val = mux_atof(fargs[0]);
mux_FPRestore();
val = exp(val);
mux_FPSet();
fval(buff, bufc, val);
}
FUNCTION(fun_power)
{
double val, val1, val2;
val1 = mux_atof(fargs[0]);
val2 = mux_atof(fargs[1]);
#ifndef HAVE_IEEE_FP_SNAN
if (val1 < 0.0)
{
safe_str("Ind", buff, bufc);
}
else
{
mux_FPRestore();
val = pow(val1, val2);
mux_FPSet();
}
#else
mux_FPRestore();
val = pow(val1, val2);
mux_FPSet();
#endif
fval(buff, bufc, val);
}
FUNCTION(fun_ln)
{
double val;
val = mux_atof(fargs[0]);
#ifndef HAVE_IEEE_FP_SNAN
if (val < 0.0)
{
safe_str("Ind", buff, bufc);
}
else if (val == 0.0)
{
safe_str("-Inf", buff, bufc);
}
else
{
mux_FPRestore();
val = log(val);
mux_FPSet();
}
#else
mux_FPRestore();
val = log(val);
mux_FPSet();
#endif
fval(buff, bufc, val);
}
FUNCTION(fun_log)
{
double val;
val = mux_atof(fargs[0]);
#ifndef HAVE_IEEE_FP_SNAN
if (val < 0.0)
{
safe_str("Ind", buff, bufc);
}
else if (val == 0.0)
{
safe_str("-Inf", buff, bufc);
}
else
{
mux_FPRestore();
val = log10(val);
mux_FPSet();
}
#else
mux_FPRestore();
val = log10(val);
mux_FPSet();
#endif
fval(buff, bufc, val);
}
FUNCTION(fun_sqrt)
{
double val;
val = mux_atof(fargs[0]);
#ifndef HAVE_IEEE_FP_SNAN
if (val < 0.0)
{
safe_str("Ind", buff, bufc);
}
else if (val == 0.0)
{
safe_chr('0', buff, bufc);
}
else
{
mux_FPRestore();
val = sqrt(val);
mux_FPSet();
}
#else
mux_FPRestore();
val = sqrt(val);
mux_FPSet();
#endif
fval(buff, bufc, val);
}
/* ---------------------------------------------------------------------------
* isnum: is the argument a number?
*/
FUNCTION(fun_isnum)
{
safe_bool(is_real(fargs[0]), buff, bufc);
}
/* ---------------------------------------------------------------------------
* israt: is the argument an rational?
*/
FUNCTION(fun_israt)
{
safe_bool(is_rational(fargs[0]), buff, bufc);
}
/* ---------------------------------------------------------------------------
* isint: is the argument an integer?
*/
FUNCTION(fun_isint)
{
safe_bool(is_integer(fargs[0], NULL), buff, bufc);
}
FUNCTION(fun_and)
{
bool val = true;
for (int i = 0; i < nfargs && val; i++)
{
val = isTRUE(mux_atol(fargs[i]));
}
safe_bool(val, buff, bufc);
}
FUNCTION(fun_or)
{
bool val = false;
for (int i = 0; i < nfargs && !val; i++)
{
val = isTRUE(mux_atol(fargs[i]));
}
safe_bool(val, buff, bufc);
}
FUNCTION(fun_andbool)
{
bool val = true;
for (int i = 0; i < nfargs && val; i++)
{
val = xlate(fargs[i]);
}
safe_bool(val, buff, bufc);
}
FUNCTION(fun_orbool)
{
bool val = false;
for (int i = 0; i < nfargs && !val; i++)
{
val = xlate(fargs[i]);
}
safe_bool(val, buff, bufc);
}
FUNCTION(fun_cand)
{
bool val = true;
char *temp = alloc_lbuf("fun_cand");
for (int i = 0; i < nfargs && val && !MuxAlarm.bAlarmed; i++)
{
char *bp = temp;
char *str = fargs[i];
mux_exec(temp, &bp, executor, caller, enactor,
EV_STRIP_CURLY | EV_FCHECK | EV_EVAL, &str, cargs, ncargs);
*bp = '\0';
val = isTRUE(mux_atol(temp));
}
free_lbuf(temp);
safe_bool(val, buff, bufc);
}
FUNCTION(fun_cor)
{
bool val = false;
char *temp = alloc_lbuf("fun_cor");
for (int i = 0; i < nfargs && !val && !MuxAlarm.bAlarmed; i++)
{
char *bp = temp;
char *str = fargs[i];
mux_exec(temp, &bp, executor, caller, enactor,
EV_STRIP_CURLY | EV_FCHECK | EV_EVAL, &str, cargs, ncargs);
*bp = '\0';
val = isTRUE(mux_atol(temp));
}
free_lbuf(temp);
safe_bool(val, buff, bufc);
}
FUNCTION(fun_candbool)
{
bool val = true;
char *temp = alloc_lbuf("fun_candbool");
for (int i = 0; i < nfargs && val && !MuxAlarm.bAlarmed; i++)
{
char *bp = temp;
char *str = fargs[i];
mux_exec(temp, &bp, executor, caller, enactor,
EV_STRIP_CURLY | EV_FCHECK | EV_EVAL, &str, cargs, ncargs);
*bp = '\0';
val = xlate(temp);
}
free_lbuf(temp);
safe_bool(val, buff, bufc);
}
FUNCTION(fun_corbool)
{
bool val = false;
char *temp = alloc_lbuf("fun_corbool");
for (int i = 0; i < nfargs && !val && !MuxAlarm.bAlarmed; i++)
{
char *bp = temp;
char *str = fargs[i];
mux_exec(temp, &bp, executor, caller, enactor,
EV_STRIP_CURLY | EV_FCHECK | EV_EVAL, &str, cargs, ncargs);
*bp = '\0';
val = xlate(temp);
}
free_lbuf(temp);
safe_bool(val, buff, bufc);
}
FUNCTION(fun_xor)
{
bool val = false;
for (int i = 0; i < nfargs; i++)
{
int tval = mux_atol(fargs[i]);
val = (val && !tval) || (!val && tval);
}
safe_bool(val, buff, bufc);
}
FUNCTION(fun_not)
{
safe_bool(!xlate(fargs[0]), buff, bufc);
}
FUNCTION(fun_t)
{
if ( nfargs <= 0
|| fargs[0][0] == '\0')
{
safe_chr('0', buff, bufc);
}
else
{
safe_bool(xlate(fargs[0]), buff, bufc);
}
}
static const char *bigones[] =
{
"",
"thousand",
"million",
"billion",
"trillion"
};
static const char *singles[] =
{
"",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
static const char *teens[] =
{
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
};
static const char *tens[] =
{
"",
"",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
};
static const char *th_prefix[] =
{
"",
"ten",
"hundred"
};
class CSpellNum
{
public:
void SpellNum(const char *p, char *buff_arg, char **bufc_arg);
private:
void TwoDigits(const char *p);
void ThreeDigits(const char *p, int iBigOne);
void ManyDigits(int n, const char *p, bool bHundreds);
void FractionalDigits(int n, const char *p);
void StartWord(void);
void AddWord(const char *p);
char *buff;
char **bufc;
bool bNeedSpace;
};
void CSpellNum::StartWord(void)
{
if (bNeedSpace)
{
safe_chr(' ', buff, bufc);
}
bNeedSpace = true;
}
void CSpellNum::AddWord(const char *p)
{
safe_str(p, buff, bufc);
}
// Handle two-character sequences.
//
void CSpellNum::TwoDigits(const char *p)
{
int n0 = p[0] - '0';
int n1 = p[1] - '0';
if (n0 == 0)
{
if (n1 != 0)
{
StartWord();
AddWord(singles[n1]);
}
return;
}
else if (n0 == 1)
{
StartWord();
AddWord(teens[n1]);
return;
}
if (n1 == 0)
{
StartWord();
AddWord(tens[n0]);
}
else
{
StartWord();
AddWord(tens[n0]);
AddWord("-");
AddWord(singles[n1]);
}
}
// Handle three-character sequences.
//
void CSpellNum::ThreeDigits(const char *p, int iBigOne)
{
if ( p[0] == '0'
&& p[1] == '0'
&& p[2] == '0')
{
return;
}
// Handle hundreds.
//
if (p[0] != '0')
{
StartWord();
AddWord(singles[p[0]-'0']);
StartWord();
AddWord("hundred");
}
TwoDigits(p+1);
if (iBigOne > 0)
{
StartWord();
AddWord(bigones[iBigOne]);
}
}
// Handle a series of patterns of three.
//
void CSpellNum::ManyDigits(int n, const char *p, bool bHundreds)
{
// Handle special Hundreds cases.
//
if ( bHundreds
&& n == 4
&& p[1] != '0')
{
TwoDigits(p);
StartWord();
AddWord("hundred");
TwoDigits(p+2);
return;
}
// Handle normal cases.
//
int ndiv = ((n + 2) / 3) - 1;
int nrem = n % 3;
char buf[3];
if (nrem == 0)
{
nrem = 3;
}
int j = nrem;
for (int i = 2; 0 <= i; i--)
{
if (j)
{
j--;
buf[i] = p[j];
}
else
{
buf[i] = '0';
}
}
ThreeDigits(buf, ndiv);
p += nrem;
while (ndiv-- > 0)
{
ThreeDigits(p, ndiv);
p += 3;
}
}
// Handle precision ending for part to the right of the decimal place.
//
void CSpellNum::FractionalDigits(int n, const char *p)
{
ManyDigits(n, p, false);
if ( 0 < n
&& n < 15)
{
int d = n / 3;
int r = n % 3;
StartWord();
if (r != 0)
{
AddWord(th_prefix[r]);
if (d != 0)
{
AddWord("-");
}
}
AddWord(bigones[d]);
AddWord("th");
INT64 i64 = mux_atoi64(p);
if (i64 != 1)
{
AddWord("s");
}
}
}
void CSpellNum::SpellNum(const char *number, char *buff_arg, char **bufc_arg)
{
buff = buff_arg;
bufc = bufc_arg;
bNeedSpace = false;
// Trim Spaces from beginning.
//
while (mux_isspace(*number))
{
number++;
}
if (*number == '-')
{
StartWord();
AddWord("negative");
number++;
}
// Trim Zeroes from Beginning.
//
while (*number == '0')
{
number++;
}
const char *pA = number;
while (mux_isdigit(*number))
{
number++;
}
size_t nA = number - pA;
const char *pB = NULL;
size_t nB = 0;
if (*number == '.')
{
number++;
pB = number;
while (mux_isdigit(*number))
{
number++;
}
nB = number - pB;
}
// Skip trailing spaces.
//
while (mux_isspace(*number))
{
number++;
}
if ( *number
|| nA >= 16
|| nB >= 15)
{
safe_str("#-1 ARGUMENT MUST BE A NUMBER", buff, bufc);
return;
}
if (nA == 0)
{
if (nB == 0)
{
StartWord();
AddWord("zero");
}
}
else
{
ManyDigits(nA, pA, true);
if (nB)
{
StartWord();
AddWord("and");
}
}
if (nB)
{
FractionalDigits(nB, pB);
}
}
FUNCTION(fun_spellnum)
{
CSpellNum sn;
sn.SpellNum(fargs[0], buff, bufc);
}
FUNCTION(fun_roman)
{
const char *number = fargs[0];
// Trim Spaces from beginning.
//
while (mux_isspace(*number))
{
number++;
}
// Trim Zeroes from Beginning.
//
while (*number == '0')
{
number++;
}
const char *pA = number;
while (mux_isdigit(*number))
{
number++;
}
size_t nA = number - pA;
// Skip trailing spaces.
//
while (mux_isspace(*number))
{
number++;
}
// Validate that argument is numeric with a value between 1 and 3999.
//
if (*number || nA < 1)
{
safe_str("#-1 ARGUMENT MUST BE A POSITIVE NUMBER", buff, bufc);
return;
}
else if ( nA > 4
|| ( nA == 1
&& pA[0] == '0')
|| ( nA == 4
&& '3' < pA[0]))
{
safe_range(buff, bufc);
return;
}
// I:1, V:5, X:10, L:50, C:100, D:500, M:1000
//
// Ones: _ I II III IV V VI VII VIII IX
// Tens: _ X XX XXX XL L LX LXX LXXX XC
// Hundreds: _ C CC CCC CD D DC DCC DCCC CM
// Thousands: _ M MM MMM
//
static const char aLetters[4][3] =
{
{ 'I', 'V', 'X' },
{ 'X', 'L', 'C' },
{ 'C', 'D', 'M' },
{ 'M', ' ', ' ' }
};
static const char *aCode[10] =
{
"",
"1",
"11",
"111",
"12",
"2",
"21",
"211",
"2111",
"13"
};
while (nA--)
{
const char *pCode = aCode[*pA - '0'];
const char *pLetters = aLetters[nA];
while (*pCode)
{
safe_chr(pLetters[*pCode - '1'], buff, bufc);
pCode++;
}
pA++;
}
}
/*-------------------------------------------------------------------------
* List-based numeric functions.
*/
FUNCTION(fun_land)
{
bool bValue = true;
if (0 < nfargs)
{
SEP sep;
if (!OPTIONAL_DELIM(2, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
char *cp = trim_space_sep(fargs[0], &sep);
while (cp && bValue)
{
char *curr = split_token(&cp, &sep);
bValue = isTRUE(mux_atol(curr));
}
}
safe_bool(bValue, buff, bufc);
}
FUNCTION(fun_lor)
{
bool bValue = false;
if (0 < nfargs)
{
SEP sep;
if (!OPTIONAL_DELIM(2, sep, DELIM_DFLT|DELIM_STRING))
{
return;
}
char *cp = trim_space_sep(fargs[0], &sep);
while (cp && !bValue)
{
char *curr = split_token(&cp, &sep);
bValue = isTRUE(mux_atol(curr));
}
}
safe_bool(bValue, buff, bufc);
}
FUNCTION(fun_band)
{
UINT64 val = UINT64_MAX_VALUE;
for (int i = 0; i < nfargs; i++)
{
if (is_integer(fargs[i], NULL))
{
val &= mux_atoi64(fargs[i]);
}
else
{
safe_str("#-1 ARGUMENTS MUST BE INTEGERS", buff, bufc);
return;
}
}
safe_i64toa(val, buff, bufc);
}
FUNCTION(fun_bor)
{
UINT64 val = 0;
for (int i = 0; i < nfargs; i++)
{
if (is_integer(fargs[i], NULL))
{
val |= mux_atoi64(fargs[i]);
}
else
{
safe_str("#-1 ARGUMENTS MUST BE INTEGERS", buff, bufc);
return;
}
}
safe_i64toa(val, buff, bufc);
}
FUNCTION(fun_bnand)
{
if ( is_integer(fargs[0], NULL)
&& is_integer(fargs[1], NULL))
{
safe_i64toa(mux_atoi64(fargs[0]) & ~(mux_atoi64(fargs[1])), buff, bufc);
}
else
{
safe_str("#-1 ARGUMENTS MUST BE INTEGERS", buff, bufc);
}
}
FUNCTION(fun_bxor)
{
UINT64 val = 0;
for (int i = 0; i < nfargs; i++)
{
if (is_integer(fargs[i], NULL))
{
val ^= mux_atoi64(fargs[i]);
}
else
{
safe_str("#-1 ARGUMENTS MUST BE INTEGERS", buff, bufc);
return;
}
}
safe_i64toa(val, buff, bufc);
}
FUNCTION(fun_crc32)
{
UINT32 ulCRC32 = 0;
for (int i = 0; i < nfargs; i++)
{
int n = strlen(fargs[i]);
ulCRC32 = CRC32_ProcessBuffer(ulCRC32, fargs[i], n);
}
safe_i64toa(ulCRC32, buff, bufc);
}
FUNCTION(fun_sha1)
{
int i;
SHA1_CONTEXT shac;
SHA1_Init(&shac);
for (i = 0; i < nfargs; i++)
{
SHA1_Compute(&shac, strlen(fargs[i]), fargs[i]);
}
SHA1_Final(&shac);
for (i = 0; i <= 4; i++)
{
char buf[9];
sprintf(buf, "%08X", shac.H[i]);
safe_str(buf, buff, bufc);
}
}
| 21.504176 | 84 | 0.469727 | [
"vector",
"solid"
] |
baa30105318efc141c121e4d054b331268fb3e23 | 8,646 | cpp | C++ | src/scoring.cpp | kkrismer/transite | 2e69b44c949e2337e71c13d75207623f81ae9bc3 | [
"MIT"
] | 6 | 2019-03-27T13:02:26.000Z | 2021-07-12T21:25:29.000Z | src/scoring.cpp | kkrismer/transite | 2e69b44c949e2337e71c13d75207623f81ae9bc3 | [
"MIT"
] | 3 | 2019-02-19T09:01:35.000Z | 2021-01-07T14:50:33.000Z | src/scoring.cpp | kkrismer/transite | 2e69b44c949e2337e71c13d75207623f81ae9bc3 | [
"MIT"
] | 1 | 2019-11-26T19:02:42.000Z | 2019-11-26T19:02:42.000Z | // [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <random>
#include <algorithm>
//' @title Score Sequences with PWM
//'
//' @description
//' C++ implementation of PWM scoring algorithm
//'
//' @param sequences list of sequences
//' @param pwm position weight matrix
//'
//' @return list of PWM scores for each sequence
//' @examples
//' motif <- get_motif_by_id("M178_0.6")[[1]]
//' sequences <- c("CAACAGCCUUAAUU", "CAGUCAAGACUCC", "CUUUGGGGAAU",
//' "UCAUUUUAUUAAA", "AAUUGGUGUCUGGAUACUUCCCUGUACAU",
//' "AUCAAAUUA", "UGUGGGG", "GACACUUAAAGAUCCU",
//' "UAGCAUUAACUUAAUG", "AUGGA", "GAAGAGUGCUCA", "AUAGAC",
//' "AGUUC", "CCAGUAA")
//' seq_char_vectors <- lapply(sequences, function(seq) {
//' unlist(strsplit(seq, ""))
//' })
//' score_sequences(seq_char_vectors, as.matrix(get_motif_matrix(motif)))
//'
//' @export
// [[Rcpp::export]]
SEXP score_sequences(Rcpp::List sequences, Rcpp::NumericMatrix pwm) {
std::vector<Rcpp::NumericVector> scores;
for(int i(0); i < sequences.size(); ++i) {
Rcpp::CharacterVector seq(sequences[i]);
if(seq.size() >= pwm.nrow()) {
Rcpp::NumericVector positionalScores(seq.size() - pwm.nrow() + 1);
for (int j(0); j < (seq.size() - pwm.nrow() + 1); ++j) {
double sum = 0;
for(int k(0); k < pwm.nrow(); ++k) {
Rcpp::String pos = seq[j + k];
if(pos == "A") {
sum += pwm(k, 0);
} else if(pos == "C") {
sum += pwm(k, 1);
} else if(pos == "G") {
sum += pwm(k, 2);
} else if(pos == "U") {
sum += pwm(k, 3);
} else if(pos == "T") {
sum += pwm(k, 3);
} else {
throw std::invalid_argument(std::string("invalid character in RNA sequence: ") + std::string(pos) + std::string(" (valid characters: A, C, G, U)"));
}
}
positionalScores[j] = sum;
}
scores.push_back(positionalScores);
} else {
Rcpp::NumericVector positionalScores(0);
scores.push_back(positionalScores);
}
}
return wrap(scores);
}
double calculate_consistency_score(Rcpp::NumericVector x) {
double score(0.0);
for(int i(0); i < x.size() - 2; ++i) {
score += std::abs(((x[i] + x[i + 2]) / 2) - x[i + 1]);
}
return score / ((double)x.size());
}
// wrapper around R's RNG such that we get a uniform distribution over
// [0,n) as required by the STL algorithm
inline int randWrapper(const int n) {
return floor(unif_rand() * n);
}
//' @title Local Consistency Score
//'
//' @description
//' C++ implementation of Local Consistency Score algorithm.
//'
//' @param x numeric vector that contains values for shuffling
//' @param numPermutations maximum number of permutations performed in
//' Monte Carlo test
//' for consistency score
//' @param minPermutations minimum number of permutations performed in
//' Monte Carlo test
//' for consistency score
//' @param e stop criterion for consistency score Monte Carlo test:
//' aborting permutation
//' process after observing \code{e} random consistency values with
//' more extreme values
//' than the actual consistency value
//' @return list with \code{score}, \code{p_value}, and \code{n} components,
//' where \code{score} is the raw local consistency score (usually not used),
//' \code{p_value} is the associated p-value for that score, obtained by
//' Monte Carlo testing, and \code{n} is the number of permutations performed
//' in the Monte Carlo test (the higher, the more significant)
//'
//' @examples
//' poor_enrichment_spectrum <- c(0.1, 0.5, 0.6, 0.4,
//' 0.7, 0.6, 1.2, 1.1, 1.8, 1.6)
//' local_consistency <- calculate_local_consistency(poor_enrichment_spectrum,
//' 1000000, 1000, 5)
//'
//' enrichment_spectrum <- c(0.1, 0.3, 0.6, 0.7, 0.8,
//' 0.9, 1.2, 1.4, 1.6, 1.4)
//' local_consistency <- calculate_local_consistency(enrichment_spectrum,
//' 1000000, 1000, 5)
//' @export
// [[Rcpp::export]]
Rcpp::List calculate_local_consistency(Rcpp::NumericVector x,
int numPermutations,
int minPermutations, int e) {
double score(calculate_consistency_score(x));
int k(0);
int i(1);
while(i <= numPermutations && (i < minPermutations || k < e)) {
// shuffle spectrum
Rcpp::NumericVector shuffledSpectrum = clone(x);
std::random_shuffle(shuffledSpectrum.begin(), shuffledSpectrum.end(),
randWrapper);
// calculate consistency score
double shuffledScore(calculate_consistency_score(shuffledSpectrum));
// lower tail probability
if(shuffledScore <= score) {
++k;
}
++i;
}
double pValue(((double)k + 1.0) / ((double)i + 1.0));
return Rcpp::List::create(Rcpp::Named("score") = score,
Rcpp::Named("p_value") = pValue,
Rcpp::Named("n") = i);
}
//' @title Motif Enrichment calculation
//'
//' @description
//' C++ implementation of Motif Enrichment calculation
//'
//' @param absoluteHits number of putative binding sites per sequence
//' (returned by \code{\link{score_transcripts}})
//' @param totalSites number of potential binding sites per sequence
//' (returned by \code{\link{score_transcripts}})
//' @param relHitsForeground relative number of hits in foreground set
//' @param n number of sequences in the foreground set
//' @param maxPermutations maximum number of foreground permutations
//' performed in
//' Monte Carlo test for enrichment score
//' @param minPermutations minimum number of foreground permutations
//' performed in
//' Monte Carlo test for enrichment score
//' @param e stop criterion for enrichment score Monte Carlo test:
//' aborting permutation process
//' after observing \code{e} random enrichment values with more extreme
//' values than the actual
//' enrichment value
//'
//' @return list with p-value and number of iterations of Monte Carlo sampling
//' for foreground enrichment
//'
//' @examples
//' foreground_seqs <- c("CAGUCAAGACUCC", "AAUUGGUUGUGGGGCUUCCCUGUACAU",
//' "AGAU", "CCAGUAA", "UGUGGGG")
//' background_seqs <- c(foreground_seqs, "CAACAGCCUUAAUU", "CUUUGGGGAAU",
//' "UCAUUUUAUUAAA", "AUCAAAUUA", "GACACUUAAAGAUCCU",
//' "UAGCAUUAACUUAAUG", "AUGGA", "GAAGAGUGCUCA",
//' "AUAGAC", "AGUUC")
//' motif_db <- get_motif_by_id("M178_0.6")
//' fg <- score_transcripts(foreground_seqs, cache = FALSE,
//' motifs = motif_db)
//' bg <- score_transcripts(background_seqs, cache = FALSE,
//' motifs = motif_db)
//'
//' mc_result <- calculate_transcript_mc(unlist(bg$absolute_hits),
//' unlist(bg$total_sites),
//' fg$df$absolute_hits / fg$df$total_sites,
//' length(foreground_seqs), 1000, 500, 5)
//' @export
// [[Rcpp::export]]
Rcpp::List calculate_transcript_mc(Rcpp::IntegerVector absoluteHits,
Rcpp::IntegerVector totalSites,
double relHitsForeground,
int n, int maxPermutations,
int minPermutations, int e) {
double relHitsBackground(((double)sum(absoluteHits)) / ((double)sum(totalSites)));
double actualScore(std::abs(relHitsForeground - relHitsBackground));
int k(0);
int i(1);
while(i <= maxPermutations && (i < minPermutations || k < e)) {
// select n transcripts randomly
int randomAbsoluteHits(0);
int randomTotalSites(0);
Rcpp::IntegerVector sampledIndices(Rcpp::sample(absoluteHits.length(),
n));
for(int j(0); j < n; ++j) {
randomAbsoluteHits += absoluteHits[sampledIndices[j] - 1];
randomTotalSites += totalSites[sampledIndices[j] - 1];
}
// calculate random score
double randomScore(((double)randomAbsoluteHits) / ((double)randomTotalSites) - relHitsBackground);
// two-tailed probability
if(std::abs(randomScore) >= actualScore) {
++k;
}
++i;
}
double pValue(((double)k + 1.0) / ((double)i + 1.0));
return Rcpp::List::create(Rcpp::Named("p_value") = pValue,
Rcpp::Named("n") = i);
}
| 38.256637 | 172 | 0.589174 | [
"vector"
] |
baa35fc45ab3b8f15fd2549093cb61762cbfa0c7 | 4,326 | cpp | C++ | Sourcecode/mxtest/core/SystemLayoutTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mxtest/core/SystemLayoutTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mxtest/core/SystemLayoutTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#include "mxtest/control/CompileControl.h"
#ifdef MX_COMPILE_CORE_TESTS
#include "cpul/cpulTestHarness.h"
#include "mxtest/core/HelperFunctions.h"
#include "mxtest/core/SystemLayoutTest.h"
#include "mxtest/core/SystemMarginsTest.h"
#include "mxtest/core/SystemDividersTest.h"
using namespace mx::core;
using namespace std;
using namespace mxtest;
TEST( Test01, SystemLayout )
{
variant v = variant::one;
SystemLayoutPtr object = tgenSystemLayout( v );
stringstream expected;
tgenSystemLayoutExpected( expected, 1, v );
stringstream actual;
// object->toStream( std::cout, 1 );
object->toStream( actual, 1 );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( ! object->hasContents() )
}
TEST( Test02, SystemLayout )
{
variant v = variant::two;
SystemLayoutPtr object = tgenSystemLayout( v );
stringstream expected;
tgenSystemLayoutExpected( expected, 1, v );
stringstream actual;
// object->toStream( std::cout, 1 );
object->toStream( actual, 1 );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
TEST( Test03, SystemLayout )
{
variant v = variant::three;
SystemLayoutPtr object = tgenSystemLayout( v );
stringstream expected;
tgenSystemLayoutExpected( expected, 1, v );
stringstream actual;
// object->toStream( std::cout, 1 );
object->toStream( actual, 1 );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
namespace mxtest
{
SystemLayoutPtr tgenSystemLayout( variant v )
{
SystemLayoutPtr o = makeSystemLayout();
switch ( v )
{
case variant::one:
{
}
break;
case variant::two:
{
o->setHasSystemMargins( true );
o->setSystemMargins( tgenSystemMargins( v ) );
o->setHasTopSystemDistance( true );
o->getTopSystemDistance()->setValue( TenthsValue( 1.1 ) );
o->setHasSystemDistance( true );
o->getSystemDistance()->setValue( TenthsValue( 2.2 ) );
o->setHasSystemDividers( true );
o->setSystemDividers( tgenSystemDividers( v ) );
}
break;
case variant::three:
{
o->setHasSystemMargins( true );
o->setSystemMargins( tgenSystemMargins( v ) );
o->setHasTopSystemDistance( true );
o->getTopSystemDistance()->setValue( TenthsValue( 3.3 ) );
o->setHasSystemDistance( true );
o->getSystemDistance()->setValue( TenthsValue( 4.4 ) );
}
break;
default:
break;
}
return o;
}
void tgenSystemLayoutExpected( std::ostream& os, int i, variant v )
{
switch ( v )
{
case variant::one:
{
streamLine( os, i, R"(<system-layout/>)", false );
}
break;
case variant::two:
{
streamLine( os, i, R"(<system-layout>)" );
tgenSystemMarginsExpected( os, i+1, v );
os << std::endl;
streamLine( os, i+1, R"(<system-distance>2.2</system-distance>)" );
streamLine( os, i+1, R"(<top-system-distance>1.1</top-system-distance>)" );
tgenSystemDividersExpected( os, i+1, v );
os << std::endl;
streamLine( os, i, R"(</system-layout>)", false );
}
break;
case variant::three:
{
streamLine( os, i, R"(<system-layout>)" );
tgenSystemMarginsExpected( os, i+1, v );
os << std::endl;
streamLine( os, i+1, R"(<system-distance>4.4</system-distance>)" );
streamLine( os, i+1, R"(<top-system-distance>3.3</top-system-distance>)" );
streamLine( os, i, R"(</system-layout>)", false );
}
break;
default:
break;
}
}
}
#endif
| 31.576642 | 91 | 0.550855 | [
"object"
] |
baad88128c2e2688f3e694fa508ff53625bcfafb | 12,352 | cc | C++ | src/elle/cryptography/envelope.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 521 | 2016-02-14T00:39:01.000Z | 2022-03-01T22:39:25.000Z | src/elle/cryptography/envelope.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 8 | 2017-02-21T11:47:33.000Z | 2018-11-01T09:37:14.000Z | src/elle/cryptography/envelope.cc | infinitio/elle | d9bec976a1217137436db53db39cda99e7024ce4 | [
"Apache-2.0"
] | 48 | 2017-02-21T10:18:13.000Z | 2022-03-25T02:35:20.000Z | #include <elle/cryptography/fwd.hh>
#include <openssl/crypto.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <elle/Buffer.hh>
#include <elle/log.hh>
#include <elle/serialization/binary.hh>
#include <elle/cryptography/Cipher.hh>
#include <elle/cryptography/Oneway.hh>
#include <elle/cryptography/Error.hh>
#include <elle/cryptography/SecretKey.hh>
#include <elle/cryptography/cryptography.hh>
#include <elle/cryptography/envelope.hh>
#include <elle/cryptography/finally.hh>
#include <elle/cryptography/raw.hh>
#include <elle/cryptography/constants.hh>
namespace elle
{
namespace cryptography
{
namespace envelope
{
/*----------.
| Functions |
`----------*/
void
seal(::EVP_PKEY* key,
::EVP_CIPHER const* cipher,
std::istream& plain,
std::ostream& code)
{
// Make sure the cryptographic system is set up.
cryptography::require();
// The following variables initialization are more complicated than
// necessary but have been made for the reader to understand the way
// the SealInit() function takes arguments, arrays and not single
// values.
// Create an array with a single public key since only one recipient
// will be allowed to decrypt the data.
::EVP_PKEY* keys[1];
keys[0] = key;
// Create an array with a single secret key.
unsigned char* _secret =
reinterpret_cast<unsigned char*>(
::OPENSSL_malloc(::EVP_PKEY_size(keys[0])));
ELLE_CRYPTOGRAPHY_FINALLY_ACTION_FREE_OPENSSL(_secret);
unsigned char* secrets[1];
secrets[0] = _secret;
int lengths[1];
// Prepare the memory area to receive the IV.
unsigned char* iv =
reinterpret_cast<unsigned char*>(
::OPENSSL_malloc(EVP_MAX_IV_LENGTH));
ELLE_CRYPTOGRAPHY_FINALLY_ACTION_FREE_OPENSSL(iv);
// Initialize the cipher context.
::EVP_CIPHER_CTX context;
::EVP_CIPHER_CTX_init(&context);
ELLE_CRYPTOGRAPHY_FINALLY_ACTION_CLEANUP_CIPHER_CONTEXT(context);
// Initialize the envelope seal operation. This operation generates
// a secret key for the provided cipher, and then encrypts that key a
// number of times (one for each public key provided in the 'keys'
// array, once in our case). This operation also generates an IV and
// places it in 'iv'.
if (::EVP_SealInit(&context,
cipher,
secrets,
lengths,
iv,
keys,
1) <= 0)
throw Error(
elle::sprintf("unable to initialize the seal process: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
ELLE_ASSERT_EQ(::EVP_PKEY_size(key), lengths[0]);
// At this point, before writing the encrypted data in the output
// stream, the parameters (secret and IV) need to be written for
// the recipient to retrieve them.
//
// We could for instance serialize the header (secret and IV) through
// a serialization layer on top of the output stream and then use the
// bare stream to output the encrypted data. Because the serialization
// layer may buffer, it is dangerous. Likewise, the serialization format
// may change in the future.
//
// For those reasons, the following simply outputs the secret and IV
// whose size is supposed to be known in advanced according to the
// cipher used.
{
// Write the secret.
code.write(reinterpret_cast<const char *>(_secret),
::EVP_PKEY_size(key));
if (!code.good())
throw Error(
elle::sprintf("unable to write the secret to the "
"code's output stream: %s",
code.rdstate()));
// Write the IV.
code.write(reinterpret_cast<const char *>(iv),
EVP_MAX_IV_LENGTH);
if (!code.good())
throw Error(
elle::sprintf("unable to write the IV to the "
"code's output stream: %s",
code.rdstate()));
}
// Compute the block size according to the
int block_size = ::EVP_CIPHER_CTX_block_size(&context);
// Encrypt the plain's stream.
std::vector<unsigned char> _input(constants::stream_block_size);
std::vector<unsigned char> _output(constants::stream_block_size +
block_size);
while (!plain.eof())
{
// Read the plain's input stream and put a block of data in a
// temporary buffer.
plain.read(reinterpret_cast<char*>(_input.data()), _input.size());
if (plain.bad())
throw Error(
elle::sprintf("unable to read the plain's input stream: %s",
plain.rdstate()));
int size_update(0);
// Encrypt the input buffer.
if (::EVP_SealUpdate(&context,
_output.data(),
&size_update,
_input.data(),
plain.gcount()) <= 0)
throw Error(
elle::sprintf("unable to apply the encryption function: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
// Write the output buffer to the code stream.
code.write(reinterpret_cast<const char *>(_output.data()),
size_update);
if (!code.good())
throw Error(
elle::sprintf("unable to write the encrypted data to the "
"code's output stream: %s",
code.rdstate()));
}
// Finalize the encryption process.
int size_final(0);
if (::EVP_SealFinal(&context,
_output.data(),
&size_final) <= 0)
throw Error(
elle::sprintf("unable to finalize the seal process: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
// Write the final output buffer to the code's output stream.
code.write(reinterpret_cast<const char *>(_output.data()),
size_final);
if (!code.good())
throw Error(
elle::sprintf("unable to write the encrypted data to the "
"code's output stream: %s",
code.rdstate()));
// Clean up the cipher context.
if (::EVP_CIPHER_CTX_cleanup(&context) <= 0)
throw Error(
elle::sprintf("unable to clean the cipher context: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
ELLE_CRYPTOGRAPHY_FINALLY_ABORT(context);
// Release the memory associated with the secret and iv.
::OPENSSL_free(iv);
ELLE_CRYPTOGRAPHY_FINALLY_ABORT(iv);
::OPENSSL_free(_secret);
ELLE_CRYPTOGRAPHY_FINALLY_ABORT(_secret);
}
void
open(::EVP_PKEY* key,
::EVP_CIPHER const* cipher,
std::istream& code,
std::ostream& plain)
{
// Make sure the cryptographic system is set up.
cryptography::require();
// Start by extracting the secret and IV from the input
// stream.
unsigned char* secret =
reinterpret_cast<unsigned char*>(
::OPENSSL_malloc(::EVP_PKEY_size(key)));
ELLE_CRYPTOGRAPHY_FINALLY_ACTION_FREE_OPENSSL(secret);
unsigned char* iv =
reinterpret_cast<unsigned char*>(
::OPENSSL_malloc(EVP_MAX_IV_LENGTH));
ELLE_CRYPTOGRAPHY_FINALLY_ACTION_FREE_OPENSSL(iv);
{
// Read the secret.
code.read(reinterpret_cast<char*>(secret), ::EVP_PKEY_size(key));
if (!code.good())
throw Error(
elle::sprintf("unable to read the secret from the code's "
"input stream: %s",
code.rdstate()));
// Read the IV.
code.read(reinterpret_cast<char*>(iv), EVP_MAX_IV_LENGTH);
if (!code.good())
throw Error(
elle::sprintf("unable to read the IV from the code's "
"input stream: %s",
code.rdstate()));
}
// Initialize the cipher context.
::EVP_CIPHER_CTX context;
::EVP_CIPHER_CTX_init(&context);
ELLE_CRYPTOGRAPHY_FINALLY_ACTION_CLEANUP_CIPHER_CONTEXT(context);
// Initialize the envelope open operation.
if (::EVP_OpenInit(&context,
cipher,
secret,
::EVP_PKEY_size(key),
iv,
key) <= 0)
throw Error(
elle::sprintf("unable to initialize the open process: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
// Compute the block size according to the
int block_size = ::EVP_CIPHER_CTX_block_size(&context);
// Decrypt the plain's stream.
std::vector<unsigned char> _input(constants::stream_block_size);
std::vector<unsigned char> _output(constants::stream_block_size +
block_size);
while (!code.eof())
{
// Read the code's input stream and put a block of data in a
// temporary buffer.
code.read(reinterpret_cast<char*>(_input.data()), _input.size());
if (code.bad())
throw Error(
elle::sprintf("unable to read the code's input stream: %s",
code.rdstate()));
int size_update(0);
// Decrypt the input buffer.
if (::EVP_OpenUpdate(&context,
_output.data(),
&size_update,
_input.data(),
code.gcount()) <= 0)
throw Error(
elle::sprintf("unable to apply the decryption function: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
// Write the output buffer to the plain stream.
plain.write(reinterpret_cast<const char *>(_output.data()),
size_update);
if (!plain.good())
throw Error(
elle::sprintf("unable to write the decrypted data to the "
"plain's output stream: %s",
plain.rdstate()));
}
// Finalize the decryption process.
int size_final(0);
if (::EVP_OpenFinal(&context,
_output.data(),
&size_final) <= 0)
throw Error(
elle::sprintf("unable to finalize the open process: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
// Write the final output buffer to the plain's output stream.
plain.write(reinterpret_cast<const char *>(_output.data()),
size_final);
if (!plain.good())
throw Error(
elle::sprintf("unable to write the decrypted data to the "
"plain's output stream: %s",
plain.rdstate()));
// Clean up the cipher context.
if (::EVP_CIPHER_CTX_cleanup(&context) <= 0)
throw Error(
elle::sprintf("unable to clean the cipher context: %s",
::ERR_error_string(ERR_get_error(), nullptr)));
ELLE_CRYPTOGRAPHY_FINALLY_ABORT(context);
// Release the memory associated with the secret and iv.
OPENSSL_free(iv);
ELLE_CRYPTOGRAPHY_FINALLY_ABORT(iv);
OPENSSL_free(secret);
ELLE_CRYPTOGRAPHY_FINALLY_ABORT(secret);
}
}
}
}
| 36.982036 | 80 | 0.538617 | [
"vector"
] |
baaf7ccfed16ac6e1491af15c82d0b64af2f6db1 | 476 | cpp | C++ | SubstituicaoDePaginas/main.cpp | Spoock01/SubstituicaoDePaginas | 9e35c842d2f385eba2cae3e3fffa8abb2786845b | [
"MIT"
] | null | null | null | SubstituicaoDePaginas/main.cpp | Spoock01/SubstituicaoDePaginas | 9e35c842d2f385eba2cae3e3fffa8abb2786845b | [
"MIT"
] | null | null | null | SubstituicaoDePaginas/main.cpp | Spoock01/SubstituicaoDePaginas | 9e35c842d2f385eba2cae3e3fffa8abb2786845b | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include "Utils.h"
#include "Fifo.h"
#include "OtmAlgorithm.h"
#include "Lru.h"
using namespace std;
const string PATH = "arquivo.txt";
int main()
{
openFile(PATH);
int size = getQuadros();
vector<int> arr = getArray();
Fifo *fifo = new Fifo(size, arr);
fifo->result();
OtmAlgorithm *otm = new OtmAlgorithm(size, arr);
otm->result();
Lru *lru = new Lru(size, arr);
lru->result();
return 0;
}
| 17.62963 | 52 | 0.621849 | [
"vector"
] |
baaff614c12ea5ba52a1bb9f16d62f343d4725e6 | 24,468 | cpp | C++ | ImportExport/KafkaImporter.cpp | 4ertus2/omniscidb | 4f4a11148f0f1f3548da16eff6ca0988a2ac1b2c | [
"Apache-2.0"
] | 1 | 2022-03-11T04:01:30.000Z | 2022-03-11T04:01:30.000Z | ImportExport/KafkaImporter.cpp | 4ertus2/omniscidb | 4f4a11148f0f1f3548da16eff6ca0988a2ac1b2c | [
"Apache-2.0"
] | null | null | null | ImportExport/KafkaImporter.cpp | 4ertus2/omniscidb | 4f4a11148f0f1f3548da16eff6ca0988a2ac1b2c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 OmniSci, 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.
*/
/**
* @file KafkaImporter.cpp
* @author Michael <michael@mapd.com>
* @brief Based on StreamInsert code but using binary columnar format for inserting a
*stream of rows with optional transformations from stdin to a DB table.
*
**/
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/regex.hpp>
#include <cstring>
#include <iostream>
#include <iterator>
#include <string>
#include "RowToColumnLoader.h"
#include "Shared/Logger.h"
#include "Shared/ThriftClient.h"
#include "Shared/sqltypes.h"
#include <chrono>
#include <thread>
#include <boost/program_options.hpp>
#include <librdkafka/rdkafkacpp.h>
#define MAX_FIELD_LEN 20000
bool print_error_data = false;
bool print_transformation = false;
static bool run = true;
static bool exit_eof = false;
static int eof_cnt = 0;
static int partition_cnt = 0;
static long msg_cnt = 0;
static int64_t msg_bytes = 0;
class RebalanceCb : public RdKafka::RebalanceCb {
private:
static void part_list_print(const std::vector<RdKafka::TopicPartition*>& partitions) {
for (unsigned int i = 0; i < partitions.size(); i++) {
LOG(INFO) << "\t" << partitions[i]->topic() << "[" << partitions[i]->partition()
<< "]";
}
}
public:
void rebalance_cb(RdKafka::KafkaConsumer* consumer,
RdKafka::ErrorCode err,
std::vector<RdKafka::TopicPartition*>& partitions) override {
LOG(INFO) << "RebalanceCb: " << RdKafka::err2str(err) << ": ";
part_list_print(partitions);
if (err == RdKafka::ERR__ASSIGN_PARTITIONS) {
consumer->assign(partitions);
partition_cnt = (int)partitions.size();
} else {
consumer->unassign();
partition_cnt = 0;
}
eof_cnt = 0;
}
};
bool msg_consume(RdKafka::Message* message,
RowToColumnLoader& row_loader,
import_export::CopyParams copy_params,
const std::map<std::string,
std::pair<std::unique_ptr<boost::regex>,
std::unique_ptr<std::string>>>& transformations,
const bool remove_quotes) {
switch (message->err()) {
case RdKafka::ERR__TIMED_OUT:
VLOG(1) << " Timed out";
break;
case RdKafka::ERR_NO_ERROR: { /* Real message */
msg_cnt++;
msg_bytes += message->len();
VLOG(1) << "Read msg at offset " << message->offset();
RdKafka::MessageTimestamp ts;
ts = message->timestamp();
if (ts.type != RdKafka::MessageTimestamp::MSG_TIMESTAMP_NOT_AVAILABLE) {
std::string tsname = "?";
if (ts.type == RdKafka::MessageTimestamp::MSG_TIMESTAMP_CREATE_TIME) {
tsname = "create time";
} else if (ts.type == RdKafka::MessageTimestamp::MSG_TIMESTAMP_LOG_APPEND_TIME) {
tsname = "log append time";
}
VLOG(1) << "Timestamp: " << tsname << " " << ts.timestamp << std::endl;
}
char buffer[message->len() + 1];
sprintf(buffer,
"%.*s\n",
static_cast<int>(message->len()),
static_cast<const char*>(message->payload()));
VLOG(1) << "Full Message received is :'" << buffer << "'";
char field[MAX_FIELD_LEN];
size_t field_i = 0;
bool backEscape = false;
auto row_desc = row_loader.get_row_descriptor();
const std::pair<std::unique_ptr<boost::regex>, std::unique_ptr<std::string>>*
xforms[row_desc.size()];
for (size_t i = 0; i < row_desc.size(); i++) {
auto it = transformations.find(row_desc[i].col_name);
if (it != transformations.end()) {
xforms[i] = &(it->second);
} else {
xforms[i] = nullptr;
}
}
std::vector<TStringValue>
row; // used to store each row as we move through the stream
for (auto iit : buffer) {
if (iit == copy_params.delimiter || iit == copy_params.line_delim) {
bool end_of_field = (iit == copy_params.delimiter);
bool end_of_row;
if (end_of_field) {
end_of_row = false;
} else {
end_of_row = (row_desc[row.size()].col_type.type != TDatumType::STR) ||
(row.size() == row_desc.size() - 1);
if (!end_of_row) {
size_t l = copy_params.null_str.size();
if (field_i >= l &&
strncmp(field + field_i - l, copy_params.null_str.c_str(), l) == 0) {
end_of_row = true;
}
}
}
if (!end_of_field && !end_of_row) {
// not enough columns yet and it is a string column
// treat the line delimiter as part of the string
field[field_i++] = iit;
} else {
field[field_i] = '\0';
field_i = 0;
TStringValue ts;
ts.str_val = std::string(field);
ts.is_null = (ts.str_val.empty() || ts.str_val == copy_params.null_str);
auto xform = row.size() < row_desc.size() ? xforms[row.size()] : nullptr;
if (!ts.is_null && xform != nullptr) {
if (print_transformation) {
std::cout << "\ntransforming\n" << ts.str_val << "\nto\n";
}
ts.str_val =
boost::regex_replace(ts.str_val, *xform->first, *xform->second);
if (ts.str_val.empty()) {
ts.is_null = true;
}
if (print_transformation) {
std::cout << ts.str_val << std::endl;
}
}
row.push_back(ts); // add column value to row
if (end_of_row || (row.size() > row_desc.size())) {
break; // found row
}
}
} else {
if (iit == '\\') {
backEscape = true;
} else if (backEscape || !remove_quotes || iit != '\"') {
field[field_i++] = iit;
backEscape = false;
}
// else if unescaped double-quote, continue without adding the
// character to the field string.
}
if (field_i >= MAX_FIELD_LEN) {
field[MAX_FIELD_LEN - 1] = '\0';
std::cerr << "String too long for buffer." << std::endl;
if (print_error_data) {
std::cerr << field << std::endl;
}
field_i = 0;
break;
}
}
if (row.size() == row_desc.size()) {
// add the new data in the column format
bool record_loaded = row_loader.convert_string_to_column(row, copy_params);
if (!record_loaded) {
// record could not be parsed correctly consider it skipped
return false;
} else {
return true;
}
} else {
if (print_error_data) {
std::cerr << "Incorrect number of columns for row: ";
std::cerr << row_loader.print_row_with_delim(row, copy_params) << std::endl;
return false;
}
}
}
case RdKafka::ERR__PARTITION_EOF:
/* Last message */
if (exit_eof && ++eof_cnt == partition_cnt) {
LOG(ERROR) << "%% EOF reached for all " << partition_cnt << " partition(s)";
run = false;
}
break;
case RdKafka::ERR__UNKNOWN_TOPIC:
case RdKafka::ERR__UNKNOWN_PARTITION:
LOG(ERROR) << "Consume failed: " << message->errstr() << std::endl;
run = false;
break;
default:
/* Errors */
LOG(ERROR) << "Consume failed: " << message->errstr();
run = false;
}
return false;
};
class ConsumeCb : public RdKafka::ConsumeCb {
public:
void consume_cb(RdKafka::Message& msg, void* opaque) override {
// reinterpret_cast<KafkaMgr*>(opaque)->
// msg_consume(&msg, opaque);
}
};
class EventCb : public RdKafka::EventCb {
public:
void event_cb(RdKafka::Event& event) override {
switch (event.type()) {
case RdKafka::Event::EVENT_ERROR:
LOG(ERROR) << "ERROR (" << RdKafka::err2str(event.err()) << "): " << event.str();
if (event.err() == RdKafka::ERR__ALL_BROKERS_DOWN) {
LOG(ERROR) << "All brokers are down, we may need special handling here";
run = false;
}
break;
case RdKafka::Event::EVENT_STATS:
VLOG(2) << "\"STATS\": " << event.str();
break;
case RdKafka::Event::EVENT_LOG:
LOG(INFO) << "LOG-" << event.severity() << "-" << event.fac().c_str() << ":"
<< event.str().c_str();
break;
case RdKafka::Event::EVENT_THROTTLE:
LOG(INFO) << "THROTTLED: " << event.throttle_time() << "ms by "
<< event.broker_name() << " id " << (int)event.broker_id();
break;
default:
LOG(INFO) << "EVENT " << event.type() << " (" << RdKafka::err2str(event.err())
<< "): " << event.str();
break;
}
}
};
// reads from a kafka topic (expects delimited string input)
void kafka_insert(
RowToColumnLoader& row_loader,
const std::map<std::string,
std::pair<std::unique_ptr<boost::regex>,
std::unique_ptr<std::string>>>& transformations,
const import_export::CopyParams& copy_params,
const bool remove_quotes,
std::string group_id,
std::string topic,
std::string brokers) {
std::string errstr;
std::string topic_str;
std::string mode;
std::string debug;
std::vector<std::string> topics;
bool do_conf_dump = false;
int use_ccb = 0;
RebalanceCb ex_rebalance_cb;
/*
* Create configuration objects
*/
RdKafka::Conf* conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
RdKafka::Conf* tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
conf->set("rebalance_cb", &ex_rebalance_cb, errstr);
if (conf->set("group.id", group_id, errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "could not set group.id " << errstr;
}
if (conf->set("compression.codec", "none", errstr) != /* can also be gzip or snappy */
RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
if (conf->set("statistics.interval.ms", "1000", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
if (conf->set("enable.auto.commit", "false", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
if (tconf->set("auto.offset.reset", "earliest", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
if (tconf->set("enable.auto.commit", "false", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
do_conf_dump = true;
topics.push_back(topic);
LOG(INFO) << "Version " << RdKafka::version_str().c_str();
LOG(INFO) << RdKafka::version();
LOG(INFO) << RdKafka::get_debug_contexts().c_str();
conf->set("metadata.broker.list", brokers, errstr);
// debug = "none";
if (!debug.empty()) {
if (conf->set("debug", debug, errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
}
ConsumeCb consume_cb;
use_ccb = 0;
if (use_ccb) {
if (conf->set("consume_cb", &consume_cb, errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
// need to set the opaque pointer here for the callbacks
// rd_kafka_conf_set_opaque(conf, this);
}
EventCb ex_event_cb;
if (conf->set("event_cb", &ex_event_cb, errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
if (conf->set("default_topic_conf", tconf, errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << errstr;
}
if (do_conf_dump) {
int pass;
for (pass = 0; pass < 2; pass++) {
std::list<std::string>* dump;
if (pass == 0) {
dump = conf->dump();
LOG(INFO) << "# Global config";
LOG(INFO) << "===============";
} else {
dump = tconf->dump();
LOG(INFO) << "# Topic config";
LOG(INFO) << "===============";
}
for (std::list<std::string>::iterator it = dump->begin(); it != dump->end();) {
std::string ts = *it;
it++;
LOG(INFO) << ts << " = " << *it;
it++;
}
LOG(INFO) << "Dump config finished";
}
}
LOG(INFO) << "FULL Dump config finished";
delete tconf;
/*
* Create consumer using accumulated global configuration.
*/
RdKafka::KafkaConsumer* consumer = RdKafka::KafkaConsumer::create(conf, errstr);
if (!consumer) {
LOG(ERROR) << "Failed to create consumer: " << errstr;
}
delete conf;
LOG(INFO) << " Created consumer " << consumer->name();
/*
* Subscribe to topics
*/
RdKafka::ErrorCode err = consumer->subscribe(topics);
if (err) {
LOG(FATAL) << "Failed to subscribe to " << topics.size()
<< " topics: " << RdKafka::err2str(err);
}
/*
* Consume messages
*/
size_t recv_rows = 0;
int skipped = 0;
int rows_loaded = 0;
while (run) {
RdKafka::Message* msg = consumer->consume(10000);
if (msg->err() == RdKafka::ERR_NO_ERROR) {
if (!use_ccb) {
bool added =
msg_consume(msg, row_loader, copy_params, transformations, remove_quotes);
if (added) {
recv_rows++;
if (recv_rows == copy_params.batch_size) {
recv_rows = 0;
row_loader.do_load(rows_loaded, skipped, copy_params);
// make sure we now commit that we are up to here to cover the mesages we just
// loaded
consumer->commitSync();
}
} else {
// LOG(ERROR) << " messsage was skipped ";
skipped++;
}
}
}
delete msg;
}
/*
* Stop consumer
*/
consumer->close();
delete consumer;
LOG(INFO) << "Consumed " << msg_cnt << " messages (" << msg_bytes << " bytes)";
LOG(FATAL) << "Consumer shut down, probably due to an error please review logs";
};
struct stuff {
RowToColumnLoader row_loader;
import_export::CopyParams copy_params;
stuff(RowToColumnLoader& rl, import_export::CopyParams& cp)
: row_loader(rl), copy_params(cp){};
};
int main(int argc, char** argv) {
std::string server_host("localhost"); // default to localhost
int port = 6274; // default port number
bool http = false;
bool https = false;
bool skip_host_verify = false;
std::string ca_cert_name{""};
std::string table_name;
std::string db_name;
std::string user_name;
std::string passwd;
std::string group_id;
std::string topic;
std::string brokers;
std::string delim_str(","), nulls("\\N"), line_delim_str("\n"), quoted("false");
size_t batch_size = 10000;
size_t retry_count = 10;
size_t retry_wait = 5;
bool remove_quotes = false;
std::vector<std::string> xforms;
std::map<std::string,
std::pair<std::unique_ptr<boost::regex>, std::unique_ptr<std::string>>>
transformations;
ThriftConnectionType conn_type;
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()("help,h", "Print help messages ");
desc.add_options()(
"table", po::value<std::string>(&table_name)->required(), "Table Name");
desc.add_options()(
"database", po::value<std::string>(&db_name)->required(), "Database Name");
desc.add_options()(
"user,u", po::value<std::string>(&user_name)->required(), "User Name");
desc.add_options()(
"passwd,p", po::value<std::string>(&passwd)->required(), "User Password");
desc.add_options()("host",
po::value<std::string>(&server_host)->default_value(server_host),
"OmniSci Server Hostname");
desc.add_options()(
"port", po::value<int>(&port)->default_value(port), "OmniSci Server Port Number");
desc.add_options()("http",
po::bool_switch(&http)->default_value(http)->implicit_value(true),
"Use HTTP transport");
desc.add_options()("https",
po::bool_switch(&https)->default_value(https)->implicit_value(true),
"Use HTTPS transport");
desc.add_options()("skip-verify",
po::bool_switch(&skip_host_verify)
->default_value(skip_host_verify)
->implicit_value(true),
"Don't verify SSL certificate validity");
desc.add_options()(
"ca-cert",
po::value<std::string>(&ca_cert_name)->default_value(ca_cert_name),
"Path to trusted server certificate. Initiates an encrypted connection");
desc.add_options()("delim",
po::value<std::string>(&delim_str)->default_value(delim_str),
"Field delimiter");
desc.add_options()("null", po::value<std::string>(&nulls), "NULL string");
desc.add_options()("line", po::value<std::string>(&line_delim_str), "Line delimiter");
desc.add_options()(
"quoted",
po::value<std::string>("ed),
"Whether the source contains quoted fields (true/false, default false)");
desc.add_options()("batch",
po::value<size_t>(&batch_size)->default_value(batch_size),
"Insert batch size");
desc.add_options()("retry_count",
po::value<size_t>(&retry_count)->default_value(retry_count),
"Number of time to retry an insert");
desc.add_options()("retry_wait",
po::value<size_t>(&retry_wait)->default_value(retry_wait),
"wait in secs between retries");
desc.add_options()("transform,t",
po::value<std::vector<std::string>>(&xforms)->multitoken(),
"Column Transformations");
desc.add_options()("print_error", "Print Error Rows");
desc.add_options()("print_transform", "Print Transformations");
desc.add_options()("topic",
po::value<std::string>(&topic)->required(),
"Kafka topic to consume from ");
desc.add_options()("group-id",
po::value<std::string>(&group_id)->required(),
"Group id this consumer is part of");
desc.add_options()("brokers",
po::value<std::string>(&brokers)->required(),
"list of kafka brokers for topic");
po::positional_options_description positionalOptions;
positionalOptions.add("table", 1);
positionalOptions.add("database", 1);
logger::LogOptions log_options(argv[0]);
log_options.max_files_ = 0; // stderr only
desc.add(log_options.get_options());
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv)
.options(desc)
.positional(positionalOptions)
.run(),
vm);
if (vm.count("help")) {
std::cout << "Usage: <table name> <database name> {-u|--user} <user> {-p|--passwd} "
"<password> [{--host} "
"<hostname>][--port <port number>][--delim <delimiter>][--null <null "
"string>][--line <line "
"delimiter>][--batch <batch size>][{-t|--transform} transformation "
"[--quoted <true|false>] "
"...][--retry_count <num_of_retries>] [--retry_wait <wait in "
"secs>][--print_error][--print_transform]\n\n";
std::cout << desc << std::endl;
return 0;
}
if (vm.count("print_error")) {
print_error_data = true;
}
if (vm.count("print_transform")) {
print_transformation = true;
}
po::notify(vm);
} catch (boost::program_options::error& e) {
std::cerr << "Usage Error: " << e.what() << std::endl;
return 1;
}
logger::init(log_options);
if (http) {
conn_type = ThriftConnectionType::HTTP;
} else if (https) {
conn_type = ThriftConnectionType::HTTPS;
} else if (!ca_cert_name.empty()) {
conn_type = ThriftConnectionType::BINARY_SSL;
} else {
conn_type = ThriftConnectionType::BINARY;
}
char delim = delim_str[0];
if (delim == '\\') {
if (delim_str.size() < 2 ||
(delim_str[1] != 'x' && delim_str[1] != 't' && delim_str[1] != 'n')) {
std::cerr << "Incorrect delimiter string: " << delim_str << std::endl;
return 1;
}
if (delim_str[1] == 't') {
delim = '\t';
} else if (delim_str[1] == 'n') {
delim = '\n';
} else {
std::string d(delim_str);
d[0] = '0';
delim = (char)std::stoi(d, nullptr, 16);
}
}
if (isprint(delim)) {
std::cout << "Field Delimiter: " << delim << std::endl;
} else if (delim == '\t') {
std::cout << "Field Delimiter: "
<< "\\t" << std::endl;
} else if (delim == '\n') {
std::cout << "Field Delimiter: "
<< "\\n"
<< std::endl;
} else {
std::cout << "Field Delimiter: \\x" << std::hex << (int)delim << std::endl;
}
char line_delim = line_delim_str[0];
if (line_delim == '\\') {
if (line_delim_str.size() < 2 ||
(line_delim_str[1] != 'x' && line_delim_str[1] != 't' &&
line_delim_str[1] != 'n')) {
std::cerr << "Incorrect delimiter string: " << line_delim_str << std::endl;
return 1;
}
if (line_delim_str[1] == 't') {
line_delim = '\t';
} else if (line_delim_str[1] == 'n') {
line_delim = '\n';
} else {
std::string d(line_delim_str);
d[0] = '0';
line_delim = (char)std::stoi(d, nullptr, 16);
}
}
if (isprint(line_delim)) {
std::cout << "Line Delimiter: " << line_delim << std::endl;
} else if (line_delim == '\t') {
std::cout << "Line Delimiter: "
<< "\\t" << std::endl;
} else if (line_delim == '\n') {
std::cout << "Line Delimiter: "
<< "\\n"
<< std::endl;
} else {
std::cout << "Line Delimiter: \\x" << std::hex << (int)line_delim << std::endl;
}
std::cout << "Null String: " << nulls << std::endl;
std::cout << "Insert Batch Size: " << std::dec << batch_size << std::endl;
if (quoted == "true") {
remove_quotes = true;
}
for (auto& t : xforms) {
auto n = t.find_first_of(':');
if (n == std::string::npos) {
std::cerr << "Transformation format: <column name>:s/<regex pattern>/<fmt string>/"
<< std::endl;
return 1;
}
std::string col_name = t.substr(0, n);
if (t.size() < n + 3 || t[n + 1] != 's' || t[n + 2] != '/') {
std::cerr << "Transformation format: <column name>:s/<regex pattern>/<fmt string>/"
<< std::endl;
return 1;
}
auto n1 = n + 3;
auto n2 = t.find_first_of('/', n1);
if (n2 == std::string::npos) {
std::cerr << "Transformation format: <column name>:s/<regex pattern>/<fmt string>/"
<< std::endl;
return 1;
}
std::string regex_str = t.substr(n1, n2 - n1);
n1 = n2 + 1;
n2 = t.find_first_of('/', n1);
if (n2 == std::string::npos) {
std::cerr << "Transformation format: <column name>:s/<regex pattern>/<fmt string>/"
<< std::endl;
return 1;
}
std::string fmt_str = t.substr(n1, n2 - n1);
std::cout << "transform " << col_name << ": s/" << regex_str << "/" << fmt_str << "/"
<< std::endl;
transformations[col_name] =
std::pair<std::unique_ptr<boost::regex>, std::unique_ptr<std::string>>(
std::unique_ptr<boost::regex>(new boost::regex(regex_str)),
std::unique_ptr<std::string>(new std::string(fmt_str)));
}
import_export::CopyParams copy_params(
delim, nulls, line_delim, batch_size, retry_count, retry_wait);
RowToColumnLoader row_loader(
ThriftClientConnection(
server_host, port, conn_type, skip_host_verify, ca_cert_name, ca_cert_name),
user_name,
passwd,
db_name,
table_name);
kafka_insert(
row_loader, transformations, copy_params, remove_quotes, group_id, topic, brokers);
return 0;
}
| 33.244565 | 90 | 0.56343 | [
"vector",
"transform"
] |
3bf96cb2a2e9429ddd5a29aae751194c1d462455 | 5,691 | cpp | C++ | AircoreCS.cpp | alancoolhand/AircoreCS | 011f37599000dbd418e9ee3a64af96e78c14a192 | [
"BSD-2-Clause"
] | null | null | null | AircoreCS.cpp | alancoolhand/AircoreCS | 011f37599000dbd418e9ee3a64af96e78c14a192 | [
"BSD-2-Clause"
] | null | null | null | AircoreCS.cpp | alancoolhand/AircoreCS | 011f37599000dbd418e9ee3a64af96e78c14a192 | [
"BSD-2-Clause"
] | 1 | 2020-10-16T13:59:07.000Z | 2020-10-16T13:59:07.000Z | /*
* Aircore CS4192 gauge driver Arduino Library
* Alan Locatelli - 2015
* Licensed under the BSD2 license, see license.txt for details.
* contains portions of code from
* SwitecX25 Arduino Library
* Guy Carpenter, Clearwater Software - 2012
* Licensed under the BSD2 license, see license.txt for details.
*
* All text above must be included in any redistribution.
*/
#include <Arduino.h>
#include <SPI.h>
#include "AircoreCS.h"
// This table defines the acceleration curve.
// 1st value is the speed step, 2nd value is delay in microseconds
// 1st value in each row must be > 1st value in subsequent row
// 1st value in last row should be == maxVel, must be <= maxVel
// This is unchanged from Switec X25 acceleration table. It is a bit slow for aircores, but OK for a test.
// Will need to tweak it.
static unsigned short defaultAccelTable[][2] = {
{ 20, 3000},
{ 50, 1500},
{ 100, 1000},
{ 150, 800},
{ 300, 600}
};
#define DEFAULT_ACCEL_TABLE_SIZE (sizeof(defaultAccelTable)/sizeof(*defaultAccelTable))
AircoreCS::AircoreCS(unsigned int cs)
{
//CS4192 driver accepts a 10bit value
this->steps = 1024;
//this is CS (chip select) pin used for this instance of the aircore. Every instance has common SCK and MOSI pins.
this->cs = cs;
pinMode(this->cs, OUTPUT);
//from CS4192 datasheet, contrary from most SPI devices, with this chip CS is normally LOW, and pulled HIGH to initiate a transfer
digitalWrite(cs,LOW);
dir = 0;
vel = 0;
stopped = true;
currentStep = 0;
targetStep = 0;
accelTable = defaultAccelTable;
maxVel = defaultAccelTable[DEFAULT_ACCEL_TABLE_SIZE-1][0]; // last value in table.
}
//according to CS4192 datasheet, in order to enable output of the chip the CS pin must be "pulsed".
//100 ms was a "random" value, but I found it to be working for me. YMMV
//For every motor this HAS to be called in void setup() AFTER SPI.begin()
void AircoreCS::pulse() {
digitalWrite(cs,HIGH);
delay(100);
digitalWrite(cs,LOW);
}
void AircoreCS::writeIO()
{
//from CS4192 datasheet, contrary from most SPI devices, with this chip CS is normally LOW, and pulled HIGH to initiate a transfer
digitalWrite(cs, HIGH);
// send in the address and value via SPI:
//CS4192 expects a 10 bit value, we're splitting it in 2 bytes and sending it.
byte byte1 = (currentStep >> 8);
byte byte0 = (currentStep & 0xFF); //0xFF = B11111111
SPI.transfer(byte1);
SPI.transfer(byte0);
// take the CS pin low to de-select the chip:
digitalWrite(cs, LOW);
}
void AircoreCS::stepUp()
{
if (currentStep < steps) {
currentStep++;
writeIO();
}
}
void AircoreCS::stepDown()
{
if (currentStep > 0) {
currentStep--;
writeIO();
}
}
void AircoreCS::zero()
{
currentStep = steps - 1;
for (unsigned int i=0;i<steps;i++) {
stepDown();
delayMicroseconds(RESET_STEP_MICROSEC);
}
currentStep = 0;
targetStep = 0;
vel = 0;
dir = 0;
}
// This function determines the speed and accel
// characteristics of the motor. Ultimately it
// steps the motor once (up or down) and computes
// the delay until the next step. Because it gets
// called once per step per motor, the calcuations
// here need to be as light-weight as possible, so
// we are avoiding floating-point arithmetic.
//
// To model acceleration we maintain vel, which indirectly represents
// velocity as the number of motor steps travelled under acceleration
// since starting. This value is used to look up the corresponding
// delay in accelTable. So from a standing start, vel is incremented
// once each step until it reaches maxVel. Under deceleration
// vel is decremented once each step until it reaches zero.
void AircoreCS::advance()
{
time0 = micros();
// detect stopped state
if (currentStep==targetStep && vel==0) {
stopped = true;
dir = 0;
return;
}
// if stopped, determine direction
if (vel==0) {
dir = currentStep<targetStep ? 1 : -1;
// do not set to 0 or it could go negative in case 2 below
vel = 1;
}
if (dir>0) {
stepUp();
} else {
stepDown();
}
// determine delta, number of steps in current direction to target.
// may be negative if we are headed away from target
int delta = dir>0 ? targetStep-currentStep : currentStep-targetStep;
if (delta>0) {
// case 1 : moving towards target (maybe under accel or decel)
if (delta < vel) {
// time to declerate
vel--;
} else if (vel < maxVel) {
// accelerating
vel++;
} else {
// at full speed - stay there
}
} else {
// case 2 : at or moving away from target (slow down!)
vel--;
}
// vel now defines delay
unsigned char i = 0;
// this is why vel must not be greater than the last vel in the table.
while (accelTable[i][0]<vel) {
i++;
}
microDelay = accelTable[i][1];
}
void AircoreCS::setPosition(unsigned int pos)
{
// pos is unsigned so don't need to check for <0
if (pos >= steps) pos = steps-1;
targetStep = pos;
if (stopped) {
// reset the timer to avoid possible time overflow giving spurious deltas
stopped = false;
time0 = micros();
microDelay = 0;
}
}
void AircoreCS::update()
{
if (!stopped) {
unsigned long delta = micros() - time0;
if (delta >= microDelay) {
advance();
}
}
}
//This updateMethod is blocking, it will give you smoother movements, but your application will wait for it to finish
void AircoreCS::updateBlocking()
{
while (!stopped) {
unsigned long delta = micros() - time0;
if (delta >= microDelay) {
advance();
}
}
}
| 25.986301 | 135 | 0.661922 | [
"model"
] |
3bfe435e9d3dfb4c9a235d24e7b766d0f5eab71f | 431 | cpp | C++ | old_codes/fibonacci2.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | old_codes/fibonacci2.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | old_codes/fibonacci2.cpp | tanishq1g/cp_codes | 80b8ccc9e195a66d6d317076fdd54a02cd21275b | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <ctime>
using namespace std;
int main() {
int n;
cin>>n;
clock_t start=clock();
int f[n];
f[0]=0;
f[1]=1;
for (int i = 2; i < n; ++i)
{
f[i]=(f[i-1]+f[i-2])%100;
}
cout<<"ans-"<<f[n-1];
clock_t stop=clock();
cout<<'\n'<<"time taken-"<<double(stop-start)/ CLOCKS_PER_SEC;
return 0;
} | 15.392857 | 63 | 0.587007 | [
"vector"
] |
3bfe8ca45fd09b24272654be41f13556081c88db | 35,120 | cpp | C++ | libgraph/src/GraphTopology.cpp | origandrew/katana | 456d64cf48a9d474dc35fb17e4d841bfa7a2f383 | [
"BSD-3-Clause"
] | null | null | null | libgraph/src/GraphTopology.cpp | origandrew/katana | 456d64cf48a9d474dc35fb17e4d841bfa7a2f383 | [
"BSD-3-Clause"
] | null | null | null | libgraph/src/GraphTopology.cpp | origandrew/katana | 456d64cf48a9d474dc35fb17e4d841bfa7a2f383 | [
"BSD-3-Clause"
] | null | null | null | #include "katana/GraphTopology.h"
#include <math.h>
#include <iostream>
#include "katana/Logging.h"
#include "katana/PropertyGraph.h"
#include "katana/RDGTopology.h"
#include "katana/Random.h"
#include "katana/Result.h"
katana::GraphTopology::~GraphTopology() = default;
void
katana::GraphTopology::Print() const noexcept {
auto print_array = [](const auto& arr, const auto& name) {
std::cout << name << ": [ ";
for (const auto& i : arr) {
std::cout << i << ", ";
}
std::cout << "]" << std::endl;
};
print_array(adj_indices_, "adj_indices_");
print_array(dests_, "dests_");
}
katana::GraphTopology::GraphTopology(
const Edge* adj_indices, size_t num_nodes, const Node* dests,
size_t num_edges) noexcept {
adj_indices_.allocateInterleaved(num_nodes);
dests_.allocateInterleaved(num_edges);
katana::ParallelSTL::copy(
&adj_indices[0], &adj_indices[num_nodes], adj_indices_.begin());
katana::ParallelSTL::copy(&dests[0], &dests[num_edges], dests_.begin());
}
katana::GraphTopology::GraphTopology(
const Edge* adj_indices, size_t num_nodes, const Node* dests,
size_t num_edges, const PropertyIndex* edge_prop_indices,
const PropertyIndex* node_prop_indices) noexcept {
adj_indices_.allocateInterleaved(num_nodes);
dests_.allocateInterleaved(num_edges);
katana::ParallelSTL::copy(
&adj_indices[0], &adj_indices[num_nodes], adj_indices_.begin());
katana::ParallelSTL::copy(&dests[0], &dests[num_edges], dests_.begin());
if (edge_prop_indices) {
edge_prop_indices_.allocateInterleaved(num_edges);
katana::ParallelSTL::copy(
&edge_prop_indices[0], &edge_prop_indices[num_edges],
edge_prop_indices_.begin());
}
if (node_prop_indices) {
node_prop_indices_.allocateInterleaved(num_nodes);
katana::ParallelSTL::copy(
&node_prop_indices[0], &node_prop_indices[num_nodes],
node_prop_indices_.begin());
}
}
katana::GraphTopology::GraphTopology(
AdjIndexVec&& adj_indices, EdgeDestVec&& dests) noexcept
: adj_indices_(std::move(adj_indices)), dests_(std::move(dests)) {}
katana::GraphTopology::GraphTopology(
AdjIndexVec&& adj_indices, EdgeDestVec&& dests,
PropIndexVec&& edge_prop_indices, PropIndexVec&& node_prop_indices) noexcept
: adj_indices_(std::move(adj_indices)),
dests_(std::move(dests)),
edge_prop_indices_(std::move(edge_prop_indices)),
node_prop_indices_(std::move(node_prop_indices)) {}
katana::GraphTopology
katana::GraphTopology::Copy(const GraphTopology& that) noexcept {
return katana::GraphTopology(
that.adj_indices_.data(), that.adj_indices_.size(), that.dests_.data(),
that.dests_.size(), that.edge_prop_indices_.data(),
that.edge_prop_indices_.data());
}
katana::GraphTopology::PropertyIndex
katana::GraphTopology::GetEdgePropertyIndexFromOutEdge(
const Edge& eid) const noexcept {
KATANA_LOG_DEBUG_ASSERT(eid < NumEdges());
return edge_prop_indices_.empty() ? eid : edge_prop_indices_[eid];
}
katana::GraphTopology::PropertyIndex
katana::GraphTopology::GetNodePropertyIndex(const Node& nid) const noexcept {
KATANA_LOG_DEBUG_ASSERT(nid < NumNodes() || NumNodes() == 0);
return node_prop_indices_.empty() ? nid : node_prop_indices_[nid];
}
katana::ShuffleTopology::~ShuffleTopology() = default;
std::shared_ptr<katana::ShuffleTopology>
katana::ShuffleTopology::MakeFrom(
const PropertyGraph*, const katana::EdgeShuffleTopology&) noexcept {
KATANA_LOG_FATAL("Not implemented yet");
std::shared_ptr<ShuffleTopology> ret;
return ret;
}
katana::EdgeShuffleTopology::~EdgeShuffleTopology() = default;
std::shared_ptr<katana::EdgeShuffleTopology>
katana::EdgeShuffleTopology::MakeTransposeCopy(
const katana::PropertyGraph* pg) {
KATANA_LOG_DEBUG_ASSERT(pg);
const auto& topology = pg->topology();
if (topology.empty()) {
EdgeShuffleTopology et;
et.tpose_state_ = katana::RDGTopology::TransposeKind::kYes;
return std::make_shared<EdgeShuffleTopology>(std::move(et));
}
AdjIndexVec out_indices;
EdgeDestVec out_dests;
PropIndexVec edge_prop_indices;
AdjIndexVec out_dests_offset;
out_indices.allocateInterleaved(topology.NumNodes());
out_dests.allocateInterleaved(topology.NumEdges());
edge_prop_indices.allocateInterleaved(topology.NumEdges());
out_dests_offset.allocateInterleaved(topology.NumNodes());
katana::ParallelSTL::fill(out_indices.begin(), out_indices.end(), Edge{0});
// Keep a copy of old destinaton ids and compute number of
// in-coming edges for the new prefix sum of out_indices.
katana::do_all(
katana::iterate(topology.OutEdges()),
[&](Edge e) {
// Counting outgoing edges in the tranpose graph by
// counting incoming edges in the original graph
auto dest = topology.OutEdgeDst(e);
__sync_add_and_fetch(&(out_indices[dest]), 1);
},
katana::no_stats());
// Prefix sum calculation of the edge index array
katana::ParallelSTL::partial_sum(
out_indices.begin(), out_indices.end(), out_indices.begin());
// temporary buffer for storing the starting point of each node's transpose
// adjacency
out_dests_offset[0] = 0;
katana::do_all(
katana::iterate(Edge{1}, Edge{topology.NumNodes()}),
[&](Edge n) { out_dests_offset[n] = out_indices[n - 1]; },
katana::no_stats());
// Update out_dests with the new destination ids
// of the transposed graphs
katana::do_all(
katana::iterate(topology.Nodes()),
[&](auto src) {
// get all outgoing edges of a particular
// node and reverse the edges.
for (GraphTopology::Edge e : topology.OutEdges(src)) {
// e = start index into edge array for a particular node
// Destination node
auto dest = topology.OutEdgeDst(e);
// Location to save edge
auto e_new = __sync_fetch_and_add(&(out_dests_offset[dest]), 1);
// Save src as destination
out_dests[e_new] = src;
// remember the original edge ID to look up properties
edge_prop_indices[e_new] =
topology.GetEdgePropertyIndexFromOutEdge(e);
}
},
katana::steal(), katana::no_stats());
return std::make_shared<EdgeShuffleTopology>(EdgeShuffleTopology{
katana::RDGTopology::TransposeKind::kYes,
katana::RDGTopology::EdgeSortKind::kAny,
std::move(out_indices),
std::move(out_dests),
std::move(edge_prop_indices),
{}});
}
std::shared_ptr<katana::EdgeShuffleTopology>
katana::EdgeShuffleTopology::MakeOriginalCopy(const katana::PropertyGraph* pg) {
GraphTopology copy_topo = GraphTopology::Copy(pg->topology());
GraphTopologyTypes::PropIndexVec edge_prop_indices;
if (copy_topo.GetEdgePropIndices().empty()) {
edge_prop_indices.allocateInterleaved(copy_topo.NumEdges());
katana::ParallelSTL::iota(
edge_prop_indices.begin(), edge_prop_indices.end(), Edge{0});
} else {
edge_prop_indices = std::move(copy_topo.GetEdgePropIndices());
}
return std::make_shared<EdgeShuffleTopology>(EdgeShuffleTopology{
katana::RDGTopology::TransposeKind::kNo,
katana::RDGTopology::EdgeSortKind::kAny,
std::move(copy_topo.GetAdjIndices()), std::move(copy_topo.GetDests()),
std::move(edge_prop_indices), std::move(copy_topo.GetNodePropIndices())});
}
std::shared_ptr<katana::EdgeShuffleTopology>
katana::EdgeShuffleTopology::Make(katana::RDGTopology* rdg_topo) {
KATANA_LOG_DEBUG_ASSERT(rdg_topo);
EdgeDestVec dests_copy;
dests_copy.allocateInterleaved(rdg_topo->num_edges());
AdjIndexVec adj_indices_copy;
adj_indices_copy.allocateInterleaved(rdg_topo->num_nodes());
PropIndexVec edge_prop_indices;
edge_prop_indices.allocateInterleaved(rdg_topo->num_edges());
if (rdg_topo->num_nodes() > 0) {
katana::ParallelSTL::copy(
&(rdg_topo->adj_indices()[0]),
&(rdg_topo->adj_indices()[rdg_topo->num_nodes()]),
adj_indices_copy.begin());
}
if (rdg_topo->num_edges() > 0) {
katana::ParallelSTL::copy(
&(rdg_topo->dests()[0]), &(rdg_topo->dests()[rdg_topo->num_edges()]),
dests_copy.begin());
katana::ParallelSTL::copy(
&(rdg_topo->edge_index_to_property_index_map()[0]),
&(rdg_topo->edge_index_to_property_index_map()[rdg_topo->num_edges()]),
edge_prop_indices.begin());
}
// Since we copy the data we need out of the RDGTopology into our own arrays,
// unbind the RDGTopologys file store to save memory.
auto res = rdg_topo->unbind_file_storage();
KATANA_LOG_ASSERT(res);
std::shared_ptr<EdgeShuffleTopology> shuffle =
std::make_shared<EdgeShuffleTopology>(EdgeShuffleTopology{
rdg_topo->transpose_state(),
rdg_topo->edge_sort_state(),
std::move(adj_indices_copy),
std::move(dests_copy),
std::move(edge_prop_indices),
{}});
return shuffle;
}
katana::Result<katana::RDGTopology>
katana::EdgeShuffleTopology::ToRDGTopology() const {
katana::RDGTopology topo = KATANA_CHECKED(katana::RDGTopology::Make(
AdjData(), NumNodes(), DestData(), NumEdges(),
katana::RDGTopology::TopologyKind::kEdgeShuffleTopology, tpose_state_,
edge_sort_state_, edge_prop_indices_.data()));
return katana::RDGTopology(std::move(topo));
}
katana::GraphTopologyTypes::edge_iterator
katana::EdgeShuffleTopology::FindEdge(
const katana::GraphTopologyTypes::Node& src,
const katana::GraphTopologyTypes::Node& dst) const noexcept {
auto e_range = OutEdges(src);
constexpr size_t kBinarySearchThreshold = 64;
if (e_range.size() > kBinarySearchThreshold &&
!has_edges_sorted_by(
katana::RDGTopology::EdgeSortKind::kSortedByDestID)) {
KATANA_WARN_ONCE(
"FindEdge(): expect poor performance. Edges not sorted by Dest ID");
}
if (e_range.size() <= kBinarySearchThreshold) {
auto iter = std::find_if(
e_range.begin(), e_range.end(),
[&](const GraphTopology::Edge& e) { return OutEdgeDst(e) == dst; });
return iter;
} else {
auto iter = std::lower_bound(
e_range.begin(), e_range.end(), dst,
internal::EdgeDestComparator<EdgeShuffleTopology>{this});
return OutEdgeDst(*iter) == dst ? iter : e_range.end();
}
}
katana::GraphTopologyTypes::edges_range
katana::EdgeShuffleTopology::FindAllEdges(
const katana::GraphTopologyTypes::Node& src,
const katana::GraphTopologyTypes::Node& dst) const noexcept {
auto e_range = OutEdges(src);
if (e_range.empty()) {
return e_range;
}
KATANA_LOG_VASSERT(
!has_edges_sorted_by(katana::RDGTopology::EdgeSortKind::kSortedByDestID),
"Must have edges sorted by kSortedByDestID");
internal::EdgeDestComparator<EdgeShuffleTopology> comp{this};
auto [first_it, last_it] =
std::equal_range(e_range.begin(), e_range.end(), dst, comp);
if (first_it == e_range.end() || OutEdgeDst(*first_it) != dst) {
// return empty range
return MakeStandardRange(e_range.end(), e_range.end());
}
auto ret_range = MakeStandardRange(first_it, last_it);
for ([[maybe_unused]] auto e : ret_range) {
KATANA_LOG_DEBUG_ASSERT(OutEdgeDst(e) == dst);
}
return ret_range;
}
void
katana::EdgeShuffleTopology::SortEdgesByDestID() noexcept {
katana::do_all(
katana::iterate(Nodes()),
[&](Node node) {
// get this node's first and last edge
auto e_beg = *OutEdges(node).begin();
auto e_end = *OutEdges(node).end();
// get iterators to locations to sort in the vector
auto begin_sort_iter = katana::make_zip_iterator(
edge_prop_indices_.begin() + e_beg, GetDests().begin() + e_beg);
auto end_sort_iter = katana::make_zip_iterator(
edge_prop_indices_.begin() + e_end, GetDests().begin() + e_end);
// rearrange vector indices based on how the destinations of this
// graph will eventually be sorted sort function not based on vector
// being passed, but rather the type and destination of the graph
std::sort(
begin_sort_iter, end_sort_iter,
[&](const auto& tup1, const auto& tup2) {
auto dst1 = std::get<1>(tup1);
auto dst2 = std::get<1>(tup2);
static_assert(
std::is_same_v<decltype(dst1), GraphTopology::Node>);
static_assert(
std::is_same_v<decltype(dst2), GraphTopology::Node>);
return dst1 < dst2;
});
KATANA_LOG_DEBUG_ASSERT(std::is_sorted(
GetDests().begin() + e_beg, GetDests().begin() + e_end));
},
katana::steal(), katana::no_stats());
// remember to update sort state
edge_sort_state_ = katana::RDGTopology::EdgeSortKind::kSortedByDestID;
}
void
katana::EdgeShuffleTopology::SortEdgesByTypeThenDest(
const PropertyGraph* pg) noexcept {
katana::do_all(
katana::iterate(Nodes()),
[&](Node node) {
// get this node's first and last edge
auto e_beg = *OutEdges(node).begin();
auto e_end = *OutEdges(node).end();
// get iterators to locations to sort in the vector
auto begin_sort_iter = katana::make_zip_iterator(
edge_prop_indices_.begin() + e_beg, GetDests().begin() + e_beg);
auto end_sort_iter = katana::make_zip_iterator(
edge_prop_indices_.begin() + e_end, GetDests().begin() + e_end);
// rearrange vector indices based on how the destinations of this
// graph will eventually be sorted sort function not based on vector
// being passed, but rather the type and destination of the graph
std::sort(
begin_sort_iter, end_sort_iter,
[&](const auto& tup1, const auto& tup2) {
// get edge type and destinations
auto e1 = std::get<0>(tup1);
auto e2 = std::get<0>(tup2);
static_assert(
std::is_same_v<decltype(e1), GraphTopology::PropertyIndex>);
static_assert(
std::is_same_v<decltype(e2), GraphTopology::PropertyIndex>);
katana::EntityTypeID data1 =
pg->GetTypeOfEdgeFromPropertyIndex(e1);
katana::EntityTypeID data2 =
pg->GetTypeOfEdgeFromPropertyIndex(e2);
if (data1 != data2) {
return data1 < data2;
}
auto dst1 = std::get<1>(tup1);
auto dst2 = std::get<1>(tup2);
static_assert(
std::is_same_v<decltype(dst1), GraphTopology::Node>);
static_assert(
std::is_same_v<decltype(dst2), GraphTopology::Node>);
return dst1 < dst2;
});
},
katana::steal(), katana::no_stats());
// remember to update sort state
edge_sort_state_ = katana::RDGTopology::EdgeSortKind::kSortedByEdgeType;
}
void
katana::EdgeShuffleTopology::SortEdgesByDestType(
const PropertyGraph*,
const katana::GraphTopologyTypes::PropIndexVec&) noexcept {
KATANA_LOG_FATAL("Not implemented yet");
}
std::shared_ptr<katana::ShuffleTopology>
katana::ShuffleTopology::MakeSortedByDegree(
const PropertyGraph*,
const katana::EdgeShuffleTopology& seed_topo) noexcept {
auto cmp = [&](const auto& i1, const auto& i2) {
auto d1 = seed_topo.OutDegree(i1);
auto d2 = seed_topo.OutDegree(i2);
// TODO(amber): Triangle-Counting needs degrees sorted in descending order. I
// need to think of a way to specify in the interface whether degrees should be
// sorted in ascending or descending order.
// return d1 < d2;
return d1 > d2;
};
return MakeNodeSortedTopo(
seed_topo, cmp, katana::RDGTopology::NodeSortKind::kSortedByDegree);
}
std::shared_ptr<katana::ShuffleTopology>
katana::ShuffleTopology::MakeSortedByNodeType(
const PropertyGraph* pg,
const katana::EdgeShuffleTopology& seed_topo) noexcept {
auto cmp = [&](const auto& i1, const auto& i2) {
auto idx1 = seed_topo.GetNodePropertyIndex(i1);
auto idx2 = seed_topo.GetNodePropertyIndex(i2);
auto k1 = pg->GetTypeOfNodeFromPropertyIndex(idx1);
auto k2 = pg->GetTypeOfNodeFromPropertyIndex(idx2);
if (k1 == k2) {
return i1 < i2;
}
return k1 < k2;
};
return MakeNodeSortedTopo(
seed_topo, cmp, katana::RDGTopology::NodeSortKind::kSortedByNodeType);
}
std::shared_ptr<katana::ShuffleTopology>
katana::ShuffleTopology::Make(katana::RDGTopology* rdg_topo) {
KATANA_LOG_DEBUG_ASSERT(rdg_topo);
EdgeDestVec dests_copy;
dests_copy.allocateInterleaved(rdg_topo->num_edges());
AdjIndexVec adj_indices_copy;
adj_indices_copy.allocateInterleaved(rdg_topo->num_nodes());
PropIndexVec edge_prop_indices_copy;
edge_prop_indices_copy.allocateInterleaved(rdg_topo->num_edges());
PropIndexVec node_prop_indices_copy;
node_prop_indices_copy.allocateInterleaved(rdg_topo->num_nodes());
katana::ParallelSTL::copy(
&(rdg_topo->adj_indices()[0]),
&(rdg_topo->adj_indices()[rdg_topo->num_nodes()]),
adj_indices_copy.begin());
katana::ParallelSTL::copy(
&(rdg_topo->dests()[0]), &(rdg_topo->dests()[rdg_topo->num_edges()]),
dests_copy.begin());
katana::ParallelSTL::copy(
&(rdg_topo->edge_index_to_property_index_map()[0]),
&(rdg_topo->edge_index_to_property_index_map()[rdg_topo->num_edges()]),
edge_prop_indices_copy.begin());
katana::ParallelSTL::copy(
&(rdg_topo->node_index_to_property_index_map()[0]),
&(rdg_topo->node_index_to_property_index_map()[rdg_topo->num_nodes()]),
node_prop_indices_copy.begin());
// Since we copy the data we need out of the RDGTopology into our own arrays,
// unbind the RDGTopologys file store to save memory.
auto res = rdg_topo->unbind_file_storage();
KATANA_LOG_ASSERT(res);
std::shared_ptr<ShuffleTopology> shuffle =
std::make_shared<ShuffleTopology>(ShuffleTopology{
rdg_topo->transpose_state(), rdg_topo->node_sort_state(),
rdg_topo->edge_sort_state(), std::move(adj_indices_copy),
std::move(node_prop_indices_copy), std::move(dests_copy),
std::move(edge_prop_indices_copy)});
return shuffle;
}
katana::Result<katana::RDGTopology>
katana::ShuffleTopology::ToRDGTopology() const {
katana::RDGTopology topo = KATANA_CHECKED(katana::RDGTopology::Make(
AdjData(), NumNodes(), DestData(), NumEdges(),
katana::RDGTopology::TopologyKind::kShuffleTopology, transpose_state(),
edge_sort_state(), node_sort_state(), edge_property_index_data(),
node_property_index_data()));
return katana::RDGTopology(std::move(topo));
}
std::shared_ptr<katana::CondensedTypeIDMap>
katana::CondensedTypeIDMap::MakeFromEdgeTypes(
const katana::PropertyGraph* pg) noexcept {
TypeIDToIndexMap edge_type_to_index;
IndexToTypeIDMap edge_index_to_type;
katana::PerThreadStorage<katana::gstl::Set<katana::EntityTypeID>> edgeTypes;
const auto& topo = pg->topology();
katana::do_all(
katana::iterate(Edge{0}, topo.NumEdges()),
[&](const Edge& e) {
katana::EntityTypeID type = pg->GetTypeOfEdgeFromTopoIndex(e);
edgeTypes.getLocal()->insert(type);
},
katana::no_stats());
// ordered map
std::set<katana::EntityTypeID> mergedSet;
for (uint32_t i = 0; i < katana::activeThreads; ++i) {
auto& edgeTypesSet = *edgeTypes.getRemote(i);
for (auto edgeType : edgeTypesSet) {
mergedSet.insert(edgeType);
}
}
// unordered map
uint32_t num_edge_types = 0u;
for (const auto& edgeType : mergedSet) {
edge_type_to_index[edgeType] = num_edge_types++;
edge_index_to_type.emplace_back(edgeType);
}
// TODO(amber): introduce a per-thread-container type that frees memory
// correctly
katana::on_each([&](unsigned, unsigned) {
// free up memory by resetting
*edgeTypes.getLocal() = gstl::Set<katana::EntityTypeID>();
});
return std::make_shared<CondensedTypeIDMap>(CondensedTypeIDMap{
std::move(edge_type_to_index), std::move(edge_index_to_type)});
}
katana::EdgeTypeAwareTopology::~EdgeTypeAwareTopology() = default;
katana::EdgeTypeAwareTopology::AdjIndexVec
katana::EdgeTypeAwareTopology::CreatePerEdgeTypeAdjacencyIndex(
const PropertyGraph& pg, const CondensedTypeIDMap& edge_type_index,
const EdgeShuffleTopology& e_topo) noexcept {
if (e_topo.empty()) {
KATANA_LOG_VASSERT(
e_topo.NumEdges() == 0, "Found graph with edges but no nodes");
return AdjIndexVec{};
}
if (edge_type_index.num_unique_types() == 0) {
KATANA_LOG_VASSERT(
e_topo.NumEdges() == 0, "Found graph with edges but no edge types");
// Graph has some nodes but no edges.
return AdjIndexVec{};
}
const size_t sz = e_topo.NumNodes() * edge_type_index.num_unique_types();
AdjIndexVec adj_indices;
adj_indices.allocateInterleaved(sz);
katana::do_all(
katana::iterate(e_topo.Nodes()),
[&](Node N) {
auto offset = N * edge_type_index.num_unique_types();
uint32_t index = 0;
for (auto e : e_topo.OutEdges(N)) {
// Since we sort the edges, we must use the
// edge_property_index because EdgeShuffleTopology rearranges the edges
const auto type = pg.GetTypeOfEdgeFromPropertyIndex(
e_topo.GetEdgePropertyIndexFromOutEdge(e));
while (type != edge_type_index.GetType(index)) {
adj_indices[offset + index] = e;
index++;
KATANA_LOG_DEBUG_ASSERT(index < edge_type_index.num_unique_types());
}
}
auto e = *e_topo.OutEdges(N).end();
while (index < edge_type_index.num_unique_types()) {
adj_indices[offset + index] = e;
index++;
}
},
katana::no_stats(), katana::steal());
return adj_indices;
}
std::shared_ptr<katana::EdgeTypeAwareTopology>
katana::EdgeTypeAwareTopology::MakeFrom(
const katana::PropertyGraph* pg,
std::shared_ptr<const CondensedTypeIDMap> edge_type_index,
EdgeShuffleTopology&& e_topo) noexcept {
KATANA_LOG_DEBUG_ASSERT(e_topo.has_edges_sorted_by(
katana::RDGTopology::EdgeSortKind::kSortedByEdgeType));
KATANA_LOG_DEBUG_ASSERT(e_topo.NumEdges() == pg->topology().NumEdges());
AdjIndexVec per_type_adj_indices =
CreatePerEdgeTypeAdjacencyIndex(*pg, *edge_type_index, e_topo);
return std::make_shared<EdgeTypeAwareTopology>(EdgeTypeAwareTopology{
std::move(e_topo), std::move(edge_type_index),
std::move(per_type_adj_indices)});
}
katana::Result<katana::RDGTopology>
katana::EdgeTypeAwareTopology::ToRDGTopology() const {
katana::RDGTopology topo = KATANA_CHECKED(katana::RDGTopology::Make(
per_type_adj_indices_.data(), NumNodes(), Base::DestData(), NumEdges(),
katana::RDGTopology::TopologyKind::kEdgeTypeAwareTopology,
transpose_state(), edge_sort_state(), Base::edge_property_index_data(),
edge_type_index_->num_unique_types(),
edge_type_index_->index_to_type_map_data()));
return katana::RDGTopology(std::move(topo));
}
std::shared_ptr<katana::EdgeTypeAwareTopology>
katana::EdgeTypeAwareTopology::Make(
katana::RDGTopology* rdg_topo,
std::shared_ptr<const CondensedTypeIDMap> edge_type_index,
EdgeShuffleTopology&& e_topo) {
KATANA_LOG_DEBUG_ASSERT(rdg_topo);
KATANA_LOG_ASSERT(
rdg_topo->edge_sort_state() ==
katana::RDGTopology::EdgeSortKind::kSortedByEdgeType);
KATANA_LOG_DEBUG_ASSERT(e_topo.has_edges_sorted_by(
katana::RDGTopology::EdgeSortKind::kSortedByEdgeType));
KATANA_LOG_VASSERT(
edge_type_index->index_to_type_map_matches(
rdg_topo->edge_condensed_type_id_map_size(),
rdg_topo->edge_condensed_type_id_map()) &&
e_topo.NumEdges() == rdg_topo->num_edges() &&
e_topo.NumNodes() == rdg_topo->num_nodes(),
"tried to load out of date EdgeTypeAwareTopology; on disk topologies "
"must be invalidated when updates occur");
AdjIndexVec per_type_adj_indices;
size_t sz = rdg_topo->num_nodes() * edge_type_index->num_unique_types();
per_type_adj_indices.allocateInterleaved(sz);
katana::ParallelSTL::copy(
&(rdg_topo->adj_indices()[0]), &(rdg_topo->adj_indices()[sz]),
per_type_adj_indices.begin());
// Since we copy the data we need out of the RDGTopology into our own arrays,
// unbind the RDGTopologys file store to save memory.
auto res = rdg_topo->unbind_file_storage();
KATANA_LOG_ASSERT(res);
return std::make_shared<EdgeTypeAwareTopology>(EdgeTypeAwareTopology{
std::move(e_topo), std::move(edge_type_index),
std::move(per_type_adj_indices)});
}
const katana::GraphTopology&
katana::PGViewCache::GetDefaultTopologyRef() const noexcept {
return *original_topo_;
}
std::shared_ptr<katana::GraphTopology>
katana::PGViewCache::GetDefaultTopology() const noexcept {
return original_topo_;
}
bool
katana::PGViewCache::ReseatDefaultTopo(
const std::shared_ptr<GraphTopology>& other) noexcept {
// We check for the original sort state to avoid doing this every time a new
// edge shuffle topo is cached.
if (original_topo_->edge_sort_state() !=
katana::RDGTopology::EdgeSortKind::kAny) {
return false;
}
original_topo_ = other;
return true;
}
void
katana::PGViewCache::DropAllTopologies() noexcept {
original_topo_ = std::make_shared<katana::GraphTopology>();
edge_shuff_topos_.clear();
fully_shuff_topos_.clear();
edge_type_aware_topos_.clear();
edge_type_id_map_.reset();
}
std::shared_ptr<katana::CondensedTypeIDMap>
katana::PGViewCache::BuildOrGetEdgeTypeIndex(
const katana::PropertyGraph* pg) noexcept {
if (edge_type_id_map_ && edge_type_id_map_->is_valid()) {
return edge_type_id_map_;
}
edge_type_id_map_ = CondensedTypeIDMap::MakeFromEdgeTypes(pg);
KATANA_LOG_DEBUG_ASSERT(edge_type_id_map_);
return edge_type_id_map_;
};
template <typename Topo>
[[maybe_unused]] bool
CheckTopology(const katana::PropertyGraph* pg, const Topo* t) noexcept {
return (pg->NumNodes() == t->NumNodes()) && (pg->NumEdges() == t->NumEdges());
}
std::shared_ptr<katana::EdgeShuffleTopology>
katana::PGViewCache::BuildOrGetEdgeShuffTopo(
katana::PropertyGraph* pg,
const katana::RDGTopology::TransposeKind& tpose_kind,
const katana::RDGTopology::EdgeSortKind& sort_kind) noexcept {
return BuildOrGetEdgeShuffTopoImpl(pg, tpose_kind, sort_kind, false);
}
std::shared_ptr<katana::EdgeShuffleTopology>
katana::PGViewCache::PopEdgeShuffTopo(
katana::PropertyGraph* pg,
const katana::RDGTopology::TransposeKind& tpose_kind,
const katana::RDGTopology::EdgeSortKind& sort_kind) noexcept {
return BuildOrGetEdgeShuffTopoImpl(pg, tpose_kind, sort_kind, true);
}
std::shared_ptr<katana::EdgeShuffleTopology>
katana::PGViewCache::BuildOrGetEdgeShuffTopoImpl(
katana::PropertyGraph* pg,
const katana::RDGTopology::TransposeKind& tpose_kind,
const katana::RDGTopology::EdgeSortKind& sort_kind, bool pop) noexcept {
// Try to find a matching topology in the cache.
auto pred = [&](const auto& topo_ptr) {
return topo_ptr->is_valid() && topo_ptr->has_transpose_state(tpose_kind) &&
topo_ptr->has_edges_sorted_by(sort_kind);
};
auto it =
std::find_if(edge_shuff_topos_.begin(), edge_shuff_topos_.end(), pred);
if (it != edge_shuff_topos_.end()) {
KATANA_LOG_DEBUG_ASSERT(CheckTopology(pg, it->get()));
if (pop) {
auto topo = *it;
edge_shuff_topos_.erase(it);
return topo;
} else {
return *it;
}
}
// Then in edge type aware topologies. We don't pop from it.
if (sort_kind == katana::RDGTopology::EdgeSortKind::kSortedByEdgeType) {
auto it = std::find_if(
edge_type_aware_topos_.begin(), edge_type_aware_topos_.end(), pred);
if (it != edge_type_aware_topos_.end()) {
KATANA_LOG_DEBUG_ASSERT(CheckTopology(pg, it->get()));
return *it;
}
}
// No matching topology in cache, see if we have it in storage
katana::RDGTopology shadow = katana::RDGTopology::MakeShadow(
katana::RDGTopology::TopologyKind::kEdgeShuffleTopology, tpose_kind,
sort_kind, katana::RDGTopology::NodeSortKind::kAny);
auto res = pg->LoadTopology(std::move(shadow));
auto new_topo = (!res) ? EdgeShuffleTopology::Make(pg, tpose_kind, sort_kind)
: EdgeShuffleTopology::Make(res.value());
KATANA_LOG_DEBUG_ASSERT(CheckTopology(pg, new_topo.get()));
if (pop) {
return new_topo;
} else {
edge_shuff_topos_.emplace_back(std::move(new_topo));
return edge_shuff_topos_.back();
}
}
std::shared_ptr<katana::ShuffleTopology>
katana::PGViewCache::BuildOrGetShuffTopo(
katana::PropertyGraph* pg,
const katana::RDGTopology::TransposeKind& tpose_kind,
const katana::RDGTopology::NodeSortKind& node_sort_todo,
const katana::RDGTopology::EdgeSortKind& edge_sort_todo) noexcept {
// try to find a matching topology in the cache
auto pred = [&](const auto& topo_ptr) {
return topo_ptr->is_valid() && topo_ptr->has_transpose_state(tpose_kind) &&
topo_ptr->has_edges_sorted_by(edge_sort_todo) &&
topo_ptr->has_nodes_sorted_by(node_sort_todo);
};
auto it =
std::find_if(fully_shuff_topos_.begin(), fully_shuff_topos_.end(), pred);
if (it != fully_shuff_topos_.end()) {
KATANA_LOG_DEBUG_ASSERT(CheckTopology(pg, it->get()));
return *it;
} else {
// no matching topology in cache, see if we have it in storage
katana::RDGTopology shadow = katana::RDGTopology::MakeShadow(
katana::RDGTopology::TopologyKind::kShuffleTopology, tpose_kind,
edge_sort_todo, node_sort_todo);
auto res = pg->LoadTopology(std::move(shadow));
if (!res) {
// no matching topology in cache or storage, generate it
// EdgeShuffleTopology e_topo below is going to serve as a seed for
// ShuffleTopology, so we only care about transpose state, and not the sort
// state. Because, when creating ShuffleTopology, once we shuffle the nodes, we
// will need to re-sort the edges even if they were already sorted
auto e_topo = BuildOrGetEdgeShuffTopo(
pg, tpose_kind, katana::RDGTopology::EdgeSortKind::kAny);
KATANA_LOG_DEBUG_ASSERT(e_topo->has_transpose_state(tpose_kind));
fully_shuff_topos_.emplace_back(ShuffleTopology::MakeFromTopo(
pg, *e_topo, node_sort_todo, edge_sort_todo));
} else {
// found matching topology in storage
katana::RDGTopology* topo = res.value();
fully_shuff_topos_.emplace_back(katana::ShuffleTopology::Make(topo));
}
KATANA_LOG_DEBUG_ASSERT(CheckTopology(pg, fully_shuff_topos_.back().get()));
return fully_shuff_topos_.back();
}
}
std::shared_ptr<katana::EdgeTypeAwareTopology>
katana::PGViewCache::BuildOrGetEdgeTypeAwareTopo(
katana::PropertyGraph* pg,
const katana::RDGTopology::TransposeKind& tpose_kind) noexcept {
// try to find a matching topology in the cache
auto pred = [&](const auto& topo_ptr) {
return topo_ptr->is_valid() && topo_ptr->has_transpose_state(tpose_kind);
};
auto it = std::find_if(
edge_type_aware_topos_.begin(), edge_type_aware_topos_.end(), pred);
if (it != edge_type_aware_topos_.end()) {
KATANA_LOG_DEBUG_ASSERT(CheckTopology(pg, it->get()));
return *it;
} else {
// no matching topology in cache, see if we have it in storage
katana::RDGTopology shadow = katana::RDGTopology::MakeShadow(
katana::RDGTopology::TopologyKind::kEdgeTypeAwareTopology, tpose_kind,
katana::RDGTopology::EdgeSortKind::kSortedByEdgeType,
katana::RDGTopology::NodeSortKind::kAny);
auto res = pg->LoadTopology(std::move(shadow));
// In either generation, or loading, the EdgeTypeAwareTopology depends on an EdgeShuffleTopology.
// This call does NOT cache the resulting edge shuffled topology.
auto sorted_topo = PopEdgeShuffTopo(
pg, tpose_kind, katana::RDGTopology::EdgeSortKind::kSortedByEdgeType);
// There are two use cases for the EdgeTypeIndex, either we:
// Are generating an EdgeTypeAwareTopology, and need the EdgeTypeIndex
// Are loading an EdgeTypeAwareTopology from storage, and need to confirm
// the EdgeTypeIndex in storage matches the one we have.
// If it doesn't match, then the EdgeTypeAwareTopology on storage is out of date and cannot be used
auto edge_type_index = BuildOrGetEdgeTypeIndex(pg);
if (res) {
// found matching topology in storage
katana::RDGTopology* rdg_topo = res.value();
edge_type_aware_topos_.emplace_back(katana::EdgeTypeAwareTopology::Make(
rdg_topo, std::move(edge_type_index), std::move(*sorted_topo)));
} else {
// no matching topology in cache or storage, generate it
edge_type_aware_topos_.emplace_back(EdgeTypeAwareTopology::MakeFrom(
pg, std::move(edge_type_index), std::move(*sorted_topo)));
}
KATANA_LOG_DEBUG_ASSERT(
CheckTopology(pg, edge_type_aware_topos_.back().get()));
return edge_type_aware_topos_.back();
}
}
katana::Result<std::vector<katana::RDGTopology>>
katana::PGViewCache::ToRDGTopology() {
std::vector<katana::RDGTopology> rdg_topos;
for (size_t i = 0; i < edge_shuff_topos_.size(); i++) {
katana::RDGTopology topo =
KATANA_CHECKED(edge_shuff_topos_[i]->ToRDGTopology());
rdg_topos.emplace_back(std::move(topo));
}
for (size_t i = 0; i < fully_shuff_topos_.size(); i++) {
katana::RDGTopology topo =
KATANA_CHECKED(fully_shuff_topos_[i]->ToRDGTopology());
rdg_topos.emplace_back(std::move(topo));
}
for (size_t i = 0; i < edge_type_aware_topos_.size(); i++) {
katana::RDGTopology topo =
KATANA_CHECKED(edge_type_aware_topos_[i]->ToRDGTopology());
rdg_topos.emplace_back(std::move(topo));
}
return std::vector<katana::RDGTopology>(std::move(rdg_topos));
}
katana::GraphTopology
katana::CreateUniformRandomTopology(
const size_t num_nodes, const size_t edges_per_node) noexcept {
KATANA_LOG_ASSERT(edges_per_node > 0);
if (num_nodes == 0) {
return GraphTopology{};
}
KATANA_LOG_ASSERT(edges_per_node <= num_nodes);
GraphTopology::AdjIndexVec adj_indices;
adj_indices.allocateInterleaved(num_nodes);
// give each node edges_per_node neighbors
katana::ParallelSTL::fill(
adj_indices.begin(), adj_indices.end(),
GraphTopology::Edge{edges_per_node});
katana::ParallelSTL::partial_sum(
adj_indices.begin(), adj_indices.end(), adj_indices.begin());
const size_t num_edges = num_nodes * edges_per_node;
KATANA_LOG_ASSERT(
adj_indices.size() > 0 &&
adj_indices[adj_indices.size() - 1] == num_edges);
GraphTopology::EdgeDestVec dests;
dests.allocateInterleaved(num_edges);
// TODO(amber): Write a parallel version of GenerateUniformRandomSequence
katana::GenerateUniformRandomSequence(
dests.begin(), dests.end(), GraphTopology::Node{0},
static_cast<GraphTopology::Node>(num_nodes - 1));
return GraphTopology{std::move(adj_indices), std::move(dests)};
}
| 36.431535 | 103 | 0.698007 | [
"vector"
] |
ce03c99a058cc8d7f21333dd38ab8620fed70c76 | 4,595 | cpp | C++ | Core/SymbolData.cpp | RyanDwyer/armips | 8eb7bf068c3350e67b16e605655cc6598c28ff52 | [
"MIT"
] | 1 | 2017-03-24T12:19:07.000Z | 2017-03-24T12:19:07.000Z | Core/SymbolData.cpp | RyanDwyer/armips | 8eb7bf068c3350e67b16e605655cc6598c28ff52 | [
"MIT"
] | null | null | null | Core/SymbolData.cpp | RyanDwyer/armips | 8eb7bf068c3350e67b16e605655cc6598c28ff52 | [
"MIT"
] | null | null | null | #include "SymbolData.h"
#include "Core/Common.h"
#include "Core/Misc.h"
#include "FileManager.h"
#include <algorithm>
SymbolData::SymbolData()
{
clear();
}
void SymbolData::clear()
{
enabled = true;
nocashSymFileName.clear();
modules.clear();
files.clear();
currentModule = 0;
currentFunction = -1;
SymDataModule defaultModule;
defaultModule.file = nullptr;
modules.push_back(defaultModule);
}
struct NocashSymEntry
{
int64_t address;
std::string text;
bool operator<(const NocashSymEntry& other) const
{
if (address != other.address)
return address < other.address;
return text < other.text;
}
};
void SymbolData::writeNocashSym()
{
if (nocashSymFileName.empty())
return;
std::vector<NocashSymEntry> entries;
for (size_t k = 0; k < modules.size(); k++)
{
SymDataModule& module = modules[k];
for (size_t i = 0; i < module.symbols.size(); i++)
{
SymDataSymbol& sym = module.symbols[i];
size_t size = 0;
for (size_t f = 0; f < module.functions.size(); f++)
{
if (module.functions[f].address == sym.address)
{
size = module.functions[f].size;
break;
}
}
NocashSymEntry entry;
entry.address = sym.address;
if (size != 0 && nocashSymVersion >= 2)
entry.text = tfm::format("%s,%08X",sym.name,size);
else
entry.text = sym.name;
if (nocashSymVersion == 1)
std::transform(entry.text.begin(), entry.text.end(), entry.text.begin(), ::tolower);
entries.push_back(entry);
}
for (const SymDataData& data: module.data)
{
NocashSymEntry entry;
entry.address = data.address;
switch (data.type)
{
case Data8:
entry.text = tfm::format(".byt:%04X",data.size);
break;
case Data16:
entry.text = tfm::format(".wrd:%04X",data.size);
break;
case Data32:
entry.text = tfm::format(".dbl:%04X",data.size);
break;
case Data64:
entry.text = tfm::format(".dbl:%04X",data.size);
break;
case DataAscii:
entry.text = tfm::format(".asc:%04X",data.size);
break;
}
entries.push_back(entry);
}
}
std::sort(entries.begin(),entries.end());
TextFile file;
if (!file.open(nocashSymFileName,TextFile::Write,TextFile::ASCII))
{
Logger::printError(Logger::Error, "Could not open sym file %s.",file.getFileName().u8string());
return;
}
file.writeLine("00000000 0");
for (size_t i = 0; i < entries.size(); i++)
{
file.writeFormat("%08X %s\n",entries[i].address,entries[i].text);
}
file.write("\x1A");
file.close();
}
void SymbolData::write()
{
writeNocashSym();
}
void SymbolData::addLabel(int64_t memoryAddress, const std::string& name)
{
if (!enabled)
return;
SymDataSymbol sym;
sym.address = memoryAddress;
sym.name = name;
for (SymDataSymbol& symbol: modules[currentModule].symbols)
{
if (symbol.address == sym.address && symbol.name == sym.name)
return;
}
modules[currentModule].symbols.push_back(sym);
}
void SymbolData::addData(int64_t address, size_t size, DataType type)
{
if (!enabled)
return;
SymDataData data;
data.address = address;
data.size = size;
data.type = type;
modules[currentModule].data.insert(data);
}
size_t SymbolData::addFileName(const std::string& fileName)
{
for (size_t i = 0; i < files.size(); i++)
{
if (files[i] == fileName)
return i;
}
files.push_back(fileName);
return files.size()-1;
}
void SymbolData::startModule(AssemblerFile* file)
{
for (size_t i = 0; i < modules.size(); i++)
{
if (modules[i].file == file)
{
currentModule = (int)i;
return;
}
}
SymDataModule module;
module.file = file;
modules.push_back(module);
currentModule = (int)modules.size()-1;
}
void SymbolData::endModule(AssemblerFile* file)
{
if (modules[currentModule].file != file)
return;
if (currentModule == 0)
{
Logger::printError(Logger::Error, "No module opened");
return;
}
if (currentFunction != -1)
{
Logger::printError(Logger::Error, "Module closed before function end");
currentFunction = -1;
}
currentModule = 0;
}
void SymbolData::startFunction(int64_t address)
{
if (currentFunction != -1)
{
endFunction(address);
}
currentFunction = (int)modules[currentModule].functions.size();
SymDataFunction func;
func.address = address;
func.size = 0;
modules[currentModule].functions.push_back(func);
}
void SymbolData::endFunction(int64_t address)
{
if (currentFunction == -1)
{
Logger::printError(Logger::Error, "Not inside a function");
return;
}
SymDataFunction& func = modules[currentModule].functions[currentFunction];
func.size = (size_t) (address-func.address);
currentFunction = -1;
}
| 19.470339 | 97 | 0.665724 | [
"vector",
"transform"
] |
ce051589baf2e19196124d588e888d60a526e5e4 | 27,244 | cc | C++ | src/search/thts.cc | thomaskeller79/exhaustive-mdp | bf52164f96abd13c88870677b8b215f5f79e195a | [
"MIT"
] | 26 | 2019-10-18T16:04:34.000Z | 2022-02-22T13:38:31.000Z | src/search/thts.cc | thomaskeller79/exhaustive-mdp | bf52164f96abd13c88870677b8b215f5f79e195a | [
"MIT"
] | 69 | 2019-10-18T10:19:13.000Z | 2021-07-19T06:51:51.000Z | src/search/thts.cc | thomaskeller79/exhaustive-mdp | bf52164f96abd13c88870677b8b215f5f79e195a | [
"MIT"
] | 14 | 2019-12-26T06:17:03.000Z | 2022-01-30T09:18:16.000Z | #include "thts.h"
#include "action_selection.h"
#include "backup_function.h"
#include "initializer.h"
#include "outcome_selection.h"
#include "recommendation_function.h"
#include "utils/logger.h"
#include "utils/system_utils.h"
#include <sstream>
std::string SearchNode::toString() const {
std::stringstream ss;
if (solved) {
ss << "SOLVED with: ";
}
ss << getExpectedRewardEstimate() << " (in "
<< numberOfVisits << " real visits)";
return ss.str();
}
THTS::THTS(std::string _name)
: ProbabilisticSearchEngine(_name),
actionSelection(nullptr),
outcomeSelection(nullptr),
backupFunction(nullptr),
initializer(nullptr),
recommendationFunction(nullptr),
currentRootNode(nullptr),
chosenOutcome(nullptr),
tipNodeOfTrial(nullptr),
states(SearchEngine::horizon + 1),
stepsToGoInCurrentState(SearchEngine::horizon),
stepsToGoInNextState(SearchEngine::horizon - 1),
appliedActionIndex(-1),
trialReward(0.0),
currentTrial(0),
initializedDecisionNodes(0),
lastUsedNodePoolIndex(0),
terminationMethod(THTS::TIME),
maxNumberOfTrials(0),
numberOfNewDecisionNodesPerTrial(1),
cacheHits(0),
uniquePolicyDueToLastAction(false),
uniquePolicyDueToRewardLock(false),
uniquePolicyDueToPreconds(false),
stepsToGoInFirstSolvedState(-1),
expectedRewardInFirstSolvedState(-std::numeric_limits<double>::max()),
numTrialsInFirstRelevantState(-1),
numSearchNodesInFirstRelevantState(-1),
numRewardLockStates(0),
numSingleApplicableActionStates(0) {
setMaxNumberOfNodes(24000000);
setTimeout(1.0);
setRecommendationFunction(new ExpectedBestArmRecommendation(this));
}
bool THTS::setValueFromString(std::string& param, std::string& value) {
// Check if this parameter encodes an ingredient
if (param == "-act") {
setActionSelection(ActionSelection::fromString(value, this));
return true;
} else if (param == "-out") {
setOutcomeSelection(OutcomeSelection::fromString(value, this));
return true;
} else if (param == "-backup") {
setBackupFunction(BackupFunction::fromString(value, this));
return true;
} else if (param == "-init") {
setInitializer(Initializer::fromString(value, this));
return true;
} else if (param == "-rec") {
setRecommendationFunction(
RecommendationFunction::fromString(value, this));
return true;
}
if (param == "-T") {
if (value == "TIME") {
setTerminationMethod(THTS::TIME);
return true;
} else if (value == "TRIALS") {
setTerminationMethod(THTS::NUMBER_OF_TRIALS);
return true;
} else if (value == "TIME_AND_TRIALS") {
setTerminationMethod(THTS::TIME_AND_NUMBER_OF_TRIALS);
return true;
} else {
return false;
}
} else if (param == "-r") {
setMaxNumberOfTrials(atoi(value.c_str()));
return true;
} else if (param == "-ndn") {
if (value == "H") {
setNumberOfNewDecisionNodesPerTrial(SearchEngine::horizon);
} else {
setNumberOfNewDecisionNodesPerTrial(atoi(value.c_str()));
}
return true;
} else if (param == "-node-limit") {
setMaxNumberOfNodes(atoi(value.c_str()));
return true;
}
return SearchEngine::setValueFromString(param, value);
}
void THTS::setActionSelection(ActionSelection* _actionSelection) {
if (actionSelection) {
delete actionSelection;
}
actionSelection = _actionSelection;
}
void THTS::setOutcomeSelection(OutcomeSelection* _outcomeSelection) {
if (outcomeSelection) {
delete outcomeSelection;
}
outcomeSelection = _outcomeSelection;
}
void THTS::setBackupFunction(BackupFunction* _backupFunction) {
if (backupFunction) {
delete backupFunction;
}
backupFunction = _backupFunction;
}
void THTS::setInitializer(Initializer* _initializer) {
if (initializer) {
delete initializer;
}
initializer = _initializer;
}
void THTS::setRecommendationFunction(
RecommendationFunction* _recommendationFunction) {
if (recommendationFunction) {
delete recommendationFunction;
}
recommendationFunction = _recommendationFunction;
}
void THTS::disableCaching() {
actionSelection->disableCaching();
outcomeSelection->disableCaching();
backupFunction->disableCaching();
initializer->disableCaching();
recommendationFunction->disableCaching();
SearchEngine::disableCaching();
}
void THTS::initSession() {
// All ingredients must have been specified
if (!actionSelection || !outcomeSelection || !backupFunction ||
!initializer || !recommendationFunction) {
SystemUtils::abort(
"Action selection, outcome selection, backup "
"function, initializer, and recommendation function "
"must be defined in a THTS search engine!");
}
actionSelection->initSession();
outcomeSelection->initSession();
backupFunction->initSession();
initializer->initSession();
recommendationFunction->initSession();
}
void THTS::initRound() {
// Reset per round statistics
stepsToGoInFirstSolvedState = -1;
expectedRewardInFirstSolvedState = -std::numeric_limits<double>::max();
numTrialsInFirstRelevantState = -1;
numSearchNodesInFirstRelevantState = -1;
numRewardLockStates = 0;
numSingleApplicableActionStates = 0;
// Notify ingredients of new round
actionSelection->initRound();
outcomeSelection->initRound();
backupFunction->initRound();
initializer->initRound();
}
void THTS::finishRound() {
// Notify ingredients of end of round
actionSelection->finishRound();
outcomeSelection->finishRound();
backupFunction->finishRound();
initializer->finishRound();
}
void THTS::initStep(State const& current) {
PDState rootState(current);
// Adjust maximal search depth and set root state
if (rootState.stepsToGo() > maxSearchDepth) {
maxSearchDepthForThisStep = maxSearchDepth;
states[maxSearchDepthForThisStep].setTo(rootState);
states[maxSearchDepthForThisStep].stepsToGo() =
maxSearchDepthForThisStep;
} else {
maxSearchDepthForThisStep = rootState.stepsToGo();
states[maxSearchDepthForThisStep].setTo(rootState);
}
assert(states[maxSearchDepthForThisStep].stepsToGo() ==
maxSearchDepthForThisStep);
stepsToGoInCurrentState = maxSearchDepthForThisStep;
stepsToGoInNextState = maxSearchDepthForThisStep - 1;
states[stepsToGoInNextState].reset(stepsToGoInNextState);
currentTrial = 0;
// Reset per step statistics
cacheHits = 0;
lastSearchTime = 0.0;
uniquePolicyDueToLastAction = false;
uniquePolicyDueToRewardLock = false;
uniquePolicyDueToPreconds = false;
// Create root node
currentRootNode = createRootNode();
// Notify ingredients of new step
actionSelection->initStep(current);
outcomeSelection->initStep();
backupFunction->initStep();
initializer->initStep(current);
}
void THTS::finishStep() {
if (uniquePolicyDueToRewardLock) {
++numRewardLockStates;
} else if (uniquePolicyDueToPreconds) {
++numSingleApplicableActionStates;
}
actionSelection->finishStep();
outcomeSelection->finishStep();
backupFunction->finishStep();
initializer->finishStep();
}
inline void THTS::initTrial() {
// Reset states and steps-to-go counter
stepsToGoInCurrentState = maxSearchDepthForThisStep;
stepsToGoInNextState = maxSearchDepthForThisStep - 1;
states[stepsToGoInNextState].reset(stepsToGoInNextState);
// Reset trial dependent variables
initializedDecisionNodes = 0;
trialReward = 0.0;
tipNodeOfTrial = nullptr;
// Notify ingredients of new trial
actionSelection->initTrial();
outcomeSelection->initTrial();
backupFunction->initTrial();
initializer->initTrial();
}
inline void THTS::initTrialStep() {
--stepsToGoInCurrentState;
--stepsToGoInNextState;
states[stepsToGoInNextState].reset(stepsToGoInNextState);
}
void THTS::estimateBestActions(State const& _rootState,
std::vector<int>& bestActions) {
assert(bestActions.empty());
stopwatch.reset();
int stepsToGo = _rootState.stepsToGo();
// Check if there is an obviously optimal policy (as, e.g., in the last step
// or in a reward lock)
int uniquePolicyOpIndex = getUniquePolicy();
if (uniquePolicyOpIndex != -1) {
bestActions.push_back(uniquePolicyOpIndex);
currentRootNode = nullptr;
// Update statistics
if ((stepsToGoInFirstSolvedState == -1) &&
(uniquePolicyDueToLastAction || uniquePolicyDueToRewardLock)) {
stepsToGoInFirstSolvedState = stepsToGo;
// expectedRewardInFirstSolvedState = TODO!
}
return;
}
// Perform trials until some termination criterion is fullfilled
while (moreTrials()) {
// Logger::logSeparator(Verbosity::DEBUG);
// Logger::logLine("TRIAL " + std::to_string(currentTrial+1),
// Verbosity::DEBUG);
visitDecisionNode(currentRootNode);
++currentTrial;
// for(unsigned int i = 0; i < currentRootNode->children.size(); ++i) {
// if (currentRootNode->children[i]) {
// Logger::logLine(SearchEngine::actionStates[i].toCompactString() +
// ": " + currentRootNode->children[i]->toString(),
// Verbosity::DEBUG);
// }
// }
// assert(currentTrial != 100);
}
recommendationFunction->recommend(currentRootNode, bestActions);
assert(!bestActions.empty());
// Update statistics
if (currentRootNode->solved && (stepsToGoInFirstSolvedState == -1)) {
// TODO: This is the first root state that was solved, so everything
// that could happen in the future is also solved. We should (at least
// in this case) make sure that we keep the tree and simply follow the
// optimal policy.
stepsToGoInFirstSolvedState = stepsToGo;
expectedRewardInFirstSolvedState =
currentRootNode->getExpectedRewardEstimate();
}
if (numTrialsInFirstRelevantState < 0 && currentTrial > 0) {
numTrialsInFirstRelevantState = currentTrial;
}
if (numSearchNodesInFirstRelevantState < 0 && lastUsedNodePoolIndex > 0) {
numSearchNodesInFirstRelevantState = lastUsedNodePoolIndex;
}
// Memorize search time
lastSearchTime = stopwatch();
}
bool THTS::moreTrials() {
// Check memory constraints and solvedness
if (currentRootNode->solved ||
(lastUsedNodePoolIndex >= maxNumberOfNodes)) {
return false;
}
if (currentTrial == 0) {
return true;
}
// Check selected termination criterion
switch (terminationMethod) {
case THTS::TIME:
if (MathUtils::doubleIsGreater(stopwatch(), timeout)) {
return false;
}
break;
case THTS::NUMBER_OF_TRIALS:
if (currentTrial == maxNumberOfTrials) {
return false;
}
break;
case THTS::TIME_AND_NUMBER_OF_TRIALS:
if (MathUtils::doubleIsGreater(stopwatch(), timeout) ||
(currentTrial == maxNumberOfTrials)) {
return false;
}
break;
}
return true;
}
void THTS::visitDecisionNode(SearchNode* node) {
if (node == currentRootNode) {
initTrial();
} else {
// Continue trial (i.e., set next state to be the current)
initTrialStep();
// Check if there is a "special" reason to stop this trial (currently,
// this is the case if the state value of the current state is cached,
// if it is a reward lock or if there is only one step left).
if (currentStateIsSolved(node)) {
if (!tipNodeOfTrial) {
tipNodeOfTrial = node;
}
return;
}
}
// Initialize node if necessary
if (!node->initialized) {
if (!tipNodeOfTrial) {
tipNodeOfTrial = node;
}
initializer->initialize(node, states[stepsToGoInCurrentState]);
if (node != currentRootNode) {
++initializedDecisionNodes;
}
}
// Logger::logLine("Current state is:", Verbosity::DEBUG);
// Logger::logLine(states[stepsToGoInCurrentState].toString(),
// Verbosity::DEBUG);
// Logger::logLine("Reward is " + std::to_string(node->immediateReward),
// Verbosity::DEBUG);
// Determine if we continue with this trial
if (continueTrial(node)) {
// Select the action that is simulated
appliedActionIndex = actionSelection->selectAction(node);
assert(node->children[appliedActionIndex]);
assert(!node->children[appliedActionIndex]->solved);
// Logger::logLine("Chosen action is: " +
// SearchEngine::actionStates[appliedActionIndex].toCompactString(),
// Verbosity::DEBUG);
// Sample successor state
calcSuccessorState(states[stepsToGoInCurrentState], appliedActionIndex,
states[stepsToGoInNextState]);
// Logger::logLine("Sampled PDState is " +
// states[stepsToGoInNextState].toCompactString(),
// Verbosity::DEBUG);
lastProbabilisticVarIndex = -1;
for (unsigned int i = 0; i < State::numberOfProbabilisticStateFluents;
++i) {
if (states[stepsToGoInNextState]
.probabilisticStateFluentAsPD(i)
.isDeterministic()) {
states[stepsToGoInNextState].probabilisticStateFluent(i) =
states[stepsToGoInNextState]
.probabilisticStateFluentAsPD(i)
.values[0];
} else {
lastProbabilisticVarIndex = i;
}
}
// Start outcome selection with the first probabilistic variable
chanceNodeVarIndex = 0;
// Continue trial with chance nodes
if (lastProbabilisticVarIndex < 0) {
visitDummyChanceNode(node->children[appliedActionIndex]);
} else {
visitChanceNode(node->children[appliedActionIndex]);
}
// Backup this node
backupFunction->backupDecisionNode(node);
trialReward += node->immediateReward;
// If the backup function labeled the node as solved, we store the
// result for the associated state in case we encounter it somewhere
// else in the tree in the future
if (node->solved) {
if (cachingEnabled &&
ProbabilisticSearchEngine::stateValueCache.find(
states[node->stepsToGo]) ==
ProbabilisticSearchEngine::stateValueCache.end()) {
ProbabilisticSearchEngine::stateValueCache
[states[node->stepsToGo]] =
node->getExpectedFutureRewardEstimate();
}
}
} else {
// The trial is finished
trialReward = node->getExpectedRewardEstimate();
}
}
bool THTS::currentStateIsSolved(SearchNode* node) {
if (stepsToGoInCurrentState == 1) {
// This node is a leaf (there is still a last decision, though, but that
// is taken care of by calcOptimalFinalReward)
calcOptimalFinalReward(states[1], trialReward);
backupFunction->backupDecisionNodeLeaf(node, trialReward);
trialReward += node->immediateReward;
return true;
} else if (ProbabilisticSearchEngine::stateValueCache.find(
states[stepsToGoInCurrentState]) !=
ProbabilisticSearchEngine::stateValueCache.end()) {
// This state has already been solved before
trialReward = ProbabilisticSearchEngine::stateValueCache
[states[stepsToGoInCurrentState]];
backupFunction->backupDecisionNodeLeaf(node, trialReward);
trialReward += node->immediateReward;
++cacheHits;
return true;
} else if (node->children.empty() &&
isARewardLock(states[stepsToGoInCurrentState])) {
// This state is a reward lock, i.e. a goal or a state that is such that
// no matter which action is applied we'll always get the same reward
calcReward(states[stepsToGoInCurrentState], 0, trialReward);
trialReward *= stepsToGoInCurrentState;
backupFunction->backupDecisionNodeLeaf(node, trialReward);
trialReward += node->immediateReward;
if (cachingEnabled) {
assert(ProbabilisticSearchEngine::stateValueCache.find(
states[stepsToGoInCurrentState]) ==
ProbabilisticSearchEngine::stateValueCache.end());
ProbabilisticSearchEngine::stateValueCache
[states[stepsToGoInCurrentState]] =
node->getExpectedFutureRewardEstimate();
}
return true;
}
return false;
}
void THTS::visitChanceNode(SearchNode* node) {
while (states[stepsToGoInNextState]
.probabilisticStateFluentAsPD(chanceNodeVarIndex)
.isDeterministic()) {
++chanceNodeVarIndex;
}
chosenOutcome = outcomeSelection->selectOutcome(
node, states[stepsToGoInNextState], chanceNodeVarIndex,
lastProbabilisticVarIndex);
if (chanceNodeVarIndex == lastProbabilisticVarIndex) {
State::calcStateFluentHashKeys(states[stepsToGoInNextState]);
State::calcStateHashKey(states[stepsToGoInNextState]);
visitDecisionNode(chosenOutcome);
} else {
++chanceNodeVarIndex;
visitChanceNode(chosenOutcome);
}
backupFunction->backupChanceNode(node, trialReward);
}
void THTS::visitDummyChanceNode(SearchNode* node) {
State::calcStateFluentHashKeys(states[stepsToGoInNextState]);
State::calcStateHashKey(states[stepsToGoInNextState]);
if (node->children.empty()) {
node->children.resize(1, nullptr);
node->children[0] = createDecisionNode(1.0);
}
assert(node->children.size() == 1);
visitDecisionNode(node->children[0]);
backupFunction->backupChanceNode(node, trialReward);
}
int THTS::getUniquePolicy() {
if (stepsToGoInCurrentState == 1) {
uniquePolicyDueToLastAction = true;
return getOptimalFinalActionIndex(states[1]);
}
std::vector<int> applicableActionIndices =
getIndicesOfApplicableActions(states[stepsToGoInCurrentState]);
if (isARewardLock(states[stepsToGoInCurrentState])) {
uniquePolicyDueToRewardLock = true;
return applicableActionIndices[0];
}
if (applicableActionIndices.size() == 1) {
uniquePolicyDueToPreconds = true;
return applicableActionIndices[0];
}
// There is no clear, unique policy
return -1;
}
SearchNode* THTS::createRootNode() {
for (SearchNode* node : nodePool) {
if (node) {
if (!node->children.empty()) {
std::vector<SearchNode*> tmp;
node->children.swap(tmp);
}
} else {
break;
}
}
SearchNode* res = nodePool[0];
if (res) {
res->reset(1.0, stepsToGoInCurrentState);
} else {
res = new SearchNode(1.0, stepsToGoInCurrentState);
nodePool[0] = res;
}
res->immediateReward = 0.0;
lastUsedNodePoolIndex = 1;
return res;
}
SearchNode* THTS::createDecisionNode(double const& prob) {
assert(lastUsedNodePoolIndex < nodePool.size());
SearchNode* res = nodePool[lastUsedNodePoolIndex];
if (res) {
res->reset(prob, stepsToGoInNextState);
} else {
res = new SearchNode(prob, stepsToGoInNextState);
nodePool[lastUsedNodePoolIndex] = res;
}
calcReward(states[stepsToGoInCurrentState], appliedActionIndex,
res->immediateReward);
++lastUsedNodePoolIndex;
return res;
}
SearchNode* THTS::createChanceNode(double const& prob) {
assert(lastUsedNodePoolIndex < nodePool.size());
SearchNode* res = nodePool[lastUsedNodePoolIndex];
if (res) {
res->reset(prob, stepsToGoInCurrentState);
} else {
res = new SearchNode(prob, stepsToGoInCurrentState);
nodePool[lastUsedNodePoolIndex] = res;
}
++lastUsedNodePoolIndex;
return res;
}
void THTS::setMaxSearchDepth(int _maxSearchDepth) {
SearchEngine::setMaxSearchDepth(_maxSearchDepth);
assert(initializer);
initializer->setMaxSearchDepth(_maxSearchDepth);
}
void THTS::printConfig(std::string indent) const {
SearchEngine::printConfig(indent);
indent += " ";
switch(terminationMethod) {
case TerminationMethod::TIME:
Logger::logLine(indent + "Termination method: TIME",
Verbosity::VERBOSE);
Logger::logLine(indent + "Timeout: " + std::to_string(timeout),
Verbosity::VERBOSE);
break;
case TerminationMethod::NUMBER_OF_TRIALS:
Logger::logLine(indent + "Termination method: NUM TRIALS",
Verbosity::VERBOSE);
Logger::logLine(
indent + "Max num trials: " + std::to_string(maxNumberOfTrials),
Verbosity::VERBOSE);
break;
case TerminationMethod::TIME_AND_NUMBER_OF_TRIALS:
Logger::logLine(
indent + "Termination method: TIME AND NUM TRIALS",
Verbosity::VERBOSE);
Logger::logLine(
indent + "Timeout: " + std::to_string(timeout),
Verbosity::VERBOSE);
Logger::logLine(
indent + "Max num trials: " + std::to_string(maxNumberOfTrials),
Verbosity::VERBOSE);
break;
}
Logger::logLine(
indent + "Max num search nodes: " + std::to_string(maxNumberOfNodes),
Verbosity::VERBOSE);
Logger::logLine(
indent + "Node pool size: " + std::to_string(nodePool.size()),
Verbosity::VERBOSE);
actionSelection->printConfig(indent);
outcomeSelection->printConfig(indent);
Logger::logLine(indent + "Trial length: CountDecisionNodes", Verbosity::VERBOSE);
Logger::logLine(indent + " Decision node count: " +
std::to_string(numberOfNewDecisionNodesPerTrial),
Verbosity::VERBOSE);
initializer->printConfig(indent);
backupFunction->printConfig(indent);
recommendationFunction->printConfig(indent);
}
void THTS::printStepStatistics(std::string indent) const {
if (uniquePolicyDueToLastAction) {
Logger::logLine(
indent + "Policy unique due to optimal last action",
Verbosity::NORMAL);
} else if (uniquePolicyDueToRewardLock) {
Logger::logLine(
indent + "Policy unique due to reward lock", Verbosity::NORMAL);
Logger::logLine(
indent + states[stepsToGoInCurrentState].toString(),
Verbosity::VERBOSE);
} else if (uniquePolicyDueToPreconds) {
Logger::logLine(
indent + "Policy unique due to single reasonable action",
Verbosity::NORMAL);
} else {
Logger::logLine(
indent + name + " step statistics:", Verbosity::NORMAL);
indent += " ";
printStateValueCacheUsage(indent);
printApplicableActionCacheUsage(indent);
Logger::logLine(
indent + "Performed trials: " + std::to_string(currentTrial),
Verbosity::NORMAL);
Logger::logLine(
indent + "Created search nodes: " +
std::to_string(lastUsedNodePoolIndex),
Verbosity::NORMAL);
Logger::logLine(
indent + "Search time: " + std::to_string(lastSearchTime),
Verbosity::NORMAL);
Logger::logLine(
indent + "Cache hits: " + std::to_string(cacheHits),
Verbosity::VERBOSE);
Logger::logLine(
indent + "Max search depth: " + std::to_string(maxSearchDepth),
Verbosity::VERBOSE);
if (currentRootNode) {
Logger::logLine(indent + "Q-value estimates:", Verbosity::VERBOSE);
Logger::logLine(
indent + " Root node: " + getCurrentRootNode()->toString(),
Verbosity::VERBOSE);
for (size_t i = 0; i < currentRootNode->children.size(); ++i) {
SearchNode const *child = currentRootNode->children[i];
if (child) {
ActionState const &action = SearchEngine::actionStates[i];
Logger::logLine(
indent + " " + action.toCompactString() + ": " +
child->toString(), Verbosity::VERBOSE);
}
}
}
Logger::logLine("", Verbosity::VERBOSE);
actionSelection->printStepStatistics(indent);
outcomeSelection->printStepStatistics(indent);
initializer->printStepStatistics(indent);
backupFunction->printStepStatistics(indent);
}
}
void THTS::printRoundStatistics(std::string indent) const {
Logger::logLine(indent + name + " round statistics:", Verbosity::NORMAL);
indent += " ";
if (Logger::runVerbosity < Verbosity::VERBOSE) {
printStateValueCacheUsage(indent, Verbosity::SILENT);
printApplicableActionCacheUsage(indent, Verbosity::SILENT);
}
Logger::logLine(
indent + "Number of remaining steps in first solved state: " +
std::to_string(stepsToGoInFirstSolvedState),
Verbosity::SILENT);
if (!MathUtils::doubleIsMinusInfinity(expectedRewardInFirstSolvedState)) {
Logger::logLine(
indent + "Expected reward in first solved state: " +
std::to_string(expectedRewardInFirstSolvedState),
Verbosity::SILENT);
}
Logger::logLine(
indent + "Number of trials in first relevant state: " +
std::to_string(numTrialsInFirstRelevantState),
Verbosity::SILENT);
Logger::logLine(
indent + "Number of search nodes in first relevant state: " +
std::to_string(numSearchNodesInFirstRelevantState),
Verbosity::SILENT);
Logger::logLine(
indent + "Number of reward lock states: " +
std::to_string(numRewardLockStates),
Verbosity::NORMAL);
Logger::logLine(
indent + "Number of states with only one applicable action: " +
std::to_string(numSingleApplicableActionStates),
Verbosity::NORMAL);
Logger::logLine("", Verbosity::VERBOSE);
actionSelection->printRoundStatistics(indent);
outcomeSelection->printRoundStatistics(indent);
initializer->printRoundStatistics(indent);
backupFunction->printRoundStatistics(indent);
}
| 33.717822 | 92 | 0.632653 | [
"vector"
] |
ce05d706ac3f26815f59bd1523883ed4fbc751a0 | 5,686 | cpp | C++ | test/tests/TestTokenisers.cpp | hjabird/Quad1D | 4f0291bc729ac689df64d0366e8947b12af28684 | [
"MIT"
] | null | null | null | test/tests/TestTokenisers.cpp | hjabird/Quad1D | 4f0291bc729ac689df64d0366e8947b12af28684 | [
"MIT"
] | null | null | null | test/tests/TestTokenisers.cpp | hjabird/Quad1D | 4f0291bc729ac689df64d0366e8947b12af28684 | [
"MIT"
] | null | null | null | #include <HBTK/Token.h>
#include <HBTK/BasicTokeniser.h>
#include <catch2/catch.hpp>
/*////////////////////////////////////////////////////////////////////////////
TestTokeniser.cpp
Test Tokeniser and Tokens.
Copyright 2018 HJA Bird
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 <sstream>
#include <vector>
TEST_CASE("Tokeniser & Tokens") {
SECTION("All whitespace & token count") {
std::string str(" \t\n");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens.size() == 3);
for (auto & i : tokens) {
REQUIRE(i.iswhitespace());
}
REQUIRE(tokens[0].value() == " ");
REQUIRE(tokens[1].value() == "\t");
REQUIRE(tokens[2].value() == "\n");
}
SECTION("Identify a number") {
std::string str("1.35");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens.size() == 3);
REQUIRE(tokens[0].isnum());
REQUIRE(tokens[0].value() == "1");
REQUIRE(tokens[2].isnum());
REQUIRE(tokens[2].value() == "35");
}
SECTION("Identify a word") {
std::string str("foo");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens.size() == 1);
REQUIRE(tokens[0].value() == "foo");
}
SECTION("Identify brackets") {
std::string str("{}()[]!.");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens[0].isbracket());
REQUIRE(tokens[1].isbracket());
REQUIRE(tokens[2].isbracket());
REQUIRE(tokens[3].isbracket());
REQUIRE(tokens[4].isbracket());
REQUIRE(tokens[5].isbracket());
REQUIRE(!tokens[6].isbracket());
REQUIRE(!tokens[7].isbracket());
REQUIRE(tokens[0].isopenbracket());
REQUIRE(!tokens[1].isopenbracket());
REQUIRE(tokens[2].isopenbracket());
REQUIRE(!tokens[3].isopenbracket());
REQUIRE(tokens[4].isopenbracket());
REQUIRE(!tokens[5].isopenbracket());
REQUIRE(!tokens[6].isopenbracket());
REQUIRE(!tokens[7].isopenbracket());
REQUIRE(!tokens[0].isclosebracket());
REQUIRE(tokens[1].isclosebracket());
REQUIRE(!tokens[2].isclosebracket());
REQUIRE(tokens[3].isclosebracket());
REQUIRE(!tokens[4].isclosebracket());
REQUIRE(tokens[5].isclosebracket());
REQUIRE(!tokens[6].isclosebracket());
REQUIRE(!tokens[7].isclosebracket());
}
SECTION("Identify variables mixed with punctuation") {
std::string str("foo+bar=foobar");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens.size() == 5);
REQUIRE(tokens[0].isword());
REQUIRE(tokens[0].value() == "foo");
REQUIRE(tokens[2].isword());
REQUIRE(tokens[2].value() == "bar");
REQUIRE(tokens[4].isword());
REQUIRE(tokens[4].value() == "foobar");
REQUIRE(tokens[1].ispunct());
REQUIRE(tokens[1].value() == "+");
REQUIRE(tokens[3].ispunct());
REQUIRE(tokens[3].value() == "=");
}
SECTION("Correct line numbering") {
std::string str("a\nb\nc\n");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens[0].line() == 1);
REQUIRE(tokens[2].line() == 2);
REQUIRE(tokens[4].line() == 3);
}
SECTION("char numbering without newline") {
std::string str("foo+bar=foobar");
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens.size() == 5);
REQUIRE(tokens[0].char_idx() == 1);
REQUIRE(tokens[2].char_idx() == 5);
REQUIRE(tokens[4].char_idx() == 9);
REQUIRE(tokens[1].char_idx() == 4);
REQUIRE(tokens[3].char_idx() == 8);
}
SECTION("char numbering with newline - no strings") {
std::string str(
"She is the fairies midwife, and she comes\n"
"In shape no bigger than an agate stone\n"
"On the forefinger of an alderman,\n"
"Drawn with a team of little atomi\n"
"Over mens noses as they lie asleep.\n"
);
std::vector<HBTK::Token> tokens;
HBTK::BasicTokeniser tokeniser(str);
while (!tokeniser.eof()) {
tokens.push_back(tokeniser.next());
}
REQUIRE(tokens[0].value() == "She");
REQUIRE(tokens[0].line() == 1);
REQUIRE(tokens[0].char_idx() == 1);
REQUIRE(tokens[37].value() == "forefinger");
REQUIRE(tokens[37].line() == 3);
REQUIRE(tokens[37].char_idx() == 8);
}
}
| 31.765363 | 78 | 0.658284 | [
"shape",
"vector"
] |
ce069a78186b8576a5150dcf90fc0b1245a1fe36 | 2,379 | cc | C++ | src/relay/op/vision/multibox_op.cc | headupinclouds/tvm | 5c410c4c31aff07b063d3c95123261af003ab33d | [
"Apache-2.0"
] | 4 | 2018-09-11T05:50:03.000Z | 2022-01-23T03:43:22.000Z | src/relay/op/vision/multibox_op.cc | jaisimhamanipatruni/tvm | af1fcf974326444d12d0b055f9955a03fd5ebbb7 | [
"Apache-2.0"
] | 3 | 2018-09-14T05:27:13.000Z | 2021-01-06T17:27:58.000Z | src/relay/op/vision/multibox_op.cc | jaisimhamanipatruni/tvm | af1fcf974326444d12d0b055f9955a03fd5ebbb7 | [
"Apache-2.0"
] | 4 | 2018-09-10T23:43:51.000Z | 2019-06-14T16:27:23.000Z | /*!
* Copyright (c) 2018 by Contributors
* \file multibox_op.cc
* \brief Multibox related operators
*/
#include <tvm/relay/op.h>
#include <tvm/relay/attrs/vision.h>
#include <vector>
namespace tvm {
namespace relay {
TVM_REGISTER_NODE_TYPE(MultiBoxPriorAttrs);
bool MultiboxPriorRel(const Array<Type>& types,
int num_inputs,
const Attrs& attrs,
const TypeReporter& reporter) {
CHECK_EQ(types.size(), 2);
const auto* data = types[0].as<TensorTypeNode>();
const MultiBoxPriorAttrs* param = attrs.as<MultiBoxPriorAttrs>();
const auto& dshape = data->shape;
CHECK_EQ(dshape.size(), 4) << "Input data should be 4D: "
"[batch, channel, height, width]";
IndexExpr in_height = dshape[2];
IndexExpr in_width = dshape[3];
int num_sizes = static_cast<int>(param->sizes.size());
int num_ratios = static_cast<int>(param->ratios.size());
// since input sizes are same in each batch, we could share MultiBoxPrior
std::vector<IndexExpr> oshape(
{1, in_height * in_width * (num_sizes + num_ratios - 1), 4});
// assign output type
reporter->Assign(types[1], TensorTypeNode::make(oshape, data->dtype));
return true;
}
Expr MakeMultiBoxPrior(Expr data,
Array<IndexExpr> sizes,
Array<IndexExpr> ratios,
Array<IndexExpr> steps,
Array<IndexExpr> offsets,
bool clip) {
auto attrs = make_node<MultiBoxPriorAttrs>();
attrs->sizes = std::move(sizes);
attrs->ratios = std::move(ratios);
attrs->steps = std::move(steps);
attrs->offsets = std::move(offsets);
attrs->clip = clip;
static const Op& op = Op::Get("vision.multibox_prior");
return CallNode::make(op, {data}, Attrs(attrs), {});
}
TVM_REGISTER_API("relay.op.vision._make.multibox_prior")
.set_body([](const TVMArgs& args, TVMRetValue* rv) {
runtime::detail::unpack_call<Expr, 6>(MakeMultiBoxPrior, args, rv);
});
RELAY_REGISTER_OP("vision.multibox_prior")
.describe(R"doc("Generate prior(anchor) boxes from data, sizes and ratios."
)doc" TVM_ADD_FILELINE)
.set_attrs_type_key("relay.attrs.MultiBoxPriorAttrs")
.set_num_inputs(1)
.add_argument("data", "Tensor", "The input tensor.")
.set_support_level(4)
.add_type_rel("MultiBoxPrior", MultiboxPriorRel);
} // namespace relay
} // namespace tvm
| 32.148649 | 75 | 0.663304 | [
"shape",
"vector"
] |
ce097c4598df7700f141c943c4eb82d07a1fcb2b | 687 | cpp | C++ | prime_number/arc116_a.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | prime_number/arc116_a.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | prime_number/arc116_a.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
using Graph = vector<vector<int>>;
// 素因数分解したときの偶数(2)に注目
// 素数は2以外は全て奇数
// 2が0個 (n % 4 == 1 || n % 4 == 3) なら奇数が多い
// 2が1個 (n % 4 == 2) なら偶数と奇数が同じ数
// 2が2個以上 (n % 4 == 0) なら偶数が多い
/*
参考リンク
ARC 116 A - Odd vs Even
https://atcoder.jp/contests/arc116/tasks/arc116_a
*/
int main() {
int T;
cin >> T;
rep(ti, T) {
ll n;
cin >> n;
if (n % 4 == 1 || n % 4 == 3) {
cout << "Odd" << endl;
} else if (n % 4 == 2) {
cout << "Same" << endl;
} else {
cout << "Even" << endl;
}
}
return 0;
} | 19.628571 | 55 | 0.497817 | [
"vector"
] |
ce09b4d85a2fce7de6dff263467e207c78f40c77 | 1,861 | hpp | C++ | pwiz/data/vendor_readers/Waters/Reader_Waters_Detail.hpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/data/vendor_readers/Waters/Reader_Waters_Detail.hpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/data/vendor_readers/Waters/Reader_Waters_Detail.hpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// 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 _READER_WATERS_DETAIL_HPP_
#define _READER_WATERS_DETAIL_HPP_
#include "pwiz/utility/misc/Export.hpp"
#include "pwiz/data/msdata/MSData.hpp"
#include <vector>
#ifdef PWIZ_READER_WATERS
#include "pwiz_aux/msrc/utility/vendor_api/Waters/WatersRawFile.hpp"
using namespace pwiz::vendor_api::Waters;
namespace pwiz {
namespace msdata {
namespace detail {
namespace Waters {
PWIZ_API_DECL
std::vector<InstrumentConfiguration> createInstrumentConfigurations(RawDataPtr rawdata);
PWIZ_API_DECL CVID translateAsInstrumentModel(RawDataPtr rawdata);
PWIZ_API_DECL void translateFunctionType(PwizFunctionType functionType, int& msLevel, CVID& spectrumType);
PWIZ_API_DECL CVID translateAsIonizationType(PwizIonizationType ionizationType);
PWIZ_API_DECL CVID translate(PwizPolarityType polarityType);
/*PWIZ_API_DECL CVID translate(MassAnalyzerType type);
PWIZ_API_DECL CVID translateAsInletType(IonizationType ionizationType);
PWIZ_API_DECL CVID translate(ActivationType activationType);*/
} // Waters
} // detail
} // msdata
} // pwiz
#endif
#endif // _READER_WATERS_DETAIL_HPP_
| 31.542373 | 107 | 0.76518 | [
"vector"
] |
ce0c4c021eeded7273bc3db7e7a84e09c483d8c4 | 9,421 | hpp | C++ | src/Base/ResultsHelpers/HeterogeneousContainer.hpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | 1 | 2017-10-23T13:22:01.000Z | 2017-10-23T13:22:01.000Z | src/Base/ResultsHelpers/HeterogeneousContainer.hpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | null | null | null | src/Base/ResultsHelpers/HeterogeneousContainer.hpp | PhilipVinc/PincoSimulator | 562192cf3b09d0e67be7e6fee67ff9b59fbc3fd3 | [
"MIT"
] | null | null | null | //
// Created by Filippo Vicentini on 12/03/2018.
//
#ifndef SIMULATOR_HETEROGENEOUSCONTAINER_HPP
#define SIMULATOR_HETEROGENEOUSCONTAINER_HPP
#include <array>
#include <vector>
#include <tuple>
#include <functional>
#include <iostream>
#include <typeindex>
#include <map>
#include <array>
#ifdef MPI_SUPPORT
#include "Base/Serialization/SerializationArchiveFormats.hpp"
#include <Libraries/eigen_cereal_serialization.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/tuple.hpp>
#include <cereal/types/map.hpp>
#include <cereal/types/string.hpp>
#endif
template <typename T>
struct allVars
{
static std::map<T, std::type_index> varTypes;
static std::map<T, const std::string> varNames;
static std::map<std::string, T> varEnums;
static std::map<T, const size_t> varFormats;
};
template <typename C>
struct saveFormat {
const static size_t format;
};
template <typename T, class C>
struct variable
{
const T enumVal;
const std::string _name;
variable (const T val, const std::string name) : enumVal(val), _name(name)
{
allVars<T>::varTypes.insert(std::pair<T,std::type_index>(val, typeid(C)));
allVars<T>::varNames.insert(std::pair<T,std::string>(val, name));
allVars<T>::varFormats.insert(std::pair<T,size_t>(val, saveFormat<C>::format));
allVars<T>::varEnums.insert(std::pair<std::string, T>(name, val));
};
};
template <class T1, class T2>
struct SameType
{
static const bool value = false;
};
template<class T>
struct SameType<T, T>
{
static const bool value = true;
};
typedef const void* rawT1;
typedef size_t rawT2;
typedef std::tuple<rawT1, rawT2> rawTuple;
template <class C>
rawTuple getData(const C& data);
template <class C>
C setData(rawTuple data, size_t frames, const std::vector<size_t>& dimensions);
template <class C>
bool AppendData(C &toExpand, C &&toAppend);
template <typename enumVar, typename... Types>
class HeterogeneousContainer
{
public:
typedef std::tuple<std::map<enumVar, Types>...> vtype;
vtype vectors;
template<int N, typename T>
struct VectorOfType: SameType<T,
typename std::tuple_element<N, vtype>::type::map::mapped_type>
{ };
template <int N, class T, class Tuple, bool Match = false> // this =false is only for clarity
struct MatchingField
{
inline static std::map<enumVar,T>& get(Tuple& tp)
{
// The "non-matching" version
return MatchingField<N+1, T, Tuple,
VectorOfType<N+1, T>::value>::get(tp);
}
inline static const std::map<enumVar,T>& get(const Tuple& tp)
{
// The "non-matching" version
return MatchingField<N+1, T, Tuple,
VectorOfType<N+1, T>::value>::get(tp);
}
};
template <int N, class T, class Tuple>
struct MatchingField<N, T, Tuple, true>
{
inline static std::map<enumVar, T>& get(Tuple& tp)
{
return std::get<N>(tp);
}
inline static const std::map<enumVar, T>& get(const Tuple& tp)
{
return std::get<N>(tp);
}
};
template <typename T>
std::map<enumVar,T>& access()
{
return MatchingField<0, T, vtype,
VectorOfType<0, T>::value>::get(vectors);
}
template <typename T>
void set(enumVar varName, T && el)
{
std::map<enumVar,T>& vec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
vec[varName] = el;
}
template <typename T>
void set(enumVar varName, T & el)
{
std::map<enumVar,T>& vec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
vec[varName] = el;
}
// Used to add a type of unknown type
template <typename T>
void setIfRightType(enumVar varName, rawTuple data, size_t frames, const std::vector<size_t>& dimensions) {
if (allVars<enumVar>::varTypes.at(varName) == typeid(T)) {
std::map<enumVar, T> &theMap = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
theMap[varName] = setData<T>(data, frames, dimensions);
}
}
void setUnknownType(enumVar varName, rawTuple data, size_t frames, const std::vector<size_t>& dimensions) {
int trash[] = {(setIfRightType<Types>(varName,data, frames, dimensions),0)...};
}
template <typename T>
T& get(enumVar varName)
{
return MatchingField<0, T, vtype,
VectorOfType<0, T>::value>::get(vectors)[varName];
}
template <typename T>
std::tuple<const void*, size_t> getRaw(enumVar varName)
{
return getData(this->get<T>(varName));
}
template <typename T>
std::vector<rawTuple> getAllTypeRaw() const
{
std::vector<rawTuple> res;
const std::map<enumVar, T>& vec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
// Note: this auto &el, the reference is essential: otherwise we would create a copy-ed object with a limited
// lifetime and therefore we would be passing pointers to potentially-released memory.
for (auto &el :vec) {
res.push_back(getData(el.second));
}
return res;
}
template <typename T>
std::vector<std::tuple<enumVar, rawTuple>> getAllIndexedTypeRaw() const
{
std::vector<std::tuple<enumVar, rawTuple>> res;
const std::map<enumVar, T>& vec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
// Note: this auto &el, the reference is essential: otherwise we would create a copy-ed object with a limited
// lifetime and therefore we would be passing pointers to potentially-released memory.
for (auto &el :vec) {
res.emplace_back(el.first, getData(el.second));
}
return res;
}
std::vector<rawTuple> GetAllRaw() const {
std::vector<rawTuple> result;
std::vector<std::vector<rawTuple>> tmp1= { (this->getAllTypeRaw<Types>())... };
for (auto el : tmp1) {
result.insert(result.end(), std::make_move_iterator(el.begin()), std::make_move_iterator(el.end()));
}
return result;
}
rawTuple GetSingleRaw(enumVar key) const {
std::vector<std::vector<std::tuple<enumVar, rawTuple>>> tmp1= { (this->getAllIndexedTypeRaw<Types>())... };
for (auto el : tmp1) {
auto cc = std::find_if(el.begin(), el.end(), [&key](const std::tuple<enumVar, rawTuple>& e) {return std::get<0>(e) == key;});
if (cc != el.end()) {
auto kk = *cc;
return std::get<1>(kk);
break;
}
}
return std::make_tuple<rawT1, rawT2>(nullptr, 0);
}
private:
/*template <typename T>
void AppendType(std::map<enumVar,T>& myVec, std::map<enumVar,T>&& otherVec) {
// std::map<enumVar,T>& myVec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
// std::map<enumVar,T>& otherVec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(otherData.vectors);
// I only iterate through the other vector, so that data that is not in other but is in this
// is carried over, and data that is in other but not in this will be 'created' thanks to using
// [] instead of ->at() on 'this' data.
for (typename std::map<enumVar,T>::iterator it=otherVec.begin(); it != otherVec.end(); ++it) {
AppendData<T>(myVec[it->first], std::move(it->second));
}
}*/
template <typename T>
bool AppendKeyType(enumVar key, std::map<enumVar,T>& myVec, std::map<enumVar,T>& otherVec) {
// std::map<enumVar,T>& myVec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(vectors);
// std::map<enumVar,T>& otherVec = MatchingField<0, T, vtype, VectorOfType<0, T>::value>::get(otherData.vectors);
// I only iterate through the other vector, so that data that is not in other but is in this
// is carried over, and data that is in other but not in this will be 'created' thanks to using
// [] instead of ->at() on 'this' data.
if (allVars<enumVar>::varTypes.at(key) == typeid(T)) {
return AppendData<T>(myVec[key], std::move(otherVec.at(key)));
}
return false;
}
public:
/*
inline void Append(HeterogeneousContainer<enumVar, Types...>&& otherData) {
//int trash[] = {(AppendType<Types>(otherData),0)...};
int trash[] = {(AppendType<Types>(MatchingField<0, Types, vtype, VectorOfType<0, Types>::value>::get(vectors),
std::move(MatchingField<0, Types, vtype, VectorOfType<0, Types>::value>::get(
otherData.vectors))), 0)...};
}*/
// returns true if the length is the sum, false if it is not.
inline bool AppendKey(enumVar key, HeterogeneousContainer<enumVar, Types...>& otherData) {
std::array<bool, sizeof...(Types)> trash({(AppendKeyType<Types>(key, access<Types>(), otherData.access<Types>()))...});
return std::any_of(trash.begin(), trash.end(), [](bool x) { return x;});
}
#ifdef MPI_SUPPORT
public:
template<class Archive>
void serialize(Archive & ar)
{
ar(vectors);
};
#endif
};
#endif //SIMULATOR_HETEROGENEOUSCONTAINER_HPP
| 33.52669 | 138 | 0.614054 | [
"object",
"vector"
] |
ce0cd9dc025a1642749f031125af2fb1479c79ee | 806 | cc | C++ | tvm/src/codegen/llvm/codegen_arm.cc | zzzDavid/heterocl | 977aae575d54a30c5bf6d869e8f71bdc815cf7e9 | [
"Apache-2.0"
] | 236 | 2019-05-19T01:48:11.000Z | 2022-03-31T09:03:54.000Z | tvm/src/codegen/llvm/codegen_arm.cc | zzzDavid/heterocl | 977aae575d54a30c5bf6d869e8f71bdc815cf7e9 | [
"Apache-2.0"
] | 248 | 2019-05-17T19:18:36.000Z | 2022-03-30T21:25:47.000Z | tvm/src/codegen/llvm/codegen_arm.cc | AlgaPeng/heterocl-2 | b5197907d1fe07485466a63671a2a906a861c939 | [
"Apache-2.0"
] | 85 | 2019-05-17T20:09:27.000Z | 2022-02-28T20:19:00.000Z | /*!
* Copyright (c) 2017 by Contributors
* \file codegen_arm.cc
* \brief ARM specific code generator
*/
#ifdef TVM_LLVM_VERSION
#include "./codegen_cpu.h"
namespace TVM {
namespace codegen {
// ARM specific code generator, this is used as an example on
// how to override behavior llvm code generator for specific target
class CodeGenARM final : public CodeGenCPU {
public:
void InitTarget(llvm::TargetMachine* tm) final {
// set native vector bits.
native_vector_bits_ = 16 * 8;
CodeGenCPU::InitTarget(tm);
}
};
TVM_REGISTER_GLOBAL("tvm.codegen.llvm.target_arm")
.set_body([](const TVMArgs& targs, TVMRetValue* rv) {
CodeGenLLVM* cg = new CodeGenARM();
*rv = static_cast<void*>(cg);
});
} // namespace codegen
} // namespace TVM
#endif // TVM_LLVM_VERSION
| 25.1875 | 67 | 0.69727 | [
"vector"
] |
ce0f47b21e69d9a70bb4dd94c8c65fd3f5ae3d1d | 7,261 | cpp | C++ | compiler/enco/frontend/tflite/src/Op/Concatenation.cpp | bogus-sudo/ONE-1 | 7052a817eff661ec2854ed2e7ee0de5e8ba82b55 | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | compiler/enco/frontend/tflite/src/Op/Concatenation.cpp | bogus-sudo/ONE-1 | 7052a817eff661ec2854ed2e7ee0de5e8ba82b55 | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | compiler/enco/frontend/tflite/src/Op/Concatenation.cpp | bogus-sudo/ONE-1 | 7052a817eff661ec2854ed2e7ee0de5e8ba82b55 | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd. 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 "Concatenation.h"
#include "IRBuilder.h"
#include "GraphBuilder.h"
#include <coco/IR/Module.h>
#include <coco/IR/FeatureLayouts.h>
#include <nncc/core/ADT/tensor/Shape.h>
#include <schema_generated.h>
#include <array>
#include <cassert>
using namespace nncc::core::ADT;
namespace
{
/**
* @brief Convert a numeric tensor axis as a ConcatF FeatureAxis value
*/
coco::ConcatF::Axis as_ConcatF_axis(uint32_t axis)
{
// NOTE The feature map (in TensorFlow) is a rank-4 (NHWC) tensor
assert(axis < 4);
coco::ConcatF::Axis res = coco::ConcatF::Axis::Unknown;
switch (axis)
{
case 0:
res = coco::ConcatF::Axis::Batch;
break;
case 1:
res = coco::ConcatF::Axis::Height;
break;
case 2:
res = coco::ConcatF::Axis::Width;
break;
case 3:
res = coco::ConcatF::Axis::Depth;
break;
default:
break;
}
return res;
}
/**
* @brief Convert a coco FeatureShape as an array of 'uint32_t' values
*/
std::array<uint32_t, 4> as_dims(const coco::FeatureShape &shape)
{
std::array<uint32_t, 4> res;
res[0] = shape.batch();
res[1] = shape.height();
res[2] = shape.width();
res[3] = shape.depth();
return res;
}
/**
* @brief Convert a tensor shape as a coco FeatureShape
*/
coco::FeatureShape as_feature_shape(const tensor::Shape &shape)
{
assert(shape.rank() == 4);
auto const B = shape.dim(0);
auto const C = shape.dim(3);
auto const H = shape.dim(1);
auto const W = shape.dim(2);
return coco::FeatureShape{B, C, H, W};
}
} // namespace
namespace tflimport
{
void ConcatenationGraphBuilder::build(const tflite::Operator *op,
GraphBuilderContext *context) const
{
assert(context != nullptr);
coco::Module *m = context->m();
coco::Data *d = context->d();
coco::Block *blk = context->block();
TensorContext &tensor_context = context->tensor();
TensorBags &bags = context->bags();
IndexVector opinputs = as_index_vector(op->inputs());
IndexVector opoutputs = as_index_vector(op->outputs());
// these are fixed in tflite
// input index 0 ~ N : any number of input features
// output index 0 : one output feature
assert(opinputs.size() > 0);
assert(opoutputs.size() == 1);
// Default parameter values are referenced from schema_generated.h
int32_t concat_axis = 0;
tflite::ActivationFunctionType activation = tflite::ActivationFunctionType_NONE;
if (auto *concatenation_params = op->builtin_options_as_ConcatenationOptions())
{
activation = concatenation_params->fused_activation_function();
concat_axis = concatenation_params->axis();
const int32_t rank = static_cast<int32_t>(tensor_context.shape(opinputs.at(0)).rank());
if (concat_axis < 0)
{
concat_axis += rank;
}
assert(concat_axis >= 0);
assert(concat_axis < rank);
}
assert(as_ConcatF_axis(concat_axis) != coco::ConcatF::Axis::Unknown);
assert(activation == tflite::ActivationFunctionType_NONE);
// Construct a vector of input objects
std::vector<coco::FeatureObject *> input_objects;
for (auto &input_index : opinputs)
{
const tensor::Shape &input_shape = tensor_context.shape(input_index);
coco::FeatureObject *input_obj = m->entity()->object()->create<coco::FeatureObject>();
coco::Bag *input_bag = bags.bag(input_index);
input_obj->bag(input_bag);
input_obj->layout(coco::FeatureLayouts::BHWC::create(as_feature_shape(input_shape)));
input_objects.emplace_back(input_obj);
}
coco::FeatureObject *last_feature = input_objects.at(0);
assert(last_feature != nullptr);
assert(last_feature->bag() != nullptr);
// Update coco IR
//
// Given a sequence of input features %in[0] / %in[1] / ... / %in[N]
// the below code constructs a sequence of eval instructions
// - Load is omitted for simplicity
//
// %tmp = eval(ConcatF(%in[0], %in[1]))
// %tmp = eval(ConcatF(%tmp, %in[2]))
// ...
// %tmp = eval(ConcatF(%tmp, %in[N]))
// %out[0] = copy(%tmp)
//
for (uint32_t n = 1; n < input_objects.size(); ++n)
{
auto const left_feature = last_feature;
auto const left_shape = left_feature->layout()->shape();
auto right_feature = input_objects.at(n);
auto right_shape = right_feature->layout()->shape();
// Compute output dimensionalities
auto compute_out_dims = [&left_shape, &right_shape, concat_axis](void) {
std::array<uint32_t, 4> out_dims;
const auto left_dims = as_dims(left_shape);
const auto right_dims = as_dims(right_shape);
for (uint32_t axis = 0; axis < 4 /* FEATURE MAP RANK */; ++axis)
{
// The dimensionality of all the axises except 'concat' axis SHOULD BE INDETICAL
assert((concat_axis == axis) || (left_dims[axis] == right_dims[axis]));
out_dims[axis] = left_dims[axis];
if (axis == concat_axis)
{
out_dims[axis] += right_dims[axis];
}
}
return out_dims;
};
const auto out_dims = compute_out_dims();
const uint32_t B = out_dims[0 /* BATCH */];
const uint32_t C = out_dims[3 /* DEPTH */];
const uint32_t H = out_dims[1 /* HEIGHT */];
const uint32_t W = out_dims[2 /* WIDTH */];
const coco::FeatureShape out_shape{B, C, H, W};
auto out_bag = m->entity()->bag()->create(B * num_elements(out_shape));
auto out_feature = m->entity()->object()->create<coco::FeatureObject>();
out_feature->bag(out_bag);
out_feature->layout(coco::FeatureLayouts::BHWC::create(out_shape));
auto left_load = op_builder(m).load(left_feature).pop();
auto right_load = op_builder(m).load(right_feature).pop();
auto concat_f = m->entity()->op()->create<coco::ConcatF>();
concat_f->axis(as_ConcatF_axis(concat_axis));
concat_f->left(left_load);
concat_f->right(right_load);
auto eval = instr_builder(m).eval(out_feature, concat_f);
// Append the constructed Shuffle instruction
blk->instr()->append(eval);
// Update 'last_feature'
last_feature = out_feature;
}
// Insert copy instruction from last_feature to output operand
int const ofm_idx = opoutputs.at(0);
auto const ofm_shape = tensor_context.shape(ofm_idx);
auto ofm_bag = bags.bag(ofm_idx);
auto ofm_obj = m->entity()->object()->create<coco::FeatureObject>();
ofm_obj->bag(ofm_bag);
ofm_obj->layout(coco::FeatureLayouts::BHWC::create(as_feature_shape(ofm_shape)));
// Create a Copy instruction from last into ofm
auto copy_ins = instr_builder(m).copy(ofm_obj, last_feature);
// Append the instruction
blk->instr()->append(copy_ins);
}
} // namespace tflimport
| 28.699605 | 91 | 0.668503 | [
"object",
"shape",
"vector"
] |
ce0fe8454c56dfc8cee63972000d2e6cb571ed5f | 1,508 | cxx | C++ | com/netfx/src/framework/xsp/isapi/timeclass.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/framework/xsp/isapi/timeclass.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/framework/xsp/isapi/timeclass.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /**
* Process Model: TimeClass defn file
*
* Copyright (c) 1999 Microsoft Corporation
*/
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "TimeClass.h"
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
TimeClass::TimeClass()
{
m_fSet = FALSE;
m_ulTime = 0;
}
/////////////////////////////////////////////////////////////////////////////
void
TimeClass::SnapCurrentTime()
{
GetSystemTimeAsFileTime((FILETIME *) &m_ulTime);
m_fSet = TRUE;
}
/////////////////////////////////////////////////////////////////////////////
DWORD
TimeClass::AgeInSeconds()
{
if (m_fSet == FALSE)
return 0;
__int64 ulTime;
GetSystemTimeAsFileTime((FILETIME *) &ulTime);
ulTime -= m_ulTime;
ulTime /= 10000000;
return DWORD(ulTime & 0xffffffff);
}
/////////////////////////////////////////////////////////////////////////////
DWORD
TimeClass::DiffInSeconds (const TimeClass & t1, const TimeClass & t2)
{
__int64 uld = t1.m_ulTime - t2.m_ulTime;
uld /= 10000000;
return DWORD(uld & 0xffffffff);
}
| 25.559322 | 78 | 0.321618 | [
"model"
] |
ce19f89e6563d4c50356f222d8cdf2b0b1c744fc | 1,774 | cpp | C++ | editor/echo/Editor/Logic/Operation/Operations/OperationTranslate.cpp | dulingzhi/echo | de7ee416c49e1494a008e0a818155d6d0f6d5a7a | [
"MIT"
] | null | null | null | editor/echo/Editor/Logic/Operation/Operations/OperationTranslate.cpp | dulingzhi/echo | de7ee416c49e1494a008e0a818155d6d0f6d5a7a | [
"MIT"
] | null | null | null | editor/echo/Editor/Logic/Operation/Operations/OperationTranslate.cpp | dulingzhi/echo | de7ee416c49e1494a008e0a818155d6d0f6d5a7a | [
"MIT"
] | null | null | null | #include "OperationTranslate.h"
#include "Studio.h"
#include "RenderWindow.h"
#include "TransformWidget.h"
namespace Studio
{
OperationTranslate::OperationTranslate()
{
}
OperationTranslate::~OperationTranslate()
{
}
void OperationTranslate::tick(const Echo::set<Echo::ui32>::type& objects)
{
if (m_selectedObjects != objects)
{
m_selectedObjects = objects;
TransformWidget* transformWidget = getTransformWidget();
if (transformWidget)
{
transformWidget->setPosition(getObjectsCenter());
transformWidget->setRenderType2d(is2d());
transformWidget->setListener(this);
}
}
}
void OperationTranslate::onTranslate(const Echo::Vector3& trans)
{
for (Echo::i32 id : m_selectedObjects)
{
Echo::Node* node = dynamic_cast<Echo::Node*>(Echo::Object::getById(id));
if (node)
{
node->setWorldPosition(node->getWorldPosition() + trans);
}
}
}
TransformWidget* OperationTranslate::getTransformWidget()
{
return AStudio::instance()->getRenderWindow()->getTransformWidget();
}
Echo::Vector3 OperationTranslate::getObjectsCenter()
{
float count = 0.f;
Echo::Vector3 position;
for (Echo::i32 id : m_selectedObjects)
{
Echo::Node* node = dynamic_cast<Echo::Node*>(Echo::Object::getById(id));
if (node)
{
count = count + 1.f;
position += node->getWorldPosition();
}
}
return count ? position / count : Echo::Vector3::INVALID;
}
bool OperationTranslate::is2d()
{
for (Echo::i32 id : m_selectedObjects)
{
Echo::Render* node = dynamic_cast<Echo::Render*>(Echo::Object::getById(id));
if (node)
{
return node->getRenderType().getValue() == "3d" ? false : true;
}
}
return (Echo::Render::getRenderTypes() & Echo::Render::Type::Type_3D) ? false : true;
}
} | 21.901235 | 87 | 0.676437 | [
"render",
"object",
"3d"
] |
ce1d86c047a97ad2d8f4955fbd1dd2f6f396c0e3 | 4,904 | cc | C++ | clouds/test/clouds_test.cc | mqtthiqs/mutable | 32fa66f5acce1bff2f0a7bdd041e29bad3222557 | [
"MIT"
] | 87 | 2015-04-14T02:00:43.000Z | 2022-01-28T03:10:47.000Z | clouds/test/clouds_test.cc | mqtthiqs/mutable | 32fa66f5acce1bff2f0a7bdd041e29bad3222557 | [
"MIT"
] | 1 | 2017-08-25T13:46:31.000Z | 2019-08-28T21:14:59.000Z | clouds/test/clouds_test.cc | mqtthiqs/mutable | 32fa66f5acce1bff2f0a7bdd041e29bad3222557 | [
"MIT"
] | 16 | 2015-10-23T12:54:47.000Z | 2021-04-05T15:12:15.000Z | // Copyright 2014 Emilie Gillet.
//
// Author: Emilie Gillet (emilie.o.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// 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.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <xmmintrin.h>
#include "clouds/dsp/granular_processor.h"
#include "clouds/resources.h"
using namespace clouds;
using namespace std;
using namespace stmlib;
const size_t kSampleRate = 32000;
const size_t kBlockSize = 32;
void write_wav_header(FILE* fp, int num_samples, int num_channels) {
uint32_t l;
uint16_t s;
fwrite("RIFF", 4, 1, fp);
l = 36 + num_samples * 2 * num_channels;
fwrite(&l, 4, 1, fp);
fwrite("WAVE", 4, 1, fp);
fwrite("fmt ", 4, 1, fp);
l = 16;
fwrite(&l, 4, 1, fp);
s = 1;
fwrite(&s, 2, 1, fp);
s = num_channels;
fwrite(&s, 2, 1, fp);
l = kSampleRate;
fwrite(&l, 4, 1, fp);
l = static_cast<uint32_t>(kSampleRate) * 2 * num_channels;
fwrite(&l, 4, 1, fp);
s = 2 * num_channels;
fwrite(&s, 2, 1, fp);
s = 16;
fwrite(&s, 2, 1, fp);
fwrite("data", 4, 1, fp);
l = num_samples * 2 * num_channels;
fwrite(&l, 4, 1, fp);
}
void TestDSP() {
size_t duration = 15;
FILE* fp_in = fopen("audio_samples/sine.wav", "rb");
FILE* fp_out = fopen("clouds.wav", "wb");
size_t remaining_samples = kSampleRate * duration;
write_wav_header(fp_out, remaining_samples, 2);
fseek(fp_in, 48, SEEK_SET);
uint8_t large_buffer[118784];
uint8_t small_buffer[65536 - 128];
GranularProcessor processor;
processor.Init(
&large_buffer[0], sizeof(large_buffer),
&small_buffer[0],sizeof(small_buffer));
processor.set_num_channels(2);
processor.set_low_fidelity(false);
processor.set_playback_mode(PLAYBACK_MODE_GRANULAR);
Parameters* p = processor.mutable_parameters();
size_t block_counter = 0;
float phase_ = 0.0f;
bool synthetic = false;
processor.Prepare();
float pot_noise = 0.0f;
while (remaining_samples) {
// uint16_t tri = (remaining_samples * 0.4);
// tri = tri > 32767 ? 65535 - tri : tri;
// float triangle = tri / 32768.0f;
p->gate = false;
p->trigger = false;// || (block_counter & 2047) > 1024;
p->freeze = false; // || (block_counter & 2047) > 1024;
p->granular.reverse = true;
pot_noise += 0.05f * ((Random::GetSample() / 32768.0f) * 0.05f - pot_noise);
p->position = Random::GetFloat();//triangle * 0.0f + 0.5f;
p->size = Random::GetFloat();//0.99f;
p->pitch = Random::GetFloat() * 24.0f; //0.0f + (triangle > 0.5f ? 1.0f : 0.0f) * 0.0f;
p->density = 0.99f;
p->texture = 0.7f;
p->dry_wet = 1.0f;
p->stereo_spread = 0.0f;
p->feedback = 0.0f;
p->reverb = 0.0f;
++block_counter;
ShortFrame input[kBlockSize];
ShortFrame output[kBlockSize];
if (synthetic) {
for (size_t i = 0; i < kBlockSize; ++i) {
phase_ += 400.0f / kSampleRate; // (block_counter & 512 ? 110.0f : 220.0f) / kSampleRate;
while (phase_ >= 1.0) {
phase_ -= 1.0;
}
input[i].l = 16384.0f * sinf(phase_ * M_PI * 2);
input[i].r = 32768.0f * (phase_ - 0.5);
// input[i].r = input[i].l = 0;
}
remaining_samples -= kBlockSize;
} else {
if (fread(
input,
sizeof(ShortFrame),
kBlockSize,
fp_in) != kBlockSize) {
break;
}
remaining_samples -= kBlockSize;
}
processor.Process(input, output, kBlockSize);
processor.Prepare();
fwrite(output, sizeof(ShortFrame), kBlockSize, fp_out);
}
fclose(fp_out);
fclose(fp_in);
}
int main(void) {
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
TestDSP();
// TestGrainSize();
}
| 30.271605 | 97 | 0.633564 | [
"vector"
] |
ce23183ec7bd343aae19b22d51428fc173d6851b | 2,495 | cpp | C++ | sequoia-engine/src/sequoia-engine/Game/PointLight.cpp | thfabian/sequoia | ed7a17452ac946e8208ff60a30fc10298d3939db | [
"MIT"
] | 2 | 2018-01-31T07:44:59.000Z | 2018-01-31T20:34:37.000Z | sequoia-engine/src/sequoia-engine/Game/PointLight.cpp | thfabian/sequoia | ed7a17452ac946e8208ff60a30fc10298d3939db | [
"MIT"
] | null | null | null | sequoia-engine/src/sequoia-engine/Game/PointLight.cpp | thfabian/sequoia | ed7a17452ac946e8208ff60a30fc10298d3939db | [
"MIT"
] | null | null | null | //===--------------------------------------------------------------------------------*- C++ -*-===//
// _____ _
// / ____| (_)
// | (___ ___ __ _ _ _ ___ _ __ _
// \___ \ / _ \/ _` | | | |/ _ \| |/ _` |
// ____) | __/ (_| | |_| | (_) | | (_| |
// |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine (2016-2017)
// | |
// |_|
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//
#include "sequoia-engine/Game/PointLight.h"
#include "sequoia-engine/Core/Format.h"
#include "sequoia-engine/Core/StringUtil.h"
#include "sequoia-engine/Game/SceneNode.h"
#include "sequoia-engine/Game/SceneNodeAlloc.h"
#include "sequoia-engine/Render/UniformStruct.h"
namespace sequoia {
namespace game {
namespace {
SEQUOIA_UNIFORM_STRUCT(PointLightStruct,
(math::vec3, Position)(math::vec3, Power)(math::vec4, Color));
} // anonymous namespace
PointLight::~PointLight() {}
PointLight::PointLight(SceneNode* node, math::vec3 power, Color color)
: Base(node, EK_PointLight), power_(power), color_(color) {}
void PointLight::toUniformVariableMap(std::unordered_map<std::string, UniformVariable>& map,
int index) {
auto normalizedColor = color_.toRGBA32f();
math::vec4 color = math::make_vec4(normalizedColor.data());
PointLightStruct light{getNode()->getPosition(), power_, color};
light.toUniformVariableMap(getUniformVariableName(), map, index);
}
const char* PointLight::getName() const { return "PointLight"; }
void PointLight::update(const SceneNodeUpdateEvent& event) {}
std::shared_ptr<SceneNodeCapability> PointLight::clone(SceneNode* node) const {
return scene::allocate_shared<PointLight>(node, power_, color_);
}
std::pair<std::string, std::string> PointLight::toStringImpl() const {
return std::make_pair(getName(), core::format("{}"
"power = {},\n"
"color = {}\n",
Base::toStringImpl().second, power_, color_));
}
} // namespace game
} // namespace sequoia
| 37.80303 | 100 | 0.507014 | [
"render"
] |
ce290b0109adf434226347215382b431ad99216b | 3,160 | cpp | C++ | src/CRC_Sensors.cpp | ChicagoRobotics/CRC_Simula_Library | 52fde47b5179c952f08e18c69efbed78749ea2e4 | [
"BSD-3-Clause"
] | 3 | 2016-11-16T23:44:26.000Z | 2018-01-29T15:31:59.000Z | src/CRC_Sensors.cpp | ChicagoRobotics/CRC_Simula_Library | 52fde47b5179c952f08e18c69efbed78749ea2e4 | [
"BSD-3-Clause"
] | 5 | 2017-02-03T03:58:18.000Z | 2018-01-23T17:57:46.000Z | src/CRC_Sensors.cpp | ChicagoRobotics/CRC_Simula_Library | 52fde47b5179c952f08e18c69efbed78749ea2e4 | [
"BSD-3-Clause"
] | 2 | 2017-01-28T17:26:15.000Z | 2019-12-23T01:05:04.000Z | /***************************************************
Uses: Provides a higher level module around the sensors on
Simula
This file is designed for the Simula project by Chicago Robotics Corp.
http://www.chicagorobotics.net/products
Copyright (c) 2016, Chicago Robotics Corp.
See README.md for license details
****************************************************/
#include "CRC_Sensors.h"
#include "CRC_IR_BinaryDistance.h"
#include "CRC_IR_AnalogDistance.h"
#include "CRC_PingDistance.h"
#include "CRC_Hardware.h"
void CRC_Sensors::init() {
lsm = Adafruit_LSM9DS0();
}
void CRC_Sensors::activate() {
//Activate sensors
digitalWrite(hardware.pinActEdge1, HIGH);
digitalWrite(hardware.pinActEdge2, HIGH);
digitalWrite(hardware.pinActPerim1, HIGH);
digitalWrite(hardware.pinActPerim2, HIGH);
digitalWrite(hardware.pinActPerim3, HIGH);
digitalWrite(hardware.pinActPerim4, HIGH);
digitalWrite(hardware.pinActFrntIR, HIGH);
lastIrPollSensors = 0;
}
void CRC_Sensors::deactivate() {
//Activate sensors
digitalWrite(hardware.pinActEdge1, LOW);
digitalWrite(hardware.pinActEdge2, LOW);
digitalWrite(hardware.pinActPerim1, LOW);
digitalWrite(hardware.pinActPerim2, LOW);
digitalWrite(hardware.pinActPerim3, LOW);
digitalWrite(hardware.pinActPerim4, LOW);
digitalWrite(hardware.pinActFrntIR, LOW);
lastIrPollSensors = 0;
}
void CRC_Sensors::readIR() {
CRC_IR_BinaryDistance edgeLeft = CRC_IR_BinaryDistance(hardware.pinActEdge1, hardware.pinEdge1);
CRC_IR_BinaryDistance edgeRight = CRC_IR_BinaryDistance(hardware.pinActEdge2, hardware.pinEdge2);
CRC_IR_AnalogDistance perimLeft = CRC_IR_AnalogDistance(hardware.pinActPerim1, hardware.pinPerim1);
CRC_IR_AnalogDistance perimLeftFront = CRC_IR_AnalogDistance(hardware.pinActPerim2, hardware.pinPerim2);
CRC_IR_AnalogDistance perimFront = CRC_IR_AnalogDistance(hardware.pinActFrntIR, hardware.pinFrntIr);
CRC_IR_AnalogDistance perimRightFront = CRC_IR_AnalogDistance(hardware.pinActPerim3, hardware.pinPerim3);
CRC_IR_AnalogDistance perimRight = CRC_IR_AnalogDistance(hardware.pinActPerim4, hardware.pinPerim4);
CRC_PingDistance frontPing = CRC_PingDistance(hardware.pinPingTrigger, hardware.pinPingEcho);
sensors.irLeftCM = perimLeft.readDistance();
sensors.irLeftFrontCM = perimLeftFront.readDistance();
sensors.irFrontCM = perimFront.readDistance();
sensors.irRightFrontCM = perimRightFront.readDistance();
sensors.irRightCM = perimRight.readDistance();
sensors.pingFrontCM = frontPing.readDistance();
//If there is no object detected, then we MAY have a cliff.
sensors.irLeftCliff = !edgeLeft.objectDetected();
sensors.irRightCliff = !edgeRight.objectDetected();
lastIrPollSensors = millis();
}
boolean CRC_Sensors::irReadingUpdated() {
unsigned long now = millis();
unsigned long diff = now - lastIrPollSensors;
if (lastIrPollSensors == 0)
{
// First Read of Sensors - pre-debounce
return false;
}
if (diff < 50)
{
// 50 ms is still a fresh reading
return true;
}
if (diff > 1200)
{
Serial.println(F("Long loop, forcing sensor read."));
return false;
//CRC_Logger.logF(CRC_Logger.LOG_TRACE, F("Forced IR Read: %ul"), diff);
}
return false;
}
| 33.617021 | 106 | 0.762342 | [
"object"
] |
ce2cd0aa26bf86fefad4cf33e05db82b02b327b3 | 5,079 | cpp | C++ | Numerical-calculus/Activity-M3/main.cpp | JoseZancanaro/CienciaDaComputacao | 0e08d9a3fd17cba38ef9d09f38026e9417b5536a | [
"MIT"
] | null | null | null | Numerical-calculus/Activity-M3/main.cpp | JoseZancanaro/CienciaDaComputacao | 0e08d9a3fd17cba38ef9d09f38026e9417b5536a | [
"MIT"
] | 1 | 2022-02-13T22:22:59.000Z | 2022-02-13T22:22:59.000Z | Numerical-calculus/Activity-M3/main.cpp | JoseZancanaro/CienciaDaComputacao | 0e08d9a3fd17cba38ef9d09f38026e9417b5536a | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <sstream>
#include <fstream>
#include "lib/equacao-diferencial/EquacaoDiferencial.hpp"
#include "lib/minimos-quadrados/MinimosQuadrados.hpp"
#include "lib/integracao/IntegracaoNumerica.hpp"
void questao01()
{
std::vector<Ponto> populacao {{1872, 9.9}, {1890, 14.3}, {1900, 17.4}, {1920, 30.6}, {1940, 41.2},
{1950, 51.9}, {1960, 70.2}, {1970, 93.1}, {1980, 119.0}, {1991, 146.2}};
std::cout << "Letra A : Reta" << std::endl;
Solucao reta = minimosQuadradosSimples(populacao, 1);
std::cout << "Solução : ";
std::for_each(reta.begin(), reta.end(), [](double x) { std::cout << x << " ";} );
std::vector<Ponto> estimativaPorReta {populacao};
estimativaPorReta.push_back({2018, 0.0});
std::for_each(estimativaPorReta.begin(), estimativaPorReta.end(), [&reta](Ponto &p) {
p.y = resolverPolinomioInterpolado(p.x, reta);
});
std::cout << std::endl;
std::for_each(estimativaPorReta.begin(), estimativaPorReta.end(), [](Ponto p) { std::cout << p.x << ":" << p.y << std::endl; });
std::cout << std::endl;
std::cout << "Letra B : Parábola" << std::endl;
Solucao parabola = minimosQuadradosSimples(populacao, 2);
std::cout << "Solução : ";
std::for_each(parabola.begin(), parabola.end(), [](double x) { std::cout << x << " ";} );
std::vector<Ponto> estimativaPorParabola {populacao};
estimativaPorParabola.push_back({2018, 0.0});
std::for_each(estimativaPorParabola.begin(), estimativaPorParabola.end(), [¶bola](Ponto &p) {
p.y = resolverPolinomioInterpolado(p.x, parabola);
});
std::cout << std::endl;
std::for_each(estimativaPorParabola.begin(), estimativaPorParabola.end(), [](Ponto p) { std::cout << p.x << ":" << p.y << std::endl; });
std::cout << std::endl;
std::cout << "Letra C : Exponencial" << std::endl;
Solucao exponencial = aproximacaoExponencialNatural(populacao);
std::cout << "Solução : ";
std::for_each(exponencial.begin(), exponencial.end(), [](double x) { std::cout << x << " ";} );
std::vector<Ponto> estimativaPorExponencial {populacao};
estimativaPorExponencial.push_back({2018, 0.0});
std::for_each(estimativaPorExponencial.begin(), estimativaPorExponencial.end(), [&exponencial](Ponto &p) {
p.y = exponencial.front() * std::exp(exponencial.back() * p.x);
});
std::cout << std::endl;
std::for_each(estimativaPorExponencial.begin(), estimativaPorExponencial.end(), [](Ponto p) { std::cout << p.x << ":" << p.y << std::endl; });
std::cout << std::endl << std::endl;
std::cout << "Letra D : Estimativa de População em 2018" << std::endl;
std::cout << "Reta : " << estimativaPorReta.back().y << std::endl;
std::cout << "Parábola : " << estimativaPorParabola.back().y << std::endl;
std::cout << "Exponenciação : " << estimativaPorExponencial.back().y << std::endl;
std::cout << std::endl;
}
void questao02()
{
const double precisao = 10E-5;
std::cout << "LETRA A : Regra dos Trapézios" << std::endl;
std::function<double(double)> funcaoTrapezio = [](double x) -> double {
return std::sin(sqrt(x));
};
std::ofstream trapezios("../Relatório/Dados/2.Trapezio.csv");
double areaTrapezios = areaPorTrapezios(funcaoTrapezio, 0.0, 0.24, precisao, &trapezios);
std::cout << "Aproximação [0.0, 0.24] = " << areaTrapezios << std::endl;
trapezios.close();
std::cout << std::endl;
std::cout << "LETRA B : Regra do 1/3 de Simpson" << std::endl;
std::function<double(double)> funcaoSimpson = [](double x) -> double {
return std::tan(x) + std::exp(x);
};
std::ofstream simpson("../Relatório/Dados/2.Simpson.csv");
double areaSimpson = areaPorSimpson(funcaoSimpson, 0.5, 1.5, precisao, &simpson);
std::cout << "Aproximação [0.5, 1.5] = " << areaSimpson << std::endl;
simpson.close();
}
void questao03()
{
std::vector<double> hs {0.2, 0.1, 0.05};
std::function<double(double, double)> diferencial = [](double x, double y) -> double {
return y - x;
};
std::function<bool(Ponto)> condicao = [](Ponto ponto) -> bool {
return ponto.x < 4.0 - 0.01;
};
for (double h : hs) {
std::stringstream ss;
ss << "../Relatório/Dados/3.Valores-" << h << ".csv";
std::ofstream tabela(ss.rdbuf()->str());
tabela << "x" << "," << "y" << std::endl;
Ponto resposta = metodoDeEuler(diferencial, {0.0,2.0}, h, condicao, &tabela);
std::cout << "Resposta para " << h << " : " << "(" << resposta.x << "," << resposta.y << ")" << std::endl;
tabela.close();
}
}
void decorar(std::function<void()> questao, int num)
{
std::cout << "--- Questão " << num << " -----------------------" << std::endl;
questao();
std::cout << "-------------------------------------" << std::endl << std::endl;
}
int main()
{
decorar(questao01, 1);
decorar(questao02, 2);
decorar(questao03, 3);
return 0;
}
| 32.767742 | 146 | 0.585155 | [
"vector"
] |
ce2e3ab2cc6c7ca47e9fc698b9832df718fc5234 | 25,943 | cpp | C++ | external/openglcts/modules/runner/glcTestRunner.cpp | greg-lunarg/VK-GL-CTS | b29bf0434c16796dc48a17a52c7fe219d558af31 | [
"Apache-2.0"
] | null | null | null | external/openglcts/modules/runner/glcTestRunner.cpp | greg-lunarg/VK-GL-CTS | b29bf0434c16796dc48a17a52c7fe219d558af31 | [
"Apache-2.0"
] | null | null | null | external/openglcts/modules/runner/glcTestRunner.cpp | greg-lunarg/VK-GL-CTS | b29bf0434c16796dc48a17a52c7fe219d558af31 | [
"Apache-2.0"
] | null | null | null | /*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2016 Google Inc.
* Copyright (c) 2016 The Khronos Group 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.
*
*/ /*!
* \file
* \brief CTS runner.
*/ /*-------------------------------------------------------------------*/
#include "glcTestRunner.hpp"
#include "deFilePath.hpp"
#include "deStringUtil.hpp"
#include "deUniquePtr.hpp"
#include "glcConfigList.hpp"
#include "qpXmlWriter.h"
#include "tcuApp.hpp"
#include "tcuCommandLine.hpp"
#include "tcuTestLog.hpp"
#include "tcuTestSessionExecutor.hpp"
#include <iterator>
namespace glcts
{
using std::vector;
using std::string;
// RunSession
class RunSession
{
public:
RunSession(tcu::Platform& platform, tcu::Archive& archive, const int numArgs, const char* const* args)
: m_cmdLine(numArgs, args)
, m_log(m_cmdLine.getLogFileName(), m_cmdLine.getLogFlags())
, m_app(platform, archive, m_log, m_cmdLine)
{
const std::string sessionInfo = "#sessionInfo commandLineParameters \"";
m_log.writeSessionInfo(sessionInfo + m_cmdLine.getInitialCmdLine() + "\"\n");
}
inline bool iterate(void)
{
return m_app.iterate();
}
inline const tcu::TestRunStatus& getResult(void) const
{
return m_app.getResult();
}
private:
tcu::CommandLine m_cmdLine;
tcu::TestLog m_log;
tcu::App m_app;
};
static void appendConfigArgs(const Config& config, std::vector<std::string>& args, const char* fboConfig)
{
if (fboConfig != NULL)
{
args.push_back(string("--deqp-gl-config-name=") + fboConfig);
args.push_back("--deqp-surface-type=fbo");
}
if (config.type != CONFIGTYPE_DEFAULT)
{
// \todo [2013-05-06 pyry] Test all surface types for some configs?
if (fboConfig == NULL)
{
if (config.surfaceTypes & SURFACETYPE_WINDOW)
args.push_back("--deqp-surface-type=window");
else if (config.surfaceTypes & SURFACETYPE_PBUFFER)
args.push_back("--deqp-surface-type=pbuffer");
else if (config.surfaceTypes & SURFACETYPE_PIXMAP)
args.push_back("--deqp-surface-type=pixmap");
}
args.push_back(string("--deqp-gl-config-id=") + de::toString(config.id));
if (config.type == CONFIGTYPE_EGL)
args.push_back("--deqp-gl-context-type=egl");
else if (config.type == CONFIGTYPE_WGL)
args.push_back("--deqp-gl-context-type=wgl");
}
}
typedef struct configInfo
{
deInt32 redBits;
deInt32 greenBits;
deInt32 blueBits;
deInt32 alphaBits;
deInt32 depthBits;
deInt32 stencilBits;
deInt32 samples;
} configInfo;
static configInfo parseConfigBitsFromName(const char* configName)
{
configInfo cfgInfo;
static const struct
{
const char* name;
int redBits;
int greenBits;
int blueBits;
int alphaBits;
} colorCfgs[] = {
{ "rgba8888", 8, 8, 8, 8 }, { "rgb565", 5, 6, 5, 0 },
};
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(colorCfgs); ndx++)
{
if (!strncmp(configName, colorCfgs[ndx].name, strlen(colorCfgs[ndx].name)))
{
cfgInfo.redBits = colorCfgs[ndx].redBits;
cfgInfo.greenBits = colorCfgs[ndx].greenBits;
cfgInfo.blueBits = colorCfgs[ndx].blueBits;
cfgInfo.alphaBits = colorCfgs[ndx].alphaBits;
configName += strlen(colorCfgs[ndx].name);
break;
}
}
static const struct
{
const char* name;
int depthBits;
} depthCfgs[] = {
{ "d0", 0 }, { "d24", 24 },
};
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(depthCfgs); ndx++)
{
if (!strncmp(configName, depthCfgs[ndx].name, strlen(depthCfgs[ndx].name)))
{
cfgInfo.depthBits = depthCfgs[ndx].depthBits;
configName += strlen(depthCfgs[ndx].name);
break;
}
}
static const struct
{
const char* name;
int stencilBits;
} stencilCfgs[] = {
{ "s0", 0 }, { "s8", 8 },
};
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(stencilCfgs); ndx++)
{
if (!strncmp(configName, stencilCfgs[ndx].name, strlen(stencilCfgs[ndx].name)))
{
cfgInfo.stencilBits = stencilCfgs[ndx].stencilBits;
configName += strlen(stencilCfgs[ndx].name);
break;
}
}
static const struct
{
const char* name;
int samples;
} multiSampleCfgs[] = {
{ "ms0", 0 }, { "ms4", 4 },
};
for (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(multiSampleCfgs); ndx++)
{
if (!strncmp(configName, multiSampleCfgs[ndx].name, strlen(multiSampleCfgs[ndx].name)))
{
cfgInfo.samples = multiSampleCfgs[ndx].samples;
configName += strlen(multiSampleCfgs[ndx].name);
break;
}
}
return cfgInfo;
}
static const char* getApiName(glu::ApiType apiType)
{
if (apiType == glu::ApiType::es(2, 0))
return "gles2";
else if (apiType == glu::ApiType::es(3, 0))
return "gles3";
else if (apiType == glu::ApiType::es(3, 1))
return "gles31";
else if (apiType == glu::ApiType::es(3, 2))
return "gles32";
else if (apiType == glu::ApiType::core(3, 0))
return "gl30";
else if (apiType == glu::ApiType::core(3, 1))
return "gl31";
else if (apiType == glu::ApiType::core(3, 2))
return "gl32";
else if (apiType == glu::ApiType::core(3, 3))
return "gl33";
else if (apiType == glu::ApiType::core(4, 0))
return "gl40";
else if (apiType == glu::ApiType::core(4, 1))
return "gl41";
else if (apiType == glu::ApiType::core(4, 2))
return "gl42";
else if (apiType == glu::ApiType::core(4, 3))
return "gl43";
else if (apiType == glu::ApiType::core(4, 4))
return "gl44";
else if (apiType == glu::ApiType::core(4, 5))
return "gl45";
else if (apiType == glu::ApiType::core(4, 6))
return "gl46";
else
throw std::runtime_error("Unknown context type");
}
static const string getCaseListFileOption(const char* mustpassDir, const char* apiName, const char* mustpassName)
{
#if DE_OS == DE_OS_ANDROID
const string case_list_option = "--deqp-caselist-resource=";
#else
const string case_list_option = "--deqp-caselist-file=";
#endif
return case_list_option + mustpassDir + apiName + "-" + mustpassName + ".txt";
}
static const string getLogFileName(const char* apiName, const char* configName, const int iterId, const int runId,
const int width, const int height, const int seed)
{
string res = string("config-") + apiName + "-" + configName + "-cfg-" + de::toString(iterId) + "-run-" +
de::toString(runId) + "-width-" + de::toString(width) + "-height-" + de::toString(height);
if (seed != -1)
{
res += "-seed-" + de::toString(seed);
}
res += ".qpa";
return res;
}
static void getBaseOptions(std::vector<std::string>& args, const char* mustpassDir, const char* apiName,
const char* configName, const char* screenRotation, int width, int height)
{
args.push_back(getCaseListFileOption(mustpassDir, apiName, configName));
args.push_back(string("--deqp-screen-rotation=") + screenRotation);
args.push_back(string("--deqp-surface-width=") + de::toString(width));
args.push_back(string("--deqp-surface-height=") + de::toString(height));
args.push_back("--deqp-watchdog=disable");
}
static bool isGLConfigCompatible(configInfo cfgInfo, const AOSPConfig& config)
{
return cfgInfo.redBits == config.redBits && cfgInfo.greenBits == config.greenBits &&
cfgInfo.blueBits == config.blueBits && cfgInfo.alphaBits == config.alphaBits &&
cfgInfo.depthBits == config.depthBits && cfgInfo.stencilBits == config.stencilBits &&
cfgInfo.samples == config.samples;
}
static void getTestRunsForAOSPEGL(vector<TestRunParams>& runs, const ConfigList& configs)
{
#include "glcAospMustpassEgl.hpp"
for (int i = 0; i < DE_LENGTH_OF_ARRAY(aosp_mustpass_egl_first_cfg); ++i)
{
configInfo cfgInfo = parseConfigBitsFromName(aosp_mustpass_egl_first_cfg[i].glConfigName);
vector<AOSPConfig>::const_iterator cfgIter;
for (cfgIter = configs.aospConfigs.begin(); cfgIter != configs.aospConfigs.end(); ++cfgIter)
{
// find first compatible config
if ((*cfgIter).type == CONFIGTYPE_EGL && isGLConfigCompatible(cfgInfo, *cfgIter))
{
break;
}
}
if (cfgIter == configs.aospConfigs.end())
{
// No suitable configuration found. Skipping EGL tests
continue;
}
const char* apiName = "egl";
const int width = aosp_mustpass_egl_first_cfg[i].surfaceWidth;
const int height = aosp_mustpass_egl_first_cfg[i].surfaceHeight;
TestRunParams params;
params.logFilename =
getLogFileName(apiName, aosp_mustpass_egl_first_cfg[i].configName, 1, i, width, height, -1);
getBaseOptions(params.args, mustpassDir, apiName, aosp_mustpass_egl_first_cfg[i].configName,
aosp_mustpass_egl_first_cfg[i].screenRotation, width, height);
params.args.push_back(string("--deqp-gl-config-name=") + string(aosp_mustpass_egl_first_cfg[i].glConfigName));
runs.push_back(params);
}
}
static void getTestRunsForAOSPES(vector<TestRunParams>& runs, const ConfigList& configs, const glu::ApiType apiType)
{
#include "glcAospMustpassEs.hpp"
for (int i = 0; i < DE_LENGTH_OF_ARRAY(aosp_mustpass_es_first_cfg); ++i)
{
if (!glu::contextSupports(glu::ContextType(apiType), aosp_mustpass_es_first_cfg[i].apiType))
continue;
configInfo cfgInfo = parseConfigBitsFromName(aosp_mustpass_es_first_cfg[i].glConfigName);
vector<AOSPConfig>::const_iterator cfgIter;
for (cfgIter = configs.aospConfigs.begin(); cfgIter != configs.aospConfigs.end(); ++cfgIter)
{
// find first compatible config
if (isGLConfigCompatible(cfgInfo, *cfgIter))
{
break;
}
}
if (cfgIter == configs.aospConfigs.end())
{
TCU_FAIL(("No suitable configuration found for GL config " +
de::toString(aosp_mustpass_es_first_cfg[i].glConfigName))
.c_str());
return;
}
const char* apiName = getApiName(aosp_mustpass_es_first_cfg[i].apiType);
const int width = aosp_mustpass_es_first_cfg[i].surfaceWidth;
const int height = aosp_mustpass_es_first_cfg[i].surfaceHeight;
TestRunParams params;
params.logFilename = getLogFileName(apiName, aosp_mustpass_es_first_cfg[i].configName, 1, i, width, height, -1);
getBaseOptions(params.args, mustpassDir, apiName, aosp_mustpass_es_first_cfg[i].configName,
aosp_mustpass_es_first_cfg[i].screenRotation, width, height);
params.args.push_back(string("--deqp-gl-config-name=") + string(aosp_mustpass_es_first_cfg[i].glConfigName));
//set surface type
if ((*cfgIter).surfaceTypes & SURFACETYPE_WINDOW)
params.args.push_back("--deqp-surface-type=window");
else if ((*cfgIter).surfaceTypes & SURFACETYPE_PBUFFER)
params.args.push_back("--deqp-surface-type=pbuffer");
else if ((*cfgIter).surfaceTypes & SURFACETYPE_PIXMAP)
params.args.push_back("--deqp-surface-type=pixmap");
runs.push_back(params);
}
}
static void getTestRunsForNoContext(glu::ApiType type, vector<TestRunParams>& runs, const ConfigList& configs, const RunParams* runParams,
const int numRunParams, const char* mustpassDir)
{
vector<Config>::const_iterator cfgIter = configs.configs.begin();
for (int i = 0; i < numRunParams; ++i)
{
if (!glu::contextSupports(glu::ContextType(type), runParams[i].apiType))
continue;
const char* apiName = getApiName(runParams[i].apiType);
const int width = runParams[i].surfaceWidth;
const int height = runParams[i].surfaceHeight;
const int seed = runParams[i].baseSeed;
TestRunParams params;
params.logFilename = getLogFileName(apiName, runParams[i].configName, 1, i, width, height, seed);
getBaseOptions(params.args, mustpassDir, apiName, runParams[i].configName, runParams[i].screenRotation, width,
height);
params.args.push_back(string("--deqp-base-seed=") + de::toString(seed));
appendConfigArgs(*cfgIter, params.args, runParams[i].fboConfig);
runs.push_back(params);
}
}
static void getTestRunsForNoContextES(glu::ApiType type, vector<TestRunParams>& runs, const ConfigList& configs)
{
#include "glcKhronosMustpassEsNocontext.hpp"
getTestRunsForNoContext(type, runs, configs, khronos_mustpass_es_nocontext_first_cfg,
DE_LENGTH_OF_ARRAY(khronos_mustpass_es_nocontext_first_cfg), mustpassDir);
}
static void getTestRunsForSingleConfig(glu::ApiType type, vector<TestRunParams>& runs, const ConfigList& configs, const RunParams* runParams,
const int numRunParams, const char* mustpassDir)
{
vector<Config>::const_iterator cfgIter = configs.configs.begin();
for (int i = 0; i < numRunParams; ++i)
{
if (type != runParams[i].apiType)
continue;
const char* apiName = getApiName(runParams[i].apiType);
const int width = runParams[i].surfaceWidth;
const int height = runParams[i].surfaceHeight;
const int seed = runParams[i].baseSeed;
TestRunParams params;
params.logFilename = getLogFileName(apiName, runParams[i].configName, 1, i, width, height, seed);
getBaseOptions(params.args, mustpassDir, apiName, runParams[i].configName, runParams[i].screenRotation, width,
height);
params.args.push_back(string("--deqp-base-seed=") + de::toString(seed));
appendConfigArgs(*cfgIter, params.args, runParams[i].fboConfig);
runs.push_back(params);
}
}
static void getTestRunsForSingleConfigES(glu::ApiType type, vector<TestRunParams>& runs, const ConfigList& configs)
{
#include "glcKhronosMustpassEsSingleConfig.hpp"
getTestRunsForSingleConfig(type, runs, configs, khronos_mustpass_es_single_config_first_cfg,
DE_LENGTH_OF_ARRAY(khronos_mustpass_es_single_config_first_cfg), mustpassDir);
}
static void getTestRunsForES(glu::ApiType type, const ConfigList& configs, vector<TestRunParams>& runs)
{
getTestRunsForAOSPEGL(runs, configs);
getTestRunsForAOSPES(runs, configs, type);
getTestRunsForNoContextES(type, runs, configs);
getTestRunsForSingleConfigES(type, runs, configs);
#include "glcKhronosMustpassEs.hpp"
for (vector<Config>::const_iterator cfgIter = configs.configs.begin(); cfgIter != configs.configs.end(); ++cfgIter)
{
const bool isFirst = cfgIter == configs.configs.begin();
const int numRunParams = isFirst ? DE_LENGTH_OF_ARRAY(khronos_mustpass_es_first_cfg) :
DE_LENGTH_OF_ARRAY(khronos_mustpass_es_other_cfg);
const RunParams* runParams = isFirst ? khronos_mustpass_es_first_cfg : khronos_mustpass_es_other_cfg;
for (int runNdx = 0; runNdx < numRunParams; runNdx++)
{
if (!glu::contextSupports(glu::ContextType(type), runParams[runNdx].apiType))
continue;
const char* apiName = getApiName(runParams[runNdx].apiType);
const int width = runParams[runNdx].surfaceWidth;
const int height = runParams[runNdx].surfaceHeight;
const int seed = runParams[runNdx].baseSeed;
TestRunParams params;
params.logFilename =
getLogFileName(apiName, runParams[runNdx].configName, cfgIter->id, runNdx, width, height, seed);
getBaseOptions(params.args, mustpassDir, apiName, runParams[runNdx].configName,
runParams[runNdx].screenRotation, width, height);
params.args.push_back(string("--deqp-base-seed=") + de::toString(seed));
appendConfigArgs(*cfgIter, params.args, runParams[runNdx].fboConfig);
runs.push_back(params);
}
}
}
static void getTestRunsForNoContextGL(glu::ApiType type, vector<TestRunParams>& runs, const ConfigList& configs)
{
#include "glcKhronosMustpassGlNocontext.hpp"
getTestRunsForNoContext(type, runs, configs, khronos_mustpass_gl_nocontext_first_cfg,
DE_LENGTH_OF_ARRAY(khronos_mustpass_gl_nocontext_first_cfg), mustpassDir);
}
static void getTestRunsForSingleConfigGL(glu::ApiType type, vector<TestRunParams>& runs, const ConfigList& configs)
{
#include "glcKhronosMustpassGlSingleConfig.hpp"
getTestRunsForSingleConfig(type, runs, configs, khronos_mustpass_gl_single_config_first_cfg,
DE_LENGTH_OF_ARRAY(khronos_mustpass_gl_single_config_first_cfg), mustpassDir);
}
static void getTestRunsForGL(glu::ApiType type, const ConfigList& configs, vector<TestRunParams>& runs)
{
getTestRunsForNoContextGL(type, runs, configs);
getTestRunsForSingleConfigGL(type, runs, configs);
#include "glcKhronosMustpassGl.hpp"
for (vector<Config>::const_iterator cfgIter = configs.configs.begin(); cfgIter != configs.configs.end(); ++cfgIter)
{
const bool isFirst = cfgIter == configs.configs.begin();
const int numRunParams = isFirst ? DE_LENGTH_OF_ARRAY(khronos_mustpass_gl_first_cfg) :
DE_LENGTH_OF_ARRAY(khronos_mustpass_gl_other_cfg);
const RunParams* runParams = isFirst ? khronos_mustpass_gl_first_cfg : khronos_mustpass_gl_other_cfg;
for (int runNdx = 0; runNdx < numRunParams; runNdx++)
{
if (type != runParams[runNdx].apiType)
continue;
const char* apiName = getApiName(runParams[runNdx].apiType);
const int width = runParams[runNdx].surfaceWidth;
const int height = runParams[runNdx].surfaceHeight;
const int seed = runParams[runNdx].baseSeed;
TestRunParams params;
params.logFilename =
getLogFileName(apiName, runParams[runNdx].configName, cfgIter->id, runNdx, width, height, seed);
getBaseOptions(params.args, mustpassDir, apiName, runParams[runNdx].configName,
runParams[runNdx].screenRotation, width, height);
params.args.push_back(string("--deqp-base-seed=") + de::toString(seed));
appendConfigArgs(*cfgIter, params.args, runParams[runNdx].fboConfig);
runs.push_back(params);
}
}
}
static void getTestRunParams(glu::ApiType type, const ConfigList& configs, vector<TestRunParams>& runs)
{
switch (type.getProfile())
{
case glu::PROFILE_CORE:
getTestRunsForGL(type, configs, runs);
break;
case glu::PROFILE_ES:
getTestRunsForES(type, configs, runs);
break;
default:
throw std::runtime_error("Unknown context type");
}
}
struct FileDeleter
{
void operator()(FILE* file) const
{
if (file)
fclose(file);
}
};
struct XmlWriterDeleter
{
void operator()(qpXmlWriter* writer) const
{
if (writer)
qpXmlWriter_destroy(writer);
}
};
static const char* getRunTypeName(glu::ApiType type)
{
if (type == glu::ApiType::es(2, 0))
return "es2";
else if (type == glu::ApiType::es(3, 0))
return "es3";
else if (type == glu::ApiType::es(3, 1))
return "es31";
else if (type == glu::ApiType::es(3, 2))
return "es32";
else if (type == glu::ApiType::core(3, 0))
return "gl30";
else if (type == glu::ApiType::core(3, 1))
return "gl31";
else if (type == glu::ApiType::core(3, 2))
return "gl32";
else if (type == glu::ApiType::core(3, 3))
return "gl33";
else if (type == glu::ApiType::core(4, 0))
return "gl40";
else if (type == glu::ApiType::core(4, 1))
return "gl41";
else if (type == glu::ApiType::core(4, 2))
return "gl42";
else if (type == glu::ApiType::core(4, 3))
return "gl43";
else if (type == glu::ApiType::core(4, 4))
return "gl44";
else if (type == glu::ApiType::core(4, 5))
return "gl45";
else if (type == glu::ApiType::core(4, 6))
return "gl46";
else
return DE_NULL;
}
#define XML_CHECK(X) \
if (!(X)) \
throw tcu::Exception("Writing XML failed")
static void writeRunSummary(const TestRunSummary& summary, const char* filename)
{
de::UniquePtr<FILE, FileDeleter> out(fopen(filename, "wb"));
if (!out)
throw tcu::Exception(string("Failed to open ") + filename);
de::UniquePtr<qpXmlWriter, XmlWriterDeleter> writer(qpXmlWriter_createFileWriter(out.get(), DE_FALSE, DE_FALSE));
if (!writer)
throw std::bad_alloc();
XML_CHECK(qpXmlWriter_startDocument(writer.get()));
{
qpXmlAttribute attribs[2];
attribs[0] = qpSetStringAttrib("Type", getRunTypeName(summary.runType));
attribs[1] = qpSetBoolAttrib("Conformant", summary.isConformant ? DE_TRUE : DE_FALSE);
XML_CHECK(qpXmlWriter_startElement(writer.get(), "Summary", DE_LENGTH_OF_ARRAY(attribs), attribs));
}
// Config run
{
qpXmlAttribute attribs[1];
attribs[0] = qpSetStringAttrib("FileName", summary.configLogFilename.c_str());
XML_CHECK(qpXmlWriter_startElement(writer.get(), "Configs", DE_LENGTH_OF_ARRAY(attribs), attribs) &&
qpXmlWriter_endElement(writer.get(), "Configs"));
}
// Record test run parameters (log filename & command line).
for (vector<TestRunParams>::const_iterator runIter = summary.runParams.begin(); runIter != summary.runParams.end();
++runIter)
{
string cmdLine;
qpXmlAttribute attribs[2];
for (vector<string>::const_iterator argIter = runIter->args.begin(); argIter != runIter->args.end(); ++argIter)
{
if (argIter != runIter->args.begin())
cmdLine += " ";
cmdLine += *argIter;
}
attribs[0] = qpSetStringAttrib("FileName", runIter->logFilename.c_str());
attribs[1] = qpSetStringAttrib("CmdLine", cmdLine.c_str());
XML_CHECK(qpXmlWriter_startElement(writer.get(), "TestRun", DE_LENGTH_OF_ARRAY(attribs), attribs) &&
qpXmlWriter_endElement(writer.get(), "TestRun"));
}
XML_CHECK(qpXmlWriter_endElement(writer.get(), "Summary"));
XML_CHECK(qpXmlWriter_endDocument(writer.get()));
}
#undef XML_CHECK
TestRunner::TestRunner(tcu::Platform& platform, tcu::Archive& archive, const char* waiverPath,
const char* logDirPath, glu::ApiType type, deUint32 flags)
: m_platform(platform)
, m_archive(archive)
, m_waiverPath(waiverPath)
, m_logDirPath(logDirPath)
, m_type(type)
, m_flags(flags)
, m_iterState(ITERATE_INIT)
, m_curSession(DE_NULL)
, m_sessionsExecuted(0)
, m_sessionsPassed(0)
, m_sessionsFailed(0)
{
}
TestRunner::~TestRunner(void)
{
delete m_curSession;
}
bool TestRunner::iterate(void)
{
switch (m_iterState)
{
case ITERATE_INIT:
init();
m_iterState = (m_sessionIter != m_runSessions.end()) ? ITERATE_INIT_SESSION : ITERATE_DEINIT;
return true;
case ITERATE_DEINIT:
deinit();
m_iterState = ITERATE_INIT;
return false;
case ITERATE_INIT_SESSION:
DE_ASSERT(m_sessionIter != m_runSessions.end());
initSession(*m_sessionIter);
if (m_flags & PRINT_SUMMARY)
m_iterState = ITERATE_DEINIT_SESSION;
else
m_iterState = ITERATE_ITERATE_SESSION;
return true;
case ITERATE_DEINIT_SESSION:
deinitSession();
++m_sessionIter;
m_iterState = (m_sessionIter != m_runSessions.end()) ? ITERATE_INIT_SESSION : ITERATE_DEINIT;
return true;
case ITERATE_ITERATE_SESSION:
if (!iterateSession())
m_iterState = ITERATE_DEINIT_SESSION;
return true;
default:
DE_ASSERT(false);
return false;
}
}
void TestRunner::init(void)
{
DE_ASSERT(m_runSessions.empty() && m_summary.runParams.empty());
tcu::print("Running %s conformance\n", glu::getApiTypeDescription(m_type));
m_summary.runType = m_type;
// Get list of configs to test.
ConfigList configList;
getDefaultConfigList(m_platform, m_type, configList);
tcu::print(" found %d compatible and %d excluded configs\n", (int)configList.configs.size(),
(int)configList.excludedConfigs.size());
// Config list run.
{
const char* configLogFilename = "configs.qpa";
TestRunParams configRun;
configRun.logFilename = configLogFilename;
configRun.args.push_back("--deqp-case=CTS-Configs.*");
m_runSessions.push_back(configRun);
m_summary.configLogFilename = configLogFilename;
}
// Conformance test type specific runs
getTestRunParams(m_type, configList, m_runSessions);
// Record run params for summary.
for (std::vector<TestRunParams>::const_iterator runIter = m_runSessions.begin() + 1; runIter != m_runSessions.end();
++runIter)
m_summary.runParams.push_back(*runIter);
// Session iterator
m_sessionIter = m_runSessions.begin();
}
void TestRunner::deinit(void)
{
// Print out totals.
bool isConformant_ = m_sessionsExecuted == m_sessionsPassed;
DE_ASSERT(m_sessionsExecuted == m_sessionsPassed + m_sessionsFailed);
tcu::print("\n%d/%d sessions passed, conformance test %s\n", m_sessionsPassed, m_sessionsExecuted,
isConformant_ ? "PASSED" : "FAILED");
m_summary.isConformant = isConformant_;
// Write out summary.
writeRunSummary(m_summary, de::FilePath::join(m_logDirPath, "cts-run-summary.xml").getPath());
m_runSessions.clear();
m_summary.clear();
}
void TestRunner::initSession(const TestRunParams& runParams)
{
DE_ASSERT(!m_curSession);
tcu::print("\n Test run %d / %d\n", (int)(m_sessionIter - m_runSessions.begin() + 1), (int)m_runSessions.size());
// Compute final args for run.
vector<string> args(runParams.args);
args.push_back(string("--deqp-log-filename=") + de::FilePath::join(m_logDirPath, runParams.logFilename).getPath());
if (!(m_flags & VERBOSE_IMAGES))
args.push_back("--deqp-log-images=disable");
if (!(m_flags & VERBOSE_SHADERS))
args.push_back("--deqp-log-shader-sources=disable");
if (!m_waiverPath.empty())
args.push_back(string("--deqp-waiver-file=") + m_waiverPath);
std::ostringstream ostr;
std::ostream_iterator<string> out_it(ostr, ", ");
std::copy(args.begin(), args.end(), out_it);
tcu::print("\n Config: %s \n\n", ostr.str().c_str());
// Translate to argc, argv
vector<const char*> argv;
argv.push_back("cts-runner"); // Dummy binary name
for (vector<string>::const_iterator i = args.begin(); i != args.end(); i++)
argv.push_back(i->c_str());
// Create session
m_curSession = new RunSession(m_platform, m_archive, (int)argv.size(), &argv[0]);
}
void TestRunner::deinitSession(void)
{
DE_ASSERT(m_curSession);
// Collect results.
// \note NotSupported is treated as pass.
const tcu::TestRunStatus& result = m_curSession->getResult();
bool isOk = result.numFailed == 0 && result.isComplete;
DE_ASSERT(result.numExecuted == result.numPassed + result.numFailed + result.numNotSupported + result.numWarnings + result.numWaived);
m_sessionsExecuted += 1;
(isOk ? m_sessionsPassed : m_sessionsFailed) += 1;
delete m_curSession;
m_curSession = DE_NULL;
}
inline bool TestRunner::iterateSession(void)
{
return m_curSession->iterate();
}
} // glcts
| 30.774614 | 141 | 0.712986 | [
"vector"
] |
ce303d54798212602711e4f2911c8fc9d54ae074 | 5,129 | cpp | C++ | moc.cpp | cephalicmarble/pleg | 0a6f6e07793a6b11aecc7ea705b315d90555e99e | [
"MIT"
] | null | null | null | moc.cpp | cephalicmarble/pleg | 0a6f6e07793a6b11aecc7ea705b315d90555e99e | [
"MIT"
] | 1 | 2021-12-08T19:47:56.000Z | 2021-12-08T19:47:56.000Z | moc.cpp | cephalicmarble/pleg | 0a6f6e07793a6b11aecc7ea705b315d90555e99e | [
"MIT"
] | null | null | null | #ifndef OBJECT_H
#define OBJECT_H
#include <iostream>
#include <list>
#include <map>
#include <boost/any.hpp>
#include <boost/type_index.hpp>
#include <boost/functional.hpp>
#include <boost/preprocessor.hpp>
using namespace boost;
using namespace std;
namespace drumlin {
#define ARG(r,data,elem) ,elem
#define VA_ARG(r,data,elem) ,va_arg(ap,elem)
typedef map<boost::any,void*> any_pointer_map_type;
struct any_pointer_map_type_find {
any_pointer_map_type_find(any_pointer_map_type &map):m_map(map){}
void *operator()(boost::any & key)
{
for(auto & any_map_ptr : m_map) {
if(key.type() == any_map_ptr.first.type())
return any_map_ptr.second;
}
return nullptr;
}
private:
any_pointer_map_type m_map;
};
template <typename... Args>
struct namedMethodMetaObject {
};
class Object;
typedef map<Object*,string> connection_map_type;
typedef map<string,void*> method_map_type;
struct metaObject {
method_map_type the_slots;
method_map_type the_signals;
method_map_type signalMap;
};
class Object
{
struct objectFactory {
list<void (*)(Object*,metaObject*)> initializers;
metaObject *create(Object *that)
{
metaObject *what = new metaObject();
for(auto &init : initializers) {
init(that,what);
}
}
};
public:
static objectFactory staticFactory;
Object(Object *m_parent = nullptr):m_metaObject(staticFactory.create(this)){}
metaObject *getMetaObject(){ return m_metaObject; }
void *get_method_object(string Identifier)
{
metaObject *meta(getMetaObject());
if(meta->the_slots.end()==meta->the_slots.find(Identifier)){
if(meta->the_signals.end()==meta->the_signals.find(Identifier)){
return nullptr;
}
return meta->the_signals.at(Identifier);
}
return meta->the_slots.at(Identifier);
}
bool connect(Object *signaller,string signal,Object *slotter,string slot)
{
if(!signaller->get_method_object(signal))
return false;
if(!slotter->get_method_object(slot))
return false;
connection_map_type *slotList(getMetaObject()->signalMap.at(signal));
slotList->insert(slotter,slot);
}
private:
Object *m_parent;
metaObject *m_metaObject;
};
//typedef function<void (Classname*,void* BOOST_PP_LIST_FOR_EACH(ARG,,BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_SIZE(ArgList),ArgList)))> signal_signature_##Identifier; \
#define SIGNAL(Identifier) Identifier##_namedMethod
#define SIGNAL(Classname,Identifier,ArgList) \
connection_map_type slotList_##Identifier; \
public: \
struct Identifier##_namedMethod { \
static void init(Object *that,metaObject *what) \
{ \
Classname *klass = ((Classname*)that); \
what->the_signals.insert({#Identifier,new Identifier##_namedMethod}); \
} \
Identifier##_namedMethod() \
{ \
Object::staticFactory.initializers.push_back({&Identifier##_namedMethod::init}); \
} \
void operator()(Classname *klass,...){ \
va_list ap; \
for(auto & pair : slotList_##Identifier) { \
va_start(ap,klass); \
auto &slot = pair.first->get_slot_##BOOST_PP_TUPLE_SIZE(ArgList)(pair.second); \
slot(klass BOOST_PP_LIST_FOR_EACH(VA_ARG,,BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_SIZE(ArgList),ArgList))); \
va_end(ap); \
} \
} \
}; \
static Identifier##_namedMethod Identifier##_namedMethod_init; \
void Identifier(Classname *klass,...) { \
}
#define SLOT(Classname,Identifier,ArgList) \
typedef function<void (Classname* BOOST_PP_LIST_FOR_EACH(ARG,,BOOST_PP_TUPLE_TO_LIST(BOOST_PP_TUPLE_SIZE(ArgList),ArgList)))> slot_signature_##Identifier; \
const slot_signature_##Identifier Identifier = nullptr; \
struct Identifier##_namedMethod { \
static void init(Object *that,metaObject *what) \
{ \
Classname *klass = ((Classname*)that); \
what->slotMap.insert({#Identifier,new Identifier##_namedMethod}); \
} \
Identifier##_namedMethod() \
{ \
Object::staticFactory.initializers.push_back({&Identifier##_namedMethod::init}); \
} \
template <class T,typename... Args> \
void operator()(Classname *klass,Args... args){ \
klass->Identifier##_impl(args...); \
} \
}; \
static Identifier##_namedMethod Identifier##_namedMethod_init; \
void Identifier##_impl ArgList;
class Class : public Object
{
public:
Class():Object(0){
connect(this,SIGNAL(signal),this,SLOT(slot));
}
void signal(int,char);
void slot(int,char);
SIGNAL(Class,signal,(int,char))
SLOT(Class,slot,(int,char))
void foo() {
signal(this,1,'c');
}
};
void Class::slot_impl(int,char)
{
cout << "twat. Keith is a twat";
}
int main()
{
Class c;
c.foo();
}
} // namespace drumlin
#endif // OBJECT_H
| 29.308571 | 166 | 0.636771 | [
"object"
] |
ce364a42fcac88e0673ee91ec5f8694a77e38639 | 5,243 | hpp | C++ | Includes/Core/FDM/FDMLinearSystem3.hpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 216 | 2017-01-25T04:34:30.000Z | 2021-07-15T12:36:06.000Z | Includes/Core/FDM/FDMLinearSystem3.hpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 323 | 2017-01-26T13:53:13.000Z | 2021-07-14T16:03:38.000Z | Includes/Core/FDM/FDMLinearSystem3.hpp | ADMTec/CubbyFlow | c71457fd04ccfaf3ef22772bab9bcec4a0a3b611 | [
"MIT"
] | 33 | 2017-01-25T05:05:49.000Z | 2021-06-17T17:30:56.000Z | // This code is based on Jet framework.
// Copyright (c) 2018 Doyub Kim
// CubbyFlow is voxel-based fluid simulation engine for computer games.
// Copyright (c) 2020 CubbyFlow Team
// Core Part: Chris Ohk, Junwoo Hwang, Jihong Sin, Seungwoo Yoo
// AI Part: Dongheon Cho, Minseo Kim
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#ifndef CUBBYFLOW_FDM_LINEAR_SYSTEM3_HPP
#define CUBBYFLOW_FDM_LINEAR_SYSTEM3_HPP
#include <Core/Array/Array.hpp>
#include <Core/Matrix/Matrix.hpp>
#include <Core/Matrix/MatrixCSR.hpp>
namespace CubbyFlow
{
//! The row of FDMMatrix3 where row corresponds to (i, j, k) grid point.
struct FDMMatrixRow3
{
//! Diagonal component of the matrix (row, row).
double center = 0.0;
//! Off-diagonal element where column refers to (i+1, j, k) grid point.
double right = 0.0;
//! Off-diagonal element where column refers to (i, j+1, k) grid point.
double up = 0.0;
//! OFf-diagonal element where column refers to (i, j, k+1) grid point.
double front = 0.0;
};
//! Vector type for 3-D finite differencing.
using FDMVector3 = Array3<double>;
//! Matrix type for 3-D finite differencing.
using FDMMatrix3 = Array3<FDMMatrixRow3>;
//! Linear system (Ax=b) for 3-D finite differencing.
struct FDMLinearSystem3
{
//! Clears all the data.
void Clear();
//! Resizes the arrays with given grid size.
void Resize(const Vector3UZ& size);
//! System matrix.
FDMMatrix3 A;
//! Solution vector.
FDMVector3 x;
//! RHS vector.
FDMVector3 b;
};
//! Compressed linear system (Ax=b) for 3-D finite differencing.
struct FDMCompressedLinearSystem3
{
//! Clears all the data.
void Clear();
//! System matrix.
MatrixCSRD A;
//! Solution vector.
VectorND x;
//! RHS vector.
VectorND b;
};
//! BLAS operator wrapper for 3-D finite differencing.
struct FDMBLAS3
{
using ScalarType = double;
using VectorType = FDMVector3;
using MatrixType = FDMMatrix3;
//! Sets entire element of given vector \p result with scalar \p s.
static void Set(ScalarType s, VectorType* result);
//! Copies entire element of given vector \p result with other vector \p v.
static void Set(const VectorType& v, VectorType* result);
//! Sets entire element of given matrix \p result with scalar \p s.
static void Set(ScalarType s, MatrixType* result);
//! Copies entire element of given matrix \p result with other matrix \p v.
static void Set(const MatrixType& m, MatrixType* result);
//! Performs dot product with vector \p a and \p b.
static double Dot(const VectorType& a, const VectorType& b);
//! Performs ax + y operation where \p a is a matrix and \p x and \p y are
//! vectors.
static void AXPlusY(double a, const VectorType& x, const VectorType& y,
VectorType* result);
//! Performs matrix-vector multiplication.
static void MVM(const MatrixType& m, const VectorType& v,
VectorType* result);
//! Computes residual vector (b - ax).
static void Residual(const MatrixType& a, const VectorType& x,
const VectorType& b, VectorType* result);
//! Returns L2-norm of the given vector \p v.
[[nodiscard]] static ScalarType L2Norm(const VectorType& v);
//! Returns Linf-norm of the given vector \p v.
[[nodiscard]] static ScalarType LInfNorm(const VectorType& v);
};
//! BLAS operator wrapper for compressed 3-D finite differencing.
struct FDMCompressedBLAS3
{
using ScalarType = double;
using VectorType = VectorND;
using MatrixType = MatrixCSRD;
//! Sets entire element of given vector \p result with scalar \p s.
static void Set(ScalarType s, VectorType* result);
//! Copies entire element of given vector \p result with other vector \p v.
static void Set(const VectorType& v, VectorType* result);
//! Sets entire element of given matrix \p result with scalar \p s.
static void Set(ScalarType s, MatrixType* result);
//! Copies entire element of given matrix \p result with other matrix \p v.
static void Set(const MatrixType& m, MatrixType* result);
//! Performs dot product with vector \p a and \p b.
static double Dot(const VectorType& a, const VectorType& b);
//! Performs ax + y operation where \p a is a matrix and \p x and \p y are
//! vectors.
static void AXPlusY(double a, const VectorType& x, const VectorType& y,
VectorType* result);
//! Performs matrix-vector multiplication.
static void MVM(const MatrixType& m, const VectorType& v,
VectorType* result);
//! Computes residual vector (b - ax).
static void Residual(const MatrixType& a, const VectorType& x,
const VectorType& b, VectorType* result);
//! Returns L2-norm of the given vector \p v.
[[nodiscard]] static ScalarType L2Norm(const VectorType& v);
//! Returns Linf-norm of the given vector \p v.
[[nodiscard]] static ScalarType LInfNorm(const VectorType& v);
};
} // namespace CubbyFlow
#endif | 32.364198 | 79 | 0.675377 | [
"vector"
] |
ce375fe33bd11ce26de21decae3083d2c378cb7a | 33,303 | cpp | C++ | Libraries/RobsJuceModules/rapt/Math/Misc/OouraFFT/fft4g.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 34 | 2017-04-19T18:26:02.000Z | 2022-02-15T17:47:26.000Z | Libraries/RobsJuceModules/rapt/Math/Misc/OouraFFT/fft4g.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 307 | 2017-05-04T21:45:01.000Z | 2022-02-03T00:59:01.000Z | Libraries/RobsJuceModules/rapt/Math/Misc/OouraFFT/fft4g.cpp | RobinSchmidt/RS-MET-Preliminary | 6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe | [
"FTL"
] | 4 | 2017-09-05T17:04:31.000Z | 2021-12-15T21:24:28.000Z | // an adapted version of the file fft4g.c from Oouras FFT package to make it work with templates
#include <math.h> // check, if necesarry..
/*
Fast Fourier/Cosine/Sine Transform
dimension :one
data length :power of 2
decimation :frequency
radix :4, 2
data :inplace
table :use
functions
cdft: Complex Discrete Fourier Transform
rdft: Real Discrete Fourier Transform
ddct: Discrete Cosine Transform
ddst: Discrete Sine Transform
dfct: Cosine Transform of RDFT (Real Symmetric DFT)
dfst: Sine Transform of RDFT (Real Anti-symmetric DFT)
function prototypes
void cdft(int, int, T *, int *, T *);
void rdft(int, int, T *, int *, T *);
void ddct(int, int, T *, int *, T *);
void ddst(int, int, T *, int *, T *);
void dfct(int, T *, T *, int *, T *);
void dfst(int, T *, T *, int *, T *);
-------- Complex DFT (Discrete Fourier Transform) --------
[definition]
<case1>
X[k] = sum_j=0^n-1 x[j]*exp(2*pi*i*j*k/n), 0<=k<n
<case2>
X[k] = sum_j=0^n-1 x[j]*exp(-2*pi*i*j*k/n), 0<=k<n
(notes: sum_j=0^n-1 is a summation from j=0 to n-1)
[usage]
<case1>
ip[0] = 0; // first time only
cdft(2*n, 1, a, ip, w);
<case2>
ip[0] = 0; // first time only
cdft(2*n, -1, a, ip, w);
[parameters]
2*n :data length (int)
n >= 1, n = power of 2
a[0...2*n-1] :input/output data (T *)
input data
a[2*j] = Re(x[j]),
a[2*j+1] = Im(x[j]), 0<=j<n
output data
a[2*k] = Re(X[k]),
a[2*k+1] = Im(X[k]), 0<=k<n
ip[0...*] :work area for bit reversal (int *)
length of ip >= 2+sqrt(n)
strictly,
length of ip >=
2+(1<<(int)(log(n+0.5)/log(2))/2).
ip[0],ip[1] are pointers of the cos/sin table.
w[0...n/2-1] :cos/sin table (T *)
w[],ip[] are initialized if ip[0] == 0.
[remark]
Inverse of
cdft(2*n, -1, a, ip, w);
is
cdft(2*n, 1, a, ip, w);
for (j = 0; j <= 2 * n - 1; j++) {
a[j] *= 1.0 / n;
}
.
-------- Real DFT / Inverse of Real DFT --------
[definition]
<case1> RDFT
R[k] = sum_j=0^n-1 a[j]*cos(2*pi*j*k/n), 0<=k<=n/2
I[k] = sum_j=0^n-1 a[j]*sin(2*pi*j*k/n), 0<k<n/2
<case2> IRDFT (excluding scale)
a[k] = (R[0] + R[n/2]*cos(pi*k))/2 +
sum_j=1^n/2-1 R[j]*cos(2*pi*j*k/n) +
sum_j=1^n/2-1 I[j]*sin(2*pi*j*k/n), 0<=k<n
[usage]
<case1>
ip[0] = 0; // first time only
rdft(n, 1, a, ip, w);
<case2>
ip[0] = 0; // first time only
rdft(n, -1, a, ip, w);
[parameters]
n :data length (int)
n >= 2, n = power of 2
a[0...n-1] :input/output data (T *)
<case1>
output data
a[2*k] = R[k], 0<=k<n/2
a[2*k+1] = I[k], 0<k<n/2
a[1] = R[n/2]
<case2>
input data
a[2*j] = R[j], 0<=j<n/2
a[2*j+1] = I[j], 0<j<n/2
a[1] = R[n/2]
ip[0...*] :work area for bit reversal (int *)
length of ip >= 2+sqrt(n/2)
strictly,
length of ip >=
2+(1<<(int)(log(n/2+0.5)/log(2))/2).
ip[0],ip[1] are pointers of the cos/sin table.
w[0...n/2-1] :cos/sin table (T *)
w[],ip[] are initialized if ip[0] == 0.
[remark]
Inverse of
rdft(n, 1, a, ip, w);
is
rdft(n, -1, a, ip, w);
for (j = 0; j <= n - 1; j++) {
a[j] *= 2.0 / n;
}
.
-------- DCT (Discrete Cosine Transform) / Inverse of DCT --------
[definition]
<case1> IDCT (excluding scale)
C[k] = sum_j=0^n-1 a[j]*cos(pi*j*(k+1/2)/n), 0<=k<n
<case2> DCT
C[k] = sum_j=0^n-1 a[j]*cos(pi*(j+1/2)*k/n), 0<=k<n
[usage]
<case1>
ip[0] = 0; // first time only
ddct(n, 1, a, ip, w);
<case2>
ip[0] = 0; // first time only
ddct(n, -1, a, ip, w);
[parameters]
n :data length (int)
n >= 2, n = power of 2
a[0...n-1] :input/output data (T *)
output data
a[k] = C[k], 0<=k<n
ip[0...*] :work area for bit reversal (int *)
length of ip >= 2+sqrt(n/2)
strictly,
length of ip >=
2+(1<<(int)(log(n/2+0.5)/log(2))/2).
ip[0],ip[1] are pointers of the cos/sin table.
w[0...n*5/4-1] :cos/sin table (T *)
w[],ip[] are initialized if ip[0] == 0.
[remark]
Inverse of
ddct(n, -1, a, ip, w);
is
a[0] *= 0.5;
ddct(n, 1, a, ip, w);
for (j = 0; j <= n - 1; j++) {
a[j] *= 2.0 / n;
}
.
-------- DST (Discrete Sine Transform) / Inverse of DST --------
[definition]
<case1> IDST (excluding scale)
S[k] = sum_j=1^n A[j]*sin(pi*j*(k+1/2)/n), 0<=k<n
<case2> DST
S[k] = sum_j=0^n-1 a[j]*sin(pi*(j+1/2)*k/n), 0<k<=n
[usage]
<case1>
ip[0] = 0; // first time only
ddst(n, 1, a, ip, w);
<case2>
ip[0] = 0; // first time only
ddst(n, -1, a, ip, w);
[parameters]
n :data length (int)
n >= 2, n = power of 2
a[0...n-1] :input/output data (T *)
<case1>
input data
a[j] = A[j], 0<j<n
a[0] = A[n]
output data
a[k] = S[k], 0<=k<n
<case2>
output data
a[k] = S[k], 0<k<n
a[0] = S[n]
ip[0...*] :work area for bit reversal (int *)
length of ip >= 2+sqrt(n/2)
strictly,
length of ip >=
2+(1<<(int)(log(n/2+0.5)/log(2))/2).
ip[0],ip[1] are pointers of the cos/sin table.
w[0...n*5/4-1] :cos/sin table (T *)
w[],ip[] are initialized if ip[0] == 0.
[remark]
Inverse of
ddst(n, -1, a, ip, w);
is
a[0] *= 0.5;
ddst(n, 1, a, ip, w);
for (j = 0; j <= n - 1; j++) {
a[j] *= 2.0 / n;
}
.
-------- Cosine Transform of RDFT (Real Symmetric DFT) --------
[definition]
C[k] = sum_j=0^n a[j]*cos(pi*j*k/n), 0<=k<=n
[usage]
ip[0] = 0; // first time only
dfct(n, a, t, ip, w);
[parameters]
n :data length - 1 (int)
n >= 2, n = power of 2
a[0...n] :input/output data (T *)
output data
a[k] = C[k], 0<=k<=n
t[0...n/2] :work area (T *)
ip[0...*] :work area for bit reversal (int *)
length of ip >= 2+sqrt(n/4)
strictly,
length of ip >=
2+(1<<(int)(log(n/4+0.5)/log(2))/2).
ip[0],ip[1] are pointers of the cos/sin table.
w[0...n*5/8-1] :cos/sin table (T *)
w[],ip[] are initialized if ip[0] == 0.
[remark]
Inverse of
a[0] *= 0.5;
a[n] *= 0.5;
dfct(n, a, t, ip, w);
is
a[0] *= 0.5;
a[n] *= 0.5;
dfct(n, a, t, ip, w);
for (j = 0; j <= n; j++) {
a[j] *= 2.0 / n;
}
.
-------- Sine Transform of RDFT (Real Anti-symmetric DFT) --------
[definition]
S[k] = sum_j=1^n-1 a[j]*sin(pi*j*k/n), 0<k<n
[usage]
ip[0] = 0; // first time only
dfst(n, a, t, ip, w);
[parameters]
n :data length + 1 (int)
n >= 2, n = power of 2
a[0...n-1] :input/output data (T *)
output data
a[k] = S[k], 0<k<n
(a[0] is used for work area)
t[0...n/2-1] :work area (T *)
ip[0...*] :work area for bit reversal (int *)
length of ip >= 2+sqrt(n/4)
strictly,
length of ip >=
2+(1<<(int)(log(n/4+0.5)/log(2))/2).
ip[0],ip[1] are pointers of the cos/sin table.
w[0...n*5/8-1] :cos/sin table (T *)
w[],ip[] are initialized if ip[0] == 0.
[remark]
Inverse of
dfst(n, a, t, ip, w);
is
dfst(n, a, t, ip, w);
for (j = 1; j <= n - 1; j++) {
a[j] *= 2.0 / n;
}
.
Appendix :
The cos/sin table is recalculated when the larger table required.
w[] and ip[] are compatible with all routines.
*/
// -------- child routines --------
template<class T>
void bitrv2(int n, int *ip, T *a)
{
int j, j1, k, k1, l, m, m2;
T xr, xi, yr, yi;
ip[0] = 0;
l = n;
m = 1;
while((m << 3) < l) {
l >>= 1;
for(j = 0; j < m; j++) {
ip[m + j] = ip[j] + l;
}
m <<= 1;
}
m2 = 2 * m;
if((m << 3) == l) {
for(k = 0; k < m; k++) {
for(j = 0; j < k; j++) {
j1 = 2 * j + ip[k];
k1 = 2 * k + ip[j];
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 += 2 * m2;
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 -= m2;
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 += 2 * m2;
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
}
j1 = 2 * k + m2 + ip[k];
k1 = j1 + m2;
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
}
}
else {
for(k = 1; k < m; k++) {
for(j = 0; j < k; j++) {
j1 = 2 * j + ip[k];
k1 = 2 * k + ip[j];
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 += m2;
xr = a[j1];
xi = a[j1 + 1];
yr = a[k1];
yi = a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
}
}
}
}
template<class T>
void bitrv2conj(int n, int *ip, T *a)
{
int j, j1, k, k1, l, m, m2;
T xr, xi, yr, yi;
ip[0] = 0;
l = n;
m = 1;
while((m << 3) < l) {
l >>= 1;
for(j = 0; j < m; j++) {
ip[m + j] = ip[j] + l;
}
m <<= 1;
}
m2 = 2 * m;
if((m << 3) == l) {
for(k = 0; k < m; k++) {
for(j = 0; j < k; j++) {
j1 = 2 * j + ip[k];
k1 = 2 * k + ip[j];
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 += 2 * m2;
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 -= m2;
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 += 2 * m2;
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
}
k1 = 2 * k + ip[k];
a[k1 + 1] = -a[k1 + 1];
j1 = k1 + m2;
k1 = j1 + m2;
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
k1 += m2;
a[k1 + 1] = -a[k1 + 1];
}
}
else {
a[1] = -a[1];
a[m2 + 1] = -a[m2 + 1];
for(k = 1; k < m; k++) {
for(j = 0; j < k; j++) {
j1 = 2 * j + ip[k];
k1 = 2 * k + ip[j];
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
j1 += m2;
k1 += m2;
xr = a[j1];
xi = -a[j1 + 1];
yr = a[k1];
yi = -a[k1 + 1];
a[j1] = yr;
a[j1 + 1] = yi;
a[k1] = xr;
a[k1 + 1] = xi;
}
k1 = 2 * k + ip[k];
a[k1 + 1] = -a[k1 + 1];
a[k1 + m2 + 1] = -a[k1 + m2 + 1];
}
}
}
template<class T>
void cft1st(int n, T *a, T *w)
{
int j, k1, k2;
T wk1r, wk1i, wk2r, wk2i, wk3r, wk3i;
T x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;
x0r = a[0] + a[2];
x0i = a[1] + a[3];
x1r = a[0] - a[2];
x1i = a[1] - a[3];
x2r = a[4] + a[6];
x2i = a[5] + a[7];
x3r = a[4] - a[6];
x3i = a[5] - a[7];
a[0] = x0r + x2r;
a[1] = x0i + x2i;
a[4] = x0r - x2r;
a[5] = x0i - x2i;
a[2] = x1r - x3i;
a[3] = x1i + x3r;
a[6] = x1r + x3i;
a[7] = x1i - x3r;
wk1r = w[2];
x0r = a[8] + a[10];
x0i = a[9] + a[11];
x1r = a[8] - a[10];
x1i = a[9] - a[11];
x2r = a[12] + a[14];
x2i = a[13] + a[15];
x3r = a[12] - a[14];
x3i = a[13] - a[15];
a[8] = x0r + x2r;
a[9] = x0i + x2i;
a[12] = x2i - x0i;
a[13] = x0r - x2r;
x0r = x1r - x3i;
x0i = x1i + x3r;
a[10] = wk1r * (x0r - x0i);
a[11] = wk1r * (x0r + x0i);
x0r = x3i + x1r;
x0i = x3r - x1i;
a[14] = wk1r * (x0i - x0r);
a[15] = wk1r * (x0i + x0r);
k1 = 0;
for(j = 16; j < n; j += 16) {
k1 += 2;
k2 = 2 * k1;
wk2r = w[k1];
wk2i = w[k1 + 1];
wk1r = w[k2];
wk1i = w[k2 + 1];
wk3r = wk1r - 2 * wk2i * wk1i;
wk3i = 2 * wk2i * wk1r - wk1i;
x0r = a[j] + a[j + 2];
x0i = a[j + 1] + a[j + 3];
x1r = a[j] - a[j + 2];
x1i = a[j + 1] - a[j + 3];
x2r = a[j + 4] + a[j + 6];
x2i = a[j + 5] + a[j + 7];
x3r = a[j + 4] - a[j + 6];
x3i = a[j + 5] - a[j + 7];
a[j] = x0r + x2r;
a[j + 1] = x0i + x2i;
x0r -= x2r;
x0i -= x2i;
a[j + 4] = wk2r * x0r - wk2i * x0i;
a[j + 5] = wk2r * x0i + wk2i * x0r;
x0r = x1r - x3i;
x0i = x1i + x3r;
a[j + 2] = wk1r * x0r - wk1i * x0i;
a[j + 3] = wk1r * x0i + wk1i * x0r;
x0r = x1r + x3i;
x0i = x1i - x3r;
a[j + 6] = wk3r * x0r - wk3i * x0i;
a[j + 7] = wk3r * x0i + wk3i * x0r;
wk1r = w[k2 + 2];
wk1i = w[k2 + 3];
wk3r = wk1r - 2 * wk2r * wk1i;
wk3i = 2 * wk2r * wk1r - wk1i;
x0r = a[j + 8] + a[j + 10];
x0i = a[j + 9] + a[j + 11];
x1r = a[j + 8] - a[j + 10];
x1i = a[j + 9] - a[j + 11];
x2r = a[j + 12] + a[j + 14];
x2i = a[j + 13] + a[j + 15];
x3r = a[j + 12] - a[j + 14];
x3i = a[j + 13] - a[j + 15];
a[j + 8] = x0r + x2r;
a[j + 9] = x0i + x2i;
x0r -= x2r;
x0i -= x2i;
a[j + 12] = -wk2i * x0r - wk2r * x0i;
a[j + 13] = -wk2i * x0i + wk2r * x0r;
x0r = x1r - x3i;
x0i = x1i + x3r;
a[j + 10] = wk1r * x0r - wk1i * x0i;
a[j + 11] = wk1r * x0i + wk1i * x0r;
x0r = x1r + x3i;
x0i = x1i - x3r;
a[j + 14] = wk3r * x0r - wk3i * x0i;
a[j + 15] = wk3r * x0i + wk3i * x0r;
}
}
template<class T>
void cftmdl(int n, int l, T *a, T *w)
{
int j, j1, j2, j3, k, k1, k2, m, m2;
T wk1r, wk1i, wk2r, wk2i, wk3r, wk3i;
T x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;
m = l << 2;
for(j = 0; j < l; j += 2) {
j1 = j + l;
j2 = j1 + l;
j3 = j2 + l;
x0r = a[j] + a[j1];
x0i = a[j + 1] + a[j1 + 1];
x1r = a[j] - a[j1];
x1i = a[j + 1] - a[j1 + 1];
x2r = a[j2] + a[j3];
x2i = a[j2 + 1] + a[j3 + 1];
x3r = a[j2] - a[j3];
x3i = a[j2 + 1] - a[j3 + 1];
a[j] = x0r + x2r;
a[j + 1] = x0i + x2i;
a[j2] = x0r - x2r;
a[j2 + 1] = x0i - x2i;
a[j1] = x1r - x3i;
a[j1 + 1] = x1i + x3r;
a[j3] = x1r + x3i;
a[j3 + 1] = x1i - x3r;
}
wk1r = w[2];
for(j = m; j < l + m; j += 2) {
j1 = j + l;
j2 = j1 + l;
j3 = j2 + l;
x0r = a[j] + a[j1];
x0i = a[j + 1] + a[j1 + 1];
x1r = a[j] - a[j1];
x1i = a[j + 1] - a[j1 + 1];
x2r = a[j2] + a[j3];
x2i = a[j2 + 1] + a[j3 + 1];
x3r = a[j2] - a[j3];
x3i = a[j2 + 1] - a[j3 + 1];
a[j] = x0r + x2r;
a[j + 1] = x0i + x2i;
a[j2] = x2i - x0i;
a[j2 + 1] = x0r - x2r;
x0r = x1r - x3i;
x0i = x1i + x3r;
a[j1] = wk1r * (x0r - x0i);
a[j1 + 1] = wk1r * (x0r + x0i);
x0r = x3i + x1r;
x0i = x3r - x1i;
a[j3] = wk1r * (x0i - x0r);
a[j3 + 1] = wk1r * (x0i + x0r);
}
k1 = 0;
m2 = 2 * m;
for(k = m2; k < n; k += m2) {
k1 += 2;
k2 = 2 * k1;
wk2r = w[k1];
wk2i = w[k1 + 1];
wk1r = w[k2];
wk1i = w[k2 + 1];
wk3r = wk1r - 2 * wk2i * wk1i;
wk3i = 2 * wk2i * wk1r - wk1i;
for(j = k; j < l + k; j += 2) {
j1 = j + l;
j2 = j1 + l;
j3 = j2 + l;
x0r = a[j] + a[j1];
x0i = a[j + 1] + a[j1 + 1];
x1r = a[j] - a[j1];
x1i = a[j + 1] - a[j1 + 1];
x2r = a[j2] + a[j3];
x2i = a[j2 + 1] + a[j3 + 1];
x3r = a[j2] - a[j3];
x3i = a[j2 + 1] - a[j3 + 1];
a[j] = x0r + x2r;
a[j + 1] = x0i + x2i;
x0r -= x2r;
x0i -= x2i;
a[j2] = wk2r * x0r - wk2i * x0i;
a[j2 + 1] = wk2r * x0i + wk2i * x0r;
x0r = x1r - x3i;
x0i = x1i + x3r;
a[j1] = wk1r * x0r - wk1i * x0i;
a[j1 + 1] = wk1r * x0i + wk1i * x0r;
x0r = x1r + x3i;
x0i = x1i - x3r;
a[j3] = wk3r * x0r - wk3i * x0i;
a[j3 + 1] = wk3r * x0i + wk3i * x0r;
}
wk1r = w[k2 + 2];
wk1i = w[k2 + 3];
wk3r = wk1r - 2 * wk2r * wk1i;
wk3i = 2 * wk2r * wk1r - wk1i;
for(j = k + m; j < l + (k + m); j += 2) {
j1 = j + l;
j2 = j1 + l;
j3 = j2 + l;
x0r = a[j] + a[j1];
x0i = a[j + 1] + a[j1 + 1];
x1r = a[j] - a[j1];
x1i = a[j + 1] - a[j1 + 1];
x2r = a[j2] + a[j3];
x2i = a[j2 + 1] + a[j3 + 1];
x3r = a[j2] - a[j3];
x3i = a[j2 + 1] - a[j3 + 1];
a[j] = x0r + x2r;
a[j + 1] = x0i + x2i;
x0r -= x2r;
x0i -= x2i;
a[j2] = -wk2i * x0r - wk2r * x0i;
a[j2 + 1] = -wk2i * x0i + wk2r * x0r;
x0r = x1r - x3i;
x0i = x1i + x3r;
a[j1] = wk1r * x0r - wk1i * x0i;
a[j1 + 1] = wk1r * x0i + wk1i * x0r;
x0r = x1r + x3i;
x0i = x1i - x3r;
a[j3] = wk3r * x0r - wk3i * x0i;
a[j3 + 1] = wk3r * x0i + wk3i * x0r;
}
}
}
template<class T>
void rftfsub(int n, T *a, int nc, T *c)
{
int j, k, kk, ks, m;
T wkr, wki, xr, xi, yr, yi;
m = n >> 1;
ks = 2 * nc / m;
kk = 0;
for(j = 2; j < m; j += 2) {
k = n - j;
kk += ks;
wkr = T(0.5) - c[nc - kk];
wki = c[kk];
xr = a[j] - a[k];
xi = a[j + 1] + a[k + 1];
yr = wkr * xr - wki * xi;
yi = wkr * xi + wki * xr;
a[j] -= yr;
a[j + 1] -= yi;
a[k] += yr;
a[k + 1] -= yi;
}
}
template<class T>
void rftbsub(int n, T *a, int nc, T *c)
{
int j, k, kk, ks, m;
T wkr, wki, xr, xi, yr, yi;
a[1] = -a[1];
m = n >> 1;
ks = 2 * nc / m;
kk = 0;
for(j = 2; j < m; j += 2) {
k = n - j;
kk += ks;
wkr = T(0.5) - c[nc - kk];
wki = c[kk];
xr = a[j] - a[k];
xi = a[j + 1] + a[k + 1];
yr = wkr * xr + wki * xi;
yi = wkr * xi - wki * xr;
a[j] -= yr;
a[j + 1] = yi - a[j + 1];
a[k] += yr;
a[k + 1] = yi - a[k + 1];
}
a[m + 1] = -a[m + 1];
}
template<class T>
void dctsub(int n, T *a, int nc, T *c)
{
int j, k, kk, ks, m;
T wkr, wki, xr;
m = n >> 1;
ks = nc / n;
kk = 0;
for(j = 1; j < m; j++) {
k = n - j;
kk += ks;
wkr = c[kk] - c[nc - kk];
wki = c[kk] + c[nc - kk];
xr = wki * a[j] - wkr * a[k];
a[j] = wkr * a[j] + wki * a[k];
a[k] = xr;
}
a[m] *= c[0];
}
template<class T>
void dstsub(int n, T *a, int nc, T *c)
{
int j, k, kk, ks, m;
T wkr, wki, xr;
m = n >> 1;
ks = nc / n;
kk = 0;
for(j = 1; j < m; j++) {
k = n - j;
kk += ks;
wkr = c[kk] - c[nc - kk];
wki = c[kk] + c[nc - kk];
xr = wki * a[k] - wkr * a[j];
a[k] = wkr * a[k] + wki * a[j];
a[j] = xr;
}
a[m] *= c[0];
}
// -------- initializing routines --------
template<class T>
void makewt(int nw, int *ip, T *w)
{
//void bitrv2(int n, int *ip, T *a);
int j, nwh;
T delta, x, y;
ip[0] = nw;
ip[1] = 1;
if(nw > 2) {
nwh = nw >> 1;
delta = T(atan(1.0)) / nwh;
w[0] = 1;
w[1] = 0;
w[nwh] = cos(delta * nwh);
w[nwh + 1] = w[nwh];
if(nwh > 2) {
for(j = 2; j < nwh; j += 2) {
x = cos(delta * j);
y = sin(delta * j);
w[j] = x;
w[j + 1] = y;
w[nw - j] = y;
w[nw - j + 1] = x;
}
bitrv2(nw, ip + 2, w);
}
}
}
template<class T>
void makect(int nc, int *ip, T *c)
{
int j, nch;
T delta;
ip[1] = nc;
if(nc > 1) {
nch = nc >> 1;
delta = T(atan(1.0)) / nch;
c[0] = cos(delta * nch);
c[nch] = T(0.5) * c[0];
for(j = 1; j < nch; j++) {
c[j] = T(0.5) * cos(delta * j);
c[nc - j] = T(0.5) * sin(delta * j);
}
}
}
// -------- sub FFTs (?) --------
template<class T>
void cftfsub(int n, T *a, T *w)
{
//void cft1st(int n, T *a, T *w);
//void cftmdl(int n, int l, T *a, T *w);
int j, j1, j2, j3, l;
T x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;
l = 2;
if(n > 8) {
cft1st(n, a, w);
l = 8;
while((l << 2) < n) {
cftmdl(n, l, a, w);
l <<= 2;
}
}
if((l << 2) == n) {
for(j = 0; j < l; j += 2) {
j1 = j + l;
j2 = j1 + l;
j3 = j2 + l;
x0r = a[j] + a[j1];
x0i = a[j + 1] + a[j1 + 1];
x1r = a[j] - a[j1];
x1i = a[j + 1] - a[j1 + 1];
x2r = a[j2] + a[j3];
x2i = a[j2 + 1] + a[j3 + 1];
x3r = a[j2] - a[j3];
x3i = a[j2 + 1] - a[j3 + 1];
a[j] = x0r + x2r;
a[j + 1] = x0i + x2i;
a[j2] = x0r - x2r;
a[j2 + 1] = x0i - x2i;
a[j1] = x1r - x3i;
a[j1 + 1] = x1i + x3r;
a[j3] = x1r + x3i;
a[j3 + 1] = x1i - x3r;
}
}
else {
for(j = 0; j < l; j += 2) {
j1 = j + l;
x0r = a[j] - a[j1];
x0i = a[j + 1] - a[j1 + 1];
a[j] += a[j1];
a[j + 1] += a[j1 + 1];
a[j1] = x0r;
a[j1 + 1] = x0i;
}
}
}
template<class T>
void cftbsub(int n, T *a, T *w)
{
//void cft1st(int n, T *a, T *w);
//void cftmdl(int n, int l, T *a, T *w);
int j, j1, j2, j3, l;
T x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;
l = 2;
if(n > 8) {
cft1st(n, a, w);
l = 8;
while((l << 2) < n) {
cftmdl(n, l, a, w);
l <<= 2;
}
}
if((l << 2) == n) {
for(j = 0; j < l; j += 2) {
j1 = j + l;
j2 = j1 + l;
j3 = j2 + l;
x0r = a[j] + a[j1];
x0i = -a[j + 1] - a[j1 + 1];
x1r = a[j] - a[j1];
x1i = -a[j + 1] + a[j1 + 1];
x2r = a[j2] + a[j3];
x2i = a[j2 + 1] + a[j3 + 1];
x3r = a[j2] - a[j3];
x3i = a[j2 + 1] - a[j3 + 1];
a[j] = x0r + x2r;
a[j + 1] = x0i - x2i;
a[j2] = x0r - x2r;
a[j2 + 1] = x0i + x2i;
a[j1] = x1r - x3i;
a[j1 + 1] = x1i - x3r;
a[j3] = x1r + x3i;
a[j3 + 1] = x1i + x3r;
}
}
else {
for(j = 0; j < l; j += 2) {
j1 = j + l;
x0r = a[j] - a[j1];
x0i = -a[j + 1] + a[j1 + 1];
a[j] += a[j1];
a[j + 1] = -a[j + 1] - a[j1 + 1];
a[j1] = x0r;
a[j1 + 1] = x0i;
}
}
}
// -------- main routines --------
template<class T>
void cdft(int n, int isgn, T *a, int *ip, T *w)
{
//void makewt(int nw, int *ip, T *w);
//void bitrv2(int n, int *ip, T *a);
//void bitrv2conj(int n, int *ip, T *a);
//void cftfsub(int n, T *a, T *w);
//void cftbsub(int n, T *a, T *w);
if(n > (ip[0] << 2)) {
makewt(n >> 2, ip, w);
}
if(n > 4) {
if(isgn >= 0) {
bitrv2(n, ip + 2, a);
cftfsub(n, a, w);
}
else {
bitrv2conj(n, ip + 2, a);
cftbsub(n, a, w);
}
}
else if(n == 4) {
cftfsub(n, a, w);
}
}
template<class T>
void rdft(int n, int isgn, T *a, int *ip, T *w)
{
//void makewt(int nw, int *ip, T *w);
//void makect(int nc, int *ip, T *c);
//void bitrv2(int n, int *ip, T *a);
//void cftfsub(int n, T *a, T *w);
//void cftbsub(int n, T *a, T *w);
//void rftfsub(int n, T *a, int nc, T *c);
//void rftbsub(int n, T *a, int nc, T *c);
int nw, nc;
T xi;
nw = ip[0];
if(n > (nw << 2)) {
nw = n >> 2;
makewt(nw, ip, w);
}
nc = ip[1];
if(n > (nc << 2)) {
nc = n >> 2;
makect(nc, ip, w + nw);
}
if(isgn >= 0) {
if(n > 4) {
bitrv2(n, ip + 2, a);
cftfsub(n, a, w);
rftfsub(n, a, nc, w + nw);
}
else if(n == 4) {
cftfsub(n, a, w);
}
xi = a[0] - a[1];
a[0] += a[1];
a[1] = xi;
}
else {
a[1] = T(0.5) * (a[0] - a[1]);
a[0] -= a[1];
if(n > 4) {
rftbsub(n, a, nc, w + nw);
bitrv2(n, ip + 2, a);
cftbsub(n, a, w);
}
else if(n == 4) {
cftfsub(n, a, w);
}
}
}
template<class T>
void ddct(int n, int isgn, T *a, int *ip, T *w)
{
//void makewt(int nw, int *ip, T *w);
//void makect(int nc, int *ip, T *c);
//void bitrv2(int n, int *ip, T *a);
//void cftfsub(int n, T *a, T *w);
//void cftbsub(int n, T *a, T *w);
//void rftfsub(int n, T *a, int nc, T *c);
//void rftbsub(int n, T *a, int nc, T *c);
//void dctsub(int n, T *a, int nc, T *c);
int j, nw, nc;
T xr;
nw = ip[0];
if(n > (nw << 2)) {
nw = n >> 2;
makewt(nw, ip, w);
}
nc = ip[1];
if(n > nc) {
nc = n;
makect(nc, ip, w + nw);
}
if(isgn < 0) {
xr = a[n - 1];
for(j = n - 2; j >= 2; j -= 2) {
a[j + 1] = a[j] - a[j - 1];
a[j] += a[j - 1];
}
a[1] = a[0] - xr;
a[0] += xr;
if(n > 4) {
rftbsub(n, a, nc, w + nw);
bitrv2(n, ip + 2, a);
cftbsub(n, a, w);
}
else if(n == 4) {
cftfsub(n, a, w);
}
}
dctsub(n, a, nc, w + nw);
if(isgn >= 0) {
if(n > 4) {
bitrv2(n, ip + 2, a);
cftfsub(n, a, w);
rftfsub(n, a, nc, w + nw);
}
else if(n == 4) {
cftfsub(n, a, w);
}
xr = a[0] - a[1];
a[0] += a[1];
for(j = 2; j < n; j += 2) {
a[j - 1] = a[j] - a[j + 1];
a[j] += a[j + 1];
}
a[n - 1] = xr;
}
}
template<class T>
void ddst(int n, int isgn, T *a, int *ip, T *w)
{
//void makewt(int nw, int *ip, T *w);
//void makect(int nc, int *ip, T *c);
//void bitrv2(int n, int *ip, T *a);
//void cftfsub(int n, T *a, T *w);
//void cftbsub(int n, T *a, T *w);
//void rftfsub(int n, T *a, int nc, T *c);
//void rftbsub(int n, T *a, int nc, T *c);
//void dstsub(int n, T *a, int nc, T *c);
int j, nw, nc;
T xr;
nw = ip[0];
if(n > (nw << 2)) {
nw = n >> 2;
makewt(nw, ip, w);
}
nc = ip[1];
if(n > nc) {
nc = n;
makect(nc, ip, w + nw);
}
if(isgn < 0) {
xr = a[n - 1];
for(j = n - 2; j >= 2; j -= 2) {
a[j + 1] = -a[j] - a[j - 1];
a[j] -= a[j - 1];
}
a[1] = a[0] + xr;
a[0] -= xr;
if(n > 4) {
rftbsub(n, a, nc, w + nw);
bitrv2(n, ip + 2, a);
cftbsub(n, a, w);
}
else if(n == 4) {
cftfsub(n, a, w);
}
}
dstsub(n, a, nc, w + nw);
if(isgn >= 0) {
if(n > 4) {
bitrv2(n, ip + 2, a);
cftfsub(n, a, w);
rftfsub(n, a, nc, w + nw);
}
else if(n == 4) {
cftfsub(n, a, w);
}
xr = a[0] - a[1];
a[0] += a[1];
for(j = 2; j < n; j += 2) {
a[j - 1] = -a[j] - a[j + 1];
a[j] -= a[j + 1];
}
a[n - 1] = -xr;
}
}
template<class T>
void dfct(int n, T *a, T *t, int *ip, T *w)
{
//void makewt(int nw, int *ip, T *w);
//void makect(int nc, int *ip, T *c);
//void bitrv2(int n, int *ip, T *a);
//void cftfsub(int n, T *a, T *w);
//void rftfsub(int n, T *a, int nc, T *c);
//void dctsub(int n, T *a, int nc, T *c);
int j, k, l, m, mh, nw, nc;
T xr, xi, yr, yi;
nw = ip[0];
if(n > (nw << 3)) {
nw = n >> 3;
makewt(nw, ip, w);
}
nc = ip[1];
if(n > (nc << 1)) {
nc = n >> 1;
makect(nc, ip, w + nw);
}
m = n >> 1;
yi = a[m];
xi = a[0] + a[n];
a[0] -= a[n];
t[0] = xi - yi;
t[m] = xi + yi;
if(n > 2) {
mh = m >> 1;
for(j = 1; j < mh; j++) {
k = m - j;
xr = a[j] - a[n - j];
xi = a[j] + a[n - j];
yr = a[k] - a[n - k];
yi = a[k] + a[n - k];
a[j] = xr;
a[k] = yr;
t[j] = xi - yi;
t[k] = xi + yi;
}
t[mh] = a[mh] + a[n - mh];
a[mh] -= a[n - mh];
dctsub(m, a, nc, w + nw);
if(m > 4) {
bitrv2(m, ip + 2, a);
cftfsub(m, a, w);
rftfsub(m, a, nc, w + nw);
}
else if(m == 4) {
cftfsub(m, a, w);
}
a[n - 1] = a[0] - a[1];
a[1] = a[0] + a[1];
for(j = m - 2; j >= 2; j -= 2) {
a[2 * j + 1] = a[j] + a[j + 1];
a[2 * j - 1] = a[j] - a[j + 1];
}
l = 2;
m = mh;
while(m >= 2) {
dctsub(m, t, nc, w + nw);
if(m > 4) {
bitrv2(m, ip + 2, t);
cftfsub(m, t, w);
rftfsub(m, t, nc, w + nw);
}
else if(m == 4) {
cftfsub(m, t, w);
}
a[n - l] = t[0] - t[1];
a[l] = t[0] + t[1];
k = 0;
for(j = 2; j < m; j += 2) {
k += l << 2;
a[k - l] = t[j] - t[j + 1];
a[k + l] = t[j] + t[j + 1];
}
l <<= 1;
mh = m >> 1;
for(j = 0; j < mh; j++) {
k = m - j;
t[j] = t[m + k] - t[m + j];
t[k] = t[m + k] + t[m + j];
}
t[mh] = t[m + mh];
m = mh;
}
a[l] = t[0];
a[n] = t[2] - t[1];
a[0] = t[2] + t[1];
}
else {
a[1] = a[0];
a[2] = t[0];
a[0] = t[1];
}
}
template<class T>
void dfst(int n, T *a, T *t, int *ip, T *w)
{
//void makewt(int nw, int *ip, T *w);
//void makect(int nc, int *ip, T *c);
//void bitrv2(int n, int *ip, T *a);
//void cftfsub(int n, T *a, T *w);
//void rftfsub(int n, T *a, int nc, T *c);
//void dstsub(int n, T *a, int nc, T *c);
int j, k, l, m, mh, nw, nc;
T xr, xi, yr, yi;
nw = ip[0];
if(n > (nw << 3)) {
nw = n >> 3;
makewt(nw, ip, w);
}
nc = ip[1];
if(n > (nc << 1)) {
nc = n >> 1;
makect(nc, ip, w + nw);
}
if(n > 2) {
m = n >> 1;
mh = m >> 1;
for(j = 1; j < mh; j++) {
k = m - j;
xr = a[j] + a[n - j];
xi = a[j] - a[n - j];
yr = a[k] + a[n - k];
yi = a[k] - a[n - k];
a[j] = xr;
a[k] = yr;
t[j] = xi + yi;
t[k] = xi - yi;
}
t[0] = a[mh] - a[n - mh];
a[mh] += a[n - mh];
a[0] = a[m];
dstsub(m, a, nc, w + nw);
if(m > 4) {
bitrv2(m, ip + 2, a);
cftfsub(m, a, w);
rftfsub(m, a, nc, w + nw);
}
else if(m == 4) {
cftfsub(m, a, w);
}
a[n - 1] = a[1] - a[0];
a[1] = a[0] + a[1];
for(j = m - 2; j >= 2; j -= 2) {
a[2 * j + 1] = a[j] - a[j + 1];
a[2 * j - 1] = -a[j] - a[j + 1];
}
l = 2;
m = mh;
while(m >= 2) {
dstsub(m, t, nc, w + nw);
if(m > 4) {
bitrv2(m, ip + 2, t);
cftfsub(m, t, w);
rftfsub(m, t, nc, w + nw);
}
else if(m == 4) {
cftfsub(m, t, w);
}
a[n - l] = t[1] - t[0];
a[l] = t[0] + t[1];
k = 0;
for(j = 2; j < m; j += 2) {
k += l << 2;
a[k - l] = -t[j] - t[j + 1];
a[k + l] = t[j] - t[j + 1];
}
l <<= 1;
mh = m >> 1;
for(j = 1; j < mh; j++) {
k = m - j;
t[j] = t[m + k] + t[m + j];
t[k] = t[m + k] - t[m + j];
}
t[0] = t[m + mh];
m = mh;
}
a[l] = t[0];
}
a[0] = 0;
}
| 24.362107 | 96 | 0.349548 | [
"transform"
] |
ce39e05f36b4c797384729a3d9709157f21be9cd | 1,579 | cc | C++ | src/future.cc | zcbenz/node-fork | b9b3923406ed9d43545932bb301e96a1746e8366 | [
"MIT"
] | 2 | 2015-11-10T22:53:01.000Z | 2018-02-18T21:51:19.000Z | src/future.cc | zcbenz/node-fork | b9b3923406ed9d43545932bb301e96a1746e8366 | [
"MIT"
] | null | null | null | src/future.cc | zcbenz/node-fork | b9b3923406ed9d43545932bb301e96a1746e8366 | [
"MIT"
] | null | null | null | #include "future.h"
#include "process.h"
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define THROW_BAD_PROCESS \
ThrowException(String::New("Future has already been got"))
namespace Fork {
static Handle<Value> get (const Arguments& args);
Handle<Value> Future (const Arguments& args) {
HandleScope scope;
if (args.Length () == 1 && !args[0]->IsFunction ())
return THROW_BAD_ARGS ;
Process *process = Process::New (args);
if (!process)
return ThrowException (Exception::Error (
String::New (strerror (errno))));
Handle<ObjectTemplate> tpl = ObjectTemplate::New ();
tpl->SetInternalFieldCount (1);
Handle<Object> future = tpl->NewInstance ();
future->SetPointerInInternalField (0, process);
future->Set (String::New ("pid"), Integer::New (process->Pid ()));
future->Set (String::New ("get"), FunctionTemplate::New (get)->GetFunction ());
// We won't wait for child until client calls `future.get()`
return scope.Close (future);
}
static Handle<Value> get (const Arguments& args) {
HandleScope scope;
Process *process = static_cast<Process*> (
args.Holder ()->GetPointerFromInternalField (0));
if (!process)
return THROW_BAD_PROCESS;
// Wait form child
waitpid (process->Pid (), NULL, 0);
// Get result
Handle<Object> result = process->End ();
// Mark as ended
args.Holder ()->SetPointerInInternalField (0, NULL);
return scope.Close (result->Get (String::New ("data")));
}
}
| 25.467742 | 83 | 0.640912 | [
"object"
] |
ce3af92fbed573cd8763a2a16f617c91da913384 | 167,074 | cpp | C++ | IGC/AdaptorOCL/SPIRV/SPIRVReader.cpp | ConiKost/intel-graphics-compiler | f5227c9658da35d08d7f711552ebcb12638ebc18 | [
"Intel",
"MIT"
] | null | null | null | IGC/AdaptorOCL/SPIRV/SPIRVReader.cpp | ConiKost/intel-graphics-compiler | f5227c9658da35d08d7f711552ebcb12638ebc18 | [
"Intel",
"MIT"
] | null | null | null | IGC/AdaptorOCL/SPIRV/SPIRVReader.cpp | ConiKost/intel-graphics-compiler | f5227c9658da35d08d7f711552ebcb12638ebc18 | [
"Intel",
"MIT"
] | null | null | null | /*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
/*========================== begin_copyright_notice ============================
This file is distributed under the University of Illinois Open Source License.
See LICENSE.TXT for details.
============================= end_copyright_notice ===========================*/
/*========================== begin_copyright_notice ============================
Copyright (C) 2014 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal with the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the documentation
and/or other materials provided with the distribution.
Neither the names of Advanced Micro Devices, Inc., nor the names of its
contributors may be used to endorse or promote products derived from this
Software without specific prior written permission.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
THE SOFTWARE.
============================= end_copyright_notice ===========================*/
// This file implements conversion of SPIR-V binary to LLVM IR.
#include "common/LLVMWarningsPush.hpp"
#include "llvm/Config/llvm-config.h"
#include "llvmWrapper/IR/DerivedTypes.h"
#include "llvmWrapper/IR/IRBuilder.h"
#include "llvmWrapper/IR/DIBuilder.h"
#include "llvmWrapper/IR/Module.h"
#include "llvmWrapper/Support/Alignment.h"
#include "llvmWrapper/Support/TypeSize.h"
#include <llvm/Support/ScaledNumber.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/Analysis/CFG.h>
#include "libSPIRV/SPIRVDebugInfoExt.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "common/LLVMWarningsPop.hpp"
#include "libSPIRV/SPIRVAsm.h"
#include "llvm/IR/InlineAsm.h"
#include "libSPIRV/SPIRVFunction.h"
#include "libSPIRV/SPIRVInstruction.h"
#include "libSPIRV/SPIRVModule.h"
#include "libSPIRV/SPIRVMemAliasingINTEL.h"
#include "SPIRVInternal.h"
#include "common/MDFrameWork.h"
#include <llvm/Transforms/Scalar.h>
#include <llvm/IR/MDBuilder.h>
#include <iostream>
#include <fstream>
#include "Probe/Assertion.h"
using namespace llvm;
namespace igc_spv{
// Prefix for placeholder global variable name.
const char* kPlaceholderPrefix = "placeholder.";
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
// Save the translated LLVM before validation for debugging purpose.
static bool DbgSaveTmpLLVM = false;
static const char *DbgTmpLLVMFileName = "_tmp_llvmspirv_module.ll";
#endif
static bool
isOpenCLKernel(SPIRVFunction *BF) {
return BF->getModule()->isEntryPoint(ExecutionModelKernel, BF->getId());
}
__attr_unused static void
dumpLLVM(Module *M, const std::string &FName) {
std::error_code EC;
raw_fd_ostream FS(FName, EC, sys::fs::F_None);
if (!FS.has_error()) {
FS << *M;
}
FS.close();
}
static MDNode*
getMDNodeStringIntVec(LLVMContext *Context, llvm::StringRef Str,
const std::vector<SPIRVWord>& IntVals) {
std::vector<Metadata*> ValueVec;
ValueVec.push_back(MDString::get(*Context, Str));
for (auto &I:IntVals)
ValueVec.push_back(ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(*Context), I)));
return MDNode::get(*Context, ValueVec);
}
static MDNode*
getMDTwoInt(LLVMContext *Context, unsigned Int1, unsigned Int2) {
std::vector<Metadata*> ValueVec;
ValueVec.push_back(ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(*Context), Int1)));
ValueVec.push_back(ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(*Context), Int2)));
return MDNode::get(*Context, ValueVec);
}
static MDNode*
getMDString(LLVMContext *Context, llvm::StringRef Str) {
std::vector<Metadata*> ValueVec;
if (!Str.empty())
ValueVec.push_back(MDString::get(*Context, Str));
return MDNode::get(*Context, ValueVec);
}
static void
addOCLVersionMetadata(LLVMContext *Context, Module *M,
llvm::StringRef MDName, unsigned Major, unsigned Minor) {
NamedMDNode *NamedMD = M->getOrInsertNamedMetadata(MDName);
NamedMD->addOperand(getMDTwoInt(Context, Major, Minor));
}
static void
addNamedMetadataString(LLVMContext *Context, Module *M,
llvm::StringRef MDName, llvm::StringRef Str) {
NamedMDNode *NamedMD = M->getOrInsertNamedMetadata(MDName);
NamedMD->addOperand(getMDString(Context, Str));
}
static void
addOCLKernelArgumentMetadata(LLVMContext *Context,
std::vector<llvm::Metadata*> &KernelMD, llvm::StringRef MDName,
SPIRVFunction *BF, std::function<Metadata *(SPIRVFunctionParameter *)>Func){
std::vector<Metadata*> ValueVec;
ValueVec.push_back(MDString::get(*Context, MDName));
BF->foreachArgument([&](SPIRVFunctionParameter *Arg) {
ValueVec.push_back(Func(Arg));
});
KernelMD.push_back(MDNode::get(*Context, ValueVec));
}
class SPIRVToLLVM;
class SPIRVToLLVMDbgTran {
public:
SPIRVToLLVMDbgTran(SPIRVModule *TBM, Module *TM, SPIRVToLLVM* s)
:BM(TBM), M(TM), SpDbg(BM), Builder(*M), SPIRVTranslator(s) {
Enable = BM->hasDebugInfo();
}
void addDbgInfoVersion() {
if (!Enable)
return;
M->addModuleFlag(Module::Warning, "Dwarf Version",
dwarf::DWARF_VERSION);
M->addModuleFlag(Module::Warning, "Debug Info Version",
DEBUG_METADATA_VERSION);
}
DIFile *getDIFile(const std::string &FileName){
return getOrInsert(FileMap, FileName, [=](){
std::string BaseName;
std::string Path;
splitFileName(FileName, BaseName, Path);
if (!BaseName.empty())
return Builder.createFile(BaseName, Path);
else
return Builder.createFile("", "");
});
}
DIFile* getDIFile(SPIRVString* inst)
{
if (!inst)
return nullptr;
return getDIFile(inst->getStr());
}
DIFile* getDIFile(SPIRVExtInst* inst)
{
OpDebugSource src(inst);
return getDIFile(src.getFileStr());
}
DICompileUnit* createCompileUnit() {
if (!Enable || cu)
return cu;
OpCompilationUnit cunit(BM->getCompilationUnit());
auto lang = cunit.getLang();
auto file = getDIFile(BM->get<SPIRVExtInst>(cunit.getSource()));
auto producer = "spirv";
auto flags = "";
auto rv = 0;
cu = Builder.createCompileUnit(lang, file, producer, false, flags, rv);
addDbgInfoVersion();
return addMDNode(BM->getCompilationUnit(), cu);
}
DIExpression* createExpression(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIExpression*>(inst))
return n;
OpDebugExpression dbgExpr(inst);
auto numOperations = dbgExpr.getNumOperations();
llvm::SmallVector<uint64_t, 5> Exprs;
for (unsigned int i = 0; i != numOperations; ++i)
{
OpDebugOperation operation(BM->get<SPIRVExtInst>(dbgExpr.getOperation(i)));
SPIRVDebug::ExpressionOpCode op = (SPIRVDebug::ExpressionOpCode)operation.getOperation();
switch (op)
{
#define CASE(dwarfOp, SPIRVOp) case SPIRVOp: Exprs.push_back(dwarfOp); break;
CASE(dwarf::DW_OP_deref, SPIRVDebug::ExpressionOpCode::Deref);
CASE(dwarf::DW_OP_plus, SPIRVDebug::ExpressionOpCode::Plus);
CASE(dwarf::DW_OP_minus, SPIRVDebug::ExpressionOpCode::Minus);
CASE(dwarf::DW_OP_plus_uconst, SPIRVDebug::ExpressionOpCode::PlusUconst);
CASE(dwarf::DW_OP_bit_piece, SPIRVDebug::ExpressionOpCode::BitPiece);
CASE(dwarf::DW_OP_swap, SPIRVDebug::ExpressionOpCode::Swap);
CASE(dwarf::DW_OP_xderef, SPIRVDebug::ExpressionOpCode::Xderef);
CASE(dwarf::DW_OP_stack_value, SPIRVDebug::ExpressionOpCode::StackValue);
CASE(dwarf::DW_OP_constu, SPIRVDebug::ExpressionOpCode::Constu);
CASE(dwarf::DW_OP_LLVM_fragment, SPIRVDebug::ExpressionOpCode::Fragment);
#if LLVM_VERSION_MAJOR >= 9
CASE(dwarf::DW_OP_LLVM_convert, SPIRVDebug::ExpressionOpCode::Convert);
#endif
CASE(dwarf::DW_OP_addr, SPIRVDebug::ExpressionOpCode::Addr);
CASE(dwarf::DW_OP_const1u, SPIRVDebug::ExpressionOpCode::Const1u);
CASE(dwarf::DW_OP_const1s, SPIRVDebug::ExpressionOpCode::Const1s);
CASE(dwarf::DW_OP_const2u, SPIRVDebug::ExpressionOpCode::Const2u);
CASE(dwarf::DW_OP_const2s, SPIRVDebug::ExpressionOpCode::Const2s);
CASE(dwarf::DW_OP_const4u, SPIRVDebug::ExpressionOpCode::Const4u);
CASE(dwarf::DW_OP_const4s, SPIRVDebug::ExpressionOpCode::Const4s);
CASE(dwarf::DW_OP_const8u, SPIRVDebug::ExpressionOpCode::Const8u);
CASE(dwarf::DW_OP_const8s, SPIRVDebug::ExpressionOpCode::Const8s);
CASE(dwarf::DW_OP_consts, SPIRVDebug::ExpressionOpCode::Consts);
CASE(dwarf::DW_OP_dup, SPIRVDebug::ExpressionOpCode::Dup);
CASE(dwarf::DW_OP_drop, SPIRVDebug::ExpressionOpCode::Drop);
CASE(dwarf::DW_OP_over, SPIRVDebug::ExpressionOpCode::Over);
CASE(dwarf::DW_OP_pick, SPIRVDebug::ExpressionOpCode::Pick);
CASE(dwarf::DW_OP_rot, SPIRVDebug::ExpressionOpCode::Rot);
CASE(dwarf::DW_OP_abs, SPIRVDebug::ExpressionOpCode::Abs);
CASE(dwarf::DW_OP_and, SPIRVDebug::ExpressionOpCode::And);
CASE(dwarf::DW_OP_div, SPIRVDebug::ExpressionOpCode::Div);
CASE(dwarf::DW_OP_mod, SPIRVDebug::ExpressionOpCode::Mod);
CASE(dwarf::DW_OP_mul, SPIRVDebug::ExpressionOpCode::Mul);
CASE(dwarf::DW_OP_neg, SPIRVDebug::ExpressionOpCode::Neg);
CASE(dwarf::DW_OP_not, SPIRVDebug::ExpressionOpCode::Not);
CASE(dwarf::DW_OP_or, SPIRVDebug::ExpressionOpCode::Or);
CASE(dwarf::DW_OP_shl, SPIRVDebug::ExpressionOpCode::Shl);
CASE(dwarf::DW_OP_shr, SPIRVDebug::ExpressionOpCode::Shr);
CASE(dwarf::DW_OP_shra, SPIRVDebug::ExpressionOpCode::Shra);
CASE(dwarf::DW_OP_xor, SPIRVDebug::ExpressionOpCode::Xor);
CASE(dwarf::DW_OP_bra, SPIRVDebug::ExpressionOpCode::Bra);
CASE(dwarf::DW_OP_eq, SPIRVDebug::ExpressionOpCode::Eq);
CASE(dwarf::DW_OP_ge, SPIRVDebug::ExpressionOpCode::Ge);
CASE(dwarf::DW_OP_gt, SPIRVDebug::ExpressionOpCode::Gt);
CASE(dwarf::DW_OP_le, SPIRVDebug::ExpressionOpCode::Le);
CASE(dwarf::DW_OP_lt, SPIRVDebug::ExpressionOpCode::Lt);
CASE(dwarf::DW_OP_ne, SPIRVDebug::ExpressionOpCode::Ne);
CASE(dwarf::DW_OP_skip, SPIRVDebug::ExpressionOpCode::Skip);
CASE(dwarf::DW_OP_lit0, SPIRVDebug::ExpressionOpCode::Lit0);
CASE(dwarf::DW_OP_lit1, SPIRVDebug::ExpressionOpCode::Lit1);
CASE(dwarf::DW_OP_lit2, SPIRVDebug::ExpressionOpCode::Lit2);
CASE(dwarf::DW_OP_lit3, SPIRVDebug::ExpressionOpCode::Lit3);
CASE(dwarf::DW_OP_lit4, SPIRVDebug::ExpressionOpCode::Lit4);
CASE(dwarf::DW_OP_lit5, SPIRVDebug::ExpressionOpCode::Lit5);
CASE(dwarf::DW_OP_lit6, SPIRVDebug::ExpressionOpCode::Lit6);
CASE(dwarf::DW_OP_lit7, SPIRVDebug::ExpressionOpCode::Lit7);
CASE(dwarf::DW_OP_lit8, SPIRVDebug::ExpressionOpCode::Lit8);
CASE(dwarf::DW_OP_lit9, SPIRVDebug::ExpressionOpCode::Lit9);
CASE(dwarf::DW_OP_lit10, SPIRVDebug::ExpressionOpCode::Lit10);
CASE(dwarf::DW_OP_lit11, SPIRVDebug::ExpressionOpCode::Lit11);
CASE(dwarf::DW_OP_lit12, SPIRVDebug::ExpressionOpCode::Lit12);
CASE(dwarf::DW_OP_lit13, SPIRVDebug::ExpressionOpCode::Lit13);
CASE(dwarf::DW_OP_lit14, SPIRVDebug::ExpressionOpCode::Lit14);
CASE(dwarf::DW_OP_lit15, SPIRVDebug::ExpressionOpCode::Lit15);
CASE(dwarf::DW_OP_lit16, SPIRVDebug::ExpressionOpCode::Lit16);
CASE(dwarf::DW_OP_lit17, SPIRVDebug::ExpressionOpCode::Lit17);
CASE(dwarf::DW_OP_lit18, SPIRVDebug::ExpressionOpCode::Lit18);
CASE(dwarf::DW_OP_lit19, SPIRVDebug::ExpressionOpCode::Lit19);
CASE(dwarf::DW_OP_lit20, SPIRVDebug::ExpressionOpCode::Lit20);
CASE(dwarf::DW_OP_lit21, SPIRVDebug::ExpressionOpCode::Lit21);
CASE(dwarf::DW_OP_lit22, SPIRVDebug::ExpressionOpCode::Lit22);
CASE(dwarf::DW_OP_lit23, SPIRVDebug::ExpressionOpCode::Lit23);
CASE(dwarf::DW_OP_lit24, SPIRVDebug::ExpressionOpCode::Lit24);
CASE(dwarf::DW_OP_lit25, SPIRVDebug::ExpressionOpCode::Lit25);
CASE(dwarf::DW_OP_lit26, SPIRVDebug::ExpressionOpCode::Lit26);
CASE(dwarf::DW_OP_lit27, SPIRVDebug::ExpressionOpCode::Lit27);
CASE(dwarf::DW_OP_lit28, SPIRVDebug::ExpressionOpCode::Lit28);
CASE(dwarf::DW_OP_lit29, SPIRVDebug::ExpressionOpCode::Lit29);
CASE(dwarf::DW_OP_lit30, SPIRVDebug::ExpressionOpCode::Lit30);
CASE(dwarf::DW_OP_lit31, SPIRVDebug::ExpressionOpCode::Lit31);
CASE(dwarf::DW_OP_reg0, SPIRVDebug::ExpressionOpCode::Reg0);
CASE(dwarf::DW_OP_reg1, SPIRVDebug::ExpressionOpCode::Reg1);
CASE(dwarf::DW_OP_reg2, SPIRVDebug::ExpressionOpCode::Reg2);
CASE(dwarf::DW_OP_reg3, SPIRVDebug::ExpressionOpCode::Reg3);
CASE(dwarf::DW_OP_reg4, SPIRVDebug::ExpressionOpCode::Reg4);
CASE(dwarf::DW_OP_reg5, SPIRVDebug::ExpressionOpCode::Reg5);
CASE(dwarf::DW_OP_reg6, SPIRVDebug::ExpressionOpCode::Reg6);
CASE(dwarf::DW_OP_reg7, SPIRVDebug::ExpressionOpCode::Reg7);
CASE(dwarf::DW_OP_reg8, SPIRVDebug::ExpressionOpCode::Reg8);
CASE(dwarf::DW_OP_reg9, SPIRVDebug::ExpressionOpCode::Reg9);
CASE(dwarf::DW_OP_reg10, SPIRVDebug::ExpressionOpCode::Reg10);
CASE(dwarf::DW_OP_reg11, SPIRVDebug::ExpressionOpCode::Reg11);
CASE(dwarf::DW_OP_reg12, SPIRVDebug::ExpressionOpCode::Reg12);
CASE(dwarf::DW_OP_reg13, SPIRVDebug::ExpressionOpCode::Reg13);
CASE(dwarf::DW_OP_reg14, SPIRVDebug::ExpressionOpCode::Reg14);
CASE(dwarf::DW_OP_reg15, SPIRVDebug::ExpressionOpCode::Reg15);
CASE(dwarf::DW_OP_reg16, SPIRVDebug::ExpressionOpCode::Reg16);
CASE(dwarf::DW_OP_reg17, SPIRVDebug::ExpressionOpCode::Reg17);
CASE(dwarf::DW_OP_reg18, SPIRVDebug::ExpressionOpCode::Reg18);
CASE(dwarf::DW_OP_reg19, SPIRVDebug::ExpressionOpCode::Reg19);
CASE(dwarf::DW_OP_reg20, SPIRVDebug::ExpressionOpCode::Reg20);
CASE(dwarf::DW_OP_reg21, SPIRVDebug::ExpressionOpCode::Reg21);
CASE(dwarf::DW_OP_reg22, SPIRVDebug::ExpressionOpCode::Reg22);
CASE(dwarf::DW_OP_reg23, SPIRVDebug::ExpressionOpCode::Reg23);
CASE(dwarf::DW_OP_reg24, SPIRVDebug::ExpressionOpCode::Reg24);
CASE(dwarf::DW_OP_reg25, SPIRVDebug::ExpressionOpCode::Reg25);
CASE(dwarf::DW_OP_reg26, SPIRVDebug::ExpressionOpCode::Reg26);
CASE(dwarf::DW_OP_reg27, SPIRVDebug::ExpressionOpCode::Reg27);
CASE(dwarf::DW_OP_reg28, SPIRVDebug::ExpressionOpCode::Reg28);
CASE(dwarf::DW_OP_reg29, SPIRVDebug::ExpressionOpCode::Reg29);
CASE(dwarf::DW_OP_reg30, SPIRVDebug::ExpressionOpCode::Reg30);
CASE(dwarf::DW_OP_reg31, SPIRVDebug::ExpressionOpCode::Reg31);
CASE(dwarf::DW_OP_breg0, SPIRVDebug::ExpressionOpCode::Breg0);
CASE(dwarf::DW_OP_breg1, SPIRVDebug::ExpressionOpCode::Breg1);
CASE(dwarf::DW_OP_breg2, SPIRVDebug::ExpressionOpCode::Breg2);
CASE(dwarf::DW_OP_breg3, SPIRVDebug::ExpressionOpCode::Breg3);
CASE(dwarf::DW_OP_breg4, SPIRVDebug::ExpressionOpCode::Breg4);
CASE(dwarf::DW_OP_breg5, SPIRVDebug::ExpressionOpCode::Breg5);
CASE(dwarf::DW_OP_breg6, SPIRVDebug::ExpressionOpCode::Breg6);
CASE(dwarf::DW_OP_breg7, SPIRVDebug::ExpressionOpCode::Breg7);
CASE(dwarf::DW_OP_breg8, SPIRVDebug::ExpressionOpCode::Breg8);
CASE(dwarf::DW_OP_breg9, SPIRVDebug::ExpressionOpCode::Breg9);
CASE(dwarf::DW_OP_breg10, SPIRVDebug::ExpressionOpCode::Breg10);
CASE(dwarf::DW_OP_breg11, SPIRVDebug::ExpressionOpCode::Breg11);
CASE(dwarf::DW_OP_breg12, SPIRVDebug::ExpressionOpCode::Breg12);
CASE(dwarf::DW_OP_breg13, SPIRVDebug::ExpressionOpCode::Breg13);
CASE(dwarf::DW_OP_breg14, SPIRVDebug::ExpressionOpCode::Breg14);
CASE(dwarf::DW_OP_breg15, SPIRVDebug::ExpressionOpCode::Breg15);
CASE(dwarf::DW_OP_breg16, SPIRVDebug::ExpressionOpCode::Breg16);
CASE(dwarf::DW_OP_breg17, SPIRVDebug::ExpressionOpCode::Breg17);
CASE(dwarf::DW_OP_breg18, SPIRVDebug::ExpressionOpCode::Breg18);
CASE(dwarf::DW_OP_breg19, SPIRVDebug::ExpressionOpCode::Breg19);
CASE(dwarf::DW_OP_breg20, SPIRVDebug::ExpressionOpCode::Breg20);
CASE(dwarf::DW_OP_breg21, SPIRVDebug::ExpressionOpCode::Breg21);
CASE(dwarf::DW_OP_breg22, SPIRVDebug::ExpressionOpCode::Breg22);
CASE(dwarf::DW_OP_breg23, SPIRVDebug::ExpressionOpCode::Breg23);
CASE(dwarf::DW_OP_breg24, SPIRVDebug::ExpressionOpCode::Breg24);
CASE(dwarf::DW_OP_breg25, SPIRVDebug::ExpressionOpCode::Breg25);
CASE(dwarf::DW_OP_breg26, SPIRVDebug::ExpressionOpCode::Breg26);
CASE(dwarf::DW_OP_breg27, SPIRVDebug::ExpressionOpCode::Breg27);
CASE(dwarf::DW_OP_breg28, SPIRVDebug::ExpressionOpCode::Breg28);
CASE(dwarf::DW_OP_breg29, SPIRVDebug::ExpressionOpCode::Breg29);
CASE(dwarf::DW_OP_breg30, SPIRVDebug::ExpressionOpCode::Breg30);
CASE(dwarf::DW_OP_breg31, SPIRVDebug::ExpressionOpCode::Breg31);
CASE(dwarf::DW_OP_regx, SPIRVDebug::ExpressionOpCode::Regx);
CASE(dwarf::DW_OP_fbreg, SPIRVDebug::ExpressionOpCode::Fbreg);
CASE(dwarf::DW_OP_bregx, SPIRVDebug::ExpressionOpCode::Bregx);
CASE(dwarf::DW_OP_piece, SPIRVDebug::ExpressionOpCode::Piece);
CASE(dwarf::DW_OP_deref_size, SPIRVDebug::ExpressionOpCode::DerefSize);
CASE(dwarf::DW_OP_xderef_size, SPIRVDebug::ExpressionOpCode::XderefSize);
CASE(dwarf::DW_OP_nop, SPIRVDebug::ExpressionOpCode::Nop);
CASE(dwarf::DW_OP_push_object_address, SPIRVDebug::ExpressionOpCode::PushObjectAddress);
CASE(dwarf::DW_OP_call2, SPIRVDebug::ExpressionOpCode::Call2);
CASE(dwarf::DW_OP_call4, SPIRVDebug::ExpressionOpCode::Call4);
CASE(dwarf::DW_OP_call_ref, SPIRVDebug::ExpressionOpCode::CallRef);
CASE(dwarf::DW_OP_form_tls_address, SPIRVDebug::ExpressionOpCode::FormTlsAddress);
CASE(dwarf::DW_OP_call_frame_cfa, SPIRVDebug::ExpressionOpCode::CallFrameCfa);
CASE(dwarf::DW_OP_implicit_value, SPIRVDebug::ExpressionOpCode::ImplicitValue);
CASE(dwarf::DW_OP_implicit_pointer, SPIRVDebug::ExpressionOpCode::ImplicitPointer);
CASE(dwarf::DW_OP_addrx, SPIRVDebug::ExpressionOpCode::Addrx);
CASE(dwarf::DW_OP_constx, SPIRVDebug::ExpressionOpCode::Constx);
CASE(dwarf::DW_OP_entry_value, SPIRVDebug::ExpressionOpCode::EntryValue);
CASE(dwarf::DW_OP_const_type, SPIRVDebug::ExpressionOpCode::ConstTypeOp);
CASE(dwarf::DW_OP_regval_type, SPIRVDebug::ExpressionOpCode::RegvalType);
CASE(dwarf::DW_OP_deref_type, SPIRVDebug::ExpressionOpCode::DerefType);
CASE(dwarf::DW_OP_xderef_type, SPIRVDebug::ExpressionOpCode::XderefType);
CASE(dwarf::DW_OP_reinterpret, SPIRVDebug::ExpressionOpCode::Reinterpret);
default:
break;
}
unsigned int numOperands = 0;
if (SPIRVDebug::OpCountMap.find(op) != SPIRVDebug::OpCountMap.end())
numOperands = SPIRVDebug::OpCountMap[op];
if (numOperands > 0)
{
for (unsigned int j = 1; j != numOperands; ++j)
{
Exprs.push_back(operation.getLiteral(j));
}
}
}
return addMDNode(inst, Builder.createExpression(Exprs));
}
DINode::DIFlags static decodeFlag(SPIRVWord spirvFlags)
{
DINode::DIFlags flags = DINode::FlagZero;
if (spirvFlags & SPIRVDebug::FlagIsArtificial)
flags |= llvm::DINode::FlagArtificial;
if (spirvFlags & SPIRVDebug::FlagIsExplicit)
flags |= llvm::DINode::FlagExplicit;
if (spirvFlags & SPIRVDebug::FlagIsPrototyped)
flags |= llvm::DINode::FlagPrototyped;
if (spirvFlags & SPIRVDebug::FlagIsLValueReference)
flags |= llvm::DINode::FlagLValueReference;
if (spirvFlags & SPIRVDebug::FlagIsRValueReference)
flags |= llvm::DINode::FlagRValueReference;
if ((spirvFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsPublic)
flags |= llvm::DINode::FlagPublic;
if ((spirvFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsProtected)
flags |= llvm::DINode::FlagProtected;
if ((spirvFlags & SPIRVDebug::FlagAccess) == SPIRVDebug::FlagIsPrivate)
flags |= llvm::DINode::FlagPrivate;
if (spirvFlags & SPIRVDebug::FlagIsObjectPointer)
flags |= llvm::DINode::FlagObjectPointer;
if (spirvFlags & SPIRVDebug::FlagIsStaticMember)
flags |= llvm::DINode::FlagStaticMember;
return flags;
}
DIType* createTypeBasic(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeBasic type(inst);
uint64_t sizeInBits = type.getSize();
unsigned int encoding;
auto enc = type.getEncoding();
auto& name = type.getName()->getStr();
switch (enc)
{
case SPIRVDebug::EncodingTag::Boolean:
encoding = dwarf::DW_ATE_boolean;
break;
case SPIRVDebug::EncodingTag::Address:
encoding = dwarf::DW_ATE_address;
break;
case SPIRVDebug::EncodingTag::Float:
encoding = dwarf::DW_ATE_float;
break;
case SPIRVDebug::EncodingTag::Signed:
encoding = dwarf::DW_ATE_signed;
break;
case SPIRVDebug::EncodingTag::Unsigned:
encoding = dwarf::DW_ATE_unsigned;
break;
case SPIRVDebug::EncodingTag::SignedChar:
encoding = dwarf::DW_ATE_signed_char;
break;
case SPIRVDebug::EncodingTag::UnsignedChar:
encoding = dwarf::DW_ATE_unsigned_char;
break;
default:
return addMDNode(inst, Builder.createUnspecifiedType(name));
}
return addMDNode(inst, Builder.createBasicType(name, sizeInBits, encoding));
}
DIType* createPtrType(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugPtrType ptrType(inst);
auto pointeeType = createType(BM->get<SPIRVExtInst>(ptrType.getBaseType()));
auto flags = ptrType.getFlags();
if (flags & SPIRVDebug::Flag::FlagIsLValueReference)
return addMDNode(inst, Builder.createReferenceType(dwarf::DW_TAG_reference_type, pointeeType, M->getDataLayout().getPointerSizeInBits()));
else if (flags & SPIRVDebug::Flag::FlagIsRValueReference)
return addMDNode(inst, Builder.createReferenceType(dwarf::DW_TAG_rvalue_reference_type, pointeeType, M->getDataLayout().getPointerSizeInBits()));
else if (flags & SPIRVDebug::Flag::FlagIsObjectPointer)
{
auto objType = Builder.createPointerType(pointeeType, M->getDataLayout().getPointerSizeInBits());
return addMDNode(inst, Builder.createObjectPointerType(objType));
}
else
return addMDNode(inst, Builder.createPointerType(pointeeType, M->getDataLayout().getPointerSizeInBits()));
}
DIType* createTypeQualifier(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeQualifier qualType(inst);
auto baseType = createType(BM->get<SPIRVExtInst>(qualType.getBaseType()));
auto qual = qualType.getQualifier();
unsigned int qualifier = 0;
if (qual == OpDebugTypeQualifier::TypeQualifier::qual_const)
qualifier = dwarf::DW_TAG_const_type;
else if (qual == OpDebugTypeQualifier::TypeQualifier::qual_restrict)
qualifier = dwarf::DW_TAG_restrict_type;
else if (qual == OpDebugTypeQualifier::TypeQualifier::qual_volatile)
qualifier = dwarf::DW_TAG_volatile_type;
return addMDNode(inst, Builder.createQualifiedType(qualifier, baseType));
}
uint64_t static getSizeInBits(DIType* type)
{
if (!type)
return 0;
auto Tag = type->getTag();
if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
Tag != dwarf::DW_TAG_restrict_type)
return type->getSizeInBits();
if (isa<llvm::DIBasicType>(type))
return type->getSizeInBits();
else if (auto DITy = dyn_cast_or_null<llvm::DIDerivedType>(type))
{
#if LLVM_VERSION_MAJOR <= 8
auto baseType = DITy->getBaseType().resolve();
#else
auto baseType = DITy->getBaseType();
#endif
return getSizeInBits(baseType);
}
else if (auto CTy = dyn_cast_or_null<llvm::DICompositeType>(type))
{
#if LLVM_VERSION_MAJOR <= 8
auto baseType = CTy->getBaseType().resolve();
#else
auto baseType = DITy->getBaseType();
#endif
return getSizeInBits(baseType);
}
return 0;
}
DIType* createMember(SPIRVExtInst* inst);
DIType* createTypeArray(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeArray arrayType(inst);
auto baseType = createType(BM->get<SPIRVExtInst>(arrayType.getBaseType()));
auto numDims = arrayType.getNumDims();
SmallVector<llvm::Metadata *, 8> subscripts;
uint64_t totalCount = 1;
for (unsigned int i = 0; i != numDims; i++)
{
auto val = BM->get<SPIRVConstant>(arrayType.getComponentCount(i))->getZExtIntValue();
subscripts.push_back(Builder.getOrCreateSubrange(0, val));
totalCount *= (uint64_t)(val);
}
DINodeArray subscriptArray = Builder.getOrCreateArray(subscripts);
return addMDNode(inst, Builder.createArrayType(totalCount * getSizeInBits(baseType), 0, baseType, subscriptArray));
}
DIType* createTypeVector(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeVector vectorType(inst);
auto size = vectorType.getNumComponents();
auto type = createType(BM->get<SPIRVExtInst>(vectorType.getBaseType()));
SmallVector<llvm::Metadata *, 8> subscripts;
subscripts.push_back(Builder.getOrCreateSubrange(0, size));
DINodeArray subscriptArray = Builder.getOrCreateArray(subscripts);
return addMDNode(inst, Builder.createVectorType(size * getSizeInBits(type), 0, type, subscriptArray));
}
DIType* createTypeDef(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeDef typeDef(inst);
auto type = createType(BM->get<SPIRVExtInst>(typeDef.getBaseType()));
auto& name = typeDef.getName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(typeDef.getSource()));
auto line = typeDef.getLine();
auto scopeContext = createScope(BM->get<SPIRVExtInst>(typeDef.getParent()));
return addMDNode(inst, Builder.createTypedef(type, name, file, line, scopeContext));
}
DIType* createTypeEnum(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeEnum typeEnum(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(typeEnum.getParent()));
auto& name = typeEnum.getName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(typeEnum.getSource()));
auto line = typeEnum.getLine();
auto size = typeEnum.getSize();
auto type = createType(BM->get<SPIRVExtInst>(typeEnum.getType()));
SmallVector<Metadata*,6> elements;
for (unsigned int i = 0; i != typeEnum.getNumItems(); i++)
{
auto item = typeEnum.getItem(i);
auto enumerator = Builder.createEnumerator(item.first->getStr(), item.second);
elements.push_back(enumerator);
}
auto nodeArray = Builder.getOrCreateArray(llvm::makeArrayRef(elements));
return addMDNode(inst, Builder.createEnumerationType(scope, name, file, line, size, 0, nodeArray, type));
}
DIType* createCompositeType(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeComposite compositeType(inst);
auto tag = compositeType.getTag();
auto& name = compositeType.getName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(compositeType.getSource()));
auto line = compositeType.getLine();
auto size = compositeType.getSize();
auto spirvFlags = compositeType.getFlags();
auto scope = createScope(BM->get<SPIRVExtInst>(compositeType.getParent()));
DINode::DIFlags flags = decodeFlag(spirvFlags);
if (!scope)
scope = cu;
#if 0
// SPIRV spec has single parent field whereas LLVM DIBuilder API requires Scope as well as DerivedFrom.
// What is expected behavior?
// parent may be OpDebugCompilationUnit/OpDebugFunction/OpDebugLexicalBlock/OpDebugTypeComposite
DIType* from = nullptr;
auto parentInst = BM->get<SPIRVExtInst>(parent);
if (parentInst->getExtOp() == OCLExtOpDbgKind::CompileUnit)
from = nullptr;
else if (parentInst->getExtOp() == OCLExtOpDbgKind::Function)
from = nullptr;//createFunction(parentInst);
else if (parentInst->getExtOp() == OCLExtOpDbgKind::LexicalBlock)
from = nullptr; //createLexicalBlock(parentInst);
else if (parentInst->getExtOp() == OCLExtOpDbgKind::TypeComposite)
from = createCompositeType(parentInst);
#endif
DIType* derivedFrom = nullptr;
DICompositeType* newNode = nullptr;
if (tag == SPIRVDebug::CompositeTypeTag::Structure)
{
newNode = addMDNode(inst, Builder.createStructType(scope, name,
file, line, size, 0, flags, derivedFrom, DINodeArray()));
}
else if (tag == SPIRVDebug::CompositeTypeTag::Union)
{
newNode = addMDNode(inst, Builder.createUnionType(scope, name,
file, line, size, 0, flags, DINodeArray()));
}
else if (tag == SPIRVDebug::CompositeTypeTag::Class)
{
// TODO: should be replaced with createClassType, when bug with creating
// ClassType with llvm::dwarf::DW_TAG_struct_type tag will be fixed
auto CT = Builder.createReplaceableCompositeType(
llvm::dwarf::DW_TAG_class_type, name, scope, file, line, 0,
size, 0, flags);
CT = llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(CT));
newNode = addMDNode(inst, CT);
}
SmallVector<Metadata*, 6> elements;
for (unsigned int i = 0; i != compositeType.getNumItems(); i++)
{
auto member = static_cast<SPIRVExtInst*>(BM->getEntry(compositeType.getItem(i)));
elements.push_back(createType(member));
}
DINodeArray Elements = Builder.getOrCreateArray(elements);
Builder.replaceArrays(newNode, Elements);
return newNode;
}
DIType* createTypeInherit(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeInheritance typeInherit(inst);
auto type = createType(BM->get<SPIRVExtInst>(typeInherit.getChild()));
auto base = createType(BM->get<SPIRVExtInst>(typeInherit.getParent()));
auto offset = typeInherit.getOffset();
auto spirvFlags = typeInherit.getFlags();
auto flags = decodeFlag(spirvFlags);
return addMDNode(inst, Builder.createInheritance(type, base, offset, flags));
}
DIType* createPtrToMember(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugPtrToMember ptrToMember(inst);
auto pointee = createType(BM->get<SPIRVExtInst>(ptrToMember.getType()));
auto Class = createType(BM->get<SPIRVExtInst>(ptrToMember.getParent()));
auto size = M->getDataLayout().getPointerSizeInBits();
return addMDNode(inst, Builder.createMemberPointerType(pointee, Class, size));
}
DITemplateParameter* createTemplateParm(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DITemplateParameter*>(inst))
return n;
auto templateOp = inst->getExtOp();
if (templateOp == OCLExtOpDbgKind::TypeTemplateParameter)
{
OpDebugTypeTemplateParm parm(inst);
auto actualType = createType(BM->get<SPIRVExtInst>(parm.getActualType()));
if (!parm.hasValue())
{
return addMDNode(inst, Builder.createTemplateTypeParameter(cu, parm.getName()->getStr(),
actualType));
}
else
{
auto val = parm.getValue();
auto constant = ConstantInt::get(Type::getInt64Ty(M->getContext()), val);
return addMDNode(inst, Builder.createTemplateValueParameter(cu, parm.getName()->getStr(),
actualType, constant));
}
}
else if (templateOp == OCLExtOpDbgKind::TypeTemplateTemplateParameter)
{
OpDebugTypeTemplateParmPack parmPack(inst);
auto& name = parmPack.getName()->getStr();
SmallVector<llvm::Metadata *, 8> Elts;
for (unsigned int i = 0; i != parmPack.getNumParms(); i++) {
Elts.push_back(createTemplateParm(BM->get<SPIRVExtInst>(parmPack.getParm(i))));
}
DINodeArray pack = Builder.getOrCreateArray(Elts);
return addMDNode(inst, Builder.createTemplateParameterPack(cu, name, nullptr, pack));
}
else if (templateOp == OCLExtOpDbgKind::TypeTemplateParameterPack)
{
OpDebugTypeTemplateTemplateParm tempTempParm(inst);
auto& name = tempTempParm.getName()->getStr();
auto& templName = tempTempParm.getTemplateName()->getStr();
return addMDNode(inst, Builder.createTemplateTemplateParameter(cu, name, nullptr, templName));
}
return nullptr;
}
MDNode* createTypeTemplate(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DITemplateParameter*>(inst))
return n;
OpDebugTypeTemplate typeTemplate(inst);
auto target = createType(BM->get<SPIRVExtInst>(typeTemplate.getTarget()));
SmallVector<llvm::Metadata *, 8> Elts;
for (unsigned int i = 0; i != typeTemplate.getNumParms(); i++)
{
auto parm = BM->get<SPIRVExtInst>(typeTemplate.getParm(i));
Elts.push_back(createTemplateParm(parm));
}
DINodeArray TParams = Builder.getOrCreateArray(Elts);
if (DICompositeType *Comp = dyn_cast<DICompositeType>(target)) {
Builder.replaceArrays(Comp, Comp->getElements(), TParams);
return Comp;
}
if (isa<DISubprogram>(target)) {
// This constant matches with one used in
// DISubprogram::getRawTemplateParams()
#if LLVM_VERSION_MAJOR == 4
const unsigned TemplateParamsIndex = 8;
#elif LLVM_VERSION_MAJOR >= 7
const unsigned TemplateParamsIndex = 9;
#endif
target->replaceOperandWith(TemplateParamsIndex, TParams.get());
IGC_ASSERT_MESSAGE(cast<DISubprogram>(target)->getRawTemplateParams() == TParams.get(), "Invalid template parameters");
return target;
}
return nullptr;
}
DIType* createType(SPIRVExtInst* type)
{
if (!type)
{
// return void type
return Builder.createNullPtrType();
}
if (auto n = getExistingNode<DIType*>(type))
return n;
switch (type->getExtOp())
{
case OCLExtOpDbgKind::TypeBasic:
return createTypeBasic(type);
case OCLExtOpDbgKind::TypePtr:
return createPtrType(type);
case OCLExtOpDbgKind::TypeComposite:
return createCompositeType(type);
case OCLExtOpDbgKind::TypeQualifier:
return createTypeQualifier(type);
case OCLExtOpDbgKind::TypeArray:
return createTypeArray(type);
case OCLExtOpDbgKind::TypeVector:
return createTypeVector(type);
case OCLExtOpDbgKind::TypeDef:
return createTypeDef(type);
case OCLExtOpDbgKind::TypeEnum:
return createTypeEnum(type);
case OCLExtOpDbgKind::TypeInheritance:
return createTypeInherit(type);
case OCLExtOpDbgKind::TypePtrToMember:
return createPtrToMember(type);
case OCLExtOpDbgKind::TypeFunction:
return createSubroutineType(type);
case OCLExtOpDbgKind::TypeTemplate:
return (DIType*)createTypeTemplate(type);
case OCLExtOpDbgKind::Function:
return (DIType*)createFunction(type);
case OCLExtOpDbgKind::TypeMember:
return createMember(type);
case OCLExtOpDbgKind::FuncDecl:
return (DIType*)createFunctionDecl(type);
case OCLExtOpDbgKind::DebugInfoNone:
return Builder.createUnspecifiedType("unspecified_type");
default:
break;
}
return addMDNode(type, Builder.createBasicType("int", 4, 0));
}
DIGlobalVariable* createGlobalVariable(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIGlobalVariable*>(inst))
return n;
OpDebugGlobalVar globalVar(inst);
auto& name = globalVar.getName()->getStr();
auto& linkageName = globalVar.getLinkageName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(globalVar.getSource()));
auto line = globalVar.getLine();
auto type = createType(BM->get<SPIRVExtInst>(globalVar.getType()));
return addMDNode(inst, Builder.createTempGlobalVariableFwdDecl(getCompileUnit(), name, linkageName, file,
(unsigned int)line, type, true));
}
DISubprogram* createFunctionDecl(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DISubprogram*>(inst))
return n;
OpDebugFuncDecl funcDcl(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(funcDcl.getParent()));
auto& name = funcDcl.getName()->getStr();
auto& linkageName = funcDcl.getLinkageName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(funcDcl.getSource()));
auto line = funcDcl.getLine();
auto type = createSubroutineType(BM->get<SPIRVExtInst>(funcDcl.getType()));
auto spirvFlags = funcDcl.getFlags();
DINode::DIFlags flags = decodeFlag(spirvFlags);
bool isDefinition = spirvFlags & SPIRVDebug::FlagIsDefinition;
bool isOptimized = spirvFlags & SPIRVDebug::FlagIsOptimized;
bool isLocal = spirvFlags & SPIRVDebug::FlagIsLocal;
SmallVector<llvm::Metadata*, 8> Elts;
DINodeArray TParams = Builder.getOrCreateArray(Elts);
llvm::DITemplateParameterArray TParamsArray = TParams.get();
if (isa<DICompositeType>(scope) || isa<DINamespace>(scope) || isa<DIModule>(scope))
return addMDNode(inst, Builder.createMethod(scope, name, linkageName, file, line, type,
isLocal, isDefinition, 0, 0, 0, nullptr, flags, isOptimized, TParamsArray));
else
return addMDNode(inst, Builder.createTempFunctionFwdDecl(scope, name, linkageName, file, (unsigned int)line, type,
isLocal, isDefinition, (unsigned int)line, flags, isOptimized, TParamsArray));
}
bool isTemplateType(SPIRVExtInst* inst)
{
return (inst->getExtOp() == OCLExtOpDbgKind::TypeTemplate);
}
bool isTypeVoid(SPIRVId id)
{
auto entry = BM->get<SPIRVEntry>(id);
return entry && entry->getOpCode() == igc_spv::Op::OpTypeVoid;
}
DISubroutineType* createSubroutineType(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DISubroutineType*>(inst))
return n;
OpDebugSubroutineType spType(inst);
std::vector<Metadata*> Args;
Args.push_back((isTypeVoid(spType.getReturnType()) || isDebugInfoNone(spType.getReturnType())) ? nullptr :
createType(BM->get<SPIRVExtInst>(spType.getReturnType())));
auto flags = decodeFlag(spType.getFlags());
for (unsigned int i = 0; i != spType.getNumParms(); i++)
{
auto parmType = spType.getParmType(i);
Args.push_back(createType(static_cast<SPIRVExtInst*>(BM->getValue(parmType))));
}
return addMDNode(inst, Builder.createSubroutineType(Builder.getOrCreateTypeArray(Args), flags));
}
bool isDebugInfoNone(SPIRVId id)
{
auto e = BM->get<SPIRVEntry>(id);
if (e->getOpCode() == igc_spv::Op::OpExtInst)
{
auto entry = BM->get<SPIRVExtInst>(id);
return entry && entry->getExtOp() == OCLExtOpDbgKind::DebugInfoNone;
}
return false;
}
DISubprogram* createFunction(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DISubprogram*>(inst))
return n;
OpDebugSubprogram sp(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(sp.getParent()));
auto& name = sp.getName()->getStr();
auto& linkageName = sp.getLinkage()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(sp.getSource()));
auto spType = createSubroutineType(BM->get<SPIRVExtInst>(sp.getType()));
auto spirvFlags = sp.getFlags();
DINode::DIFlags flags = decodeFlag(spirvFlags);
bool isDefinition = spirvFlags & SPIRVDebug::FlagIsDefinition;
bool isOptimized = spirvFlags & SPIRVDebug::FlagIsOptimized;
bool isLocal = spirvFlags & SPIRVDebug::FlagIsLocal;
auto funcSPIRVId = sp.getSPIRVFunction();
DISubprogram* decl = nullptr;
if (sp.hasDeclaration() &&
!isDebugInfoNone(sp.getDecl()))
decl = (DISubprogram*)createType(BM->get<SPIRVExtInst>(sp.getDecl()));
SmallVector<llvm::Metadata *, 8> Elts;
DINodeArray TParams = Builder.getOrCreateArray(Elts);
llvm::DITemplateParameterArray TParamsArray = TParams.get();
DISubprogram* diSP = nullptr;
if ((isa<DICompositeType>(scope) || isa<DINamespace>(scope) || isa<DIModule>(scope)) && !isDefinition)
{
diSP = Builder.createMethod(scope, name, linkageName, file, sp.getLine(), spType, isLocal, isDefinition,
0, 0, 0, nullptr, flags, isOptimized, TParamsArray);
}
else
{
diSP = Builder.createFunction(scope, name, linkageName, file, sp.getLine(), spType, isLocal, isDefinition,
sp.getScopeLine(), flags, isOptimized, TParamsArray, decl);
}
FuncIDToDISP[funcSPIRVId] = diSP;
return addMDNode(inst, diSP);
}
DIScope* createLexicalBlock(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIScope*>(inst))
return n;
OpDebugLexicalBlock lb(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(lb.getParent()));
auto file = getDIFile(BM->get<SPIRVExtInst>(lb.getSource()));
if (!scope || isa<DIFile>(scope))
return nullptr;
if(lb.hasNameSpace() || isa<DICompileUnit>(scope))
return addMDNode(inst, Builder.createNameSpace(scope, lb.getNameSpace()->getStr(), file, lb.getLine(), false));
return addMDNode(inst, Builder.createLexicalBlock(scope, file, lb.getLine(), lb.getColumn()));
}
DILexicalBlockFile* createLexicalBlockDiscriminator(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DILexicalBlockFile*>(inst))
return n;
OpDebugLexicalBlkDiscriminator lbDisc(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(lbDisc.getParent()));
auto file = getDIFile(BM->get<SPIRVExtInst>(lbDisc.getSource()));
auto disc = lbDisc.getDiscriminator();
return addMDNode(inst, Builder.createLexicalBlockFile(scope, file, disc));
}
DILocation* createInlinedAt(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DILocation*>(inst))
return n;
OpDebugInlinedAt inlinedAt(inst);
DILocation* iat = nullptr;
auto line = inlinedAt.getLine();
auto scope = createScope(BM->get<SPIRVExtInst>(inlinedAt.getScope()));
if(inlinedAt.inlinedAtPresent())
iat = createInlinedAt(BM->get<SPIRVExtInst>(inlinedAt.getInlinedAt()));
return addMDNode(inst, createLocation(line, 0, scope, iat));
}
DIModule* createModuleINTEL(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIModule*>(inst))
return n;
OpDebugModuleINTEL moduleINTEL(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(moduleINTEL.getParent()));
auto& name = BM->get<SPIRVString>(moduleINTEL.getName())->getStr();
auto cfgMacros = BM->get<SPIRVString>(moduleINTEL.getConfigurationMacros())->getStr();
auto inclPath = BM->get<SPIRVString>(moduleINTEL.getIncludePath())->getStr();
DIModule* diModule;
#if LLVM_VERSION_MAJOR <= 10
llvm::StringRef iSysRoot = StringRef(); // Empty string
diModule = addMDNode(inst, Builder.createModule(scope, name, cfgMacros, inclPath, iSysRoot));
#else // LLVM_VERSION_MAJOR >= 11
auto file = getDIFile(BM->get<SPIRVExtInst>(moduleINTEL.getSource()));
auto line = moduleINTEL.getLine();
auto apiNotesFile = BM->get<SPIRVString>(moduleINTEL.getAPINotesFile())->getStr();
#if LLVM_VERSION_MAJOR == 11
diModule = addMDNode(inst, Builder.createModule(scope, name, cfgMacros, inclPath, apiNotesFile, file, line));
#elif LLVM_VERSION_MAJOR >= 12
bool isDecl = moduleINTEL.getIsDecl() ? true : false;
diModule = addMDNode(inst, Builder.createModule(scope, name, cfgMacros, inclPath, apiNotesFile, file, line, isDecl));
#endif
#endif // LLVM_VERSION_MAJOR >= 11.
return diModule;
}
DINode* createImportedEntity(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DINode*>(inst))
return n;
OpDebugImportedEntity importedEntity(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(importedEntity.getParent()));
auto file = getDIFile(BM->get<SPIRVExtInst>(importedEntity.getSource()));
auto line = importedEntity.getLine();
auto entity = importedEntity.getEntity();
DINode* diNode = nullptr;
if (BM->get<SPIRVExtInst>(entity)->getExtOp() == OCLExtOpDbgKind::ModuleINTEL)
{
auto diModule = createModuleINTEL(BM->get<SPIRVExtInst>(entity));
diNode = addMDNode(inst, Builder.createImportedModule(scope, diModule, file, line));
}
return diNode;
}
DIScope* createScope(SPIRVExtInst* inst)
{
if (!inst)
return nullptr;
if (inst->isString())
{
// Treat inst as a SPIRVInstruction instead of SPIRVExtInst
// This is a WA since SPIRV emitter emits OpString as
// scope of DebugFunction ext opcode.
return getDIFile(((SPIRVString*)inst)->getStr());
}
if (inst->getExtOp() == OCLExtOpDbgKind::Scope)
{
OpDebugScope scope(inst);
return createScope(BM->get<SPIRVExtInst>(scope.getScope()));
}
if (inst->getExtOp() == OCLExtOpDbgKind::Function)
{
return createFunction(inst);
}
else if (inst->getExtOp() == OCLExtOpDbgKind::LexicalBlock)
{
return createLexicalBlock(inst);
}
else if (inst->getExtOp() == OCLExtOpDbgKind::LexicalBlockDiscriminator)
{
return createLexicalBlockDiscriminator(inst);
}
else if (inst->getExtOp() == OCLExtOpDbgKind::CompileUnit)
{
return createCompileUnit();
}
else if (inst->getExtOp() == OCLExtOpDbgKind::TypeComposite ||
inst->getExtOp() == OCLExtOpDbgKind::TypeTemplate)
{
return createType(inst);
}
else if (inst->getExtOp() == OCLExtOpDbgKind::ModuleINTEL)
{
return createModuleINTEL(inst);
}
else
{
return getDIFile("unexpected path in getScope()");
}
return nullptr;
}
DILocation* getInlinedAtFromScope(SPIRVExtInst* inst)
{
if (inst->getExtOp() == OCLExtOpDbgKind::Scope)
{
OpDebugScope scope(inst);
if (!scope.hasInlinedAt())
return nullptr;
return createInlinedAt(BM->get<SPIRVExtInst>(scope.getInlinedAt()));
}
return nullptr;
}
DILocalVariable* createInlinedLocalVar(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DILocalVariable*>(inst))
return n;
OpDebugInlinedLocalVar var(inst);
auto origVar = createLocalVar(BM->get<SPIRVExtInst>(var.getVar()));
//auto inlinedAt = createInlinedAt(BM->get<SPIRVExtInst>(var.getInlinedAt()));
return addMDNode(inst, origVar);
}
DILocalVariable* createLocalVar(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DILocalVariable*>(inst))
return n;
OpDebugLocalVar var(inst);
auto scope = createScope(BM->get<SPIRVExtInst>(var.getParent()));
auto& name = BM->get<SPIRVString>(var.getName())->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(var.getSource()));
auto type = createType(BM->get<SPIRVExtInst>(var.getType()));
auto spirvFlags = var.getFlags();
auto line = var.getLine();
auto flags = decodeFlag(spirvFlags);
if (var.isParamVar())
{
return addMDNode(inst, Builder.createParameterVariable(scope, name, var.getArgNo(), file, line, type, false, flags));
}
else
{
return addMDNode(inst, Builder.createAutoVariable(scope, name, file, line, type, false, flags));
}
}
DIGlobalVariableExpression* createGlobalVar(SPIRVExtInst* inst);
DILocation* createLocation(SPIRVWord line, SPIRVWord column, DIScope* scope, DILocation* inlinedAt = nullptr)
{
if (scope && isa<DIFile>(scope))
return nullptr;
return DILocation::get(M->getContext(), (unsigned int)line, (unsigned int)column, scope, inlinedAt);
}
Instruction* createDbgDeclare(SPIRVExtInst* inst, Value* localVar, BasicBlock* insertAtEnd)
{
// Format
// 8 12 <id> Result Type Result <id> <id> Set 28 <id> Local Variable <id> Variable <id> Expression
OpDebugDeclare dbgDcl(inst);
auto scope = createScope(inst->getDIScope());
auto iat = getInlinedAtFromScope(inst->getDIScope());
if (!scope)
return nullptr;
auto dbgDclInst = Builder.insertDeclare(localVar,
createLocalVar(BM->get<SPIRVExtInst>(dbgDcl.getVar())),
createExpression(BM->get<SPIRVExtInst>(dbgDcl.getExpression())),
createLocation(inst->getLine()->getLine(), inst->getLine()->getColumn(), scope, iat),
insertAtEnd);
return dbgDclInst;
}
Instruction* createDbgValue(SPIRVExtInst* inst, Value* localVar, BasicBlock* insertAtEnd)
{
OpDebugValue dbgValue(inst);
auto scope = createScope(inst->getDIScope());
auto iat = getInlinedAtFromScope(inst->getDIScope());
if (!scope)
return nullptr;
auto dbgValueInst = Builder.insertDbgValueIntrinsic(localVar, 0,
createLocalVar(BM->get<SPIRVExtInst>(dbgValue.getVar())),
createExpression(BM->get<SPIRVExtInst>(dbgValue.getExpression())),
createLocation(inst->getLine()->getLine(), inst->getLine()->getColumn(), scope, iat),
insertAtEnd);
return dbgValueInst;
}
void transGlobals()
{
if (!Enable)
return;
auto globalVars = BM->getGlobalVars();
for (auto& gvar : globalVars)
{
(void)createGlobalVar(gvar);
}
}
void transImportedEntities()
{
if (!Enable)
return;
auto importedEntities = BM->getImportedEntities();
for (auto& importedEntity : importedEntities)
{
(void)createImportedEntity(importedEntity);
}
}
void transDbgInfo(SPIRVValue *SV, Value *V);
void finalize() {
if (!Enable)
return;
Builder.finalize();
}
template<typename T>
T getExistingNode(SPIRVInstruction* inst)
{
auto it = MDMap.find(inst);
if (it != MDMap.end())
return (T)it->second;
return nullptr;
}
template<typename T>
T addMDNode(SPIRVInstruction* inst, T node)
{
MDMap[inst] = node;
return node;
}
DISubprogram* getDISP(SPIRVId id)
{
auto it = FuncIDToDISP.find(id);
if (it != FuncIDToDISP.end())
return (*it).second;
return nullptr;
}
private:
SPIRVModule *BM;
Module *M;
SPIRVDbgInfo SpDbg;
IGCLLVM::DIBuilder Builder;
bool Enable;
DICompileUnit* cu = nullptr;
SPIRVToLLVM* SPIRVTranslator = nullptr;
std::unordered_map<std::string, DIFile*> FileMap;
std::unordered_map<Function *, DISubprogram*> FuncMap;
std::unordered_map<SPIRVInstruction*, MDNode*> MDMap;
std::unordered_map<SPIRVId, DISubprogram*> FuncIDToDISP;
DICompileUnit* getCompileUnit() { return cu; }
void splitFileName(const std::string &FileName,
std::string &BaseName,
std::string &Path) {
auto Loc = FileName.find_last_of("/\\");
if (Loc != std::string::npos) {
BaseName = FileName.substr(Loc + 1);
Path = FileName.substr(0, Loc);
} else {
BaseName = FileName;
Path = ".";
}
}
};
class SPIRVToLLVM {
public:
SPIRVToLLVM(Module *LLVMModule, SPIRVModule *TheSPIRVModule)
:M((IGCLLVM::Module*)LLVMModule), BM(TheSPIRVModule), DbgTran(BM, M, this){
if (M)
Context = &M->getContext();
else
Context = NULL;
}
Type *transType(SPIRVType *BT);
GlobalValue::LinkageTypes transLinkageType(const SPIRVValue* V);
/// Decode SPIR-V encoding of vector type hint execution mode.
Type *decodeVecTypeHint(LLVMContext &C, unsigned code);
std::string transTypeToOCLTypeName(SPIRVType *BT, bool IsSigned = true);
std::vector<Type *> transTypeVector(const std::vector<SPIRVType *>&);
bool translate();
bool transAddressingModel();
enum class BoolAction
{
Promote,
Truncate,
Noop
};
Value *transValue(SPIRVValue *, Function *F, BasicBlock *,
bool CreatePlaceHolder = true, BoolAction Action = BoolAction::Promote);
Value *transValueWithoutDecoration(SPIRVValue *, Function *F, BasicBlock *,
bool CreatePlaceHolder);
bool transDecoration(SPIRVValue *, Value *);
bool transAlign(SPIRVValue *, Value *);
Instruction *transOCLBuiltinFromExtInst(SPIRVExtInst *BC, BasicBlock *BB);
std::vector<Value *> transValue(const std::vector<SPIRVValue *>&, Function *F,
BasicBlock *, BoolAction Action = BoolAction::Promote);
Function *transFunction(SPIRVFunction *F);
bool transFPContractMetadata();
bool transKernelMetadata();
bool transNonTemporalMetadata(Instruction* I);
template <typename SPIRVInstType>
void transAliasingMemAccess(SPIRVInstType* BI, Instruction* I);
void addMemAliasMetadata(Instruction* I, SPIRVId AliasListId,
uint32_t AliasMDKind);
void transSourceLanguage();
bool transSourceExtension();
/*InlineAsm*/ Value *transAsmINTEL(SPIRVAsmINTEL *BA, Function *F,
BasicBlock *BB);
CallInst *transAsmCallINTEL(SPIRVAsmCallINTEL *BI, Function *F,
BasicBlock *BB);
Type* m_NamedBarrierType = nullptr;
Type* getNamedBarrierType();
Value *transConvertInst(SPIRVValue* BV, Function* F, BasicBlock* BB);
Instruction *transSPIRVBuiltinFromInst(SPIRVInstruction *BI, BasicBlock *BB);
void transOCLVectorLoadStore(std::string& UnmangledName,
std::vector<SPIRVWord> &BArgs);
/// Post-process translated LLVM module for OpenCL.
bool postProcessOCL();
Instruction* transDebugInfo(SPIRVExtInst*, llvm::BasicBlock*);
SPIRVToLLVMDbgTran& getDbgTran() { return DbgTran; }
/// \brief Post-process OpenCL builtin functions returning struct type.
///
/// Some OpenCL builtin functions are translated to SPIR-V instructions with
/// struct type result, e.g. NDRange creation functions. Such functions
/// need to be post-processed to return the struct through sret argument.
bool postProcessFunctionsReturnStruct(Function *F);
/// \brief Post-process OpenCL builtin functions having aggregate argument.
///
/// These functions are translated to functions with aggregate type argument
/// first, then post-processed to have pointer arguments.
bool postProcessFunctionsWithAggregateArguments(Function *F);
typedef DenseMap<SPIRVType *, Type *> SPIRVToLLVMTypeMap;
typedef DenseMap<SPIRVValue *, Value *> SPIRVToLLVMValueMap;
typedef DenseMap<SPIRVFunction *, Function *> SPIRVToLLVMFunctionMap;
typedef DenseMap<GlobalVariable *, SPIRVBuiltinVariableKind> BuiltinVarMap;
typedef std::unordered_map<SPIRVId, MDNode*> SPIRVToLLVMMDAliasInstMap;
// A SPIRV value may be translated to a load instruction of a placeholder
// global variable. This map records load instruction of these placeholders
// which are supposed to be replaced by the real values later.
typedef std::map<SPIRVValue *, LoadInst*> SPIRVToLLVMPlaceholderMap;
typedef std::map<const BasicBlock*, const SPIRVValue*>
SPIRVToLLVMLoopMetadataMap;
Value *getTranslatedValue(SPIRVValue *BV);
private:
IGCLLVM::Module *M;
BuiltinVarMap BuiltinGVMap;
LLVMContext *Context;
SPIRVModule *BM;
SPIRVToLLVMTypeMap TypeMap;
SPIRVToLLVMValueMap ValueMap;
SPIRVToLLVMFunctionMap FuncMap;
SPIRVToLLVMPlaceholderMap PlaceholderMap;
SPIRVToLLVMDbgTran DbgTran;
GlobalVariable *m_NamedBarrierVar;
GlobalVariable *m_named_barrier_id;
DICompileUnit* compileUnit = nullptr;
// These storages are used to prevent duplication of alias.scope/noalias
// metadata
SPIRVToLLVMMDAliasInstMap MDAliasDomainMap;
SPIRVToLLVMMDAliasInstMap MDAliasScopeMap;
SPIRVToLLVMMDAliasInstMap MDAliasListMap;
// Loops metadata is translated in the end of a function translation.
// This storage contains pairs of translated loop header basic block and loop
// metadata SPIR-V instruction in SPIR-V representation of this basic block.
SPIRVToLLVMLoopMetadataMap FuncLoopMetadataMap;
Type *mapType(SPIRVType *BT, Type *T) {
TypeMap[BT] = T;
return T;
}
// If a value is mapped twice, the existing mapped value is a placeholder,
// which must be a load instruction of a global variable whose name starts
// with kPlaceholderPrefix.
Value *mapValue(SPIRVValue *BV, Value *V) {
auto Loc = ValueMap.find(BV);
if (Loc != ValueMap.end()) {
if (Loc->second == V)
return V;
auto LD = dyn_cast<LoadInst>(Loc->second);
IGC_ASSERT_EXIT(nullptr != LD);
auto Placeholder = dyn_cast<GlobalVariable>(LD->getPointerOperand());
IGC_ASSERT_EXIT(nullptr != Placeholder);
IGC_ASSERT_EXIT_MESSAGE(Placeholder->getName().startswith(kPlaceholderPrefix), "A value is translated twice");
// Replaces placeholders for PHI nodes
LD->replaceAllUsesWith(V);
LD->eraseFromParent();
Placeholder->eraseFromParent();
}
ValueMap[BV] = V;
return V;
}
bool isSPIRVBuiltinVariable(GlobalVariable *GV,
SPIRVBuiltinVariableKind *Kind = nullptr) {
auto Loc = BuiltinGVMap.find(GV);
if (Loc == BuiltinGVMap.end())
return false;
if (Kind)
*Kind = Loc->second;
return true;
}
// OpenCL function always has NoUnwound attribute.
// Change this if it is no longer true.
bool isFuncNoUnwind() const { return true;}
bool isSPIRVCmpInstTransToLLVMInst(SPIRVInstruction *BI) const;
bool transOCLBuiltinsFromVariables();
bool transOCLBuiltinFromVariable(GlobalVariable *GV,
SPIRVBuiltinVariableKind Kind);
MDString *transOCLKernelArgTypeName(SPIRVFunctionParameter *);
Value *mapFunction(SPIRVFunction *BF, Function *F) {
FuncMap[BF] = F;
return F;
}
Type *getTranslatedType(SPIRVType *BT);
SPIRVErrorLog &getErrorLog() {
return BM->getErrorLog();
}
void setCallingConv(CallInst *Call) {
Function *F = Call->getCalledFunction();
Call->setCallingConv(F->getCallingConv());
}
void setAttrByCalledFunc(CallInst *Call);
Type *transFPType(SPIRVType* T);
BinaryOperator *transShiftLogicalBitwiseInst(SPIRVValue* BV, BasicBlock* BB,
Function* F);
Instruction *transCmpInst(SPIRVValue* BV, BasicBlock* BB, Function* F);
Instruction *transLifetimeInst(SPIRVInstTemplateBase* BV, BasicBlock* BB, Function* F);
uint64_t calcImageType(const SPIRVValue *ImageVal);
std::string transOCLImageTypeName(igc_spv::SPIRVTypeImage* ST);
std::string transOCLSampledImageTypeName(igc_spv::SPIRVTypeSampledImage* ST);
std::string transOCLImageTypeAccessQualifier(igc_spv::SPIRVTypeImage* ST);
std::string transOCLPipeTypeAccessQualifier(igc_spv::SPIRVTypePipe* ST);
Value *oclTransConstantSampler(igc_spv::SPIRVConstantSampler* BCS);
template<class Source, class Func>
bool foreachFuncCtlMask(Source, Func);
template <typename LoopInstType>
void setLLVMLoopMetadata(const LoopInstType* LM, Instruction* BI);
void transLLVMLoopMetadata(const Function* F);
inline llvm::Metadata *getMetadataFromName(std::string Name);
inline std::vector<llvm::Metadata *>
getMetadataFromNameAndParameter(std::string Name, SPIRVWord Parameter);
Value *promoteBool(Value *pVal, BasicBlock *BB);
Value *truncBool(Value *pVal, BasicBlock *BB);
Type *truncBoolType(SPIRVType *SPVType, Type *LLType);
void transMemAliasingINTELDecorations(SPIRVValue* BV, Value* V);
};
DIGlobalVariableExpression* SPIRVToLLVMDbgTran::createGlobalVar(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIGlobalVariableExpression*>(inst))
return n;
OpDebugGlobalVar var(inst);
auto ctxt = createScope(BM->get<SPIRVExtInst>(var.getParent()));
auto& name = var.getName()->getStr();
auto& linkageName = var.getLinkageName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(var.getSource()));
auto type = createType(BM->get<SPIRVExtInst>(var.getType()));
auto varValue = static_cast<SPIRVValue*>(BM->getEntry(var.getVariable()));
auto flags = var.getFlags();
bool isLocal = (flags & SPIRVDebug::Flag::FlagIsLocal) ? true : false;
auto globalVarMD = addMDNode(inst, Builder.createGlobalVariableExpression(ctxt, name, linkageName, file, var.getLine(), type, isLocal));
llvm::Value* llvmValue = nullptr;
if (varValue)
{
llvmValue = SPIRVTranslator->getTranslatedValue(varValue);
if (llvmValue && dyn_cast_or_null<GlobalVariable>(llvmValue))
{
dyn_cast<GlobalVariable>(llvmValue)->addDebugInfo(globalVarMD);
}
}
return globalVarMD;
}
void SPIRVToLLVMDbgTran::transDbgInfo(SPIRVValue *SV, Value *V) {
if (!SV)
return;
if (!Enable || !SV->hasLine() || !SV->getDIScope())
return;
if (auto I = dyn_cast<Instruction>(V)) {
IGC_ASSERT_MESSAGE(SV->isInst(), "Invalid instruction");
auto SI = static_cast<SPIRVInstruction *>(SV);
IGC_ASSERT(nullptr != SI);
IGC_ASSERT_MESSAGE(nullptr != SI->getParent(), "Invalid instruction");
IGC_ASSERT_MESSAGE(nullptr != SI->getParent()->getParent(), "Invalid instruction");
auto Line = SV->getLine();
DILocation* iat = nullptr;
DIScope* scope = nullptr;
if (SV->getDIScope())
{
scope = SPIRVTranslator->getDbgTran().createScope(SV->getDIScope());
iat = SPIRVTranslator->getDbgTran().getInlinedAtFromScope(SV->getDIScope());
}
SPIRVTranslator->getDbgTran().createLocation(Line->getLine(),
Line->getColumn(), scope, iat);
if(scope && !isa<DIFile>(scope))
I->setDebugLoc(DILocation::get(scope->getContext(), Line->getLine(), Line->getColumn(),
scope, iat));
}
}
DIType* SPIRVToLLVMDbgTran::createMember(SPIRVExtInst* inst)
{
if (auto n = getExistingNode<DIType*>(inst))
return n;
OpDebugTypeMember typeMember(inst);
auto scope = createType(BM->get<SPIRVExtInst>(typeMember.getParent()));
auto& name = typeMember.getName()->getStr();
auto file = getDIFile(BM->get<SPIRVExtInst>(typeMember.getSource()));
auto line = typeMember.getLine();
auto size = typeMember.getSize();
auto offset = typeMember.getOffset();
auto flagRaw = typeMember.getFlags();
auto type = createType(BM->get<SPIRVExtInst>(typeMember.getType()));
auto flags = decodeFlag(flagRaw);
if (flags & DINode::FlagStaticMember && typeMember.hasInitConst())
{
SPIRVValue* constVal = (SPIRVValue*)BM->getEntry(typeMember.getInitConstId());
auto val = SPIRVTranslator->transValue(constVal, nullptr, nullptr);
return addMDNode(inst, Builder.createStaticMemberType(scope, name, file, line, type, flags,
llvm::cast<llvm::Constant>(val)));
}
return addMDNode(inst, Builder.createMemberType(scope, name, file, line, size, 0, offset, flags, type));
}
Type *
SPIRVToLLVM::getTranslatedType(SPIRVType *BV){
auto Loc = TypeMap.find(BV);
if (Loc != TypeMap.end())
return Loc->second;
return nullptr;
}
Value *
SPIRVToLLVM::getTranslatedValue(SPIRVValue *BV){
auto Loc = ValueMap.find(BV);
if (Loc != ValueMap.end())
return Loc->second;
return nullptr;
}
void
SPIRVToLLVM::setAttrByCalledFunc(CallInst *Call) {
Function *F = Call->getCalledFunction();
if (F->isIntrinsic()) {
return;
}
Call->setCallingConv(F->getCallingConv());
Call->setAttributes(F->getAttributes());
}
// Translate aliasing decorations applied to instructions. These decorations
// are mapped on alias.scope and noalias metadata in LLVM. Translation of
// optional string operand isn't yet supported in the translator.
void SPIRVToLLVM::transMemAliasingINTELDecorations(SPIRVValue* BV, Value* V) {
if (!BV->isInst())
return;
Instruction* Inst = dyn_cast<Instruction>(V);
if (!Inst)
return;
std::vector<SPIRVId> AliasListIds;
uint32_t AliasMDKind;
if (BV->hasDecorateId(DecorationAliasScopeINTEL)) {
AliasMDKind = LLVMContext::MD_alias_scope;
AliasListIds =
BV->getDecorationIdLiterals(DecorationAliasScopeINTEL);
}
else if (BV->hasDecorateId(DecorationNoAliasINTEL)) {
AliasMDKind = LLVMContext::MD_noalias;
AliasListIds =
BV->getDecorationIdLiterals(DecorationNoAliasINTEL);
}
else
return;
assert(AliasListIds.size() == 1 &&
"Memory aliasing decorations must have one argument");
addMemAliasMetadata(Inst, AliasListIds[0], AliasMDKind);
}
SPIRAddressSpace
getOCLOpaqueTypeAddrSpace(Op OpCode)
{
switch (OpCode)
{
case OpTypePipe:
// these types are handled in special way at SPIRVToLLVM::transType
return SPIRAS_Global;
default:
//OpTypeQueue:
//OpTypeEvent:
//OpTypeDeviceEvent:
//OpTypeReserveId
return SPIRAS_Private;
}
}
bool
SPIRVToLLVM::transOCLBuiltinsFromVariables(){
std::vector<GlobalVariable *> WorkList;
for (auto I = M->global_begin(), E = M->global_end(); I != E; ++I) {
SPIRVBuiltinVariableKind Kind = BuiltInCount;
if (!isSPIRVBuiltinVariable(&(*I), &Kind))
continue;
if (!transOCLBuiltinFromVariable(&(*I), Kind))
return false;
WorkList.push_back(&(*I));
}
for (auto &I:WorkList) {
I->eraseFromParent();
}
return true;
}
// For integer types shorter than 32 bit, unsigned/signedness can be inferred
// from zext/sext attribute.
MDString *
SPIRVToLLVM::transOCLKernelArgTypeName(SPIRVFunctionParameter *Arg) {
auto Ty = Arg->isByVal() ? Arg->getType()->getPointerElementType() :
Arg->getType();
return MDString::get(*Context, transTypeToOCLTypeName(Ty, !Arg->isZext()));
}
// Variable like GlobalInvocationId[x] -> get_global_id(x).
// Variable like WorkDim -> get_work_dim().
bool SPIRVToLLVM::transOCLBuiltinFromVariable(GlobalVariable *GV,
SPIRVBuiltinVariableKind Kind) {
std::string FuncName;
if (!SPIRSPIRVBuiltinVariableMap::find(Kind, &FuncName))
return false;
decorateSPIRVBuiltin(FuncName);
Function *Func = M->getFunction(FuncName);
if (!Func) {
Type *ReturnTy = GV->getType()->getPointerElementType();
FunctionType *FT = FunctionType::get(ReturnTy, false);
Func = Function::Create(FT, GlobalValue::ExternalLinkage, FuncName, M);
Func->setCallingConv(CallingConv::SPIR_FUNC);
Func->addFnAttr(Attribute::NoUnwind);
Func->addFnAttr(Attribute::ReadNone);
}
SmallVector<Instruction *, 4> Deletes;
SmallVector<Instruction *, 4> Users;
for (auto UI : GV->users()) {
LoadInst *LD = nullptr;
if (auto ASCast = dyn_cast<AddrSpaceCastInst>(&*UI)) {
for (auto ASCastUser : ASCast->users()) {
LD = cast<LoadInst>(&*ASCastUser);
Users.push_back(LD);
Deletes.push_back(LD);
}
Deletes.push_back(ASCast);
} else {
LD = cast<LoadInst>(&*UI);
Users.push_back(LD);
Deletes.push_back(LD);
}
}
for (auto &I : Users) {
auto Call = CallInst::Create(Func, "", I);
Call->takeName(I);
Call->setDebugLoc(I->getDebugLoc());
setAttrByCalledFunc(Call);
I->replaceAllUsesWith(Call);
}
for (auto &I : Deletes) {
if (I->use_empty())
I->eraseFromParent();
else
IGC_ASSERT(0);
}
return true;
}
Type *
SPIRVToLLVM::transFPType(SPIRVType* T) {
switch(T->getFloatBitWidth()) {
case 16: return Type::getHalfTy(*Context);
case 32: return Type::getFloatTy(*Context);
case 64: return Type::getDoubleTy(*Context);
default:
llvm_unreachable("Invalid type");
return nullptr;
}
}
std::string
SPIRVToLLVM::transOCLImageTypeName(igc_spv::SPIRVTypeImage* ST) {
return getSPIRVTypeName(
kSPIRVTypeName::Image,
getSPIRVImageTypePostfixes(
getSPIRVImageSampledTypeName(ST->getSampledType()),
ST->getDescriptor(),
ST->hasAccessQualifier()
? ST->getAccessQualifier()
: AccessQualifierReadOnly));
}
std::string
SPIRVToLLVM::transOCLSampledImageTypeName(igc_spv::SPIRVTypeSampledImage* ST) {
return std::string(kLLVMName::builtinPrefix) + kSPIRVTypeName::SampledImage;
}
inline llvm::Metadata *SPIRVToLLVM::getMetadataFromName(std::string Name) {
return llvm::MDNode::get(*Context, llvm::MDString::get(*Context, Name));
}
inline std::vector<llvm::Metadata *>
SPIRVToLLVM::getMetadataFromNameAndParameter(std::string Name,
SPIRVWord Parameter) {
return {MDString::get(*Context, Name),
ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), Parameter))};
}
template <typename LoopInstType>
void SPIRVToLLVM::setLLVMLoopMetadata(const LoopInstType* LM, Instruction* BI) {
if (!LM)
return;
IGC_ASSERT(BI && isa<BranchInst>(BI));
auto Temp = MDNode::getTemporary(*Context, None);
auto Self = MDNode::get(*Context, Temp.get());
Self->replaceOperandWith(0, Self);
SPIRVWord LC = LM->getLoopControl();
if (LC == LoopControlMaskNone) {
BI->setMetadata("llvm.loop", Self);
return;
}
unsigned NumParam = 0;
std::vector<llvm::Metadata *> Metadata;
std::vector<SPIRVWord> LoopControlParameters = LM->getLoopControlParameters();
Metadata.push_back(llvm::MDNode::get(*Context, Self));
// To correctly decode loop control parameters, order of checks for loop
// control masks must match with the order given in the spec (see 3.23),
// i.e. check smaller-numbered bits first.
// Unroll and UnrollCount loop controls can't be applied simultaneously with
// DontUnroll loop control.
if (LC & LoopControlUnrollMask)
Metadata.push_back(getMetadataFromName("llvm.loop.unroll.enable"));
else if (LC & LoopControlDontUnrollMask)
Metadata.push_back(getMetadataFromName("llvm.loop.unroll.disable"));
if (LC & LoopControlDependencyInfiniteMask)
Metadata.push_back(getMetadataFromName("llvm.loop.ivdep.enable"));
if (LC & LoopControlDependencyLengthMask) {
if (!LoopControlParameters.empty()) {
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.ivdep.safelen",
LoopControlParameters[NumParam])));
++NumParam;
IGC_ASSERT_MESSAGE(NumParam <= LoopControlParameters.size(), "Missing loop control parameter!");
}
}
// Placeholder for LoopControls added in SPIR-V 1.4 spec (see 3.23)
if (LC & LoopControlMinIterationsMask) {
++NumParam;
IGC_ASSERT_MESSAGE(NumParam <= LoopControlParameters.size(), "Missing loop control parameter!");
}
if (LC & LoopControlMaxIterationsMask) {
++NumParam;
IGC_ASSERT_MESSAGE(NumParam <= LoopControlParameters.size(), "Missing loop control parameter!");
}
if (LC & LoopControlIterationMultipleMask) {
++NumParam;
IGC_ASSERT_MESSAGE(NumParam <= LoopControlParameters.size(), "Missing loop control parameter!");
}
if (LC & LoopControlPeelCountMask) {
++NumParam;
IGC_ASSERT_MESSAGE(NumParam <= LoopControlParameters.size(), "Missing loop control parameter!");
}
if (LC & LoopControlPartialCountMask && !(LC & LoopControlDontUnrollMask)) {
// If unroll factor is set as '1' - disable loop unrolling
if (1 == LoopControlParameters[NumParam])
Metadata.push_back(getMetadataFromName("llvm.loop.unroll.disable"));
else
Metadata.push_back(llvm::MDNode::get(
*Context,
getMetadataFromNameAndParameter("llvm.loop.unroll.count",
LoopControlParameters[NumParam])));
++NumParam;
IGC_ASSERT_MESSAGE(NumParam <= LoopControlParameters.size(), "Missing loop control parameter!");
}
llvm::MDNode *Node = llvm::MDNode::get(*Context, Metadata);
// Set the first operand to refer itself
Node->replaceOperandWith(0, Node);
BI->setMetadata("llvm.loop", Node);
}
void SPIRVToLLVM::transLLVMLoopMetadata(const Function *F) {
assert(F);
if (!FuncLoopMetadataMap.empty()) {
// In SPIRV loop metadata is linked to a header basic block of a loop
// whilst in LLVM IR it is linked to a latch basic block (the one
// whose back edge goes to a header basic block) of the loop.
using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
SmallVector<Edge, 32> Edges;
FindFunctionBackedges(*F, Edges);
for (const auto &BkEdge : Edges) {
// Check that loop header BB contains loop metadata.
const auto LMDItr = FuncLoopMetadataMap.find(BkEdge.second);
if (LMDItr == FuncLoopMetadataMap.end())
continue;
auto *BI = const_cast<Instruction *>(BkEdge.first->getTerminator());
const auto *LMD = LMDItr->second;
if (LMD->getOpCode() == OpLoopMerge) {
const auto *LM = static_cast<const SPIRVLoopMerge *>(LMD);
setLLVMLoopMetadata<SPIRVLoopMerge>(LM, BI);
} else if (LMD->getOpCode() == OpLoopControlINTEL) {
const auto *LCI = static_cast<const SPIRVLoopControlINTEL *>(LMD);
setLLVMLoopMetadata<SPIRVLoopControlINTEL>(LCI, BI);
}
}
// Loop metadata map should be re-filled during each function translation.
FuncLoopMetadataMap.clear();
}
}
GlobalValue::LinkageTypes
SPIRVToLLVM::transLinkageType(const SPIRVValue* V) {
if (V->getLinkageType() == LinkageTypeInternal) {
return GlobalValue::InternalLinkage;
}
else if (V->getLinkageType() == LinkageTypeImport) {
// Function declaration
if (V->getOpCode() == OpFunction) {
if (static_cast<const SPIRVFunction*>(V)->getNumBasicBlock() == 0)
return GlobalValue::ExternalLinkage;
}
// Variable declaration
if (V->getOpCode() == OpVariable) {
if (static_cast<const SPIRVVariable*>(V)->getInitializer() == 0)
return GlobalValue::ExternalLinkage;
}
// Definition
return GlobalValue::AvailableExternallyLinkage;
}
else if (V->getLinkageType() == LinkageTypeLinkOnceODR) {
return GlobalValue::LinkOnceODRLinkage;
}
else {// LinkageTypeExport
if (V->getOpCode() == OpVariable) {
if (static_cast<const SPIRVVariable*>(V)->getInitializer() == 0 )
// Tentative definition
return GlobalValue::CommonLinkage;
}
return GlobalValue::ExternalLinkage;
}
}
Type *
SPIRVToLLVM::transType(SPIRVType *T) {
auto Loc = TypeMap.find(T);
if (Loc != TypeMap.end())
return Loc->second;
T->validate();
switch(T->getOpCode()) {
case OpTypeVoid:
return mapType(T, Type::getVoidTy(*Context));
case OpTypeBool:
return mapType(T, Type::getInt8Ty(*Context));
case OpTypeInt:
return mapType(T, Type::getIntNTy(*Context, T->getIntegerBitWidth()));
case OpTypeFloat:
return mapType(T, transFPType(T));
case OpTypeArray:
return mapType(T, ArrayType::get(transType(T->getArrayElementType()),
T->getArrayLength()));
case OpTypeTokenINTEL:
return mapType(T, Type::getTokenTy(*Context));
case OpTypePointer:
return mapType(T, PointerType::get(transType(T->getPointerElementType()),
SPIRSPIRVAddrSpaceMap::rmap(T->getPointerStorageClass())));
case OpTypeVector:
return mapType(T, IGCLLVM::FixedVectorType::get(transType(T->getVectorComponentType()),
T->getVectorComponentCount()));
case OpTypeOpaque:
return mapType(T, StructType::create(*Context, T->getName()));
case OpTypeFunction: {
auto FT = static_cast<SPIRVTypeFunction *>(T);
auto RT = transType(FT->getReturnType());
std::vector<Type *> PT;
for (size_t I = 0, E = FT->getNumParameters(); I != E; ++I)
PT.push_back(transType(FT->getParameterType(I)));
return mapType(T, FunctionType::get(RT, PT, false));
}
case OpTypeImage:{
return mapType(T, getOrCreateOpaquePtrType(M,
transOCLImageTypeName(static_cast<SPIRVTypeImage *>(T))));
}
case OpTypeSampler:
//ulong __builtin_spirv_OpTypeSampler
return mapType(T, Type::getInt64Ty(*Context));
case OpTypeSampledImage:
case OpTypeVmeImageINTEL: {
//ulong3 __builtin_spirv_OpSampledImage
return mapType(T, IGCLLVM::FixedVectorType::get(Type::getInt64Ty(*Context), 3));
}
case OpTypeStruct: {
auto ST = static_cast<SPIRVTypeStruct *>(T);
auto Name = ST->getName();
if (Name.empty())
Name = "structtype";
auto *pStructTy = StructType::create(*Context, Name);
mapType(ST, pStructTy);
SmallVector<Type *, 4> MT;
for (size_t I = 0, E = ST->getMemberCount(); I != E; ++I)
MT.push_back(transType(ST->getMemberType(I)));
for (auto& CI : ST->getContinuedInstructions())
for (size_t I = 0, E = CI->getNumElements(); I != E; ++I)
MT.push_back(transType(CI->getMemberType(I)));
pStructTy->setBody(MT, ST->isPacked());
return pStructTy;
}
case OpTypePipeStorage:
{
return mapType(T, Type::getInt8PtrTy(*Context, SPIRAS_Global));
}
case OpTypeNamedBarrier:
{
return mapType(T, getNamedBarrierType());
}
case OpTypeBufferSurfaceINTEL: {
return mapType(T,
getOrCreateOpaquePtrType(M, "intel.buffer_rw_t",
SPIRAddressSpace::SPIRAS_Global));
}
default: {
auto OC = T->getOpCode();
if (isOpaqueGenericTypeOpCode(OC) ||
isSubgroupAvcINTELTypeOpCode(OC))
{
auto name = isSubgroupAvcINTELTypeOpCode(OC) ?
OCLSubgroupINTELTypeOpCodeMap::rmap(OC) :
BuiltinOpaqueGenericTypeOpCodeMap::rmap(OC);
auto *pST = IGCLLVM::getTypeByName(M, name);
pST = pST ? pST : StructType::create(*Context, name);
return mapType(T, PointerType::get(pST, getOCLOpaqueTypeAddrSpace(OC)));
}
llvm_unreachable("Not implemented");
}
}
return 0;
}
std::string
SPIRVToLLVM::transTypeToOCLTypeName(SPIRVType *T, bool IsSigned) {
switch(T->getOpCode()) {
case OpTypeVoid:
return "void";
case OpTypeBool:
return "bool";
case OpTypeInt: {
std::string Prefix = IsSigned ? "" : "u";
switch(T->getIntegerBitWidth()) {
case 8:
return Prefix + "char";
case 16:
return Prefix + "short";
case 32:
return Prefix + "int";
case 64:
return Prefix + "long";
default:
llvm_unreachable("invalid integer size");
return Prefix + std::string("int") + T->getIntegerBitWidth() + "_t";
}
}
break;
case OpTypeFloat:
switch(T->getFloatBitWidth()){
case 16:
return "half";
case 32:
return "float";
case 64:
return "double";
default:
llvm_unreachable("invalid floating pointer bitwidth");
return std::string("float") + T->getFloatBitWidth() + "_t";
}
break;
case OpTypeArray:
return "array";
case OpTypePointer: {
SPIRVType* ET = T->getPointerElementType();
if (isa<OpTypeFunction>(ET)) {
SPIRVTypeFunction* TF = static_cast<SPIRVTypeFunction*>(ET);
std::string name = transTypeToOCLTypeName(TF->getReturnType());
name += " (*)(";
for (unsigned I = 0, E = TF->getNumParameters(); I < E; ++I)
name += transTypeToOCLTypeName(TF->getParameterType(I)) + ',';
name.back() = ')'; // replace the last comma with a closing brace.
return name;
}
return transTypeToOCLTypeName(ET) + "*";
}
case OpTypeVector:
return transTypeToOCLTypeName(T->getVectorComponentType()) +
T->getVectorComponentCount();
case OpTypeOpaque:
return T->getName();
case OpTypeFunction:
return "function";
case OpTypeStruct: {
auto Name = T->getName();
if (Name.find("struct.") == 0)
Name[6] = ' ';
else if (Name.find("union.") == 0)
Name[5] = ' ';
return Name;
}
case OpTypePipe:
return "pipe";
case OpTypeSampler:
return "sampler_t";
case OpTypeImage:
return rmap<std::string>(static_cast<SPIRVTypeImage *>(T)->getDescriptor());
default:
if (isOpaqueGenericTypeOpCode(T->getOpCode())) {
auto Name = BuiltinOpaqueGenericTypeOpCodeMap::rmap(T->getOpCode());
if (Name.find("opencl.") == 0) {
return Name.substr(7);
} else {
return Name;
}
}
llvm_unreachable("Not implemented");
return "unknown";
}
}
std::vector<Type *>
SPIRVToLLVM::transTypeVector(const std::vector<SPIRVType *> &BT) {
std::vector<Type *> T;
for (auto I: BT)
T.push_back(transType(I));
return T;
}
std::vector<Value *>
SPIRVToLLVM::transValue(const std::vector<SPIRVValue *> &BV, Function *F,
BasicBlock *BB, BoolAction Action) {
std::vector<Value *> V;
for (auto I: BV)
V.push_back(transValue(I, F, BB, true, Action));
return V;
}
bool
SPIRVToLLVM::isSPIRVCmpInstTransToLLVMInst(SPIRVInstruction* BI) const {
auto OC = BI->getOpCode();
return isCmpOpCode(OC) &&
!(OC >= OpLessOrGreater && OC <= OpUnordered);
}
Value *
SPIRVToLLVM::transValue(SPIRVValue *BV, Function *F, BasicBlock *BB,
bool CreatePlaceHolder, BoolAction Action)
{
auto procBool = [&](Value *v)
{
if (Action == BoolAction::Noop)
return v;
if (!BV->hasType())
return v;
if (!BV->getType()->isTypeVectorOrScalarBool())
return v;
return Action == BoolAction::Promote ?
promoteBool(v, BB) :
truncBool(v, BB);
};
SPIRVToLLVMValueMap::iterator Loc = ValueMap.find(BV);
if (Loc != ValueMap.end() && (!PlaceholderMap.count(BV) || CreatePlaceHolder))
{
return procBool(Loc->second);
}
BV->validate();
auto V = transValueWithoutDecoration(BV, F, BB, CreatePlaceHolder);
if (!V) {
return nullptr;
}
V->setName(BV->getName());
if (!transDecoration(BV, V)) {
IGC_ASSERT_EXIT_MESSAGE(0, "trans decoration fail");
return nullptr;
}
return procBool(V);
}
Value *
SPIRVToLLVM::transConvertInst(SPIRVValue* BV, Function* F, BasicBlock* BB) {
SPIRVUnary* BC = static_cast<SPIRVUnary*>(BV);
auto Src = transValue(BC->getOperand(0), F, BB, BB ? true : false);
auto Dst = transType(BC->getType());
CastInst::CastOps CO = Instruction::BitCast;
bool IsExt = Dst->getScalarSizeInBits()
> Src->getType()->getScalarSizeInBits();
switch (BC->getOpCode()) {
case OpPtrCastToGeneric:
case OpGenericCastToPtr:
CO = Instruction::AddrSpaceCast;
break;
case OpSConvert:
CO = IsExt ? Instruction::SExt : Instruction::Trunc;
break;
case OpUConvert:
CO = IsExt ? Instruction::ZExt : Instruction::Trunc;
break;
case OpFConvert:
CO = IsExt ? Instruction::FPExt : Instruction::FPTrunc;
break;
default:
CO = static_cast<CastInst::CastOps>(OpCodeMap::rmap(BC->getOpCode()));
}
IGC_ASSERT_MESSAGE(CastInst::isCast(CO), "Invalid cast op code");
if (BB)
return CastInst::Create(CO, Src, Dst, BV->getName(), BB);
return ConstantExpr::getCast(CO, dyn_cast<Constant>(Src), Dst);
}
static void applyFPFastMathModeDecorations(const SPIRVValue* BV,
Instruction* Inst) {
SPIRVWord V;
FastMathFlags FMF;
if (BV->hasDecorate(DecorationFPFastMathMode, 0, &V)) {
if (V & FPFastMathModeNotNaNMask)
FMF.setNoNaNs();
if (V & FPFastMathModeNotInfMask)
FMF.setNoInfs();
if (V & FPFastMathModeNSZMask)
FMF.setNoSignedZeros();
if (V & FPFastMathModeAllowRecipMask)
FMF.setAllowReciprocal();
if (V & FPFastMathModeAllowContractINTELMask)
FMF.setAllowContract();
if (V & FPFastMathModeAllowReassocINTELMask)
FMF.setAllowReassoc();
if (V & FPFastMathModeFastMask)
FMF.setFast();
Inst->setFastMathFlags(FMF);
}
}
BinaryOperator *SPIRVToLLVM::transShiftLogicalBitwiseInst(SPIRVValue* BV,
BasicBlock* BB,Function* F) {
SPIRVBinary* BBN = static_cast<SPIRVBinary*>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
Instruction::BinaryOps BO;
auto OP = BBN->getOpCode();
if (isLogicalOpCode(OP))
OP = IntBoolOpMap::rmap(OP);
BO = static_cast<Instruction::BinaryOps>(OpCodeMap::rmap(OP));
auto Inst = BinaryOperator::Create(BO,
transValue(BBN->getOperand(0), F, BB),
transValue(BBN->getOperand(1), F, BB), BV->getName(), BB);
if (BV->hasDecorate(DecorationNoSignedWrap)) {
Inst->setHasNoSignedWrap(true);
}
if (BV->hasDecorate(DecorationNoUnsignedWrap)) {
Inst->setHasNoUnsignedWrap(true);
}
applyFPFastMathModeDecorations(BV, Inst);
return Inst;
}
Instruction *
SPIRVToLLVM::transLifetimeInst(SPIRVInstTemplateBase* BI, BasicBlock* BB, Function* F)
{
auto ID = (BI->getOpCode() == OpLifetimeStart) ?
Intrinsic::lifetime_start :
Intrinsic::lifetime_end;
#if LLVM_VERSION_MAJOR >= 7
auto *pFunc = Intrinsic::getDeclaration(M, ID, llvm::ArrayRef<llvm::Type*>(PointerType::getInt8PtrTy(*Context)));
#else
auto *pFunc = Intrinsic::getDeclaration(M, ID);
#endif
auto *pPtr = transValue(BI->getOperand(0), F, BB);
Value *pArgs[] =
{
ConstantInt::get(Type::getInt64Ty(*Context), BI->getOpWord(1)),
CastInst::CreatePointerCast(pPtr, PointerType::getInt8PtrTy(*Context), "", BB)
};
auto *pCI = CallInst::Create(pFunc, pArgs, "", BB);
return pCI;
}
Instruction *
SPIRVToLLVM::transCmpInst(SPIRVValue* BV, BasicBlock* BB, Function* F) {
SPIRVCompare* BC = static_cast<SPIRVCompare*>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
SPIRVType* BT = BC->getOperand(0)->getType();
Instruction* Inst = nullptr;
if (BT->isTypeVectorOrScalarInt()
|| BT->isTypePointer()
|| BT->isTypeQueue()
|| BT->isTypeBool())
Inst = new ICmpInst(*BB, CmpMap::rmap(BC->getOpCode()),
transValue(BC->getOperand(0), F, BB),
transValue(BC->getOperand(1), F, BB));
else if (BT->isTypeVectorOrScalarFloat())
Inst = new FCmpInst(*BB, CmpMap::rmap(BC->getOpCode()),
transValue(BC->getOperand(0), F, BB),
transValue(BC->getOperand(1), F, BB));
IGC_ASSERT_MESSAGE(Inst, "not implemented");
if (PlaceholderMap.count(BV) && Inst){
if (BV->getType()->isTypeBool())
Inst = cast<Instruction>(promoteBool(Inst, BB));
else
IGC_ASSERT(Inst->getType() == transType(BC->getType()));
IGC_ASSERT_MESSAGE(Inst, "Out of memory");
}
return Inst;
}
bool
SPIRVToLLVM::postProcessOCL() {
// I think we dont need it
std::vector <Function*> structFuncs;
for (auto& F : M->functions())
{
if (F.getReturnType()->isStructTy())
{
structFuncs.push_back(&F);
}
}
for (auto structFunc : structFuncs)
postProcessFunctionsReturnStruct(structFunc);
std::vector<Function*> aggrFuncs;
for (auto& F : M->functions())
{
if (std::any_of(F.arg_begin(), F.arg_end(), [](Argument& arg) { return arg.getType()->isAggregateType(); }) )
{
aggrFuncs.push_back(&F);
}
}
for (auto aggrFunc : aggrFuncs)
postProcessFunctionsWithAggregateArguments(aggrFunc);
return true;
}
bool
SPIRVToLLVM::postProcessFunctionsReturnStruct(Function *F) {
if (!F->getReturnType()->isStructTy())
return false;
std::string Name = F->getName().str();
F->setName(Name + ".old");
std::vector<Type *> ArgTys;
getFunctionTypeParameterTypes(F->getFunctionType(), ArgTys);
ArgTys.insert(ArgTys.begin(), PointerType::get(F->getReturnType(),
SPIRAS_Private));
auto newFType = FunctionType::get(Type::getVoidTy(*Context), ArgTys, false);
auto NewF = cast<Function>(M->getOrInsertFunction(Name, newFType));
NewF->setCallingConv(F->getCallingConv());
if (!F->isDeclaration()) {
ValueToValueMapTy VMap;
llvm::SmallVector<llvm::ReturnInst*, 8> Returns;
auto OldArgIt = F->arg_begin();
auto NewArgIt = NewF->arg_begin();
++NewArgIt; // Skip first argument that we added.
for (; OldArgIt != F->arg_end(); ++OldArgIt, ++NewArgIt) {
NewArgIt->setName(OldArgIt->getName());
VMap[&*OldArgIt] = &*NewArgIt;
}
CloneFunctionInto(NewF, F, VMap, true, Returns);
auto DL = M->getDataLayout();
const auto ptrSize = DL.getPointerSize();
for (auto RetInst : Returns) {
IGCLLVM::IRBuilder<> builder(RetInst);
Type* retTy = RetInst->getReturnValue()->getType();
Value* returnedValPtr = builder.CreateAlloca(retTy);
builder.CreateStore(RetInst->getReturnValue(), returnedValPtr);
auto size = DL.getTypeAllocSize(retTy);
builder.CreateMemCpy(&*NewF->arg_begin(), returnedValPtr, size, ptrSize);
builder.CreateRetVoid();
RetInst->eraseFromParent();
}
}
for (auto I = F->user_begin(), E = F->user_end(); I != E;) {
if (auto CI = dyn_cast<CallInst>(*I++)) {
auto Args = getArguments(CI);
IGCLLVM::IRBuilder<> builder(CI);
//auto Alloca = new AllocaInst(CI->getType(), "", CI);
auto Alloca = builder.CreateAlloca(CI->getType());
Args.insert(Args.begin(), Alloca);
auto NewCI = CallInst::Create(NewF, Args, "", CI);
NewCI->setCallingConv(CI->getCallingConv());
auto Load = new LoadInst(
#if LLVM_VERSION_MAJOR > 7
Alloca->getType()->getPointerElementType(),
#endif
Alloca,"",CI);
CI->replaceAllUsesWith(Load);
CI->eraseFromParent();
}
}
F->dropAllReferences();
F->removeFromParent();
return true;
}
bool
SPIRVToLLVM::postProcessFunctionsWithAggregateArguments(Function* F) {
auto Name = F->getName();
auto Attrs = F->getAttributes();
auto DL = M->getDataLayout();
auto ptrSize = DL.getPointerSize();
mutateFunction (F,
[=](CallInst *CI, std::vector<Value *> &Args) {
auto FBegin = CI->getParent()->getParent()->begin()->getFirstInsertionPt();
IGCLLVM::IRBuilder<> builder(&(*FBegin));
for (auto &I:Args) {
auto T = I->getType();
if (!T->isAggregateType())
continue;
if (auto constVal = dyn_cast<Constant>(I)) {
I = new GlobalVariable(*M, T, true, GlobalValue::InternalLinkage, constVal);
} else {
builder.SetInsertPoint(CI);
Value* allocaInst = builder.CreateAlloca(T);
builder.CreateStore(I, allocaInst);
I = allocaInst;
}
builder.SetInsertPoint(&*FBegin);
auto Alloca = builder.CreateAlloca(T);
Alloca->setAlignment(IGCLLVM::getCorrectAlign(ptrSize));
auto size = DL.getTypeAllocSize(T);
builder.SetInsertPoint(CI);
builder.CreateMemCpy(Alloca, I, size, ptrSize);
if (T->isArrayTy()) {
I = ptrSize > 4
? builder.CreateConstInBoundsGEP2_64(Alloca, 0, 0)
: builder.CreateConstInBoundsGEP2_32(nullptr, Alloca, 0, 0);
} else if (T->isStructTy()) {
I = Alloca;
} else {
llvm_unreachable("Unknown aggregate type!");
}
}
return Name.str();
}, false, &Attrs);
return true;
}
std::string
SPIRVToLLVM::transOCLPipeTypeAccessQualifier(igc_spv::SPIRVTypePipe* ST) {
return SPIRSPIRVAccessQualifierMap::rmap(ST->getAccessQualifier());
}
Value *
SPIRVToLLVM::oclTransConstantSampler(igc_spv::SPIRVConstantSampler* BCS) {
auto Lit = (BCS->getAddrMode() << 1) |
BCS->getNormalized() |
((BCS->getFilterMode() + 1) << 4);
auto Ty = IntegerType::getInt64Ty(*Context);
return ConstantInt::get(Ty, Lit);
}
static void insertCastAfter(Instruction* I, Instruction* Cast)
{
if (I->getOpcode() == Instruction::PHI) // put cast after last phi in BB
{
BasicBlock* BB = I->getParent();
IGC_ASSERT_MESSAGE(BB, "Invalid parent");
BasicBlock::iterator BBI = BB->end();
do {
--BBI;
} while (!isa<PHINode>(BBI));
Instruction* lastPhi = &(*BBI);
IGC_ASSERT_MESSAGE(lastPhi, "BasicBlock most contain at least one PHI");
Cast->insertAfter(lastPhi);
}
else
{
Cast->insertAfter(I);
}
}
Value *SPIRVToLLVM::promoteBool(Value *pVal, BasicBlock *BB)
{
if (!pVal->getType()->getScalarType()->isIntegerTy(1))
return pVal;
auto *PromoType = isa<VectorType>(pVal->getType()) ?
cast<Type>(IGCLLVM::FixedVectorType::get(Type::getInt8Ty(pVal->getContext()),
(unsigned)cast<IGCLLVM::FixedVectorType>(pVal->getType())->getNumElements())) :
Type::getInt8Ty(pVal->getContext());
if (auto *C = dyn_cast<Constant>(pVal))
return ConstantExpr::getZExtOrBitCast(C, PromoType);
if (BB == nullptr)
return pVal;
if (auto *Arg = dyn_cast<Argument>(pVal))
{
auto &entry = BB->getParent()->getEntryBlock();
Instruction *Cast = nullptr;
if (entry.empty())
{
Cast = CastInst::CreateZExtOrBitCast(Arg, PromoType, "i1promo", BB);
}
else
{
auto IP = entry.begin();
while (isa<AllocaInst>(IP)) ++IP;
if (IP == BB->end())
Cast = CastInst::CreateZExtOrBitCast(Arg, PromoType, "i1promo", BB);
else
Cast = CastInst::CreateZExtOrBitCast(Arg, PromoType, "i1promo", &(*IP));
}
return Cast;
}
auto *pInst = cast<Instruction>(pVal);
auto *Cast = CastInst::CreateZExtOrBitCast(pInst, PromoType, "i1promo");
insertCastAfter(pInst, Cast);
return Cast;
}
Value *SPIRVToLLVM::truncBool(Value *pVal, BasicBlock *BB)
{
if (!pVal->getType()->getScalarType()->isIntegerTy(8))
return pVal;
auto *TruncType = isa<VectorType>(pVal->getType()) ?
cast<Type>(IGCLLVM::FixedVectorType::get(Type::getInt1Ty(pVal->getContext()),
(unsigned)cast<IGCLLVM::FixedVectorType>(pVal->getType())->getNumElements())) :
Type::getInt1Ty(pVal->getContext());
if (auto *C = dyn_cast<Constant>(pVal))
return ConstantExpr::getTruncOrBitCast(C, TruncType);
if (BB == nullptr)
return pVal;
if (auto *Arg = dyn_cast<Argument>(pVal))
{
auto &entry = BB->getParent()->getEntryBlock();
Instruction *Cast = nullptr;
if (entry.empty())
{
Cast = CastInst::CreateTruncOrBitCast(Arg, TruncType, "i1trunc", BB);
}
else
{
auto IP = entry.begin();
while (isa<AllocaInst>(IP))
{
if (++IP == BB->end())
break;
}
if (IP == BB->end())
Cast = CastInst::CreateTruncOrBitCast(Arg, TruncType, "i1trunc", BB);
else
Cast = CastInst::CreateTruncOrBitCast(Arg, TruncType, "i1trunc", &(*IP));
}
return Cast;
}
auto *pInst = cast<Instruction>(pVal);
auto *Cast = CastInst::CreateTruncOrBitCast(pInst, TruncType, "i1trunc");
insertCastAfter(pInst, Cast);
return Cast;
}
Type *SPIRVToLLVM::truncBoolType(SPIRVType *SPVType, Type *LLType)
{
if (!SPVType->isTypeVectorOrScalarBool())
return LLType;
return isa<VectorType>(LLType) ?
cast<Type>(IGCLLVM::FixedVectorType::get(Type::getInt1Ty(LLType->getContext()),
(unsigned)cast<IGCLLVM::FixedVectorType>(LLType)->getNumElements())) :
Type::getInt1Ty(LLType->getContext());
}
// Translate aliasing memory access masks for SPIRVLoad and SPIRVStore
// instructions. These masks are mapped on alias.scope and noalias
// metadata in LLVM. Translation of optional string operand isn't yet supported
// in the translator.
template <typename SPIRVInstType>
void SPIRVToLLVM::transAliasingMemAccess(SPIRVInstType* BI, Instruction* I) {
static_assert(std::is_same<SPIRVInstType, SPIRVStore>::value ||
std::is_same<SPIRVInstType, SPIRVLoad>::value,
"Only stores and loads can be aliased by memory access mask");
bool IsAliasScope = BI->SPIRVMemoryAccess::isAliasScope();
bool IsNoAlias = BI->SPIRVMemoryAccess::isNoAlias();
if (!(IsAliasScope || IsNoAlias))
return;
uint32_t AliasMDKind = IsAliasScope ? LLVMContext::MD_alias_scope
: LLVMContext::MD_noalias;
SPIRVId AliasListId = BI->SPIRVMemoryAccess::getAliasing();
addMemAliasMetadata(I, AliasListId, AliasMDKind);
}
// Create and apply alias.scope/noalias metadata
void SPIRVToLLVM::addMemAliasMetadata(Instruction* I, SPIRVId AliasListId,
uint32_t AliasMDKind) {
SPIRVAliasScopeListDeclINTEL* AliasList =
BM->get<SPIRVAliasScopeListDeclINTEL>(AliasListId);
std::vector<SPIRVId> AliasScopeIds = AliasList->getArguments();
MDBuilder MDB(*Context);
SmallVector<Metadata*, 4> MDScopes;
for (const auto ScopeId : AliasScopeIds) {
SPIRVAliasScopeDeclINTEL* AliasScope =
BM->get<SPIRVAliasScopeDeclINTEL>(ScopeId);
std::vector<SPIRVId> AliasDomainIds = AliasScope->getArguments();
// Currently we expect exactly one argument for aliasing scope
// instruction.
// TODO: add translation of string scope and domain operand.
assert(AliasDomainIds.size() == 1 &&
"AliasScopeDeclINTEL must have exactly one argument");
SPIRVId AliasDomainId = AliasDomainIds[0];
// Create and store unique domain and scope metadata
MDAliasDomainMap.emplace(AliasDomainId,
MDB.createAnonymousAliasScopeDomain());
MDAliasScopeMap.emplace(ScopeId, MDB.createAnonymousAliasScope(
MDAliasDomainMap[AliasDomainId]));
MDScopes.emplace_back(MDAliasScopeMap[ScopeId]);
}
// Create and store unique alias.scope/noalias metadata
MDAliasListMap.emplace(
AliasListId,
MDNode::concatenate(I->getMetadata(LLVMContext::MD_alias_scope),
MDNode::get(*Context, MDScopes)));
I->setMetadata(AliasMDKind, MDAliasListMap[AliasListId]);
}
/// For instructions, this function assumes they are created in order
/// and appended to the given basic block. An instruction may use a
/// instruction from another BB which has not been translated. Such
/// instructions should be translated to place holders at the point
/// of first use, then replaced by real instructions when they are
/// created.
///
/// When CreatePlaceHolder is true, create a load instruction of a
/// global variable as placeholder for SPIRV instruction. Otherwise,
/// create instruction and replace placeholder if there is one.
Value *
SPIRVToLLVM::transValueWithoutDecoration(SPIRVValue *BV, Function *F,
BasicBlock *BB, bool CreatePlaceHolder){
auto OC = BV->getOpCode();
IntBoolOpMap::rfind(OC, &OC);
// Translation of non-instruction values
switch(OC) {
case OpSpecConstant:
case OpConstant: {
SPIRVConstant *BConst = static_cast<SPIRVConstant *>(BV);
SPIRVType *BT = BV->getType();
Type *LT = transType(BT);
uint64_t V = BConst->getZExtIntValue();
if(BV->hasDecorate(DecorationSpecId)) {
IGC_ASSERT_EXIT_MESSAGE(OC == OpSpecConstant, "Only SpecConstants can be specialized!");
SPIRVWord specid = *BV->getDecorate(DecorationSpecId).begin();
if(BM->isSpecConstantSpecialized(specid))
V = BM->getSpecConstant(specid);
}
switch(BT->getOpCode()) {
case OpTypeBool:
case OpTypeInt:
return mapValue(BV, ConstantInt::get(LT, V,
static_cast<SPIRVTypeInt*>(BT)->isSigned()));
case OpTypeFloat: {
const llvm::fltSemantics *FS = nullptr;
switch (BT->getFloatBitWidth()) {
case 16:
FS = &APFloat::IEEEhalf();
break;
case 32:
FS = &APFloat::IEEEsingle();
break;
case 64:
FS = &APFloat::IEEEdouble();
break;
default:
IGC_ASSERT_EXIT_MESSAGE(0, "invalid float type");
break;
}
return mapValue(BV, ConstantFP::get(*Context, APFloat(*FS,
APInt(BT->getFloatBitWidth(), V))));
}
default:
llvm_unreachable("Not implemented");
return NULL;
}
}
break;
case OpSpecConstantTrue:
if (BV->hasDecorate(DecorationSpecId)) {
SPIRVWord specid = *BV->getDecorate(DecorationSpecId).begin();
if (BM->isSpecConstantSpecialized(specid)) {
if (BM->getSpecConstant(specid))
return mapValue(BV, ConstantInt::getTrue(*Context));
else
return mapValue(BV, ConstantInt::getFalse(*Context));
}
}
// intentional fall-through: if decoration was not specified, treat this
// as a OpConstantTrue (default spec constant value)
case OpConstantTrue:
return mapValue(BV, ConstantInt::getTrue(*Context));
case OpSpecConstantFalse:
if (BV->hasDecorate(DecorationSpecId)) {
SPIRVWord specid = *BV->getDecorate(DecorationSpecId).begin();
if (BM->isSpecConstantSpecialized(specid)) {
if (BM->getSpecConstant(specid))
return mapValue(BV, ConstantInt::getTrue(*Context));
else
return mapValue(BV, ConstantInt::getFalse(*Context));
}
}
// intentional fall-through: if decoration was not specified, treat this
// as a OpConstantFalse (default spec constant value)
case OpConstantFalse:
return mapValue(BV, ConstantInt::getFalse(*Context));
case OpConstantNull: {
auto LT = transType(BV->getType());
return mapValue(BV, Constant::getNullValue(LT));
}
case OpSpecConstantComposite:
case OpConstantComposite: {
auto BCC = static_cast<SPIRVConstantComposite*>(BV);
std::vector<Constant *> CV;
for (auto &I:BCC->getElements())
CV.push_back(dyn_cast<Constant>(transValue(I, F, BB)));
for (auto& CI : BCC->getContinuedInstructions()) {
for (auto& I : CI->getElements())
CV.push_back(dyn_cast<Constant>(transValue(I, F, BB)));
}
switch(BV->getType()->getOpCode()) {
case OpTypeVector:
return mapValue(BV, ConstantVector::get(CV));
case OpTypeArray:
return mapValue(BV, ConstantArray::get(
dyn_cast<ArrayType>(transType(BCC->getType())), CV));
case OpTypeStruct:
return mapValue(BV, ConstantStruct::get(
dyn_cast<StructType>(transType(BCC->getType())), CV));
default:
llvm_unreachable("not implemented");
return nullptr;
}
}
break;
case OpCompositeConstruct: {
auto BCC = static_cast<SPIRVCompositeConstruct*>(BV);
std::vector<Value *> CV;
for(auto &I : BCC->getElements())
{
CV.push_back( transValue( I,F,BB ) );
}
switch(BV->getType()->getOpCode()) {
case OpTypeVector:
{
Type *T = transType( BCC->getType() );
Value *undef = llvm::UndefValue::get( T );
Value *elm1 = undef;
uint32_t pos = 0;
auto CreateCompositeConstruct = [&]( Value* Vec,Value* ValueToBeInserted,uint32_t Pos )
{
Value *elm = InsertElementInst::Create(
Vec,
ValueToBeInserted,
ConstantInt::get( *Context,APInt( 32,Pos ) ),
BCC->getName(),BB );
return elm;
};
for(unsigned i = 0; i < CV.size(); i++)
{
if(CV[i]->getType()->isVectorTy())
{
for(uint32_t j = 0; j < cast<IGCLLVM::FixedVectorType>(CV[i]->getType())->getNumElements(); j++)
{
Value *v = ExtractElementInst::Create( CV[i],ConstantInt::get( *Context,APInt( 32,j ) ),BCC->getName(),BB );
elm1 = CreateCompositeConstruct( elm1,v,pos++ );
}
}
else
{
elm1 = CreateCompositeConstruct( elm1,CV[i],pos++ );
}
}
return mapValue( BV,elm1 );
}
break;
case OpTypeArray:
case OpTypeStruct:
{
Type *T = transType( BV->getType() );
Value *undef = llvm::UndefValue::get( T );
Value *elm1 = undef;
for(unsigned i = 0; i < CV.size(); i++)
{
elm1 = InsertValueInst::Create(
elm1,
CV[i],
i,
BCC->getName(),BB );
}
return mapValue( BV,elm1 );
}
break;
default:
llvm_unreachable( "not implemented" );
return nullptr;
}
}
break;
case OpConstantSampler: {
auto BCS = static_cast<SPIRVConstantSampler*>(BV);
return mapValue(BV, oclTransConstantSampler(BCS));
}
case OpSpecConstantOp: {
auto BI = createInstFromSpecConstantOp(
static_cast<SPIRVSpecConstantOp*>(BV));
return mapValue(BV, transValue(BI, nullptr, nullptr, false));
}
case OpConstFunctionPointerINTEL: {
SPIRVConstFunctionPointerINTEL* BC =
static_cast<SPIRVConstFunctionPointerINTEL*>(BV);
SPIRVFunction* F = BC->getFunction();
BV->setName(F->getName());
return mapValue(BV, transFunction(F));
}
case OpConstantPipeStorage:
{
auto CPS = static_cast<SPIRVConstantPipeStorage*>(BV);
const uint32_t packetSize = CPS->GetPacketSize();
const uint32_t packetAlign = CPS->GetPacketAlignment();
const uint32_t maxNumPackets = CPS->GetCapacity();
// This value matches the definition from the runtime and that from pipe.cl.
const uint32_t INTEL_PIPE_HEADER_RESERVED_SPACE = 128;
const uint32_t numPacketsAlloc = maxNumPackets + 1;
const uint32_t bufSize = packetSize * numPacketsAlloc + INTEL_PIPE_HEADER_RESERVED_SPACE;
SmallVector<uint8_t, 256> buf(bufSize, 0);
// Initialize the pipe_max_packets field in the control structure.
for (unsigned i = 0; i < 4; i++)
buf[i] = (uint8_t)((numPacketsAlloc >> (8 * i)) & 0xff);
auto *pInit = ConstantDataArray::get(*Context, buf);
GlobalVariable *pGV = new GlobalVariable(
*M,
pInit->getType(),
false,
GlobalVariable::InternalLinkage,
pInit,
Twine("pipebuf"),
nullptr,
GlobalVariable::ThreadLocalMode::NotThreadLocal,
SPIRAS_Global);
pGV->setAlignment(IGCLLVM::getCorrectAlign(std::max(4U, packetAlign)));
auto *pStorageTy = transType(CPS->getType());
return mapValue(CPS, ConstantExpr::getBitCast(pGV, pStorageTy));
}
case OpUndef:
return mapValue(BV, UndefValue::get(transType(BV->getType())));
case OpVariable: {
auto BVar = static_cast<SPIRVVariable *>(BV);
auto Ty = transType(BVar->getType()->getPointerElementType());
bool IsConst = BVar->isConstant();
llvm::GlobalValue::LinkageTypes LinkageTy = transLinkageType(BVar);
Constant *Initializer = nullptr;
SPIRVStorageClassKind BS = BVar->getStorageClass();
SPIRVValue *Init = BVar->getInitializer();
if (Init)
Initializer = dyn_cast<Constant>(transValue(Init, F, BB, false));
else if (LinkageTy == GlobalValue::CommonLinkage)
// In LLVM variables with common linkage type must be initilized by 0
Initializer = Constant::getNullValue(Ty);
else if (BS == StorageClassWorkgroupLocal)
Initializer = UndefValue::get(Ty);
if (BS == StorageClassFunction && !Init) {
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
IGCLLVM::IRBuilder<> builder(BB);
//return mapValue(BV, new AllocaInst(Ty, BV->getName(), BB));
return mapValue(BV, builder.CreateAlloca(Ty, nullptr, BV->getName()));
}
auto AddrSpace = SPIRSPIRVAddrSpaceMap::rmap(BS);
auto LVar = new GlobalVariable(*M, Ty, IsConst, LinkageTy, Initializer,
BV->getName(), 0, GlobalVariable::NotThreadLocal, AddrSpace);
GlobalVariable::UnnamedAddr addrType = (IsConst && Ty->isArrayTy() &&
Ty->getArrayElementType()->isIntegerTy(8)) ? GlobalVariable::UnnamedAddr::Global :
GlobalVariable::UnnamedAddr::None;
LVar->setUnnamedAddr(addrType);
SPIRVBuiltinVariableKind BVKind = BuiltInCount;
if (BVar->isBuiltin(&BVKind))
BuiltinGVMap[LVar] = BVKind;
return mapValue(BV, LVar);
}
break;
case OpVariableLengthArrayINTEL: {
auto* VLA = static_cast<SPIRVVariableLengthArrayINTEL*>(BV);
llvm::Type* Ty = transType(BV->getType()->getPointerElementType());
llvm::Value* ArrSize = transValue(VLA->getOperand(0), F, BB, false);
return mapValue(
BV, new AllocaInst(Ty, SPIRAS_Private, ArrSize, BV->getName(), BB));
}
case OpSaveMemoryINTEL: {
Function* StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
return mapValue(BV, CallInst::Create(StackSave, "", BB));
}
case OpRestoreMemoryINTEL: {
auto* Restore = static_cast<SPIRVRestoreMemoryINTEL*>(BV);
llvm::Value* Ptr = transValue(Restore->getOperand(0), F, BB, false);
Function* StackRestore = Intrinsic::getDeclaration(M, Intrinsic::stackrestore);
return mapValue(BV, CallInst::Create(StackRestore, { Ptr }, "", BB));
}
case OpFunctionParameter: {
auto BA = static_cast<SPIRVFunctionParameter*>(BV);
IGC_ASSERT_MESSAGE(F, "Invalid function");
unsigned ArgNo = 0;
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
++I, ++ArgNo) {
if (ArgNo == BA->getArgNo())
return mapValue(BV, &(*I));
}
IGC_ASSERT_EXIT_MESSAGE(0, "Invalid argument");
return NULL;
}
break;
case OpFunction:
return mapValue(BV, transFunction(static_cast<SPIRVFunction *>(BV)));
case OpAsmINTEL:
return mapValue(BV, transAsmINTEL(static_cast<SPIRVAsmINTEL *>(BV), F, BB));
case OpLabel:
return mapValue(BV, BasicBlock::Create(*Context, BV->getName(), F));
break;
default:
// do nothing
break;
}
// During translation of OpSpecConstantOp we create an instruction
// corresponding to the Opcode operand and then translate this instruction.
// For such instruction BB and F should be nullptr, because it is a constant
// expression declared out of scope of any basic block or function.
// All other values require valid BB pointer.
IGC_ASSERT_MESSAGE(((isSpecConstantOpAllowedOp(OC) && !F && !BB) || BB), "Invalid BB");
// Creation of place holder
if (CreatePlaceHolder) {
auto GV = new GlobalVariable(*M,
transType(BV->getType()),
false,
GlobalValue::PrivateLinkage,
nullptr,
std::string(kPlaceholderPrefix) + BV->getName(),
0, GlobalVariable::NotThreadLocal, 0);
auto LD = new LoadInst(
#if LLVM_VERSION_MAJOR > 7
GV->getType()->getPointerElementType(),
#endif
GV, BV->getName(), BB);
PlaceholderMap[BV] = LD;
return mapValue(BV, LD);
}
// Translation of instructions
switch (BV->getOpCode()) {
case OpBranch: {
auto *BR = static_cast<SPIRVBranch *>(BV);
auto *BI = BranchInst::Create(
cast<BasicBlock>(transValue(BR->getTargetLabel(), F, BB)), BB);
// Loop metadata will be translated in the end of function translation.
return mapValue(BV, BI);
}
break;
case OpBranchConditional: {
auto *BR = static_cast<SPIRVBranchConditional *>(BV);
auto *BC = BranchInst::Create(
cast<BasicBlock>(transValue(BR->getTrueLabel(), F, BB)),
cast<BasicBlock>(transValue(BR->getFalseLabel(), F, BB)),
// cond must be an i1, truncate bool to i1 if it was an i8.
transValue(BR->getCondition(), F, BB, true, BoolAction::Truncate), BB);
// Loop metadata will be translated in the end of function translation.
return mapValue(BV, BC);
}
break;
case OpPhi: {
auto Phi = static_cast<SPIRVPhi *>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
auto LPhi = dyn_cast<PHINode>(mapValue(BV, PHINode::Create(
transType(Phi->getType()),
Phi->getPairs().size() / 2,
Phi->getName(),
BB)));
Phi->foreachPair([&](SPIRVValue *IncomingV, SPIRVBasicBlock *IncomingBB,
size_t Index){
auto Translated = transValue(IncomingV, F, BB);
LPhi->addIncoming(Translated,
dyn_cast<BasicBlock>(transValue(IncomingBB, F, BB)));
});
return LPhi;
}
break;
case OpReturn:
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
return mapValue(BV, ReturnInst::Create(*Context, BB));
break;
case OpReturnValue: {
auto RV = static_cast<SPIRVReturnValue *>(BV);
return mapValue(BV, ReturnInst::Create(*Context,
transValue(RV->getReturnValue(), F, BB), BB));
}
break;
case OpStore: {
SPIRVStore *BS = static_cast<SPIRVStore*>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
auto *pValue = transValue(BS->getSrc(), F, BB);
auto *pPointer = transValue(BS->getDst(), F, BB);
bool isVolatile =
BS->hasDecorate(DecorationVolatile) || BS->SPIRVMemoryAccess::isVolatile() != 0;
unsigned alignment = BS->SPIRVMemoryAccess::getAlignment();
if (auto *CS = dyn_cast<ConstantStruct>(pValue))
{
// Break up a store with a literal struct as the value as we don't have any
// legalization infrastructure to do it:
// Ex.
// store %0 { <2 x i32> <i32 -2100480000, i32 2100480000>, %1 { i32 -2100483600, i8 -128 } }, %0 addrspace(1)* %a
// =>
// %CS.tmpstore = alloca %0
// %0 = getelementptr inbounds %0* %CS.tmpstore, i32 0, i32 0
// store <2 x i32> <i32 -2100480000, i32 2100480000>, <2 x i32>* %0
// %1 = getelementptr inbounds %0* %CS.tmpstore, i32 0, i32 1
// %2 = getelementptr inbounds %1* %1, i32 0, i32 0
// store i32 -2100483600, i32* %2
// %3 = getelementptr inbounds %1* %1, i32 0, i32 1
// store i8 -128, i8* %3
// %4 = bitcast %0 addrspace(1)* %a to i8 addrspace(1)*
// %5 = bitcast %0* %CS.tmpstore to i8*
// call void @llvm.memcpy.p1i8.p0i8.i64(i8 addrspace(1)* %4, i8* %5, i64 16, i32 0, i1 false)
// So we emit this store in a similar fashion as clang would.
IGCLLVM::IRBuilder<> IRB(&F->getEntryBlock(), F->getEntryBlock().begin());
auto DL = M->getDataLayout();
std::function<void(ConstantStruct*, Value*)>
LowerConstantStructStore = [&](ConstantStruct *CS, Value *pointer)
{
for (unsigned I = 0, E = CS->getNumOperands(); I != E; I++)
{
auto *op = CS->getOperand(I);
auto *pGEP = IRB.CreateConstInBoundsGEP2_32(nullptr, pointer, 0, I);
if (auto *InnerCS = dyn_cast<ConstantStruct>(op))
LowerConstantStructStore(InnerCS, pGEP);
else
IRB.CreateStore(op, pGEP);
}
};
auto *pAlloca = IRB.CreateAlloca(pValue->getType(), nullptr, "CS.tmpstore");
IRB.SetInsertPoint(BB);
LowerConstantStructStore(CS, pAlloca);
auto *pDst = IRB.CreateBitCast(pPointer,
Type::getInt8PtrTy(*Context, pPointer->getType()->getPointerAddressSpace()));
auto *pSrc = IRB.CreateBitCast(pAlloca, Type::getInt8PtrTy(*Context));
auto *pMemCpy = IRB.CreateMemCpy(pDst, pSrc,
DL.getTypeAllocSize(pAlloca->getAllocatedType()),
alignment, isVolatile);
return mapValue(BV, pMemCpy);
}
StoreInst *SI = new StoreInst(
pValue,
pPointer,
isVolatile,
IGCLLVM::getCorrectAlign(alignment),
BB);
if(BS->SPIRVMemoryAccess::isNonTemporal())
transNonTemporalMetadata(SI);
transAliasingMemAccess<SPIRVStore>(BS, SI);
return mapValue(BV, SI);
}
break;
case OpLoad: {
SPIRVLoad *BL = static_cast<SPIRVLoad*>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
auto val = transValue(BL->getSrc(), F, BB);
LoadInst* LI = new LoadInst(
#if LLVM_VERSION_MAJOR > 7
val->getType()->getPointerElementType(),
#endif
val,
BV->getName(),
BL->hasDecorate(DecorationVolatile) || BL->SPIRVMemoryAccess::isVolatile() != 0,
IGCLLVM::getCorrectAlign(BL->SPIRVMemoryAccess::getAlignment()),
BB);
if(BL->SPIRVMemoryAccess::isNonTemporal())
transNonTemporalMetadata(LI);
transAliasingMemAccess<SPIRVLoad>(BL, LI);
return mapValue(BV, LI);
}
break;
case OpCopyMemorySized: {
SPIRVCopyMemorySized *BC = static_cast<SPIRVCopyMemorySized *>(BV);
CallInst *CI = nullptr;
llvm::Value *Dst = transValue(BC->getTarget(), F, BB);
unsigned Align = BC->getAlignment();
llvm::Value *Size = transValue(BC->getSize(), F, BB);
bool IsVolatile = BC->SPIRVMemoryAccess::isVolatile();
IGCLLVM::IRBuilder<> Builder(BB);
// If we copy from zero-initialized array, we can optimize it to llvm.memset
if (BC->getSource()->getOpCode() == OpBitcast) {
SPIRVValue *Source =
static_cast<SPIRVBitcast *>(BC->getSource())->getOperand(0);
if (Source->isVariable()) {
auto *Init = static_cast<SPIRVVariable *>(Source)->getInitializer();
if (Init && Init->getOpCode() == OpConstantNull) {
SPIRVType *Ty = static_cast<SPIRVConstantNull *>(Init)->getType();
if (Ty->isTypeArray()) {
Type* Int8Ty = Type::getInt8Ty(Dst->getContext());
llvm::Value* Src = ConstantInt::get(Int8Ty, 0);
llvm::Value* newDst = Dst;
if (!Dst->getType()->getPointerElementType()->isIntegerTy(8)) {
Type* Int8PointerTy = Type::getInt8PtrTy(Dst->getContext(),
Dst->getType()->getPointerAddressSpace());
newDst = llvm::BitCastInst::CreatePointerCast(Dst,
Int8PointerTy, "", BB);
}
CI = Builder.CreateMemSet(newDst, Src, Size, IGCLLVM::getCorrectAlign(Align), IsVolatile);
}
}
}
}
if (!CI) {
llvm::Value *Src = transValue(BC->getSource(), F, BB);
CI = Builder.CreateMemCpy(Dst, Src, Size, Align, IsVolatile);
}
if (isFuncNoUnwind())
CI->getFunction()->addFnAttr(Attribute::NoUnwind);
return mapValue(BV, CI);
}
break;
case OpCopyObject: {
auto BI = static_cast<SPIRVInstTemplateBase*>(BV);
auto source = transValue( BI->getOperand( 0 ),F,BB );
return mapValue( BV,source );
}
case OpSelect: {
SPIRVSelect *BS = static_cast<SPIRVSelect*>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
return mapValue(BV, SelectInst::Create(
// cond must be an i1, truncate bool to i1 if it was an i8.
transValue(BS->getCondition(), F, BB, true, BoolAction::Truncate),
transValue(BS->getTrueValue(), F, BB),
transValue(BS->getFalseValue(), F, BB),
BV->getName(), BB));
}
break;
case OpLoopMerge: // Will be translated after all other function's
case OpLoopControlINTEL: // instructions are translated.
{
FuncLoopMetadataMap[BB] = BV;
return nullptr;
}
break;
case OpSwitch: {
auto BS = static_cast<SPIRVSwitch *>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
auto Select = transValue(BS->getSelect(), F, BB);
auto LS = SwitchInst::Create(Select,
dyn_cast<BasicBlock>(transValue(BS->getDefault(), F, BB)),
BS->getNumPairs(), BB);
BS->foreachPair(
[&](SPIRVSwitch::LiteralTy Literals, SPIRVBasicBlock *Label) {
IGC_ASSERT_MESSAGE(!Literals.empty(), "Literals should not be empty");
IGC_ASSERT_MESSAGE(Literals.size() <= 2, "Number of literals should not be more then two");
uint64_t Literal = uint64_t(Literals.at(0));
if (Literals.size() == 2) {
Literal += uint64_t(Literals.at(1)) << 32;
}
LS->addCase(ConstantInt::get(dyn_cast<IntegerType>(Select->getType()), Literal),
dyn_cast<BasicBlock>(transValue(Label, F, BB)));
});
return mapValue(BV, LS);
}
break;
case OpAccessChain:
case OpInBoundsAccessChain:
case OpPtrAccessChain:
case OpInBoundsPtrAccessChain: {
auto AC = static_cast<SPIRVAccessChainBase *>(BV);
auto Base = transValue(AC->getBase(), F, BB);
auto Index = transValue(AC->getIndices(), F, BB);
if (!AC->hasPtrIndex())
Index.insert(Index.begin(), getInt32(M, 0));
auto IsInbound = AC->isInBounds();
Value *V = nullptr;
if (BB) {
auto GEP = GetElementPtrInst::Create(nullptr, Base, Index, BV->getName(), BB);
GEP->setIsInBounds(IsInbound);
V = GEP;
} else {
V = ConstantExpr::getGetElementPtr(nullptr, dyn_cast<Constant>(Base), Index, IsInbound);
}
return mapValue(BV, V);
}
break;
case OpCompositeExtract: {
SPIRVCompositeExtract *CE = static_cast<SPIRVCompositeExtract *>(BV);
auto Type = CE->getComposite()->getType();
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
if (Type->isTypeVector())
{
IGC_ASSERT_MESSAGE(CE->getIndices().size() == 1, "Invalid index");
return mapValue(BV, ExtractElementInst::Create(
transValue(CE->getComposite(), F, BB),
ConstantInt::get(*Context, APInt(32, CE->getIndices()[0])),
BV->getName(), BB));
}
else
{
return mapValue(BV, ExtractValueInst::Create(
transValue(CE->getComposite(), F, BB),
CE->getIndices(),
BV->getName(), BB));
}
}
break;
case OpVectorExtractDynamic: {
auto CE = static_cast<SPIRVVectorExtractDynamic *>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
return mapValue(BV, ExtractElementInst::Create(
transValue(CE->getVector(), F, BB),
transValue(CE->getIndex(), F, BB),
BV->getName(), BB));
}
break;
case OpCompositeInsert: {
auto CI = static_cast<SPIRVCompositeInsert *>(BV);
auto Type = CI->getComposite()->getType();
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
if (Type->isTypeVector())
{
IGC_ASSERT_MESSAGE(CI->getIndices().size() == 1, "Invalid index");
return mapValue(BV, InsertElementInst::Create(
transValue(CI->getComposite(), F, BB),
transValue(CI->getObject(), F, BB),
ConstantInt::get(*Context, APInt(32, CI->getIndices()[0])),
BV->getName(), BB));
}
else
{
return mapValue(BV, InsertValueInst::Create(
transValue(CI->getComposite(), F, BB),
transValue(CI->getObject(), F, BB),
CI->getIndices(),
BV->getName(), BB));
}
}
break;
case OpVectorInsertDynamic: {
auto CI = static_cast<SPIRVVectorInsertDynamic *>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
return mapValue(BV, InsertElementInst::Create(
transValue(CI->getVector(), F, BB),
transValue(CI->getComponent(), F, BB),
transValue(CI->getIndex(), F, BB),
BV->getName(), BB));
}
break;
case OpVectorShuffle: {
auto VS = static_cast<SPIRVVectorShuffle *>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
std::vector<Constant *> Components;
IntegerType *Int32Ty = IntegerType::get(*Context, 32);
for (auto I : VS->getComponents()) {
if (I == static_cast<SPIRVWord>(-1))
Components.push_back(UndefValue::get(Int32Ty));
else
Components.push_back(ConstantInt::get(Int32Ty, I));
}
return mapValue(BV, new ShuffleVectorInst(
transValue(VS->getVector1(), F, BB),
transValue(VS->getVector2(), F, BB),
ConstantVector::get(Components),
BV->getName(), BB));
}
break;
case OpAssumeTrueKHR: {
IRBuilder<> Builder(BB);
SPIRVAssumeTrueKHR* BC = static_cast<SPIRVAssumeTrueKHR*>(BV);
Value* Condition = transValue(BC->getCondition(), F, BB);
Condition = Builder.CreateTrunc(Condition, Type::getInt1Ty(*Context));
return mapValue(BV, Builder.CreateAssumption(Condition));
}
case OpExpectKHR: {
IRBuilder<> Builder(BB);
SPIRVExpectKHRInstBase* BC = static_cast<SPIRVExpectKHRInstBase*>(BV);
Value* Val = transValue(BC->getOperand(0), F, BB);
Value* ExpVal = transValue(BC->getOperand(1), F, BB);
Function* ExpectFn = Intrinsic::getDeclaration(M, Intrinsic::expect, Val->getType());
return mapValue(
BV, Builder.CreateCall(ExpectFn, {Val, ExpVal}));
}
case OpFunctionCall: {
SPIRVFunctionCall *BC = static_cast<SPIRVFunctionCall *>(BV);
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
auto Call = CallInst::Create(
transFunction(BC->getFunction()),
transValue(BC->getArgumentValues(), F, BB),
BC->getName(),
BB);
setCallingConv(Call);
setAttrByCalledFunc(Call);
return mapValue(BV, Call);
}
break;
case OpAsmCallINTEL:
return mapValue(
BV, transAsmCallINTEL(static_cast<SPIRVAsmCallINTEL *>(BV), F, BB));
case OpFunctionPointerCallINTEL: {
SPIRVFunctionPointerCallINTEL *BC =
static_cast<SPIRVFunctionPointerCallINTEL*>(BV);
auto func = transValue(BC->getCalledValue(), F, BB);
auto Call = CallInst::Create(
#if LLVM_VERSION_MAJOR > 7
llvm::cast<llvm::FunctionType>(
llvm::cast<llvm::PointerType>(func->getType())->getElementType()),
#endif
func,
transValue(BC->getArgumentValues(), F, BB),
BC->getName(),
BB);
// Assuming we are calling a regular device function
Call->setCallingConv(CallingConv::SPIR_FUNC);
// Don't set attributes, because at translation time we don't know which
// function exactly we are calling.
return mapValue(BV, Call);
}
case OpExtInst:
return mapValue(BV, transOCLBuiltinFromExtInst(
static_cast<SPIRVExtInst *>(BV), BB));
break;
case OpSNegate: {
SPIRVUnary *BC = static_cast<SPIRVUnary*>(BV);
return mapValue(BV, BinaryOperator::CreateNSWNeg(
transValue(BC->getOperand(0), F, BB),
BV->getName(), BB));
}
case OpFNegate: {
SPIRVUnary *BC = static_cast<SPIRVUnary*>(BV);
auto Neg =
#if LLVM_VERSION_MAJOR <= 10
BinaryOperator
#else
UnaryOperator
#endif
::CreateFNeg(
transValue(BC->getOperand(0), F, BB),
BV->getName(), BB);
applyFPFastMathModeDecorations(BV, Neg);
return mapValue(BV, Neg);
}
break;
case OpNot: {
SPIRVUnary *BC = static_cast<SPIRVUnary*>(BV);
return mapValue(BV, BinaryOperator::CreateNot(
transValue(BC->getOperand(0), F, BB),
BV->getName(), BB));
}
break;
case OpSizeOf:
{
auto BI = static_cast<SPIRVSizeOf*>(BV);
IGC_ASSERT_MESSAGE(BI->getOpWords().size() == 1, "OpSizeOf takes one argument!");
// getOperands() returns SPIRVValue(s) but this argument is a SPIRVType so
// we have to just grab it by its entry id.
auto pArg = BI->get<SPIRVTypePointer>(BI->getOpWord(0));
auto pointee = pArg->getPointerElementType();
auto DL = M->getDataLayout();
uint64_t size = DL.getTypeAllocSize(transType(pointee));
return mapValue(BV, ConstantInt::get(Type::getInt32Ty(*Context), size));
}
case OpCreatePipeFromPipeStorage:
{
auto BI = static_cast<SPIRVCreatePipeFromPipeStorage*>(BV);
IGC_ASSERT_MESSAGE(BI->getOpWords().size() == 1, "OpCreatePipeFromPipeStorage takes one argument!");
return mapValue(BI, CastInst::CreateTruncOrBitCast(
transValue(BI->getOperand(0), F, BB),
transType(BI->getType()),
"", BB));
}
case OpUnreachable:
{
return mapValue(BV, new UnreachableInst(*Context, BB));
}
case OpLifetimeStart:
case OpLifetimeStop:
{
return mapValue(BV,
transLifetimeInst(static_cast<SPIRVInstTemplateBase*>(BV), BB, F));
}
case OpVectorTimesScalar:
{
auto BI = static_cast<SPIRVInstTemplateBase*>(BV);
auto Vector = transValue(BI->getOperand(0), F, BB);
auto Scalar = transValue(BI->getOperand(1), F, BB);
auto VecType = cast<IGCLLVM::FixedVectorType>(Vector->getType());
auto Undef = UndefValue::get(VecType);
auto ScalarVec = InsertElementInst::Create(Undef, Scalar,
ConstantInt::getNullValue(Type::getInt32Ty(*Context)), "", BB);
for (unsigned i = 1; i < VecType->getNumElements(); i++)
{
ScalarVec = InsertElementInst::Create(ScalarVec, Scalar,
ConstantInt::get(Type::getInt32Ty(*Context), i), "", BB);
}
return mapValue(BV, BinaryOperator::CreateFMul(Vector, ScalarVec, "", BB));
}
case OpSMod:
{
auto BI = static_cast<SPIRVSRem*>(BV);
auto *a = transValue(BI->getOperand(0), F, BB);
auto *b = transValue(BI->getOperand(1), F, BB);
auto *zero = ConstantInt::getNullValue(a->getType());
auto *ShiftAmt = ConstantInt::get(
a->getType()->getScalarType(),
a->getType()->getScalarSizeInBits() - 1);
auto *ShiftOp = isa<VectorType>(a->getType()) ?
ConstantVector::getSplat(
IGCLLVM::getElementCount((unsigned)cast<IGCLLVM::FixedVectorType>(a->getType())->getNumElements()), ShiftAmt) :
ShiftAmt;
// OCL C:
//
// int mod(int a, int b)
// {
// int out = a % b;
// if (((a >> 31) != (b >> 31)) & out != 0)
// {
// // only add b to out if sign(a) != sign(b) and out != 0.
// out += b;
// }
//
// return out;
// }
// %out = srem %a, %b
auto *out = BinaryOperator::CreateSRem(a, b, "", BB);
// %sha = ashr %a, 31
auto *sha = BinaryOperator::CreateAShr(a, ShiftOp, "", BB);
// %shb = ashr %b, 31
auto *shb = BinaryOperator::CreateAShr(b, ShiftOp, "", BB);
// %cmp1 = icmp ne %sha, %shb
auto *cmp1 = CmpInst::Create(Instruction::ICmp, llvm::CmpInst::ICMP_NE,
sha, shb, "", BB);
// %cmp2 = icmp ne %out, 0
auto *cmp2 = CmpInst::Create(Instruction::ICmp, llvm::CmpInst::ICMP_NE,
out, zero, "", BB);
// %and = and %cmp1, %cmp2
auto *and1 = BinaryOperator::CreateAnd(cmp1, cmp2, "", BB);
// %add = add %out, %b
auto *add = BinaryOperator::CreateAdd(out, b, "", BB);
// %sel = select %and, %add, %out
auto *sel = SelectInst::Create(and1, add, out, "", BB);
return mapValue(BV, sel);
}
case OpArithmeticFenceINTEL:
{
// Translate arithmetic fence to it's operand to avoid crash on unknown opcode.
// It is planned to be translated into @llvm.arithmetic.fence.f64 in the future.
auto* BC = static_cast<SPIRVUnary*>(BV);
return mapValue(BV, transValue(BC->getOperand(0), F, BB));
}
default: {
auto OC = BV->getOpCode();
if (isSPIRVCmpInstTransToLLVMInst(static_cast<SPIRVInstruction*>(BV))) {
return mapValue(BV, transCmpInst(BV, BB, F));
} else if (isCvtOpCode(OC)) {
auto BI = static_cast<SPIRVInstruction *>(BV);
Value *Inst = nullptr;
if (BI->hasFPRoundingMode() || BI->isSaturatedConversion() || OC == OpGenericCastToPtrExplicit)
Inst = transSPIRVBuiltinFromInst(BI, BB);
else
Inst = transConvertInst(BV, F, BB);
return mapValue(BV, Inst);
} else if (OCLSPIRVBuiltinMap::find(OC) ||
isIntelSubgroupOpCode(OC)) {
return mapValue(BV, transSPIRVBuiltinFromInst(
static_cast<SPIRVInstruction *>(BV), BB));
} else if (isBinaryShiftLogicalBitwiseOpCode(OC) ||
isLogicalOpCode(OC)) {
return mapValue(BV, transShiftLogicalBitwiseInst(BV, BB, F));
}
return mapValue(BV, transSPIRVBuiltinFromInst(
static_cast<SPIRVInstruction *>(BV), BB));
}
IGC_ASSERT_EXIT_MESSAGE(0, "Translation of SPIRV instruction not implemented");
return NULL;
}
}
template<class SourceTy, class FuncTy>
bool
SPIRVToLLVM::foreachFuncCtlMask(SourceTy Source, FuncTy Func) {
SPIRVWord FCM = Source->getFuncCtlMask();
SPIRSPIRVFuncCtlMaskMap::foreach([&](Attribute::AttrKind Attr,
SPIRVFunctionControlMaskKind Mask){
if (FCM & Mask)
Func(Attr);
});
return true;
}
Function *
SPIRVToLLVM::transFunction(SPIRVFunction *BF) {
auto Loc = FuncMap.find(BF);
if (Loc != FuncMap.end())
return Loc->second;
auto IsKernel = BM->isEntryPoint(ExecutionModelKernel, BF->getId());
auto Linkage = IsKernel ? GlobalValue::ExternalLinkage :
transLinkageType(BF);
FunctionType *FT = dyn_cast<FunctionType>(transType(BF->getFunctionType()));
Function *F = dyn_cast<Function>(mapValue(BF, Function::Create(FT, Linkage,
BF->getName(), M)));
mapFunction(BF, F);
if (BF->hasDecorate(DecorationReferencedIndirectlyINTEL))
F->addFnAttr("referenced-indirectly");
if (!F->isIntrinsic()) {
F->setCallingConv(IsKernel ? CallingConv::SPIR_KERNEL :
CallingConv::SPIR_FUNC);
if (isFuncNoUnwind())
F->addFnAttr(Attribute::NoUnwind);
foreachFuncCtlMask(BF, [&](Attribute::AttrKind Attr){
F->addFnAttr(Attr);
});
}
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
++I) {
auto BA = BF->getArgument(I->getArgNo());
mapValue(BA, &(*I));
const std::string &ArgName = BA->getName();
if (!ArgName.empty())
I->setName(ArgName);
BA->foreachAttr([&](SPIRVFuncParamAttrKind Kind){
if (Kind == FunctionParameterAttributeCount)
return;
F->addAttribute(I->getArgNo() + 1, SPIRSPIRVFuncParamAttrMap::rmap(Kind));
});
}
BF->foreachReturnValueAttr([&](SPIRVFuncParamAttrKind Kind){
if (Kind == FunctionParameterAttributeCount)
return;
F->addAttribute(AttributeList::ReturnIndex,
SPIRSPIRVFuncParamAttrMap::rmap(Kind));
});
// Creating all basic blocks before creating instructions.
for (size_t I = 0, E = BF->getNumBasicBlock(); I != E; ++I) {
transValue(BF->getBasicBlock(I), F, nullptr, true, BoolAction::Noop);
}
for (size_t I = 0, E = BF->getNumBasicBlock(); I != E; ++I) {
SPIRVBasicBlock *BBB = BF->getBasicBlock(I);
BasicBlock *BB = dyn_cast<BasicBlock>(transValue(BBB, F, nullptr, true, BoolAction::Noop));
for (size_t BI = 0, BE = BBB->getNumInst(); BI != BE; ++BI) {
SPIRVInstruction *BInst = BBB->getInst(BI);
transValue(BInst, F, BB, false, BoolAction::Noop);
}
}
transLLVMLoopMetadata(F);
return F;
}
Value *SPIRVToLLVM::transAsmINTEL(SPIRVAsmINTEL *BA, Function *F, BasicBlock *BB) {
bool HasSideEffect = BA->hasDecorate(DecorationSideEffectsINTEL);
return InlineAsm::get(
dyn_cast<FunctionType>(transType(BA->getFunctionType())),
BA->getInstructions(), BA->getConstraints(), HasSideEffect,
/* IsAlignStack */ false, InlineAsm::AsmDialect::AD_ATT);
}
CallInst *SPIRVToLLVM::transAsmCallINTEL(SPIRVAsmCallINTEL *BI, Function *F,
BasicBlock *BB) {
auto *IA = cast<InlineAsm>(transValue(BI->getAsm(), F, BB));
auto Args = transValue(BM->getValues(BI->getArguments()), F, BB);
return CallInst::Create(IA, Args, BI->getName(), BB);
}
uint64_t SPIRVToLLVM::calcImageType(const SPIRVValue *ImageVal)
{
const SPIRVTypeImage* TI = nullptr;
if (ImageVal->getType()->isTypeSampledImage()) {
TI = static_cast<SPIRVTypeSampledImage*>(ImageVal->getType())->getImageType();
}
else if (ImageVal->getType()->isTypeVmeImageINTEL()) {
TI = static_cast<SPIRVTypeVmeImageINTEL*>(ImageVal->getType())->getImageType();
}
else {
TI = static_cast<SPIRVTypeImage*>(ImageVal->getType());
}
const auto &Desc = TI->getDescriptor();
uint64_t ImageType = 0;
ImageType |= ((uint64_t)Desc.Dim & 0x7) << 59;
ImageType |= ((uint64_t)Desc.Depth & 0x1) << 58;
ImageType |= ((uint64_t)Desc.Arrayed & 0x1) << 57;
ImageType |= ((uint64_t)Desc.MS & 0x1) << 56;
ImageType |= ((uint64_t)Desc.Sampled & 0x3) << 62;
ImageType |= ((uint64_t)TI->getAccessQualifier() & 0x3) << 54;
return ImageType;
}
Instruction *
SPIRVToLLVM::transSPIRVBuiltinFromInst(SPIRVInstruction *BI, BasicBlock *BB) {
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
const auto OC = BI->getOpCode();
auto Ops = BI->getOperands();
// builtins use bool for scalar and ucharx for vector bools. Truncate
// or promote as necessary.
std::vector<Value *> operands;
for (auto I : Ops)
{
BoolAction Action = I->getType()->isTypeBool() ?
BoolAction::Truncate :
BoolAction::Promote;
operands.push_back(transValue(I, BB->getParent(), BB, true, Action));
}
{
// Update image ops to add 'image type' to operands:
switch (OC)
{
case OpSampledImage:
case OpVmeImageINTEL:
case OpImageRead:
case OpImageWrite:
case OpImageQuerySize:
case OpImageQuerySizeLod:
{
// resolving argument imageType for
// __builtin_spirv_OpSampledImage(%opencl.image2d_t.read_only addrspace(1)* %srcimg0,
// i64 imageType, i32 20)
Type *pType = Type::getInt64Ty(*Context);
uint64_t ImageType = calcImageType(BI->getOperands()[0]);
operands.insert(operands.begin() + 1, ConstantInt::get(pType, ImageType));
break;
}
default:
break;
}
// WA for image inlining:
switch (OC)
{
case OpImageSampleExplicitLod:
case OpImageRead:
case OpImageWrite:
case OpImageQueryFormat:
case OpImageQueryOrder:
case OpImageQuerySizeLod:
case OpImageQuerySize:
case OpImageQueryLevels:
case OpImageQuerySamples:
{
auto type = getOrCreateOpaquePtrType(M, "struct.ImageDummy");
auto val = Constant::getNullValue(type);
operands.push_back(val);
break;
}
default:
break;
}
}
bool hasReturnTypeInTypeList = false;
std::string suffix;
if (isCvtOpCode(OC))
{
hasReturnTypeInTypeList = true;
if (BI->isSaturatedConversion() &&
!(BI->getOpCode() == OpSatConvertSToU || BI->getOpCode() == OpSatConvertUToS))
{
suffix += "_Sat";
}
SPIRVFPRoundingModeKind kind;
std::string rounding_string;
if (BI->hasFPRoundingMode(&kind))
{
switch (kind)
{
case FPRoundingModeRTE:
rounding_string = "_RTE";
break;
case FPRoundingModeRTZ:
rounding_string = "_RTZ";
break;
case FPRoundingModeRTP:
rounding_string = "_RTP";
break;
case FPRoundingModeRTN:
rounding_string = "_RTN";
break;
default:
break;
}
}
suffix += rounding_string;
}
std::vector<Type*> ArgTys;
for (auto &v : operands)
{
// replace function by function pointer
auto *ArgTy = v->getType()->isFunctionTy() ?
v->getType()->getPointerTo() :
v->getType();
ArgTys.push_back(ArgTy);
}
// OpImageSampleExplicitLod: SImage | Coordinate | ImageOperands | LOD
// OpImageWrite: Image | Image Type | Coordinate | Texel
// OpImageRead: Image | Image Type | Coordinate
// Look for opaque image pointer operands and convert it with an i64 type
bool convertImageToI64 = (OC != OpSubgroupImageBlockReadINTEL && OC != OpSubgroupImageBlockWriteINTEL);
if (convertImageToI64)
{
for (auto i = 0U; i < BI->getOperands().size(); i++) {
SPIRVValue* imagePtr = BI->getOperands()[i];
if (imagePtr->getType()->isTypeImage())
{
IGC_ASSERT(isa<PointerType>(transType(imagePtr->getType())));
Value* ImageArgVal = llvm::PtrToIntInst::Create(
Instruction::PtrToInt,
transValue(imagePtr, BB->getParent(), BB),
Type::getInt64Ty(*Context),
"ImageArgVal",
BB);
// replace opaque pointer type with i64 type
IGC_ASSERT(ArgTys[i] == transType(imagePtr->getType()));
ArgTys[i] = ImageArgVal->getType();
operands[i] = ImageArgVal;
}
}
}
if (isImageOpCode(OC))
{
// Writes have a void return type that is not part of the mangle.
if (OC != OpImageWrite)
{
hasReturnTypeInTypeList = true;
}
// need to widen coordinate type
SPIRVValue* coordinate = BI->getOperands()[1];
Type* coordType = transType(coordinate->getType());
Value *imageCoordinateWiden = nullptr;
if (!isa<VectorType>(coordType))
{
Value *undef = UndefValue::get(IGCLLVM::FixedVectorType::get(coordType, 4));
imageCoordinateWiden = InsertElementInst::Create(
undef,
transValue(coordinate, BB->getParent(), BB),
ConstantInt::get(Type::getInt32Ty(*Context), 0),
"",
BB);
}
else if (cast<IGCLLVM::FixedVectorType>(coordType)->getNumElements() != 4)
{
Value *undef = UndefValue::get(coordType);
SmallVector<Constant*, 4> shuffleIdx;
for (unsigned i = 0; i < cast<IGCLLVM::FixedVectorType>(coordType)->getNumElements(); i++)
shuffleIdx.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
for (uint64_t i = (unsigned)cast<IGCLLVM::FixedVectorType>(coordType)->getNumElements(); i < 4; i++)
shuffleIdx.push_back(ConstantInt::get(Type::getInt32Ty(*Context), 0));
imageCoordinateWiden = new ShuffleVectorInst(
transValue(coordinate, BB->getParent(), BB),
undef,
ConstantVector::get(shuffleIdx),
"",
BB);
}
if (imageCoordinateWiden != nullptr)
{
const uint32_t CoordArgIdx = (OC == OpImageSampleExplicitLod) ? 1 : 2;
ArgTys[CoordArgIdx] = imageCoordinateWiden->getType();
operands[CoordArgIdx] = imageCoordinateWiden;
}
}
if (OC == OpImageQuerySizeLod ||
OC == OpImageQuerySize ||
OC == OpSubgroupBlockReadINTEL ||
OC == OpSubgroupImageBlockReadINTEL)
{
hasReturnTypeInTypeList = true;
}
Type *RetTy = Type::getVoidTy(*Context);
if (BI->hasType())
{
auto *pTrans = transType(BI->getType());
RetTy = BI->getType()->isTypeBool() ?
truncBoolType(BI->getType(), pTrans) :
pTrans;
}
if (hasReturnTypeInTypeList)
{
ArgTys.insert(ArgTys.begin(), RetTy);
}
std::string builtinName(getSPIRVBuiltinName(OC, BI, ArgTys, suffix));
// Fix mangling of VME builtins.
if (isIntelVMEOpCode(OC)) {
decltype(ArgTys) ArgTysWithVME_WA;
for (auto t : ArgTys) {
if (isa<PointerType>(t) &&
t->getPointerElementType()->isStructTy()) {
ArgTysWithVME_WA.push_back(t->getPointerElementType());
}
else {
ArgTysWithVME_WA.push_back(t);
}
}
builtinName = getSPIRVBuiltinName(OC, BI, ArgTysWithVME_WA, suffix);
}
if (hasReturnTypeInTypeList)
{
ArgTys.erase(ArgTys.begin());
}
Function* Func = M->getFunction(builtinName);
FunctionType* FT = FunctionType::get(RetTy, ArgTys, false);
if (!Func || Func->getFunctionType() != FT)
{
Func = Function::Create(FT, GlobalValue::ExternalLinkage, builtinName, M);
Func->setCallingConv(CallingConv::SPIR_FUNC);
if (isFuncNoUnwind())
Func->addFnAttr(Attribute::NoUnwind);
}
auto Call = CallInst::Create(Func, operands, "", BB);
Call->setName(BI->getName());
setAttrByCalledFunc(Call);
return Call;
}
Type* SPIRVToLLVM::getNamedBarrierType()
{
if (!m_NamedBarrierType)
{
llvm::SmallVector<Type*, 3> NamedBarrierSturctType(3, Type::getInt32Ty(*Context));
m_NamedBarrierType = StructType::create(*Context, NamedBarrierSturctType, "struct.__namedBarrier")->getPointerTo(SPIRAS_Local);
}
return m_NamedBarrierType;
}
bool
SPIRVToLLVM::translate() {
if (!transAddressingModel())
return false;
compileUnit = DbgTran.createCompileUnit();
for (unsigned I = 0, E = BM->getNumVariables(); I != E; ++I) {
auto BV = BM->getVariable(I);
if (BV->getStorageClass() != StorageClassFunction)
transValue(BV, nullptr, nullptr, true, BoolAction::Noop);
}
for (unsigned I = 0, E = BM->getNumFunctions(); I != E; ++I) {
transFunction(BM->getFunction(I));
}
for(auto& funcs : FuncMap)
{
auto diSP = getDbgTran().getDISP(funcs.first->getId());
if (diSP)
funcs.second->setSubprogram(diSP);
}
if (!transKernelMetadata())
return false;
if (!transFPContractMetadata())
return false;
transSourceLanguage();
if (!transSourceExtension())
return false;
if (!transOCLBuiltinsFromVariables())
return false;
if (!postProcessOCL())
return false;
DbgTran.transGlobals();
DbgTran.transImportedEntities();
DbgTran.finalize();
return true;
}
bool
SPIRVToLLVM::transAddressingModel() {
switch (BM->getAddressingModel()) {
case AddressingModelPhysical64:
M->setTargetTriple(SPIR_TARGETTRIPLE64);
M->setDataLayout(SPIR_DATALAYOUT64);
break;
case AddressingModelPhysical32:
M->setTargetTriple(SPIR_TARGETTRIPLE32);
M->setDataLayout(SPIR_DATALAYOUT32);
break;
case AddressingModelLogical:
// Do not set target triple and data layout
break;
default:
SPIRVCKRT(0, InvalidAddressingModel, "Actual addressing mode is " +
(unsigned)BM->getAddressingModel());
}
return true;
}
bool
SPIRVToLLVM::transDecoration(SPIRVValue *BV, Value *V) {
if (!transAlign(BV, V))
return false;
transMemAliasingINTELDecorations(BV, V);
DbgTran.transDbgInfo(BV, V);
return true;
}
bool
SPIRVToLLVM::transFPContractMetadata() {
bool ContractOff = false;
for (unsigned I = 0, E = BM->getNumFunctions(); I != E; ++I) {
SPIRVFunction *BF = BM->getFunction(I);
if (!isOpenCLKernel(BF))
continue;
if (BF->getExecutionMode(ExecutionModeContractionOff)) {
ContractOff = true;
break;
}
}
if (!ContractOff)
M->getOrInsertNamedMetadata(igc_spv::kSPIR2MD::FPContract);
return true;
}
std::string SPIRVToLLVM::transOCLImageTypeAccessQualifier(
igc_spv::SPIRVTypeImage* ST) {
return SPIRSPIRVAccessQualifierMap::rmap(ST->getAccessQualifier());
}
Type *
SPIRVToLLVM::decodeVecTypeHint(LLVMContext &C, unsigned code) {
unsigned VecWidth = code >> 16;
unsigned Scalar = code & 0xFFFF;
Type *ST = nullptr;
switch (Scalar) {
case 0:
case 1:
case 2:
case 3:
ST = IntegerType::get(C, 1 << (3 + Scalar));
break;
case 4:
ST = Type::getHalfTy(C);
break;
case 5:
ST = Type::getFloatTy(C);
break;
case 6:
ST = Type::getDoubleTy(C);
break;
default:
llvm_unreachable("Invalid vec type hint");
}
if (VecWidth < 1)
return ST;
return IGCLLVM::FixedVectorType::get(ST, VecWidth);
}
// Information of types of kernel arguments may be additionally stored in
// 'OpString "kernel_arg_type.%kernel_name%.type1,type2,type3,..' instruction.
// Try to find such instruction and generate metadata based on it.
static bool transKernelArgTypeMedataFromString(
LLVMContext *Ctx, std::vector<llvm::Metadata*> &KernelMD, SPIRVModule *BM,
Function *Kernel, std::string MDName)
{
std::string ArgTypePrefix =
std::string(MDName) + "." + Kernel->getName().str() + ".";
auto ArgTypeStrIt = std::find_if(
BM->getStringVec().begin(), BM->getStringVec().end(),
[=](SPIRVString *S) { return S->getStr().find(ArgTypePrefix) == 0; });
if (ArgTypeStrIt == BM->getStringVec().end())
return false;
std::string ArgTypeStr =
(*ArgTypeStrIt)->getStr().substr(ArgTypePrefix.size());
std::vector<Metadata *> TypeMDs;
TypeMDs.push_back(MDString::get(*Ctx, MDName));
int countBraces = 0;
std::string::size_type start = 0;
for (std::string::size_type i = 0; i < ArgTypeStr.length(); i++) {
switch (ArgTypeStr[i]) {
case '<':
countBraces++;
break;
case '>':
countBraces--;
break;
case ',':
if (countBraces == 0) {
TypeMDs.push_back(MDString::get(*Ctx, ArgTypeStr.substr(start, i - start)));
start = i + 1;
}
}
}
KernelMD.push_back(MDNode::get(*Ctx, TypeMDs));
return true;
}
// Some of the metadata may disappear when linking LLVM modules; attributes are much more permament.
static void convertAnnotaionsToAttributes(llvm::Function *F, const std::vector<std::string> &annotations)
{
for (const std::string &annotation : annotations)
{
if (annotation == "igc-force-stackcall")
{
F->addFnAttr("igc-force-stackcall");
}
else if (annotation == "sycl-unmasked")
{
F->addFnAttr("sycl-unmasked");
}
}
}
bool
SPIRVToLLVM::transNonTemporalMetadata(Instruction* I) {
Constant* One = ConstantInt::get(Type::getInt32Ty(*Context), 1);
MDNode* Node = MDNode::get(*Context, ConstantAsMetadata::get(One));
I->setMetadata(M->getMDKindID("nontemporal"), Node);
return true;
}
bool
SPIRVToLLVM::transKernelMetadata()
{
IGC::ModuleMetaData MD;
NamedMDNode *KernelMDs = M->getOrInsertNamedMetadata(SPIR_MD_KERNELS);
for (unsigned I = 0, E = BM->getNumFunctions(); I != E; ++I)
{
SPIRVFunction *BF = BM->getFunction(I);
Function *F = static_cast<Function *>(getTranslatedValue(BF));
IGC_ASSERT_MESSAGE(F, "Invalid translated function");
// __attribute__((annotate("some_user_annotation"))) are passed via
// UserSemantic decoration on functions.
if (BF->hasDecorate(DecorationUserSemantic)) {
auto &funcInfo = MD.FuncMD[F];
funcInfo.UserAnnotations = BF->getDecorationStringLiteral(DecorationUserSemantic);
convertAnnotaionsToAttributes(F, funcInfo.UserAnnotations);
}
if (F->getCallingConv() != CallingConv::SPIR_KERNEL || F->isDeclaration())
continue;
std::vector<llvm::Metadata*> KernelMD;
KernelMD.push_back(ValueAsMetadata::get(F));
// Generate metadata for kernel_arg_address_spaces
addOCLKernelArgumentMetadata(Context, KernelMD,
SPIR_MD_KERNEL_ARG_ADDR_SPACE, BF,
[=](SPIRVFunctionParameter *Arg){
SPIRVType *ArgTy = Arg->getType();
SPIRAddressSpace AS = SPIRAS_Private;
if (ArgTy->isTypePointer())
AS = SPIRSPIRVAddrSpaceMap::rmap(ArgTy->getPointerStorageClass());
else if (ArgTy->isTypeOCLImage() || ArgTy->isTypePipe())
AS = SPIRAS_Global;
return ConstantAsMetadata::get(
ConstantInt::get(Type::getInt32Ty(*Context), AS));
});
// Generate metadata for kernel_arg_access_qual
addOCLKernelArgumentMetadata(Context, KernelMD,
SPIR_MD_KERNEL_ARG_ACCESS_QUAL, BF,
[=](SPIRVFunctionParameter *Arg){
std::string Qual;
auto T = Arg->getType();
if (T->isTypeOCLImage()) {
auto ST = static_cast<SPIRVTypeImage *>(T);
Qual = transOCLImageTypeAccessQualifier(ST);
}
else if (T->isTypePipe()){
auto PT = static_cast<SPIRVTypePipe *>(T);
Qual = transOCLPipeTypeAccessQualifier(PT);
}
else
Qual = "none";
return MDString::get(*Context, Qual);
});
// Generate metadata for kernel_arg_type
if (!transKernelArgTypeMedataFromString(Context, KernelMD, BM, F,
SPIR_MD_KERNEL_ARG_TYPE)) {
addOCLKernelArgumentMetadata(Context, KernelMD,
SPIR_MD_KERNEL_ARG_TYPE, BF,
[=](SPIRVFunctionParameter *Arg) {
return transOCLKernelArgTypeName(Arg);
});
}
if (!transKernelArgTypeMedataFromString(Context, KernelMD, BM, F,
SPIR_MD_KERNEL_ARG_TYPE_QUAL))
// Generate metadata for kernel_arg_type_qual
addOCLKernelArgumentMetadata(Context, KernelMD,
SPIR_MD_KERNEL_ARG_TYPE_QUAL, BF,
[=](SPIRVFunctionParameter *Arg){
std::string Qual;
if (Arg->hasDecorate(DecorationVolatile))
Qual = kOCLTypeQualifierName::Volatile;
Arg->foreachAttr([&](SPIRVFuncParamAttrKind Kind){
Qual += Qual.empty() ? "" : " ";
switch (Kind){
case FunctionParameterAttributeNoAlias:
Qual += kOCLTypeQualifierName::Restrict;
break;
case FunctionParameterAttributeNoWrite:
Qual += kOCLTypeQualifierName::Const;
break;
default:
// do nothing.
break;
}
});
if (Arg->getType()->isTypePipe()) {
Qual += Qual.empty() ? "" : " ";
Qual += kOCLTypeQualifierName::Pipe;
}
return MDString::get(*Context, Qual);
});
// Generate metadata for kernel_arg_base_type
addOCLKernelArgumentMetadata(Context, KernelMD,
SPIR_MD_KERNEL_ARG_BASE_TYPE, BF,
[=](SPIRVFunctionParameter *Arg){
return transOCLKernelArgTypeName(Arg);
});
// Generate metadata for kernel_arg_name
bool ArgHasName = true;
BF->foreachArgument([&](SPIRVFunctionParameter *Arg) {
ArgHasName &= !Arg->getName().empty();
});
if (ArgHasName)
addOCLKernelArgumentMetadata(Context, KernelMD,
SPIR_MD_KERNEL_ARG_NAME, BF,
[=](SPIRVFunctionParameter *Arg) {
return MDString::get(*Context, Arg->getName());
});
// Generate metadata for reqd_work_group_size
if (auto EM = BF->getExecutionMode(ExecutionModeLocalSize)) {
KernelMD.push_back(getMDNodeStringIntVec(Context,
igc_spv::kSPIR2MD::WGSize, EM->getLiterals()));
}
// Generate metadata for work_group_size_hint
if (auto EM = BF->getExecutionMode(ExecutionModeLocalSizeHint)) {
KernelMD.push_back(getMDNodeStringIntVec(Context,
igc_spv::kSPIR2MD::WGSizeHint, EM->getLiterals()));
}
// Generate metadata for vec_type_hint
if (auto EM = BF->getExecutionMode(ExecutionModeVecTypeHint)) {
std::vector<Metadata*> MetadataVec;
MetadataVec.push_back(MDString::get(*Context, igc_spv::kSPIR2MD::VecTyHint));
Type *VecHintTy = decodeVecTypeHint(*Context, EM->getLiterals()[0]);
MetadataVec.push_back(ValueAsMetadata::get(UndefValue::get(VecHintTy)));
MetadataVec.push_back(
ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(*Context),
0)));
KernelMD.push_back(MDNode::get(*Context, MetadataVec));
}
auto &funcInfo = MD.FuncMD[F];
// Generate metadata for initializer
if (BF->getExecutionMode(ExecutionModeInitializer)) {
funcInfo.IsInitializer = true;
}
// Generate metadata for finalizer
if (BF->getExecutionMode(ExecutionModeFinalizer)) {
funcInfo.IsFinalizer = true;
}
// Generate metadata for SubgroupSize
if (auto EM = BF->getExecutionMode(ExecutionModeSubgroupSize))
{
unsigned subgroupSize = EM->getLiterals()[0];
std::vector<Metadata*> MetadataVec;
MetadataVec.push_back(MDString::get(*Context, igc_spv::kSPIR2MD::ReqdSubgroupSize));
MetadataVec.push_back(
ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(*Context),
subgroupSize)));
KernelMD.push_back(MDNode::get(*Context, MetadataVec));
}
// Generate metadata for SubgroupsPerWorkgroup
if (auto EM = BF->getExecutionMode(ExecutionModeSubgroupsPerWorkgroup))
{
funcInfo.CompiledSubGroupsNumber = EM->getLiterals()[0];
}
// Generate metadata for MaxByteOffset decorations
{
bool ArgHasMaxByteOffset = false;
BF->foreachArgument([&](SPIRVFunctionParameter *Arg)
{
SPIRVWord offset;
ArgHasMaxByteOffset |= Arg->hasMaxByteOffset(offset);
});
if (ArgHasMaxByteOffset)
{
BF->foreachArgument([&](SPIRVFunctionParameter *Arg)
{
SPIRVWord offset;
bool ok = Arg->hasMaxByteOffset(offset);
// If the decoration is not present on an argument of the function,
// encode that as a zero in the metadata. That currently seems
// like a degenerate case wouldn't be worth optimizing.
unsigned val = ok ? offset : 0;
funcInfo.maxByteOffsets.push_back(val);
});
}
}
llvm::MDNode *Node = MDNode::get(*Context, KernelMD);
KernelMDs->addOperand(Node);
}
IGC::serialize(MD, M);
return true;
}
bool
SPIRVToLLVM::transAlign(SPIRVValue *BV, Value *V) {
if (auto AL = dyn_cast<AllocaInst>(V)) {
SPIRVWord Align = 0;
if (BV->hasAlignment(&Align))
AL->setAlignment(IGCLLVM::getCorrectAlign(Align));
return true;
}
if (auto GV = dyn_cast<GlobalVariable>(V)) {
SPIRVWord Align = 0;
if (BV->hasAlignment(&Align))
GV->setAlignment(IGCLLVM::getCorrectAlign(Align));
return true;
}
return true;
}
void
SPIRVToLLVM::transOCLVectorLoadStore(std::string& UnmangledName,
std::vector<SPIRVWord> &BArgs) {
if (UnmangledName.find("vload") == 0 &&
UnmangledName.find("n") != std::string::npos) {
if (BArgs.back() > 1) {
UnmangledName.replace(UnmangledName.find("n"), 1, std::to_string(BArgs.back()));
} else {
UnmangledName.erase(UnmangledName.find("n"), 1);
}
} else if (UnmangledName.find("vstore") == 0) {
if (UnmangledName.find("n") != std::string::npos) {
auto T = BM->getValueType(BArgs[0]);
if (T->isTypeVector()) {
auto W = T->getVectorComponentCount();
UnmangledName.replace(UnmangledName.find("n"), 1, std::to_string(W));
} else {
UnmangledName.erase(UnmangledName.find("n"), 1);
}
}
}
}
Instruction* SPIRVToLLVM::transDebugInfo(SPIRVExtInst* BC, BasicBlock* BB)
{
if (!BC)
return nullptr;
auto extOp = (OCLExtOpDbgKind)BC->getExtOp();
switch (extOp)
{
case OCLExtOpDbgKind::DbgDcl:
{
OpDebugDeclare dbgDcl(BC);
auto lvar = dbgDcl.getLocalVar();
SPIRVValue* spirvVal = static_cast<SPIRVValue*>(BM->getEntry(lvar));
SPIRVToLLVMValueMap::iterator Loc = ValueMap.find(spirvVal);
if (Loc != ValueMap.end())
{
return DbgTran.createDbgDeclare(BC, Loc->second, BB);
}
break;
}
case OCLExtOpDbgKind::DbgVal:
{
OpDebugValue dbgValue(BC);
llvm::Value* Value = nullptr;
auto lvar = dbgValue.getValueVar();
SPIRVValue* spirvVal = static_cast<SPIRVValue*>(BM->getEntry(lvar));
if (spirvVal->getOpCode() == Op::OpConstant)
{
Value = transValueWithoutDecoration(spirvVal, BB->getParent(), BB, false);
}
else {
SPIRVToLLVMValueMap::iterator Loc = ValueMap.find(spirvVal);
if (Loc != ValueMap.end())
{
SPIRVToLLVMValueMap::iterator Loc = ValueMap.find(spirvVal);
Value = Loc->second;
}
}
if(Value)
{
return DbgTran.createDbgValue(BC, Value, BB);
}
break;
}
default:
break;
}
return nullptr;
}
Instruction *
SPIRVToLLVM::transOCLBuiltinFromExtInst(SPIRVExtInst *BC, BasicBlock *BB) {
IGC_ASSERT_MESSAGE(BB, "Invalid BB");
SPIRVWord EntryPoint = BC->getExtOp();
SPIRVExtInstSetKind Set = BM->getBuiltinSet(BC->getExtSetId());
bool IsPrintf = false;
std::string FuncName;
if (Set == SPIRVEIS_DebugInfo ||
Set == SPIRVEIS_OpenCL_DebugInfo_100)
{
return transDebugInfo(BC, BB);
}
IGC_ASSERT_MESSAGE(Set == SPIRVEIS_OpenCL, "Not OpenCL extended instruction");
if (EntryPoint == igc_OpenCLLIB::printf)
IsPrintf = true;
else {
FuncName = OCLExtOpMap::map(static_cast<OCLExtOpKind>(
EntryPoint));
}
auto BArgs = BC->getArguments();
transOCLVectorLoadStore(FuncName, BArgs);
// keep builtin functions written with bool as i1, truncate down if necessary.
auto Args = transValue(BC->getValues(BArgs), BB->getParent(), BB, BoolAction::Truncate);
std::vector<Type*> ArgTypes;
for (auto &v : Args)
{
ArgTypes.push_back(v->getType());
}
bool IsVarArg = false;
if (IsPrintf)
{
FuncName = "printf";
IsVarArg = true;
ArgTypes.resize(1);
}
else
{
decorateSPIRVExtInst(FuncName, ArgTypes);
}
FunctionType *FT = FunctionType::get(
truncBoolType(BC->getType(), transType(BC->getType())),
ArgTypes,
IsVarArg);
Function *F = M->getFunction(FuncName);
if (!F) {
F = Function::Create(FT,
GlobalValue::ExternalLinkage,
FuncName,
M);
F->setCallingConv(CallingConv::SPIR_FUNC);
if (isFuncNoUnwind())
F->addFnAttr(Attribute::NoUnwind);
}
CallInst *Call = CallInst::Create(F,
Args,
BC->getName(),
BB);
setCallingConv(Call);
Call->addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
return Call;
}
// SPIR-V only contains language version. Use OpenCL language version as
// SPIR version.
void
SPIRVToLLVM::transSourceLanguage() {
SPIRVWord Ver = 0;
SpvSourceLanguage Lang = BM->getSourceLanguage(&Ver);
if (Lang == SpvSourceLanguageOpenCL_C || Lang == SpvSourceLanguageOpenCL_CPP) {
unsigned short Major = 0;
unsigned char Minor = 0;
unsigned char Rev = 0;
std::tie(Major, Minor, Rev) = decodeOCLVer(Ver);
addOCLVersionMetadata(Context, M, kSPIR2MD::SPIRVer, Major, Minor);
addOCLVersionMetadata(Context, M, kSPIR2MD::OCLVer, Major, Minor);
}
}
bool
SPIRVToLLVM::transSourceExtension() {
auto ExtSet = rmap<OclExt::Kind>(BM->getExtension());
auto CapSet = rmap<OclExt::Kind>(BM->getCapability());
for (auto &I:CapSet)
ExtSet.insert(I);
auto OCLExtensions = getStr(map<std::string>(ExtSet));
std::string OCLOptionalCoreFeatures;
bool First = true;
static const char *OCLOptCoreFeatureNames[] = {
"cl_images",
"cl_doubles",
};
for (auto &I:OCLOptCoreFeatureNames) {
size_t Loc = OCLExtensions.find(I);
if (Loc != std::string::npos) {
OCLExtensions.erase(Loc, strlen(I));
if (First)
First = false;
else
OCLOptionalCoreFeatures += ' ';
OCLOptionalCoreFeatures += I;
}
}
addNamedMetadataString(Context, M, kSPIR2MD::Extensions, OCLExtensions);
addNamedMetadataString(Context, M, kSPIR2MD::OptFeatures,
OCLOptionalCoreFeatures);
return true;
}
__attr_unused static void dumpSPIRVBC(const char* fname, const char* data, unsigned int size)
{
FILE* fp;
fp = fopen(fname, "wb");
if(fp != NULL) {
fwrite(data, 1, size, fp);
fclose(fp);
}
}
bool ReadSPIRV(LLVMContext &C, std::istream &IS, Module *&M,
std::string &ErrMsg,
std::unordered_map<uint32_t, uint64_t> *specConstants) {
std::unique_ptr<SPIRVModule> BM( SPIRVModule::createSPIRVModule() );
BM->setSpecConstantMap(specConstants);
IS >> *BM;
bool Succeed = BM->getError(ErrMsg) == SPIRVEC_Success;
if (Succeed) {
BM->resolveUnknownStructFields();
M = new Module("", C);
SPIRVToLLVM BTL(M, BM.get());
if (!BTL.translate()) {
BM->getError(ErrMsg);
Succeed = false;
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
if (DbgSaveTmpLLVM)
dumpLLVM(M, DbgTmpLLVMFileName);
#endif
}
if (!Succeed) {
delete M;
M = nullptr;
}
return Succeed;
}
}
| 35.806687 | 155 | 0.645265 | [
"vector"
] |
ce3cbde67e3330b20fba5f0668fcc852eb4b74ff | 10,905 | cpp | C++ | src/allocator.cpp | tyage/lilith | ff177c0173bed7325b108e2801f0344aa31ba3fd | [
"MIT"
] | null | null | null | src/allocator.cpp | tyage/lilith | ff177c0173bed7325b108e2801f0344aa31ba3fd | [
"MIT"
] | null | null | null | src/allocator.cpp | tyage/lilith | ff177c0173bed7325b108e2801f0344aa31ba3fd | [
"MIT"
] | 1 | 2021-02-05T11:36:17.000Z | 2021-02-05T11:36:17.000Z | #include "allocator.hpp"
#include "prelude.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cassert>
#ifdef DEBUG
#define DEBUG_SHOW 1
#else
#define DEBUG_SHOW 0
#endif
#define DEBUGMSG if(DEBUG_SHOW)
// value.cppの中で、Valueの下2bitに情報をつめこんでいるので、allocの返り値は最低でも4byte alignmentはないと壊れる。
enum class AllocatorStrategy {
NOP,
PreAllocateNOP,
MarkSweep,
MoveCompact,
};
AllocatorStrategy const strategy = AllocatorStrategy::MoveCompact;
void* NOP_alloc(size_t size) {
// 全部おもらし。
return std::malloc(size);
}
bool is_cons(Value v) {
return !is_atom_bool(v);
}
size_t roundup(size_t size, size_t round) {
if(size % round == 0) return size;
return (size / round + 1) * round;
}
// すべての型を破壊する。それらは再生できない。
void set(unsigned char val, void* base, size_t offset = 0) {
*(static_cast<unsigned char*>(base) + offset) = val;
}
unsigned char get(void* base, size_t offset = 0) {
return *(static_cast<unsigned char*>(base) + offset);
}
void* PreAlloc_pointer_slice_alloc(size_t size) {
// おもらしするポインタずらし。
size_t const block_size = 1024 * 32 * 1024;
size_t const alignment_size = 4;
static void* current_block = nullptr;
static size_t current_offset = block_size;
size = roundup(size, alignment_size);
if(size + current_offset > block_size) {
current_block = std::malloc(block_size);
current_offset = 0;
}
void* result = current_block;
current_block = static_cast<char*>(current_block) + size;
current_offset += size;
return result;
}
/*
class MarkSweepAllocator {
size_t static const header_size = 4; // 4も管理用領域に必要無いけど、4-align(mallocは16-alignという仮定)。
struct Object {
unsigned char header[header_size];
Value cell[2];
unsigned char static const alive = 0x1;
unsigned char static const dead = 0;
unsigned char static const marked = 0xff;
};
size_t static const base = sizeof(Object);
// size_t static const in_block = 1024 * 1024;
size_t static const in_block = 1024;
size_t static const block_size = base * in_block;
struct Block {
Object* area;
size_t offset;
Block() {
void* p = std::malloc(block_size);
std::memset(p, 0, block_size);
area = static_cast<Object*>(p);
offset = 0;
}
Object* alloc() {
for(; offset < in_block; ++offset){
Object* obj = area + offset;
if(get(obj) != Object::alive) {
set(Object::alive, obj);
return obj;
}
}
return nullptr;
}
void show_map() {
std::cout << "----------" << std::endl;
for(size_t i{}; i < in_block; ++i) {
Object* obj = &area[i];
std::cout << int(get(obj)) << ",";
}
std::cout << std::endl;
std::cout << "----------" << std::endl;
}
void sweep() {
show_map();
int cnt{};
for(size_t i{}; i < in_block; ++i) {
Object* obj = area + i;
if(get(obj) == Object::marked) {
set(Object::alive, obj);
} else {
++cnt;
std::cout << (int)get(obj) << std::endl;
set(Object::dead, obj);
std::cout << "sweeping " << show(*obj->cell) << std::endl;
*(obj->cell) = make_symbol("dead!");
*(obj->cell+1) = make_symbol("beef!");
}
}
offset = 0;
std::cout << cnt << " objects destroied" << std::endl;
show_map();
}
size_t alive_cnt() {
int cnt{};
for(size_t i{}; i < in_block; ++i) {
Object* obj = &area[i];
if(get(obj) == Object::alive) {
++cnt;
}
}
return cnt;
}
};
std::vector<Block> blocks;
public:
MarkSweepAllocator() {}
Value* alloc_cons() {
for(size_t i{}; i < blocks.size(); ++i) {
auto& b = blocks[i];
auto p = b.alloc();
if(p) return (Value*)((char*)(p) + 4);
std::cout << "!block" << i << "is full!" << std::endl;
std::cout << b.alive_cnt() << std::endl;
}
blocks.emplace_back();
return blocks.back().alloc()->cell;
}
void mark_cons(Value v) {
std::cout << "marking: " << show(v) << std::endl;
if(!is_cons(v)) {
std::cout << "not cons skip!" << std::endl;
return;
}
if(get(to_ptr(v), -4) == Object::marked) {
std::cout << "already marked!" << std::endl;
return; // 他のpathで既にmarkされてる。
}
set(Object::marked, to_ptr(v), -4);
std::cout << "mark!" << std::endl;
mark_cons(car(v));
mark_cons(cdr(v));
}
void sweep() {
for(auto& b: blocks) {
b.sweep();
std::cout << "####### " << b.alive_cnt() << " objects alive" << std::endl;
}
std::cout << "####### " << blocks.size() << "blocks" << std::endl;
}
void collect(Value rootset) {
mark_cons(rootset);
sweep();
std::cout << "!!!!!!";
show_env(rootset);
std::cout << std::endl;
show(rootset);
std::cout << (rootset) << "!!!!!!";
std::cout << std::endl;
}
} markSweepAllocator;
*/
// indexでアクセスできるメモリ
template<class T, size_t PerPage = 256> class PandoraBox {
std::vector<T*> pages;
public:
PandoraBox() : pages{} {}
T& operator[](size_t i) {
assert(i < pages.size() * PerPage);
return *(pages[i / PerPage] + i % PerPage);
}
// O(n)かかってヤバそうなら考えましょう。
// pageの増減時にしか変わらないのでなんとかできそう。
size_t addr2page(T const* t) {
for(size_t i{}; i < pages.size(); ++i) {
if (pages[i] <= t && t < pages[i] + PerPage) return i; // ここの比較本当はアドレスでやるとダメなので整数型にしないといけない気はするけど実際動かないことはなさそう。
}
[[unlikely]] throw "never";
}
size_t get_index(T const* t) {
size_t page = addr2page(t);
size_t offset = t - pages[page];
assert(offset <= PerPage);
return page * PerPage + offset;
}
void alloc_page() {
T* p = static_cast<T*>(std::malloc(sizeof(T) * PerPage));
if(!p) throw std::bad_alloc();
pages.push_back(p);
}
void release_page() {
std::free(pages.back());
pages.pop_back();
}
size_t capacity() { return pages.size() * PerPage; }
};
class MoveCompactAllocator {
std::vector<bool> bitmap;
size_t static constexpr PerPage = 2;
PandoraBox<ConsCell, PerPage> heap;
size_t offset;
public:
MoveCompactAllocator() : bitmap{}, heap{}, offset{} {}
ConsCell* alloc_cons() {
if (offset >= heap.capacity()) heap.alloc_page();
auto addr = &heap[offset];
++offset;
return addr;
}
void mark_cons(Value v) {
DEBUGMSG std::cout << "marking: " << show(v) << " addr: " << to_ptr(v) << std::endl;
if(!is_cons(v)) {
DEBUGMSG std::cout << "not cons skip! " << std::endl;
return;
}
ConsCell* vp = to_ptr(v);
auto base = heap.get_index(vp);
if (bitmap[base]) {
DEBUGMSG std::cout << "already marked!" << std::endl;
return;
}
bitmap[base] = true;
mark_cons(car(v));
mark_cons(cdr(v));
}
Value compact(Value root) {
size_t free = 0;
size_t scan = heap.capacity() - 1;
while(free != scan) {
if (free > scan) break; // このへんも境界怪しい。
while(bitmap[free]) ++free;
while(!bitmap[scan]) --scan;
// https://gyazo.com/d778d19b52397d0a7930a01ebba11695
auto to = &heap[free];
auto from = &heap[scan];
std::cout << "to: " << to << " from: " << from << " free: " << std::dec << free << " scan: " << scan << std::endl;
// DEBUGMSG std::cout << "to content is " << show(to_Value(to, nullptr)) << std::endl;
// DEBUGMSG std::cout << "from content is " << show(to_Value(static_cast<void*>(to), nullptr)) << "(is nil?: " << (nil() == from->cell[0]) << ")" << std::endl;
to->cell[0] = from->cell[0];
to->cell[1] = from->cell[1];
*reinterpret_cast<ConsCell**>(from) = to;
// 引っ越し先のアドレスを元の住所に書いておく。1cellで2Value分の領域があり、Valueはstd::uintptr_tなので必ず収まる。
// scanより後ろで、bitが立っているところは引越しした。
++free;
--scan;
}
std::cout << "scan is " << std::dec << scan << std::endl;
for(size_t i{}; i < scan; ++i) {
auto e = &heap[i];
for(size_t j{}; j < 2; ++j) {
auto v = e->cell[j];
if (!is_cons(v)) continue;
ConsCell* vp = to_ptr(v);
auto base = heap.get_index(vp);
if (base > scan) { // 境界?
// これread/writeバリアでやったほうがいいかもしれない。
e->cell[j] = to_Value(*(reinterpret_cast<ConsCell**>(&heap[base])), nullptr);
}
}
}
// rootも引越ししてるかもしれないので、新たなrootを返す。
ConsCell* vp = to_ptr(root);
auto base = heap.get_index(vp);
if (base > scan) { // 境界?
// これread/writeバリアでやったほうがいいかもしれない。
return to_Value(*(reinterpret_cast<ConsCell**>(&heap[base])), nullptr);
}
offset = scan + 1;
// 以下の1行を入れると何故か動かない。
// for(size_t unused_page_cnt = heap.capacity() % PerPage - offset % PerPage; unused_page_cnt > 0; --unused_page_cnt) heap.release_page();
return root;
}
void show_bitmap() {
for(auto e: bitmap) {
std::cout << (e ? '.' : ' ');
}
std::cout << "| kokomade" << std::endl;
for(size_t i{}; i < bitmap.size(); ++i) { /*
auto base = pages[i / par_page] + i % par_page;
auto head = base->cell[0];
auto tail = base->cell[1];
std::cout << "addr index: " << std::dec << i << "(raw: " << base << ") mark: " << bitmap[i] << std::hex << " content: " << show(to_Value(base, nullptr))
<< " (raw: " << head << ", " << tail << ")" << std::endl; */
}
}
Value collect(Value root) {
assert(heap.capacity() > 0); // allocする前にcollectすることなんて無いでしょw
bitmap = std::vector<bool>(heap.capacity());
mark_cons(root);
DEBUGMSG std::cout << "marked bit cnt is " << std::count(begin(bitmap), end(bitmap), true) << std::endl;
show_bitmap();
Value new_root = compact(root);
// show_bitmap();
DEBUGMSG std::cout << "!!!!!!" << show_env(new_root) << std::endl;
DEBUGMSG std::cout << "!!!!!!" << show(new_root) << std::endl;
DEBUGMSG std::cout << "old root: " << std::hex << root << " new root: " << new_root << std::endl;
return new_root;
}
} moveCompactAllocator;
static int alloc_cnt = 0;
void* alloc(size_t size) {
switch(strategy) {
case AllocatorStrategy::NOP:
default:
return NOP_alloc(size);
case AllocatorStrategy::PreAllocateNOP:
return PreAlloc_pointer_slice_alloc(size);
}
}
ConsCell* alloc_cons() {
++alloc_cnt;
switch(strategy) { /*
case AllocatorStrategy::MarkSweep:
return markSweepAllocator.alloc_cons(); */
case AllocatorStrategy::MoveCompact:
return moveCompactAllocator.alloc_cons();
default:
size_t const cell_size = sizeof(Value) * 2;
return static_cast<ConsCell*>(alloc(cell_size));
}
}
Value collect(Value root) {
std::cout << alloc_cnt << " cons total allocations!" << std::endl;
switch(strategy) { /*
case AllocatorStrategy::MarkSweep:
markSweepAllocator.collect(root);
return; */
case AllocatorStrategy::MoveCompact:
return moveCompactAllocator.collect(root);
default:
return root; // nop
}
}
| 29.00266 | 164 | 0.581568 | [
"object",
"vector"
] |
ce3cc939e36dd1c64a8f51252cb3abaad0567ff2 | 1,812 | cpp | C++ | Algorithms_Training/Difficulty_Medium/Problem_26_binary-tree-level-order-traversal/main.cpp | AlazzR/CLRS-Introduction-to-Algorithm | 36566e2506074b5c17aee6e003af7d935cd3d4dd | [
"CC0-1.0"
] | null | null | null | Algorithms_Training/Difficulty_Medium/Problem_26_binary-tree-level-order-traversal/main.cpp | AlazzR/CLRS-Introduction-to-Algorithm | 36566e2506074b5c17aee6e003af7d935cd3d4dd | [
"CC0-1.0"
] | null | null | null | Algorithms_Training/Difficulty_Medium/Problem_26_binary-tree-level-order-traversal/main.cpp | AlazzR/CLRS-Introduction-to-Algorithm | 36566e2506074b5c17aee6e003af7d935cd3d4dd | [
"CC0-1.0"
] | null | null | null | //https://leetcode.com/problems/binary-tree-level-order-traversal/submissions/
#include<iostream>
#include<deque>
#include<vector>
using std::vector;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(val), left(left), right(right) {}
void printTree()
{
std::deque<TreeNode*> queue;
queue.push_back(this);
int levels = 0;
while (!queue.empty())
{
std::deque<TreeNode*> que;
std::cout << "lvl: " << levels++;
while (!queue.empty())
{
TreeNode* tmp = queue.front();
queue.pop_front();
std::cout << " val: " << tmp->val << "\t";
if (tmp->left != nullptr)
que.push_back(tmp->left);
if (tmp->right != nullptr)
que.push_back(tmp->right);
}
std::cout << std::endl;
queue = que;
}
}
};
vector<vector<int>> levelOrder(TreeNode* root)
{
std::vector<std::vector<int>> levels;
if (root == nullptr)
return levels;
std::deque<TreeNode*> q1 = { root };
while (!(q1.empty()))
{
std::deque<TreeNode*> q2;
std::vector<int> level;
while (!(q1.empty()))
{
TreeNode* tmp = q1.front();
q1.pop_front();
level.push_back(tmp->val);
if (tmp->left != nullptr)
q2.push_back(tmp->left);
if (tmp->right != nullptr)
q2.push_back(tmp->right);
}
levels.push_back(level);
q1 = q2;//copy q2 onto q1
}
for (auto& level : levels)
{
for (const auto& v : level)
std::cout << v << '\t';
std::cout << std::endl;
}
return levels;
}
int main(int argc, char* argv[])
{
TreeNode root = TreeNode(3);
TreeNode n1 = TreeNode(9);
TreeNode n2 = TreeNode(20);
TreeNode n3 = TreeNode(15);
TreeNode n4 = TreeNode(7);
root.left = &n1;
root.right = &n2;
n2.left = &n3;
n2.right = &n4;
root.printTree();
levelOrder(&root);
return 0;
} | 20.133333 | 111 | 0.608168 | [
"vector"
] |
ce3f7d372cebfc9ffda52380eed0c8195c6b12c8 | 20,072 | cpp | C++ | libs/core/algorithms/tests/unit/algorithms/util/test_range.cpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 1,822 | 2015-01-03T11:22:37.000Z | 2022-03-31T14:49:59.000Z | libs/core/algorithms/tests/unit/algorithms/util/test_range.cpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 3,288 | 2015-01-05T17:00:23.000Z | 2022-03-31T18:49:41.000Z | libs/core/algorithms/tests/unit/algorithms/util/test_range.cpp | Andrea-MariaDB-2/hpx | e230dddce4a8783817f38e07f5a77e624f64f826 | [
"BSL-1.0"
] | 431 | 2015-01-07T06:22:14.000Z | 2022-03-31T14:50:04.000Z | // Copyright (c) 2015-2017 Francisco Jose Tapia
// Copyright (c) 2020 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#include <hpx/modules/testing.hpp>
#include <hpx/parallel/util/range.hpp>
#include <algorithm>
#include <cstdint>
#include <functional>
#include <vector>
using namespace hpx::parallel::util;
// template <typename Iter, typename Sent>
// std::ostream& operator<<(std::ostream& out, range<Iter, Sent> R)
// {
// out << "[ " << (R.end() - R.begin()) << "] ";
// if (!R.valid())
// return out;
// while (R.begin() != R.end())
// out << (*(R.begin()++)) << " ";
// out << std::endl;
// return out;
// }
struct xk
{
unsigned tail : 3;
unsigned num : 24;
xk(unsigned N = 0, unsigned T = 0)
: tail(T)
, num(N)
{
}
bool operator<(xk A) const
{
return (unsigned) num < (unsigned) A.num;
}
};
// std::ostream& operator<<(std::ostream& out, xk x)
// {
// out << "[" << x.num << "-" << x.tail << "] ";
// return out;
// }
void test1(void)
{
using iter_t = typename std::vector<std::uint64_t>::iterator;
using range_t = range<iter_t>;
std::vector<std::uint64_t> A, B;
A.resize(10, 0);
B.resize(10, 0);
for (uint32_t i = 0; i < 10; ++i)
A[i] = i;
range_t RA(A.begin(), A.end()), RB(B.begin(), B.end());
// test copy copy constructor
range_t RC(RA);
HPX_TEST(RC.size() == RA.size());
RC.begin() = RC.end();
RC = RA;
// test of move
RB = hpx::parallel::util::init_move(RB, RA);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(B[i] == i);
// test of uninitialized_move , destroy
struct forensic
{
std::int64_t N;
forensic(std::uint64_t K = 0)
{
N = (std::int64_t) K;
}
~forensic()
{
N = -1;
}
};
typedef typename std::vector<forensic>::iterator fIter;
typedef hpx::parallel::util::range<fIter> frange_t;
char K[160];
forensic* PAux = reinterpret_cast<forensic*>(&K[0]);
range<forensic*> F1(PAux, PAux + 20);
std::vector<forensic> V;
for (uint32_t i = 0; i < 10; ++i)
V.emplace_back(i);
F1 = hpx::parallel::util::uninit_move(F1, frange_t(V.begin(), V.end()));
for (uint32_t i = 0; i < 10; ++i)
HPX_TEST(PAux[i].N == i);
hpx::parallel::util::destroy_range(F1);
}
void test2()
{
using iter_t = typename std::vector<std::uint64_t>::iterator;
std::vector<std::uint64_t> V1;
V1.resize(100, 0);
range<iter_t> R1(V1.begin(), V1.end());
uint64_t K = 999;
range<iter_t> R2 = init(R1, K);
while (R2.begin() != R2.end())
{
HPX_TEST(*R2.begin() == 999);
R2 = range<iter_t>(R2.begin() + 1, R2.end());
}
}
// TEST OF HALF_MERGE
void test3()
{
using iter_t = typename std::vector<std::uint64_t>::iterator;
using rng = range<iter_t>;
using compare = std::less<std::uint64_t>;
compare comp;
std::vector<std::uint64_t> A, B;
rng RA(A.begin(), A.end()), RB(B.begin(), B.end());
rng Rx(A.begin(), A.end());
rng Rz(Rx);
// src1 empty
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.clear();
RB = rng(B.begin(), B.end());
HPX_TEST(RB.begin() == RB.end());
RA = rng(A.begin(), A.end());
Rx = RA;
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 10);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(*(Rz.begin() + i) == i);
// src2 empty
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 10; i++)
B.push_back(i);
A.resize(10, 0);
Rz = rng(A.begin(), A.end());
RB = rng(B.begin(), B.end());
RA = rng(A.end(), A.end());
Rx = rng(A.begin(), A.end());
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 10);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(*(Rz.begin() + i) == i);
// merged even , odd numbers
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 20; i += 2)
B.push_back(i);
HPX_TEST(B.size() == 10);
A.resize(10, 0);
for (std::uint32_t i = 1; i < 20; i += 2)
A.push_back(i);
HPX_TEST(A.size() == 20);
RA = rng(A.begin() + 10, A.end());
RB = rng(B.begin(), B.begin() + 10);
Rx = rng(A.begin(), A.end());
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(A[i] == i);
// in src1 0-10 in src2 10-20
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 10; ++i)
B.push_back(i);
A.resize(10, 0);
for (std::uint32_t i = 10; i < 20; i++)
A.push_back(i);
RA = rng(A.begin() + 10, A.end());
RB = rng(B.begin(), B.begin() + 10);
Rx = rng(A.begin(), A.end());
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(A[i] == i);
// in src2 0-10 in src1 10-20
A.clear();
B.clear();
for (std::uint32_t i = 10; i < 20; ++i)
B.push_back(i);
A.resize(10, 0);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
RA = rng(A.begin() + 10, A.end());
RB = rng(B.begin(), B.begin() + 10);
Rx = rng(A.begin(), A.end());
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(A[i] == i);
}
// TEST OF STABILITY
void test4()
{
using iter_t = typename std::vector<xk>::iterator;
using rng = range<iter_t>;
using compare = std::less<xk>;
compare comp;
std::vector<xk> A, B;
rng RA(A.begin(), A.end()), RB(B.begin(), B.end());
rng Rx(A.begin(), A.end());
rng Rz(Rx);
// the smallest elements at the beginning of src1
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 50; ++i)
B.emplace_back(i, 0);
for (std::uint32_t i = 0; i < 50; ++i)
B.emplace_back(100 + i * 2, 0);
A.resize(100, 0);
for (std::uint32_t i = 0; i < 100; i++)
A.emplace_back(100 + i * 2, 1);
RA = rng(A.begin() + 100, A.end());
RB = rng(B.begin(), B.begin() + 100);
Rx = rng(A.begin(), A.end());
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 200);
for (std::uint32_t i = 0; i < 50; ++i)
HPX_TEST(A[i].num == i && A[i].tail == 0);
for (std::uint32_t i = 50; i < 150; ++i)
{
std::uint32_t K = i + 50;
std::uint32_t M = K % 2;
HPX_TEST(A[i].num == K - M && A[i].tail == M);
}
for (std::uint32_t i = 150; i < 200; ++i)
HPX_TEST(A[i].num == 2 * i - 100 && A[i].tail == 1);
// the smallest elements at the beginning of src2
A.clear();
B.clear();
A.resize(100, 0);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(i, 1);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(100 + i * 2, 1);
for (std::uint32_t i = 0; i < 100; i++)
B.emplace_back(100 + i * 2, 0);
RA = rng(A.begin() + 100, A.end());
RB = rng(B.begin(), B.begin() + 100);
Rx = rng(A.begin(), A.end());
Rz = half_merge(Rx, RB, RA, comp);
HPX_TEST(Rz.size() == 200);
for (std::uint32_t i = 0; i < 50; ++i)
HPX_TEST(A[i].num == i && A[i].tail == 1);
for (std::uint32_t i = 50; i < 150; ++i)
{
std::uint32_t K = i + 50;
std::uint32_t M = K % 2;
HPX_TEST(A[i].num == K - M && A[i].tail == M);
}
for (std::uint32_t i = 150; i < 200; ++i)
HPX_TEST(A[i].num == 2 * i - 100 && A[i].tail == 0);
}
// TEST OF FULL_MERGE
void test5()
{
using compare = std::less<std::uint64_t>;
using rng = range<std::uint64_t*>;
std::vector<std::uint64_t> A, B;
compare comp;
A.clear();
B.clear();
B.assign(21, 0);
for (std::uint32_t i = 0; i < 20; i += 2)
A.push_back(i);
for (std::uint32_t i = 1; i < 20; i += 2)
A.push_back(i);
A.push_back(0);
rng A1(&A[0], &A[10]), A2(&A[10], &A[20]);
rng B1(&B[0], &B[20]);
rng C1(A1);
C1 = full_merge(B1, A1, A2, comp);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
A.clear();
B.clear();
B.assign(20, 100);
for (std::uint32_t i = 0; i < 20; i++)
A.push_back(i);
A.push_back(0);
full_merge(B1, rng(&A[0], &A[10]), rng(&A[10], &A[20]), comp);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
A.clear();
B.clear();
B.assign(21, 100);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(10 + i);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
A.push_back(0);
full_merge(B1, rng(&A[0], &A[10]), rng(&A[10], &A[20]), comp);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
}
// TEST OF FULL_MERGE
void test6()
{
typedef typename std::vector<std::uint64_t>::iterator Iter;
typedef range<Iter> rng;
typedef std::less<std::uint64_t> compare;
compare comp;
std::vector<std::uint64_t> A, B;
rng RA1(A.begin(), A.end()), RA2(A.begin(), A.end());
rng RB(B.begin(), B.end());
rng Rz(RB);
// src1 empty
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.clear();
B.resize(20, 100);
RB = rng(B.begin(), B.end());
RA1 = rng(A.begin(), A.begin());
RA2 = rng(A.begin(), A.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 10);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(*(Rz.begin() + i) == i);
// src2 empty
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.resize(10, 0);
RA1 = rng(A.begin(), A.end());
RA2 = rng(A.end(), A.end());
RB = rng(B.begin(), B.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 10);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(*(Rz.begin() + i) == i);
// merged even , odd numbers
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 20; i += 2)
A.push_back(i);
HPX_TEST(A.size() == 10);
for (std::uint32_t i = 1; i < 20; i += 2)
A.push_back(i);
HPX_TEST(A.size() == 20);
B.resize(20, 0);
RA1 = rng(A.begin(), A.begin() + 10);
RA2 = rng(A.begin() + 10, A.end());
RB = rng(B.begin(), B.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
// in src1 0-10 in src2 10-20
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 20; ++i)
A.push_back(i);
B.resize(20, 0);
RA1 = rng(A.begin(), A.begin() + 10);
RA2 = rng(A.begin() + 10, A.end());
RB = rng(B.begin(), B.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
// in src2 0-10 in src1 10-20
A.clear();
B.clear();
for (std::uint32_t i = 10; i < 20; ++i)
A.push_back(i);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.resize(20, 0);
RA1 = rng(A.begin(), A.begin() + 10);
RA2 = rng(A.begin() + 10, A.end());
RB = rng(B.begin(), B.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
};
// TEST OF STABILITY
void test7()
{
typedef typename std::vector<xk>::iterator Iter;
typedef range<Iter> rng;
typedef std::less<xk> compare;
compare comp;
std::vector<xk> A, B;
rng RA1(A.begin(), A.end()), RA2(A.begin(), A.end());
rng RB(B.begin(), B.end());
rng Rz(RB);
// the smallest elements at the beginning of src1
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(i, 0);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(100 + i * 2, 0);
for (std::uint32_t i = 0; i < 100; i++)
A.emplace_back(100 + i * 2, 1);
B.resize(200, 0);
RA1 = rng(A.begin(), A.begin() + 100);
RA2 = rng(A.begin() + 100, A.end());
RB = rng(B.begin(), B.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 200);
for (std::uint32_t i = 0; i < 50; ++i)
HPX_TEST(B[i].num == i && B[i].tail == 0);
for (std::uint32_t i = 50; i < 150; ++i)
{
std::uint32_t K = i + 50;
std::uint32_t M = K % 2;
HPX_TEST(B[i].num == K - M && B[i].tail == M);
}
for (std::uint32_t i = 150; i < 200; ++i)
HPX_TEST(B[i].num == 2 * i - 100 && B[i].tail == 1);
// the smallest elements at the beginning of src2
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 100; i++)
A.emplace_back(100 + i * 2, 0);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(i, 1);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(100 + i * 2, 1);
B.resize(200, 0);
RA1 = rng(A.begin(), A.begin() + 100);
RA2 = rng(A.begin() + 100, A.end());
RB = rng(B.begin(), B.end());
Rz = full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 200);
for (std::uint32_t i = 0; i < 50; ++i)
HPX_TEST(B[i].num == i && B[i].tail == 1);
for (std::uint32_t i = 50; i < 150; ++i)
{
std::uint32_t K = i + 50;
std::uint32_t M = K % 2;
HPX_TEST(B[i].num == K - M && B[i].tail == M);
}
for (std::uint32_t i = 150; i < 200; ++i)
HPX_TEST(B[i].num == 2 * i - 100 && B[i].tail == 0);
}
// TEST OF UNINITIALIZED_FULL_MERGE
void test8()
{
typedef std::less<std::uint64_t> compare;
typedef range<std::uint64_t*> rng;
std::vector<std::uint64_t> A, B;
compare comp;
A.clear();
B.clear();
B.assign(21, 0);
for (std::uint32_t i = 0; i < 20; i += 2)
A.push_back(i);
for (std::uint32_t i = 1; i < 20; i += 2)
A.push_back(i);
A.push_back(0);
rng A1(&A[0], &A[10]), A2(&A[10], &A[20]);
rng B1(&B[0], &B[20]);
rng C1(A1);
C1 = uninit_full_merge(B1, A1, A2, comp);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
A.clear();
B.clear();
B.assign(21, 100);
for (std::uint32_t i = 0; i < 20; i++)
A.push_back(i);
A.push_back(0);
uninit_full_merge(B1, rng(&A[0], &A[10]), rng(&A[10], &A[20]), comp);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
A.clear();
B.clear();
B.assign(21, 100);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(10 + i);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
A.push_back(0);
uninit_full_merge(B1, rng(&A[0], &A[10]), rng(&A[10], &A[20]), comp);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
}
// TEST OF FULL_MERGE
void test9()
{
typedef typename std::vector<std::uint64_t>::iterator Iter;
typedef range<Iter> rng;
typedef std::less<std::uint64_t> compare;
compare comp;
std::vector<std::uint64_t> A, B;
rng RA1(A.begin(), A.end()), RA2(A.begin(), A.end());
std::uint64_t val = 0;
range<std::uint64_t*> RB(&val, &val);
range<std::uint64_t*> Rz(RB);
// src1 empty
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.clear();
B.resize(21, 100);
RB = range<std::uint64_t*>(&B[0], &B[20]);
RA1 = rng(A.begin(), A.begin());
RA2 = rng(A.begin(), A.end());
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 10);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(*(Rz.begin() + i) == i);
// src2 empty
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.resize(11, 0);
RA1 = rng(A.begin(), A.end());
RA2 = rng(A.end(), A.end());
RB = range<std::uint64_t*>(&B[0], &B[10]);
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 10);
for (std::uint32_t i = 0; i < 10; ++i)
HPX_TEST(*(Rz.begin() + i) == i);
// merged even , odd numbers
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 20; i += 2)
A.push_back(i);
HPX_TEST(A.size() == 10);
for (std::uint32_t i = 1; i < 20; i += 2)
A.push_back(i);
HPX_TEST(A.size() == 20);
B.resize(21, 0);
RA1 = rng(A.begin(), A.begin() + 10);
RA2 = rng(A.begin() + 10, A.end());
RB = range<std::uint64_t*>(&B[0], &B[20]);
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
// in src1 0-10 in src2 10-20
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 20; ++i)
A.push_back(i);
B.resize(21, 0);
RA1 = rng(A.begin(), A.begin() + 10);
RA2 = rng(A.begin() + 10, A.end());
RB = range<std::uint64_t*>(&B[0], &B[20]);
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
// in src2 0-10 in src1 10-20
A.clear();
B.clear();
for (std::uint32_t i = 10; i < 20; ++i)
A.push_back(i);
for (std::uint32_t i = 0; i < 10; i++)
A.push_back(i);
B.resize(21, 0);
RA1 = rng(A.begin(), A.begin() + 10);
RA2 = rng(A.begin() + 10, A.end());
RB = range<std::uint64_t*>(&B[0], &B[20]);
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 20);
for (std::uint32_t i = 0; i < 20; ++i)
HPX_TEST(B[i] == i);
}
// TEST OF STABILITY
void test10()
{
typedef typename std::vector<xk>::iterator Iter;
typedef range<Iter> rng;
typedef std::less<xk> compare;
compare comp;
std::vector<xk> A, B;
rng RA1(A.begin(), A.end()), RA2(A.begin(), A.end());
range<xk*> RB;
range<xk*> Rz;
// the smallest elements at the beginning of src1
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(i, 0);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(100 + i * 2, 0);
for (std::uint32_t i = 0; i < 100; i++)
A.emplace_back(100 + i * 2, 1);
B.resize(201, 0);
RA1 = rng(A.begin(), A.begin() + 100);
RA2 = rng(A.begin() + 100, A.end());
RB = range<xk*>(&B[0], &B[200]);
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 200);
for (std::uint32_t i = 0; i < 50; ++i)
HPX_TEST(B[i].num == i && B[i].tail == 0);
for (std::uint32_t i = 50; i < 150; ++i)
{
std::uint32_t K = i + 50;
std::uint32_t M = K % 2;
HPX_TEST(B[i].num == K - M && B[i].tail == M);
};
for (std::uint32_t i = 150; i < 200; ++i)
HPX_TEST(B[i].num == 2 * i - 100 && B[i].tail == 1);
// the smallest elements at the beginning of src2
A.clear();
B.clear();
for (std::uint32_t i = 0; i < 100; i++)
A.emplace_back(100 + i * 2, 0);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(i, 1);
for (std::uint32_t i = 0; i < 50; ++i)
A.emplace_back(100 + i * 2, 1);
B.resize(201, 0);
RA1 = rng(A.begin(), A.begin() + 100);
RA2 = rng(A.begin() + 100, A.end());
RB = range<xk*>(&B[0], &B[200]);
Rz = uninit_full_merge(RB, RA1, RA2, comp);
HPX_TEST(Rz.size() == 200);
for (std::uint32_t i = 0; i < 50; ++i)
HPX_TEST(B[i].num == i && B[i].tail == 1);
for (std::uint32_t i = 50; i < 150; ++i)
{
std::uint32_t K = i + 50;
std::uint32_t M = K % 2;
HPX_TEST(B[i].num == K - M && B[i].tail == M);
};
for (std::uint32_t i = 150; i < 200; ++i)
HPX_TEST(B[i].num == 2 * i - 100 && B[i].tail == 0);
}
int main(int, char*[])
{
test1();
test2();
test3();
test4();
test5();
test6();
test7();
test8();
test9();
test10();
return hpx::util::report_errors();
};
| 26.550265 | 80 | 0.496612 | [
"vector"
] |
ce483dd5ef9fa936c1352ef580a25724d9d24c7d | 1,802 | cpp | C++ | Decision_tables/Cpp/DecisionTables/Source.cpp | ncoe/rosetta | 15c2302a247dfbcea694ff095238a525c60226d4 | [
"MIT"
] | 3 | 2018-02-26T18:12:31.000Z | 2019-08-26T06:47:30.000Z | Decision_tables/Cpp/DecisionTables/Source.cpp | ncoe/rosetta | 15c2302a247dfbcea694ff095238a525c60226d4 | [
"MIT"
] | null | null | null | Decision_tables/Cpp/DecisionTables/Source.cpp | ncoe/rosetta | 15c2302a247dfbcea694ff095238a525c60226d4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
const std::vector<std::pair<std::string, std::string>> conditions = {
{"Printer prints", "NNNNYYYY"},
{"A red light is flashing", "YYNNYYNN"},
{"Printer is recognized by computer", "NYNYNYNY"}
};
const std::vector<std::pair<std::string, std::string>> actions = {
{"Check the power cable", "NNYNNNNN"},
{"Check the printer-computer cable", "YNYNNNNN"},
{"Ensure printer software is installed", "YNYNYNYN"},
{"Check/replace ink", "YYNNNYNN"},
{"Check for paper jam", "NYNYNNNN"},
};
int main() {
const size_t nc = conditions.size();
const size_t na = actions.size();
const size_t nr = conditions[0].second.size();
const int np = 7;
auto answers = new bool[nc];
std::string input;
std::cout << "Please answer the following questions with a y or n:\n";
for (size_t c = 0; c < nc; c++) {
char ans;
do {
std::cout << conditions[c].first << "? ";
std::getline(std::cin, input);
ans = std::toupper(input[0]);
} while (ans != 'Y' && ans != 'N');
answers[c] = ans == 'Y';
}
std::cout << "Recommended action(s)\n";
for (size_t r = 0; r < nr; r++) {
for (size_t c = 0; c < nc; c++) {
char yn = answers[c] ? 'Y' : 'N';
if (conditions[c].second[r] != yn) {
goto outer;
}
}
if (r == np) {
std::cout << " None (no problem detected)\n";
} else {
for (auto action : actions) {
if (action.second[r] == 'Y') {
std::cout << " " << action.first << '\n';
}
}
}
break;
outer: {}
}
delete[] answers;
return 0;
}
| 27.723077 | 74 | 0.49667 | [
"vector"
] |
ce48ff59470db09e928a485bb539b0656996ec87 | 1,386 | inl | C++ | include/Nazara/Core/MemoryStream.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 11 | 2019-11-27T00:40:43.000Z | 2020-01-29T14:31:52.000Z | include/Nazara/Core/MemoryStream.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T00:29:08.000Z | 2020-01-08T18:53:39.000Z | include/Nazara/Core/MemoryStream.inl | jayrulez/NazaraEngine | e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99 | [
"BSD-3-Clause-Clear",
"Apache-2.0",
"MIT"
] | 7 | 2019-11-27T10:27:40.000Z | 2020-01-15T17:43:33.000Z | // Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/MemoryStream.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::MemoryStream
* \brief Constructs a MemoryStream object by default
*/
inline MemoryStream::MemoryStream() :
Stream(StreamOption::None, OpenMode_ReadWrite),
m_pos(0)
{
}
/*!
* \brief Constructs a MemoryStream object with a byte array
*
* \param byteArray Bytes to stream
* \param openMode Reading/writing mode for the stream
*/
inline MemoryStream::MemoryStream(ByteArray* byteArray, OpenModeFlags openMode) :
MemoryStream()
{
SetBuffer(byteArray, openMode);
}
/*!
* \brief Gets the internal buffer
* \return Buffer of bytes
*
* \remark Produces a NazaraAssert if buffer is invalid
*/
inline ByteArray& MemoryStream::GetBuffer()
{
NazaraAssert(m_buffer, "Invalid buffer");
return *m_buffer;
}
/*!
* \brief Gets the internal buffer
* \return Buffer of bytes
*
* \remark Produces a NazaraAssert if buffer is invalid
*/
inline const ByteArray& MemoryStream::GetBuffer() const
{
NazaraAssert(m_buffer, "Invalid buffer");
return *m_buffer;
}
}
#include <Nazara/Core/DebugOff.hpp>
| 22.354839 | 82 | 0.722222 | [
"object"
] |
ce4e8e15444e96a98c11143600bb3d3e13b1a872 | 1,763 | hpp | C++ | src/conditionals.hpp | plewis/lorad | bdc70e966e423e92aef66ef9d52220a5c241e6f3 | [
"MIT"
] | null | null | null | src/conditionals.hpp | plewis/lorad | bdc70e966e423e92aef66ef9d52220a5c241e6f3 | [
"MIT"
] | null | null | null | src/conditionals.hpp | plewis/lorad | bdc70e966e423e92aef66ef9d52220a5c241e6f3 | [
"MIT"
] | null | null | null | #pragma once
// Uncomment the following define to enable LoRaD for variable topologies as well as fixed topologies.
#define LORAD_VARIABLE_TOPOLOGY
// Uncomment the following define to implement the generalized steppingstone method described in
// Y Fan, R Wu, MH Chen, L Kuo, and PO Lewis. 2011. Choosing among Partition Models in Bayesian
// Phylogenetics. Molecular Biology and Evolution 28(1):523-532.
#define POLGSS
// Uncomment the following to use edge length and rate heterogeneity priors described in this chapter:
// MT Holder, PO Lewis, DL Swofford, and D Bryant. 2014. Variable tree topology stepping-stone marginal
// likelihood estimation. Chapter 5, pp. 95-111, in: MH Chen, L Kuo, and PO Lewis (eds.), Bayesian
// phylogenetics: methods, algorithms, and applications. Chapman and Hall/CRC Mathematical and Computational
// Biology Series, 365 pages. ISBN-13: 978-1-4665-00790-2
//#define HOLDER_ETAL_PRIOR
//
// Conditional defines below here will probably be eliminated soon because they are no longer useful
//
// Uncomment the following define to track the lengths of runs of the focal topology and exclude the
// first focalburnin iterations from each run. The focal topology is always the topology supplied
// via the treefile option (i.e. start the run with the topology you are interested in tracking.
// The focalburnin option does not seem to have much of an effect.
//#define TRACK_RUNS_OF_FOCAL_TREE
// Uncomment the following define to standardize the log-transformed parameter vector using the mode
// rather than the mean. The mode used is the highest point on the log-transformed posterior kernel surface.
//#define MODE_CENTER
// Uncomment the following define only if std::regex is not available
//#define USE_BOOST_REGEX
| 50.371429 | 108 | 0.785026 | [
"vector"
] |
ce53d0c43c492a4f1215d15488ff1b7658d90904 | 7,183 | cpp | C++ | modules/features2d/test/test_descriptors_invariance.cpp | gitwithmch/opencv | a8844de7b5ffad08b4463536d21aadd6c0d1f3b3 | [
"BSD-3-Clause"
] | 17 | 2020-03-13T00:10:28.000Z | 2021-09-06T17:13:17.000Z | modules/features2d/test/test_descriptors_invariance.cpp | gitwithmch/opencv | a8844de7b5ffad08b4463536d21aadd6c0d1f3b3 | [
"BSD-3-Clause"
] | 1 | 2020-03-12T08:10:07.000Z | 2020-03-12T08:10:07.000Z | modules/features2d/test/test_descriptors_invariance.cpp | gitwithmch/opencv | a8844de7b5ffad08b4463536d21aadd6c0d1f3b3 | [
"BSD-3-Clause"
] | 2 | 2020-03-13T09:05:32.000Z | 2021-08-13T08:28:14.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "test_precomp.hpp"
#include "test_invariance_utils.hpp"
using namespace std;
using namespace cv;
using std::tr1::make_tuple;
using std::tr1::get;
using namespace testing;
#define SHOW_DEBUG_LOG 1
typedef std::tr1::tuple<std::string, Ptr<FeatureDetector>, Ptr<DescriptorExtractor>, float>
String_FeatureDetector_DescriptorExtractor_Float_t;
const static std::string IMAGE_TSUKUBA = "features2d/tsukuba.png";
const static std::string IMAGE_BIKES = "detectors_descriptors_evaluation/images_datasets/bikes/img1.png";
#define Value(...) Values(String_FeatureDetector_DescriptorExtractor_Float_t(__VA_ARGS__))
static
void rotateKeyPoints(const vector<KeyPoint>& src, const Mat& H, float angle, vector<KeyPoint>& dst)
{
// suppose that H is rotation given from rotateImage() and angle has value passed to rotateImage()
vector<Point2f> srcCenters, dstCenters;
KeyPoint::convert(src, srcCenters);
perspectiveTransform(srcCenters, dstCenters, H);
dst = src;
for(size_t i = 0; i < dst.size(); i++)
{
dst[i].pt = dstCenters[i];
float dstAngle = src[i].angle + angle;
if(dstAngle >= 360.f)
dstAngle -= 360.f;
dst[i].angle = dstAngle;
}
}
class DescriptorInvariance : public TestWithParam<String_FeatureDetector_DescriptorExtractor_Float_t>
{
protected:
virtual void SetUp() {
// Read test data
const std::string filename = cvtest::TS::ptr()->get_data_path() + get<0>(GetParam());
image0 = imread(filename);
ASSERT_FALSE(image0.empty()) << "couldn't read input image";
featureDetector = get<1>(GetParam());
descriptorExtractor = get<2>(GetParam());
minInliersRatio = get<3>(GetParam());
}
Ptr<FeatureDetector> featureDetector;
Ptr<DescriptorExtractor> descriptorExtractor;
float minInliersRatio;
Mat image0;
};
typedef DescriptorInvariance DescriptorScaleInvariance;
typedef DescriptorInvariance DescriptorRotationInvariance;
TEST_P(DescriptorRotationInvariance, rotation)
{
Mat image1, mask1;
const int borderSize = 16;
Mat mask0(image0.size(), CV_8UC1, Scalar(0));
mask0(Rect(borderSize, borderSize, mask0.cols - 2*borderSize, mask0.rows - 2*borderSize)).setTo(Scalar(255));
vector<KeyPoint> keypoints0;
Mat descriptors0;
featureDetector->detect(image0, keypoints0, mask0);
std::cout << "Keypoints: " << keypoints0.size() << std::endl;
EXPECT_GE(keypoints0.size(), 15u);
descriptorExtractor->compute(image0, keypoints0, descriptors0);
BFMatcher bfmatcher(descriptorExtractor->defaultNorm());
const float minIntersectRatio = 0.5f;
const int maxAngle = 360, angleStep = 15;
for(int angle = 0; angle < maxAngle; angle += angleStep)
{
Mat H = rotateImage(image0, mask0, static_cast<float>(angle), image1, mask1);
vector<KeyPoint> keypoints1;
rotateKeyPoints(keypoints0, H, static_cast<float>(angle), keypoints1);
Mat descriptors1;
descriptorExtractor->compute(image1, keypoints1, descriptors1);
vector<DMatch> descMatches;
bfmatcher.match(descriptors0, descriptors1, descMatches);
int descInliersCount = 0;
for(size_t m = 0; m < descMatches.size(); m++)
{
const KeyPoint& transformed_p0 = keypoints1[descMatches[m].queryIdx];
const KeyPoint& p1 = keypoints1[descMatches[m].trainIdx];
if(calcIntersectRatio(transformed_p0.pt, 0.5f * transformed_p0.size,
p1.pt, 0.5f * p1.size) >= minIntersectRatio)
{
descInliersCount++;
}
}
float descInliersRatio = static_cast<float>(descInliersCount) / keypoints0.size();
EXPECT_GE(descInliersRatio, minInliersRatio);
#if SHOW_DEBUG_LOG
std::cout
<< "angle = " << angle
<< ", inliers = " << descInliersCount
<< ", descInliersRatio = " << static_cast<float>(descInliersCount) / keypoints0.size()
<< std::endl;
#endif
}
}
TEST_P(DescriptorScaleInvariance, scale)
{
vector<KeyPoint> keypoints0;
featureDetector->detect(image0, keypoints0);
std::cout << "Keypoints: " << keypoints0.size() << std::endl;
EXPECT_GE(keypoints0.size(), 15u);
Mat descriptors0;
descriptorExtractor->compute(image0, keypoints0, descriptors0);
BFMatcher bfmatcher(descriptorExtractor->defaultNorm());
for(int scaleIdx = 1; scaleIdx <= 3; scaleIdx++)
{
float scale = 1.f + scaleIdx * 0.5f;
Mat image1;
resize(image0, image1, Size(), 1./scale, 1./scale, INTER_LINEAR_EXACT);
vector<KeyPoint> keypoints1;
scaleKeyPoints(keypoints0, keypoints1, 1.0f/scale);
Mat descriptors1;
descriptorExtractor->compute(image1, keypoints1, descriptors1);
vector<DMatch> descMatches;
bfmatcher.match(descriptors0, descriptors1, descMatches);
const float minIntersectRatio = 0.5f;
int descInliersCount = 0;
for(size_t m = 0; m < descMatches.size(); m++)
{
const KeyPoint& transformed_p0 = keypoints0[descMatches[m].queryIdx];
const KeyPoint& p1 = keypoints0[descMatches[m].trainIdx];
if(calcIntersectRatio(transformed_p0.pt, 0.5f * transformed_p0.size,
p1.pt, 0.5f * p1.size) >= minIntersectRatio)
{
descInliersCount++;
}
}
float descInliersRatio = static_cast<float>(descInliersCount) / keypoints0.size();
EXPECT_GE(descInliersRatio, minInliersRatio);
#if SHOW_DEBUG_LOG
std::cout
<< "scale = " << scale
<< ", inliers = " << descInliersCount
<< ", descInliersRatio = " << static_cast<float>(descInliersCount) / keypoints0.size()
<< std::endl;
#endif
}
}
/*
* Descriptors's rotation invariance check
*/
INSTANTIATE_TEST_CASE_P(BRISK, DescriptorRotationInvariance,
Value(IMAGE_TSUKUBA, BRISK::create(), BRISK::create(), 0.99f));
INSTANTIATE_TEST_CASE_P(ORB, DescriptorRotationInvariance,
Value(IMAGE_TSUKUBA, ORB::create(), ORB::create(), 0.99f));
INSTANTIATE_TEST_CASE_P(AKAZE, DescriptorRotationInvariance,
Value(IMAGE_TSUKUBA, AKAZE::create(), AKAZE::create(), 0.99f));
INSTANTIATE_TEST_CASE_P(AKAZE_DESCRIPTOR_KAZE, DescriptorRotationInvariance,
Value(IMAGE_TSUKUBA, AKAZE::create(AKAZE::DESCRIPTOR_KAZE), AKAZE::create(AKAZE::DESCRIPTOR_KAZE), 0.99f));
/*
* Descriptor's scale invariance check
*/
INSTANTIATE_TEST_CASE_P(AKAZE, DescriptorScaleInvariance,
Value(IMAGE_BIKES, AKAZE::create(), AKAZE::create(), 0.6f));
INSTANTIATE_TEST_CASE_P(AKAZE_DESCRIPTOR_KAZE, DescriptorScaleInvariance,
Value(IMAGE_BIKES, AKAZE::create(AKAZE::DESCRIPTOR_KAZE), AKAZE::create(AKAZE::DESCRIPTOR_KAZE), 0.55f));
| 36.835897 | 131 | 0.663093 | [
"vector"
] |
ce58e32e719bc8c76cfe6486a95b415dc0b1a4fa | 12,519 | cc | C++ | src/large_pages/node_large_page.cc | theanarkh/read-nodejs-v14 | cccb59c703058c35a9e841fec4f1b454f22e4e0e | [
"MIT"
] | 2 | 2020-09-16T01:30:55.000Z | 2020-09-28T02:17:07.000Z | src/large_pages/node_large_page.cc | theanarkh/read-nodejs-v14 | cccb59c703058c35a9e841fec4f1b454f22e4e0e | [
"MIT"
] | null | null | null | src/large_pages/node_large_page.cc | theanarkh/read-nodejs-v14 | cccb59c703058c35a9e841fec4f1b454f22e4e0e | [
"MIT"
] | null | null | null | // Copyright (C) 2018 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
//
// SPDX-License-Identifier: MIT
#include "node_large_page.h"
#include "util.h"
#include "uv.h"
#include <fcntl.h> // _O_RDWR
#include <sys/types.h>
#include <sys/mman.h>
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#include <sys/user.h>
#elif defined(__APPLE__)
#include <mach/vm_map.h>
#endif
#include <unistd.h> // readlink
#include <cerrno> // NOLINT(build/include)
#include <climits> // PATH_MAX
#include <clocale>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>
// The functions in this file map the text segment of node into 2M pages.
// The algorithm is simple
// Find the text region of node binary in memory
// 1: Examine the /proc/self/maps to determine the currently mapped text
// region and obtain the start and end
// Modify the start to point to the very beginning of node text segment
// (from variable nodetext setup in ld.script)
// Align the address of start and end to Large Page Boundaries
//
// 2: Move the text region to large pages
// Map a new area and copy the original code there
// Use mmap using the start address with MAP_FIXED so we get exactly the
// same virtual address
// Use madvise with MADV_HUGEPAGE to use Anonymous 2M Pages
// If successful copy the code there and unmap the original region.
#if defined(__linux__)
extern "C" {
extern char __executable_start;
} // extern "C"
#endif // defined(__linux__)
namespace node {
struct text_region {
char* from;
char* to;
int total_hugepages;
bool found_text_region;
};
static const size_t hps = 2L * 1024 * 1024;
static void PrintWarning(const char* warn) {
fprintf(stderr, "Hugepages WARNING: %s\n", warn);
}
static void PrintSystemError(int error) {
PrintWarning(strerror(error));
}
inline uintptr_t hugepage_align_up(uintptr_t addr) {
return (((addr) + (hps) - 1) & ~((hps) - 1));
}
inline uintptr_t hugepage_align_down(uintptr_t addr) {
return ((addr) & ~((hps) - 1));
}
// The format of the maps file is the following
// address perms offset dev inode pathname
// 00400000-00452000 r-xp 00000000 08:02 173521 /usr/bin/dbus-daemon
// This is also handling the case where the first line is not the binary.
static struct text_region FindNodeTextRegion() {
struct text_region nregion;
nregion.found_text_region = false;
#if defined(__linux__)
std::ifstream ifs;
std::string map_line;
std::string permission;
std::string dev;
char dash;
uintptr_t start, end, offset, inode;
ifs.open("/proc/self/maps");
if (!ifs) {
PrintWarning("could not open /proc/self/maps");
return nregion;
}
while (std::getline(ifs, map_line)) {
std::istringstream iss(map_line);
iss >> std::hex >> start;
iss >> dash;
iss >> std::hex >> end;
iss >> permission;
iss >> offset;
iss >> dev;
iss >> inode;
if (inode == 0)
continue;
std::string pathname;
iss >> pathname;
if (start != reinterpret_cast<uintptr_t>(&__executable_start))
continue;
// The next line is our .text section.
if (!std::getline(ifs, map_line))
break;
iss = std::istringstream(map_line);
iss >> std::hex >> start;
iss >> dash;
iss >> std::hex >> end;
iss >> permission;
if (permission != "r-xp")
break;
char* from = reinterpret_cast<char*>(hugepage_align_up(start));
char* to = reinterpret_cast<char*>(hugepage_align_down(end));
if (from >= to)
break;
size_t size = to - from;
nregion.found_text_region = true;
nregion.from = from;
nregion.to = to;
nregion.total_hugepages = size / hps;
break;
}
ifs.close();
#elif defined(__FreeBSD__)
std::string exename;
{
char selfexe[PATH_MAX];
size_t count = sizeof(selfexe);
if (uv_exepath(selfexe, &count))
return nregion;
exename = std::string(selfexe, count);
}
size_t numpg;
int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, getpid()};
const size_t miblen = arraysize(mib);
if (sysctl(mib, miblen, nullptr, &numpg, nullptr, 0) == -1) {
return nregion;
}
// Enough for struct kinfo_vmentry.
numpg = numpg * 4 / 3;
auto alg = std::vector<char>(numpg);
if (sysctl(mib, miblen, alg.data(), &numpg, nullptr, 0) == -1) {
return nregion;
}
char* start = alg.data();
char* end = start + numpg;
while (start < end) {
kinfo_vmentry* entry = reinterpret_cast<kinfo_vmentry*>(start);
const size_t cursz = entry->kve_structsize;
if (cursz == 0) {
break;
}
if (entry->kve_path[0] == '\0') {
continue;
}
bool excmapping = ((entry->kve_protection & KVME_PROT_READ) &&
(entry->kve_protection & KVME_PROT_EXEC));
if (!strcmp(exename.c_str(), entry->kve_path) && excmapping) {
char* estart =
reinterpret_cast<char*>(hugepage_align_up(entry->kve_start));
char* eend =
reinterpret_cast<char*>(hugepage_align_down(entry->kve_end));
size_t size = eend - estart;
nregion.found_text_region = true;
nregion.from = estart;
nregion.to = eend;
nregion.total_hugepages = size / hps;
break;
}
start += cursz;
}
#elif defined(__APPLE__)
struct vm_region_submap_info_64 map;
mach_msg_type_number_t count = VM_REGION_SUBMAP_INFO_COUNT_64;
vm_address_t addr = 0UL;
vm_size_t size = 0;
natural_t depth = 1;
while (true) {
if (vm_region_recurse_64(mach_task_self(), &addr, &size, &depth,
reinterpret_cast<vm_region_info_64_t>(&map),
&count) != KERN_SUCCESS) {
break;
}
if (map.is_submap) {
depth++;
} else {
char* start = reinterpret_cast<char*>(hugepage_align_up(addr));
char* end = reinterpret_cast<char*>(hugepage_align_down(addr+size));
size_t esize = end - start;
if (end > start && (map.protection & VM_PROT_READ) != 0 &&
(map.protection & VM_PROT_EXECUTE) != 0) {
nregion.found_text_region = true;
nregion.from = start;
nregion.to = end;
nregion.total_hugepages = esize / hps;
break;
}
addr += size;
size = 0;
}
}
#endif
return nregion;
}
#if defined(__linux__)
static bool IsTransparentHugePagesEnabled() {
std::ifstream ifs;
ifs.open("/sys/kernel/mm/transparent_hugepage/enabled");
if (!ifs) {
PrintWarning("could not open /sys/kernel/mm/transparent_hugepage/enabled");
return false;
}
std::string always, madvise;
if (ifs.is_open()) {
while (ifs >> always >> madvise) {}
}
ifs.close();
return always == "[always]" || madvise == "[madvise]";
}
#elif defined(__FreeBSD__)
static bool IsSuperPagesEnabled() {
// It is enabled by default on amd64.
unsigned int super_pages = 0;
size_t super_pages_length = sizeof(super_pages);
return sysctlbyname("vm.pmap.pg_ps_enabled",
&super_pages,
&super_pages_length,
nullptr,
0) != -1 &&
super_pages >= 1;
}
#endif
// Moving the text region to large pages. We need to be very careful.
// 1: This function itself should not be moved.
// We use a gcc attributes
// (__section__) to put it outside the ".text" section
// (__aligned__) to align it at 2M boundary
// (__noline__) to not inline this function
// 2: This function should not call any function(s) that might be moved.
// a. map a new area and copy the original code there
// b. mmap using the start address with MAP_FIXED so we get exactly
// the same virtual address (except on macOS).
// c. madvise with MADV_HUGEPAGE
// d. If successful copy the code there and unmap the original region
int
#if !defined(__APPLE__)
__attribute__((__section__(".lpstub")))
#else
__attribute__((__section__("__TEXT,__lpstub")))
#endif
__attribute__((__aligned__(hps)))
__attribute__((__noinline__))
MoveTextRegionToLargePages(const text_region& r) {
void* nmem = nullptr;
void* tmem = nullptr;
int ret = 0;
size_t size = r.to - r.from;
void* start = r.from;
// Allocate temporary region preparing for copy.
nmem = mmap(nullptr, size,
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (nmem == MAP_FAILED) {
PrintSystemError(errno);
return -1;
}
memcpy(nmem, r.from, size);
#if defined(__linux__)
// We already know the original page is r-xp
// (PROT_READ, PROT_EXEC, MAP_PRIVATE)
// We want PROT_WRITE because we are writing into it.
// We want it at the fixed address and we use MAP_FIXED.
tmem = mmap(start, size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1 , 0);
if (tmem == MAP_FAILED) {
PrintSystemError(errno);
return -1;
}
ret = madvise(tmem, size, 14 /* MADV_HUGEPAGE */);
if (ret == -1) {
PrintSystemError(errno);
ret = munmap(tmem, size);
if (ret == -1) {
PrintSystemError(errno);
}
if (-1 == munmap(nmem, size)) PrintSystemError(errno);
return -1;
}
memcpy(start, nmem, size);
#elif defined(__FreeBSD__)
tmem = mmap(start, size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED |
MAP_ALIGNED_SUPER, -1 , 0);
if (tmem == MAP_FAILED) {
PrintSystemError(errno);
if (-1 == munmap(nmem, size)) PrintSystemError(errno);
return -1;
}
#elif defined(__APPLE__)
// There is not enough room to reserve the mapping close
// to the region address so we content to give a hint
// without forcing the new address being closed to.
// We explicitally gives all permission since we plan
// to write into it.
tmem = mmap(start, size,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS,
VM_FLAGS_SUPERPAGE_SIZE_2MB, 0);
if (tmem == MAP_FAILED) {
PrintSystemError(errno);
if (-1 == munmap(nmem, size)) PrintSystemError(errno);
return -1;
}
memcpy(tmem, nmem, size);
ret = mprotect(start, size, PROT_READ | PROT_WRITE | PROT_EXEC);
if (ret == -1) {
PrintSystemError(errno);
ret = munmap(tmem, size);
if (ret == -1) {
PrintSystemError(errno);
}
if (-1 == munmap(nmem, size)) PrintSystemError(errno);
return -1;
}
memcpy(start, tmem, size);
#endif
ret = mprotect(start, size, PROT_READ | PROT_EXEC);
if (ret == -1) {
PrintSystemError(errno);
ret = munmap(tmem, size);
if (ret == -1) {
PrintSystemError(errno);
}
if (-1 == munmap(nmem, size)) PrintSystemError(errno);
return -1;
}
if (-1 == munmap(nmem, size)) PrintSystemError(errno);
return ret;
}
// This is the primary API called from main.
int MapStaticCodeToLargePages() {
struct text_region r = FindNodeTextRegion();
if (r.found_text_region == false) {
PrintWarning("failed to find text region");
return -1;
}
#if defined(__FreeBSD__)
if (r.from < reinterpret_cast<void*>(&MoveTextRegionToLargePages))
return -1;
#endif
return MoveTextRegionToLargePages(r);
}
bool IsLargePagesEnabled() {
#if defined(__linux__)
return IsTransparentHugePagesEnabled();
#elif defined(__FreeBSD__)
return IsSuperPagesEnabled();
#elif defined(__APPLE__)
// pse-36 flag is present in recent mac x64 products.
return true;
#endif
}
} // namespace node
| 28.452273 | 79 | 0.661315 | [
"vector"
] |
ce5a25540f5a5af769c1c9c525470407495125f4 | 2,359 | cpp | C++ | Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/RHI/DX12/Code/Source/Platform/Windows/RHI/WindowsVersionQuery.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "RHI/Atom_RHI_DX12_precompiled.h"
#include <RHI/WindowsVersionQuery.h>
namespace AZ
{
namespace DX12
{
namespace Platform
{
bool GetWindowsVersionFromSystemDLL(WindowsVersion* windowsVersion)
{
// We get the file version of one of the system DLLs to get the OS version.
constexpr const char* dllName = "Kernel32.dll";
VS_FIXEDFILEINFO* fileInfo = nullptr;
DWORD handle;
DWORD infoSize = GetFileVersionInfoSize(dllName, &handle);
if (infoSize > 0)
{
AZStd::vector<BYTE> versionData(infoSize);
if (GetFileVersionInfo(dllName, handle, infoSize, versionData.data()) != 0)
{
UINT len;
const char* subBlock = "\\";
if (VerQueryValue(versionData.data(), subBlock, reinterpret_cast<LPVOID*>(&fileInfo), &len) != 0)
{
windowsVersion->m_majorVersion = HIWORD(fileInfo->dwProductVersionMS);
windowsVersion->m_minorVersion = LOWORD(fileInfo->dwProductVersionMS);
windowsVersion->m_buildVersion = HIWORD(fileInfo->dwProductVersionLS);
return true;
}
}
}
return false;
}
bool GetWindowsVersion(WindowsVersion* windowsVersion)
{
static WindowsVersion s_cachedVersion;
static bool s_isCached = false;
if (s_isCached)
{
*windowsVersion = s_cachedVersion;
return true;
}
bool readOk = GetWindowsVersionFromSystemDLL(windowsVersion);
if (readOk)
{
s_cachedVersion = *windowsVersion;
s_isCached = true;
}
return readOk;
}
}
}
}
| 37.444444 | 158 | 0.503603 | [
"vector",
"3d"
] |
ce5bb38be2b3146fc3e2c4253b1bfb6d126ae9f6 | 9,119 | cpp | C++ | android/fanLua/fan/src/main/jni/bxPlugin.cpp | bugblat/fan | 854b2c0c6b94270bd08a2cf58bfa1871d34bb8ef | [
"MIT"
] | 5 | 2016-01-21T21:22:04.000Z | 2022-02-16T22:26:59.000Z | android/fanLua/fan/src/main/jni/bxPlugin.cpp | bugblat/fan | 854b2c0c6b94270bd08a2cf58bfa1871d34bb8ef | [
"MIT"
] | null | null | null | android/fanLua/fan/src/main/jni/bxPlugin.cpp | bugblat/fan | 854b2c0c6b94270bd08a2cf58bfa1871d34bb8ef | [
"MIT"
] | 2 | 2015-12-29T15:32:52.000Z | 2017-06-22T15:23:08.000Z | #include <vector>
#include "gideros.h"
#include "lua.h"
#include "lauxlib.h"
#define LUA_LIB
#include <jni.h>
#include <android/log.h>
using namespace std;
LUALIB_API int loader(lua_State *L);
//--------------------------------------------
namespace {
const char *pluginNAME = "bxPlugin";
const char *pluginTABLE = "bx";
const char *pluginVERSION = "1.0";
JNIEnv *ENV = 0; // Store Java Environment reference
jclass cls = 0; // Store our main class, what we will use as plugin
//--------------------------------------------
const char* javaClassName = "com/giderosmobile/android/bxPlugin";
bool getMethodID(jmethodID& aMethodID, const char *aName, const char *aArgSig) {
__android_log_print(ANDROID_LOG_DEBUG, "getMethodID", "module:%s", aName);
if (ENV == 0) // exit if no Java Env
return false;
if (cls == 0) { // if no class, try to retrieve it
cls = ENV->FindClass(javaClassName);
if(!cls)
return false;
}
if (aMethodID == 0) {
/****************
* 1. argument cls - reference to Java class, where we have this method
* 2. argument name of the method to get
* 3. argument what arguments does method accept and what it returns
****************/
aMethodID = ENV->GetStaticMethodID(cls, aName, aArgSig);
}
return (aMethodID != 0);
}
//------------------------------------------
int version(lua_State *L) {
const char *ver = __TIME__ "," __DATE__;
lua_pushstring(L, ver);
return 1;
}
//--------------------------------------------
int addTwoIntsLoc(lua_State *L) { // for testing
int a = lua_tointeger(L, -1);
int b = lua_tointeger(L, -2);
lua_pushnumber(L, a+b);
return 1;
}
//--------------------------------------------
int addTwoIntegers(lua_State *L) { // for testing
static jmethodID methodID = 0;
int a = lua_tointeger(L, -1);
int b = lua_tointeger(L, -2);
int result = 9999;
if (getMethodID(methodID, "addTwoIntegers", "(II)I")) {
result = ENV->CallStaticIntMethod(cls, methodID, a, b);
}
lua_pushnumber(L, result);
return 1;
}
//------------------------------------------
int open(lua_State *L) {
static jmethodID methodID = 0;
bool ok = false;
if (getMethodID(methodID, "open", "()Z")) {
ok = ENV->CallStaticBooleanMethod(cls, methodID);
}
lua_pushboolean(L, ok);
return 1;
}
//------------------------------------------
int close(lua_State *L) {
static jmethodID methodID = 0;
if (getMethodID(methodID, "close", "()V")) {
ENV->CallStaticVoidMethod(cls, methodID);
}
return 0;
}
//------------------------------------------
int isOpen(lua_State *L) {
static jmethodID methodID = 0;
bool ok = false;
if (getMethodID(methodID, "isOpen", "()Z")) {
ok = ENV->CallStaticBooleanMethod(cls, methodID);
}
lua_pushboolean(L, ok);
return 1;
}
//------------------------------------------
int rescan(lua_State *L) {
static jmethodID methodID = 0;
bool ok = false;
if (getMethodID(methodID, "rescan", "()Z")) {
ok = ENV->CallStaticBooleanMethod(cls, methodID);
}
lua_pushboolean(L, ok);
return 1;
}
//------------------------------------------
int serialNumber(lua_State *L) {
char *s = (char *)("ERROR");
static jmethodID methodID = 0;
if (getMethodID(methodID, "serialNumber", "()Ljava/lang/String;")) {
jstring jstr = (jstring)ENV->CallStaticObjectMethod(cls, methodID);
s = (char *)ENV->GetStringUTFChars(jstr, 0);
}
lua_pushlstring(L, s, strlen(s));
return 1;
}
//--------------------------------------------
int ta(lua_State *L) {
static jmethodID methodID = 0;
if (getMethodID(methodID, "ta", "(I)V")) {
int v = lua_tointeger(L, -1);
ENV->CallStaticVoidMethod(cls, methodID, v);
}
return 0;
}
//--------------------------------------------
int td(lua_State *L) {
static jmethodID methodID = 0;
if (getMethodID(methodID, "td", "(I)V")) {
int v = lua_tointeger(L, -1);
ENV->CallStaticVoidMethod(cls, methodID, v);
}
return 0;
}
//--------------------------------------------
int tt(lua_State *L) {
static jmethodID methodID = 0;
if (getMethodID(methodID, "tt", "(I)V")) {
int v = lua_tointeger(L, -1);
ENV->CallStaticVoidMethod(cls, methodID, v);
}
return 0;
}
//--------------------------------------------
int th(lua_State *L) {
static jmethodID methodID = 0;
if (getMethodID(methodID, "th", "(I)V")) {
int v = lua_tointeger(L, -1);
ENV->CallStaticVoidMethod(cls, methodID, v);
}
return 0;
}
//------------------------------------------
int flush(lua_State *L) {
static jmethodID methodID = 0;
bool ok = false;
if (getMethodID(methodID, "appFlush", "()Z")) {
ok = ENV->CallStaticBooleanMethod(cls, methodID);
}
lua_pushboolean(L, ok);
return 1;
}
//------------------------------------------
int appWrite(lua_State *L) {
static jmethodID methodID = 0;
bool b = (lua_istable(L, -1) != 0);
if (!b) {
lua_pop(L, 1);
lua_pushboolean(L, false);
return 1;
}
size_t count = lua_objlen(L, -1);
vector<uint8_t> vec;
vec.resize(count);
for (size_t i=0; i<count; i++) {
lua_rawgeti(L, -1, i+1);
int v = lua_tointeger(L, -1);
vec.push_back(v);
lua_pop(L, 1);
}
lua_pop(L, 1);
bool ok = false;
if (getMethodID(methodID, "appWrite", "([BI)Z")) {
jbyteArray jBuff = ENV->NewByteArray(count);
ENV->SetByteArrayRegion(jBuff, 0, count, (jbyte *)&vec[0]);
ok = ENV->CallStaticBooleanMethod(cls, methodID, jBuff, count);
ENV->DeleteLocalRef(jBuff);
}
lua_pushboolean(L, ok);
return 1;
}
//------------------------------------------
int appRead(lua_State *L) {
int count = lua_tointeger(L, -1);
static jmethodID methodID = 0;
if (getMethodID(methodID, "appRead", "(I)[B")) {
jbyteArray jBuff = (jbyteArray)ENV->CallStaticObjectMethod(cls, methodID, count);
int retlen = ENV->GetArrayLength(jBuff);
char *buf = new char[retlen];
ENV->GetByteArrayRegion (jBuff, 0, retlen, reinterpret_cast<jbyte*>(buf));
lua_pushboolean(L, true);
lua_pushlstring(L, buf, retlen);
delete[] buf;
}
else {
lua_pushboolean(L, false);
const char *s = "ERROR";
lua_pushlstring(L, s, sizeof(s));
}
return 2;
}
//------------------------------------------
int appReadReg(lua_State *L) {
int count = lua_tointeger(L, -1);
int regNum = lua_tointeger(L, -2);
static jmethodID methodID = 0;
if (getMethodID(methodID, "appReadReg", "(II)[B")) {
jbyteArray jBuff = (jbyteArray)ENV->CallStaticObjectMethod(cls, methodID, regNum, count);
int retlen = ENV->GetArrayLength(jBuff);
char *buf = new char[retlen];
ENV->GetByteArrayRegion (jBuff, 0, retlen, reinterpret_cast<jbyte*>(buf));
lua_pushboolean(L, true);
lua_pushlstring(L, buf, retlen);
delete[] buf;
}
else {
lua_pushboolean(L, false);
const char *s = "ERROR";
lua_pushlstring(L, s, sizeof(s));
}
return 2;
}
//------------------------------------------
const struct luaL_Reg functionList[] = {
{ "version" , version },
{ "addTwoIntsLoc" , addTwoIntsLoc },
{ "addTwoIntegers", addTwoIntegers },
{ "open" , open },
{ "close" , close },
{ "isOpen" , isOpen },
{ "rescan" , rescan },
{ "serialNumber" , serialNumber },
{ "ta" , ta },
{ "td" , td },
{ "tt" , tt },
{ "th" , th },
{ "flush" , flush },
{ "write" , appWrite },
{ "read" , appRead },
{ "readReg" , appReadReg },
{ 0 , 0 }
};
//--------------------------------------------
void g_initializePlugin(lua_State* L) {
ENV = g_getJNIEnv();
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, loader);
lua_setfield(L, -2, pluginNAME);
lua_pop(L, 2);
}
//--------------------------------------------
void g_deinitializePlugin(lua_State *L) {}
} // end of anonymous namespace
//----------------------------------------------
LUALIB_API int loader(lua_State *L) {
//__android_log_print(ANDROID_LOG_DEBUG, "bxPlugin", "loader called");
luaL_register(L, pluginTABLE, functionList);
return 1;
}
//--------------------------------------------
REGISTER_PLUGIN(pluginTABLE, pluginVERSION)
// EOF ----------------------------------------------------------------
/*
*/
| 28.4081 | 95 | 0.493256 | [
"vector"
] |
ce5ca257be37c36e955f982253ea8c303dca82c1 | 6,197 | hpp | C++ | cpp/include/sentient/core/type_traits.hpp | hyper-level-nerds/sentient | 963219d8c01a1efaed4f53fa1793e734b92b983e | [
"BSL-1.0"
] | null | null | null | cpp/include/sentient/core/type_traits.hpp | hyper-level-nerds/sentient | 963219d8c01a1efaed4f53fa1793e734b92b983e | [
"BSL-1.0"
] | null | null | null | cpp/include/sentient/core/type_traits.hpp | hyper-level-nerds/sentient | 963219d8c01a1efaed4f53fa1793e734b92b983e | [
"BSL-1.0"
] | null | null | null | #ifndef __SENTIENT_CORE_TYPE_TRAITS_HPP__
#define __SENTIENT_CORE_TYPE_TRAITS_HPP__
/**
* @file type_traits.hpp
* @author Jin (jaehwanspin@gmail.com)
* @brief Type(Model) attributes utilities
* @version 0.1
* @date 2022-03-26
*
* @copyright Copyright (c) 2022
*
*/
#include <type_traits>
#include <tuple>
#include <boost/hana/define_struct.hpp>
namespace sentient
{
namespace type_traits
{
namespace internal
{
template<typename... Tps>
struct is_type_helper {};
}
/**
* @author Jin
* @brief basic sentient model attribute
*
*/
struct sentient_model_attr
{ using base_type = sentient_model_attr; };
/**
* @author Jin
* @brief static sized model attribute
*
*/
struct static_model_attr : sentient_model_attr
{ using model_flexiblity_attr_type = static_model_attr; };
/**
* @author Jin
* @brief dynamic sized model attribute
*
*/
struct dynamic_model_attr : sentient_model_attr
{ using model_flexiblity_attr_type = dynamic_model_attr; };
/**
* @author Jin
* @brief
*
* @tparam _DatabaseName
*/
template <typename _Derived, size_t _PkIdx, char ... _TableNamePrefix>
struct dbms_compatible_attr : sentient_model_attr
{
static constexpr size_t dbms_pk_idx_value = _PkIdx;
using dbms_compatible_type = _Derived;
// static constexpr std::tuple<_DatabaseName ...> param_pack = { _DatabaseName... };
static constexpr const char table_name_prefix[sizeof...(_TableNamePrefix)] = { (_TableNamePrefix)... };
};
/**
* @author Jin
* @brief matafunc returns true if the model type is sentient-based model
*
* @tparam _Model
*/
template <typename _Model>
struct is_sentient_model :
std::is_same<typename _Model::base_type, sentient_model_attr> { };
template <typename _Model>
constexpr inline bool is_sentient_model_v = is_sentient_model<_Model>::value;
/**
* @author Jin
* @brief metafunc returns true if the model has satatic size
*
* @tparam _Model
*/
template <typename _Model>
struct is_static_model :
std::is_same<typename _Model::model_flexiblity_attr_type, static_model_attr> { };
template <typename _Model>
constexpr inline bool is_static_model_v = is_static_model<_Model>::value;
/**
* @author Jin
* @brief
*
* @tparam _Model
*/
template <typename _Model>
struct is_dynamic_model :
std::is_same<typename _Model::model_flexiblity_attr_type, dynamic_model_attr> { };
template <typename _Model>
constexpr inline bool is_dynamic_model_v = is_dynamic_model<_Model>::value;
/**
* @author Jin
* @brief
*
* @tparam _Model
* @tparam typename
*/
template <typename _Model, typename _Tp = void>
struct is_dbms_compatible_model : std::false_type { };
template <typename _Model>
struct is_dbms_compatible_model<
_Model,
std::conditional_t<false,
typename _Model::dbms_compatible_type,
void
>
> : std::true_type { };
template <typename _Model, typename _Tp = void>
constexpr inline bool is_dbms_compatible_model_v = is_dbms_compatible_model<_Model, _Tp>::value;
/**
* @author Jin
* @brief
*
* @tparam _Tp
* @tparam _Up
*/
template<typename _Tp, typename _Up = void>
struct is_datetime : std::false_type {};
template<typename _Tp>
struct is_datetime<
_Tp,
std::conditional_t<
false,
internal::is_type_helper<
decltype(std::declval<_Tp>().year),
decltype(std::declval<_Tp>().month),
decltype(std::declval<_Tp>().day),
decltype(std::declval<_Tp>().hours),
decltype(std::declval<_Tp>().minutes),
decltype(std::declval<_Tp>().seconds)
>,
void
>
> : public std::true_type {};
template <typename _Model, typename _Tp>
inline constexpr bool is_datetime_v = is_datetime<_Model, _Tp>::value;
/**
* @author Jin
* @brief check if the type is a standard spec implemented container
*
* @tparam _Tp
* @tparam _Up
*/
template<typename _Tp, typename _Up = void>
struct is_stl_spec_container : std::false_type {};
template<typename _Tp>
struct is_stl_spec_container<
_Tp,
std::conditional_t<
false,
internal::is_type_helper<
typename _Tp::value_type,
typename _Tp::size_type,
typename _Tp::allocator_type,
typename _Tp::iterator,
typename _Tp::const_iterator,
decltype(std::declval<_Tp>().size()),
decltype(std::declval<_Tp>().begin()),
decltype(std::declval<_Tp>().end()),
decltype(std::declval<_Tp>().cbegin()),
decltype(std::declval<_Tp>().cend())
>,
void
>
> : public std::true_type {};
template <typename _Tp, typename _Up = void>
constexpr inline bool is_stl_spec_container_v = is_stl_spec_container<_Tp, _Up>::value;
template<typename _Tp, typename _Up = void>
struct is_stl_spec_string : std::false_type { };
namespace protocol_traits
{
namespace message_based_protocols
{
/**
* @author Jin
* @brief protocol STX
*
* @tparam _Tp
* @tparam _Val
*/
template <typename _Tp, _Tp _Val>
struct protocol_stx
{ using stx_type = _Tp; static constexpr stx_type stx_value = _Val; };
/**
* @author Jin
* @brief protocol from
*
* @tparam _Tp
*/
template <typename _Tp>
struct protocol_from { using from_type = _Tp; };
/**
* @author Jin
* @brief protocol to
*
* @tparam _Tp
*/
template <typename _Tp>
struct protocol_to { using to_type = _Tp; };
template <typename _Tp>
struct protocol_sequence_number { using sequence_number_type = _Tp; };
template <typename _Tp>
struct protocol_command_code { using command_code_type = _Tp; };
template <typename _Tp>
struct protocol_crc { using crc_type = _Tp; };
template <typename _Tp, _Tp _Val>
struct protocol_etx
{
using etx_type = _Tp; static constexpr etx_type etx_value = _Val; };
}
namespace stream_based_protocols
{
template <char ... _Stx>
struct protocol_stx
{ static constexpr const char stx_value[sizeof...(_Stx)] = { (_Stx)... }; };
}
}
namespace concepts
{
} // concepts
} // type_traits
} // sentient
#endif | 24.59127 | 105 | 0.668872 | [
"model"
] |
ce5edae2102c72d37a3698be75067f35ae23c50a | 5,697 | cpp | C++ | sources/Notebook.cpp | shmooel28/notebook-part-b | 9f2cb1212695fb4b96b755f51899b7f8608a7d9b | [
"MIT"
] | null | null | null | sources/Notebook.cpp | shmooel28/notebook-part-b | 9f2cb1212695fb4b96b755f51899b7f8608a7d9b | [
"MIT"
] | null | null | null | sources/Notebook.cpp | shmooel28/notebook-part-b | 9f2cb1212695fb4b96b755f51899b7f8608a7d9b | [
"MIT"
] | null | null | null | #include"Direction.hpp"
#include<string>
#include<iostream>
#include"Notebook.hpp"
#include<vector>
using namespace std;
namespace ariel
{
Notebook::Notebook()
{
}
Notebook::~Notebook()
{
}
void Notebook::erase(int page,int row,int col,Direction d,int number_of_char)
{
const int max_col = 100;
if (page < 0 || row < 0 || col < 0 || col >= max_col)
{
throw runtime_error("connot be udner 0");
}
if (number_of_char < 0)
{
throw runtime_error("negative langth");
}
if (d == Direction::Horizontal)
{
if (number_of_char + col > max_col)
{
throw runtime_error("not over 100");
}
for (int i = 0; i < number_of_char; i++)
{
note_b[page][row][col+i] = '~';
}
}
else
{
for (int i = 0; i < number_of_char; i++)
{
note_b[page][row+i][col] = '~';
}
}
}
string Notebook::read(int page,int row,int col,Direction d,int number_of_char)
{
const int max = 126;
const int minim = 32;
const int max_col = 100;
if (page < 0 || row < 0 || col < 0 || col >= max_col)
{
throw runtime_error("connot be udner 0");
}
if (number_of_char < 0)
{
throw runtime_error("negative langth");
}
string ans;
if (d == Direction::Horizontal)
{
if (number_of_char + col > max_col)
{
throw runtime_error("not over 100");
}
for (int i = 0; i < number_of_char; i++)
{
if(note_b[page][row][col+i] == '~')
{
ans += note_b[page][row][col+i];
}
else
{
if (note_b[page][row][col+i] >= minim && note_b[page][row][col+i] <= max )
{
ans += note_b[page][row][col+i];
}
else
{
ans += '_';
}
}
}
}
else
{
for (int i = 0; i < number_of_char; i++)
{
if(note_b[page][row+i][col]=='~')
{
ans += note_b[page][row+i][col];
}
else
{
if (note_b[page][row+i][col] >= minim && note_b[page][row+i][col] <= max )
{
ans += note_b[page][row+i][col];
}
else
{
ans += '_';
}
}
}
}
return ans;
}
void Notebook::write(int page,int row,int col,Direction d,string str)
{
const int max = 125;
const int minim = 32;
const int max_col = 100;
if (page < 0 || row < 0 || col < 0 || col >= max_col)
{
throw runtime_error("connot be udner 0");
}
if (d == Direction::Horizontal)
{
if (int(str.length()) + col > max_col)
{
throw runtime_error("not over 100");
}
for (int i = 0; i < int(str.length()); i++)
{
if (str[(unsigned int)i] > max || str[(unsigned int)i] < minim )
{
throw runtime_error("bad input");
}
if (note_b[page][row][col+i] == '~'|| str[(unsigned int)i] == '~')
{
throw runtime_error("alredy write");
}
if (note_b[page][row][col+i] < max && note_b[page][row][col+i] > minim )
{
if (note_b[page][row][col+i] == '_')
{
note_b[page][row][col+i] = str[(unsigned int)i];
}
else
{
throw runtime_error("cant writ rwice");
}
}
else
{
note_b[page][row][col+i] = str[(unsigned int)i];
}
}
}
else
{
for (int i = 0; i < int(str.length()); i++)
{
if (str[(unsigned int)i] > max || str[(unsigned int)i] < minim )
{
throw runtime_error("bad input");
}
if (note_b[page][row][col+i] == '~'|| str[(unsigned int)i] == '~')
{
throw runtime_error("alredy write");
}
if (note_b[page][row+i][col] < max && note_b[page][row+i][col] > minim )
{
if (note_b[page][row+i][col] == '_')
{
note_b[page][row+i][col] = str[(unsigned int)i];
}
else
{
throw runtime_error("cant writ rwice");
}
}
else
{
note_b[page][row+i][col] = str[(unsigned int)i];
}
}
}
}
void Notebook::show(int page)
{
if (page < 0)
{
throw runtime_error("negative page");
}
cout<<"show"<<note_b[page][0][0]<<endl;
}
}
| 28.628141 | 94 | 0.358083 | [
"vector"
] |
ce608f298de2e5955b7e01b654e321a5d9f288b3 | 8,157 | hpp | C++ | packages/utility/core/src/Utility_ArrayView.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/utility/core/src/Utility_ArrayView.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/utility/core/src/Utility_ArrayView.hpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file Utility_ArrayView.hpp
//! \author Alex Robinson
//! \brief The array view class declaration
//!
//---------------------------------------------------------------------------//
#ifndef UTILITY_ARRAY_VIEW_HPP
#define UTILITY_ARRAY_VIEW_HPP
// Std Lib Includes
#include <vector>
#include <array>
#include <tuple>
#include <utility>
// FRENSIE Includes
#include "Utility_View.hpp"
#include "Utility_TypeNameTraits.hpp"
#include "Utility_TypeTraits.hpp"
namespace Utility{
class Slice;
/*! The array view class
*
* This class was inspired by the Teuchos::ArrayView class found in
* the Trilinos Software package
* (https://trilinos.org/docs/dev/packages/teuchos/doc/html/index.html).
* \ingroup view
*/
template<typename T>
class ArrayView : public View<T*>
{
public:
//! Default constructor
ArrayView();
//! Iterator constructor
ArrayView( T* start, T* end );
//! Range constructor
ArrayView( T* array_start, const typename ArrayView<T>::size_type array_size );
//! Vector constructor
explicit ArrayView( std::vector<T>& vector );
//! Const vector constructor
template<typename U>
explicit ArrayView( const std::vector<U>& vector );
//! Array constructor
template<size_t N>
explicit ArrayView( std::array<T,N>& array );
//! Const array constructor
template<typename U,size_t N>
explicit ArrayView( const std::array<U,N>& array );
//! Copy constructor
ArrayView( const ArrayView<T>& other_view );
//! Const array view copy constructor
template<typename U>
ArrayView( const ArrayView<U>& other_view );
//! Assignment operator
ArrayView<T>& operator=( const ArrayView<T>& other_view );
//! Const view assignment operator
template<typename U>
ArrayView<T>& operator=( const ArrayView<U>& other_view );
//! Destructor
~ArrayView()
{ /* ... */ }
//! Fill the array with values
void fill( const T& value );
//! Return a sub-array view
ArrayView<T> operator()( const typename ArrayView<T>::size_type offset,
const typename ArrayView<T>::size_type size ) const;
//! Return a sub-array view
ArrayView<T> operator|( const Utility::Slice& slice ) const;
//! Return a const array view
ArrayView<const typename std::remove_const<T>::type> toConst() const;
//! Implicitly convert to a const array view
operator ArrayView<const typename std::remove_const<T>::type>() const;
//! Return a std::vector
std::vector<typename std::remove_const<T>::type> toVector() const;
//! Implicitly convert to a std::vector
operator std::vector<typename std::remove_const<T>::type>() const;
//! Return a direct pointer to the memory array used internally
typename View<T*>::pointer data() const;
};
/*! The slice class
*
* Use this class when overloading the | operator to create an ArrayView
* of a slice of an array
* \ingroup view
*/
class Slice
{
public:
//! Constructor
Slice( const size_t offset, const size_t extent )
: d_offset( offset ),
d_extent( extent )
{ /* ... */ }
//! Tuple constructor
template<template<typename,typename> class Tuple,
typename T,
typename U>
Slice( const Tuple<T,U>& tuple )
: d_offset( std::get<0>( tuple ) ),
d_extent( std::get<1>( tuple ) )
{ /* ... */ }
//! Tuple move constructor
template<template<typename,typename> class Tuple,
typename T,
typename U>
Slice( Tuple<T,U>&& tuple )
: d_offset( std::move( std::get<0>( tuple ) ) ),
d_extent( std::move( std::get<1>( tuple ) ) )
{ /* ... */ }
//! C-array constructor
Slice( const size_t offset_extent[2] )
: d_offset( offset_extent[0] ),
d_extent( offset_extent[1] )
{ /* ... */ }
//! Destructor
~Slice()
{ /* ... */ }
//! Get the offset
size_t offset() const
{ return d_offset; }
//! Get the extent
size_t extent() const
{ return d_extent; }
private:
// The offset
size_t d_offset;
// the extent
size_t d_extent;
};
/*! Create a slice object
* \ingroup view
*/
inline Slice slice( size_t offset, size_t extent )
{
return Slice( offset, extent );
}
/*! Create an array view of a std::vector
* \ingroup view
*/
template<typename T>
inline ArrayView<T> arrayView( std::vector<T>& vector )
{
return ArrayView<T>( vector );
}
/*! Create a const array view of a std::vector
* \ingroup view
*/
template<typename T>
inline ArrayView<const T> arrayView( const std::vector<T>& vector )
{
return ArrayView<const T>( vector );
}
/*! Create a const array view of a std::vector
* \ingroup view
*/
template<typename T>
inline ArrayView<const T> arrayViewOfConst( const std::vector<T>& vector )
{
return ArrayView<const T>( vector );
}
/*! Create an array view of a std::array
* \ingroup view
*/
template<typename T, size_t N>
inline ArrayView<T> arrayView( std::array<T,N>& array )
{
return ArrayView<T>( array );
}
/*! Create a const array view of a std::array
* \ingroup view
*/
template<typename T, size_t N>
inline ArrayView<const T> arrayView( const std::array<T,N>& array )
{
return ArrayView<const T>( array );
}
/*! Create a const array view of a std::array
* \ingroup view
*/
template<typename T, size_t N>
inline ArrayView<const T> arrayViewOfConst( const std::array<T,N>& array )
{
return ArrayView<const T>( array );
}
/*! Const cast array view
* \ingroup view
*/
template<typename T2, typename T1>
inline ArrayView<T2> av_const_cast( const ArrayView<T1>& array_view )
{
return ArrayView<T2>( const_cast<T2*>( array_view.begin() ),
array_view.size() );
}
/*! Reinterpret cast array view
* \ingroup view
*/
template<typename T2, typename T1>
inline ArrayView<T2> av_reinterpret_cast( const ArrayView<T1>& array_view )
{
return ArrayView<T2>( reinterpret_cast<T2*>( const_cast<ArrayView<T1>&>(array_view).begin() ),
reinterpret_cast<T2*>( const_cast<ArrayView<T1>&>(array_view).end() ) );
}
/*! \brief Partial specialization of IsSequenceContainerWithContiguousMemory
* for Utility::ArrayView
* \ingroup view
* \ingroup type_traits
*/
template<typename T>
struct IsSequenceContainerWithContiguousMemory<Utility::ArrayView<T> > : public std::true_type
{ /* ... */ };
/*! Partial specialization of ToStringTraits for Utility::ArrayView
* \ingroup view
* \ingroup to_string_traits
*/
template<typename T>
struct ToStringTraits<Utility::ArrayView<T> > : public ToStringTraits<Utility::View<T*> >
{ /* ... */ };
/*! Partial specialization of Utility::TypeNameTraits for Utility::ArrayView
* \ingroup view
* \ingroup type_name_traits
*/
template<typename T>
struct TypeNameTraits<Utility::ArrayView<T> >
{
//! Get the type name
static inline std::string name()
{ return std::string("Utility::ArrayView<") + Utility::typeName<T>()+">"; }
};
/*! Partial specialization of ComparisonTraits for Utility::ArrayView
* \ingroup view
* \ingroup comparison_traits
*/
template<typename T>
struct ComparisonTraits<Utility::ArrayView<T> > : public ComparisonTraits<Utility::View<T*> >
{ /* ... */ };
} // end Utility namespace
namespace std{
//! Partial specialization of common_type for Utility::ArrayView
template<typename T>
struct common_type<Utility::ArrayView<T>,Utility::ArrayView<const T> >
{
typedef Utility::ArrayView<const T> type;
};
//! Partial specialization of common_type for Utility::ArrayView
template<typename T>
struct common_type<Utility::ArrayView<const T>,Utility::ArrayView<T> >
{
typedef Utility::ArrayView<const T> type;
};
} // end std namespace
//---------------------------------------------------------------------------//
// Template includes
//---------------------------------------------------------------------------//
#include "Utility_ArrayView_def.hpp"
//---------------------------------------------------------------------------//
#endif // end UTILITY_ARRAY_VIEW_HPP
//---------------------------------------------------------------------------//
// end Utility_ArrayView.hpp
//---------------------------------------------------------------------------//
| 25.411215 | 96 | 0.635037 | [
"object",
"vector"
] |
ce6a32ebc351f5cca6e58f45254810b51200dba7 | 2,024 | cpp | C++ | MGR_PBR/src/engine/Skybox.cpp | KosssteK/master-thesis | d3c3f6f3b1f5c56e047da63b00927d948974c32a | [
"MIT"
] | null | null | null | MGR_PBR/src/engine/Skybox.cpp | KosssteK/master-thesis | d3c3f6f3b1f5c56e047da63b00927d948974c32a | [
"MIT"
] | null | null | null | MGR_PBR/src/engine/Skybox.cpp | KosssteK/master-thesis | d3c3f6f3b1f5c56e047da63b00927d948974c32a | [
"MIT"
] | null | null | null | #include "Skybox.h"
#include <string>
#include "render/VertexBufferLayout.h"
CAT::Skybox::Skybox(const std::string &path)
: shader("res/shaders/skybox.shader"),
verticiesNumber(0),
texture(path),
m_Size(500),
m_PositionsCount(108),
m_Positions{
-m_Size, m_Size, -m_Size,
-m_Size, -m_Size, -m_Size,
m_Size, -m_Size, -m_Size,
m_Size, -m_Size, -m_Size,
m_Size, m_Size, -m_Size,
-m_Size, m_Size, -m_Size,
-m_Size, -m_Size, m_Size,
-m_Size, -m_Size, -m_Size,
-m_Size, m_Size, -m_Size,
-m_Size, m_Size, -m_Size,
-m_Size, m_Size, m_Size,
-m_Size, -m_Size, m_Size,
m_Size, -m_Size, -m_Size,
m_Size, -m_Size, m_Size,
m_Size, m_Size, m_Size,
m_Size, m_Size, m_Size,
m_Size, m_Size, -m_Size,
m_Size, -m_Size, -m_Size,
-m_Size, -m_Size, m_Size,
-m_Size, m_Size, m_Size,
m_Size, m_Size, m_Size,
m_Size, m_Size, m_Size,
m_Size, -m_Size, m_Size,
-m_Size, -m_Size, m_Size,
-m_Size, m_Size, -m_Size,
m_Size, m_Size, -m_Size,
m_Size, m_Size, m_Size,
m_Size, m_Size, m_Size,
-m_Size, m_Size, m_Size,
-m_Size, m_Size, -m_Size,
-m_Size, -m_Size, -m_Size,
-m_Size, -m_Size, m_Size,
m_Size, -m_Size, -m_Size,
m_Size, -m_Size, -m_Size,
-m_Size, -m_Size, m_Size,
m_Size, -m_Size, m_Size }
{
VertexBufferLayout layout;
layout.Push<float>(3);
VertexBuffer vb(GetPositions(), GetPositionsSize());
vertexArray.AddBuffer(vb, layout);
vertexArray.Unbind();
}
CAT::Skybox::~Skybox()
{
}
CAT::Container * CAT::Skybox::AddChild(CAT::Container & container)
{
return nullptr;
}
void CAT::Skybox::Update()
{
}
void CAT::Skybox::UpdateTransform(glm::mat4 projection, glm::mat4 view, glm::mat4 model)
{
MVP = projection * view * GetMVPMatrix(model);
}
void CAT::Skybox::Draw()
{
shader.Bind();
shader.SetUniformMat4f("u_MVP", MVP);
texture.Bind();
vertexArray.Bind();
GLCall(glDrawArrays(GL_TRIANGLES, 0, 36));
}
float* CAT::Skybox::GetPositions()
{
return m_Positions;
}
float CAT::Skybox::GetPositionsSize()
{
return m_PositionsCount * sizeof(float);
} | 20.444444 | 88 | 0.682312 | [
"render",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.