hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1b66205636344040cd32ed0528606e802d6995e8 | 34,219 | cpp | C++ | libs/openFrameworks/gl/ofGLRenderer.cpp | Studio236/project-440 | 4608d029ef5ef422f776804ff13736c1ec5565a9 | [
"MIT"
] | 1 | 2016-03-13T15:04:27.000Z | 2016-03-13T15:04:27.000Z | libs/openFrameworks/gl/ofGLRenderer.cpp | Studio236/project-440 | 4608d029ef5ef422f776804ff13736c1ec5565a9 | [
"MIT"
] | 1 | 2015-09-11T15:09:39.000Z | 2015-09-11T15:09:39.000Z | libs/openFrameworks/gl/ofGLRenderer.cpp | Studio236/project-440 | 4608d029ef5ef422f776804ff13736c1ec5565a9 | [
"MIT"
] | null | null | null | #include "ofGLRenderer.h"
#include "ofMesh.h"
#include "ofPath.h"
#include "ofGraphics.h"
#include "ofAppRunner.h"
#include "ofMesh.h"
#include "ofBitmapFont.h"
#include "ofGLUtils.h"
#include "ofImage.h"
#include "ofFbo.h"
//----------------------------------------------------------
ofGLRenderer::ofGLRenderer(bool useShapeColor){
bBackgroundAuto = true;
linePoints.resize(2);
rectPoints.resize(4);
triPoints.resize(3);
currentFbo = NULL;
}
//----------------------------------------------------------
void ofGLRenderer::update(){
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofMesh & vertexData, bool useColors, bool useTextures, bool useNormals){
if(vertexData.getNumVertices()){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData.getVerticesPointer()->x);
}
if(vertexData.getNumNormals() && useNormals){
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, sizeof(ofVec3f), &vertexData.getNormalsPointer()->x);
}
if(vertexData.getNumColors() && useColors){
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), &vertexData.getColorsPointer()->r);
}
if(vertexData.getNumTexCoords() && useTextures){
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, sizeof(ofVec2f), &vertexData.getTexCoordsPointer()->x);
}
if(vertexData.getNumIndices()){
#ifdef TARGET_OPENGLES
glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer());
#else
glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_INT,vertexData.getIndexPointer());
#endif
}else{
glDrawArrays(ofGetGLPrimitiveMode(vertexData.getMode()), 0, vertexData.getNumVertices());
}
if(vertexData.getNumColors()){
glDisableClientState(GL_COLOR_ARRAY);
}
if(vertexData.getNumNormals()){
glDisableClientState(GL_NORMAL_ARRAY);
}
if(vertexData.getNumTexCoords()){
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofMesh & vertexData, ofPolyRenderMode renderType, bool useColors, bool useTextures, bool useNormals){
if (bSmoothHinted) startSmoothing();
#ifndef TARGET_OPENGLES
glPushAttrib(GL_POLYGON_BIT);
glPolygonMode(GL_FRONT_AND_BACK, ofGetGLPolyMode(renderType));
draw(vertexData,useColors,useTextures,useNormals);
glPopAttrib(); //TODO: GLES doesnt support polygon mode, add renderType to gl renderer?
#else
if(vertexData.getNumVertices()){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), vertexData.getVerticesPointer());
}
if(vertexData.getNumNormals() && useNormals){
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, 0, vertexData.getNormalsPointer());
}
if(vertexData.getNumColors() && useColors){
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), vertexData.getColorsPointer());
}
if(vertexData.getNumTexCoords() && useTextures){
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, vertexData.getTexCoordsPointer());
}
GLenum drawMode;
switch(renderType){
case OF_MESH_POINTS:
drawMode = GL_POINTS;
break;
case OF_MESH_WIREFRAME:
drawMode = GL_LINES;
break;
case OF_MESH_FILL:
drawMode = ofGetGLPrimitiveMode(vertexData.getMode());
break;
default:
drawMode = ofGetGLPrimitiveMode(vertexData.getMode());
break;
}
if(vertexData.getNumIndices()){
glDrawElements(drawMode, vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer());
}else{
glDrawArrays(drawMode, 0, vertexData.getNumVertices());
}
if(vertexData.getNumColors() && useColors){
glDisableClientState(GL_COLOR_ARRAY);
}
if(vertexData.getNumNormals() && useNormals){
glDisableClientState(GL_NORMAL_ARRAY);
}
if(vertexData.getNumTexCoords() && useTextures){
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
#endif
if (bSmoothHinted) endSmoothing();
}
//----------------------------------------------------------
void ofGLRenderer::draw(vector<ofPoint> & vertexData, ofPrimitiveMode drawMode){
if(!vertexData.empty()) {
if (bSmoothHinted) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData[0].x);
glDrawArrays(ofGetGLPrimitiveMode(drawMode), 0, vertexData.size());
if (bSmoothHinted) endSmoothing();
}
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofPolyline & poly){
if(!poly.getVertices().empty()) {
// use smoothness, if requested:
if (bSmoothHinted) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &poly.getVertices()[0].x);
glDrawArrays(poly.isClosed()?GL_LINE_LOOP:GL_LINE_STRIP, 0, poly.size());
// use smoothness, if requested:
if (bSmoothHinted) endSmoothing();
}
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofPath & shape){
ofColor prevColor;
if(shape.getUseShapeColor()){
prevColor = ofGetStyle().color;
}
if(shape.isFilled()){
ofMesh & mesh = shape.getTessellation();
if(shape.getUseShapeColor()){
setColor( shape.getFillColor() * ofGetStyle().color,shape.getFillColor().a/255. * ofGetStyle().color.a);
}
draw(mesh);
}
if(shape.hasOutline()){
float lineWidth = ofGetStyle().lineWidth;
if(shape.getUseShapeColor()){
setColor( shape.getStrokeColor() * ofGetStyle().color, shape.getStrokeColor().a/255. * ofGetStyle().color.a);
}
setLineWidth( shape.getStrokeWidth() );
vector<ofPolyline> & outlines = shape.getOutline();
for(int i=0; i<(int)outlines.size(); i++)
draw(outlines[i]);
setLineWidth(lineWidth);
}
if(shape.getUseShapeColor()){
setColor(prevColor);
}
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){
if(image.isUsingTexture()){
ofTexture& tex = image.getTextureReference();
if(tex.bAllocated()) {
tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh);
} else {
ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated";
}
}
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofFloatImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){
if(image.isUsingTexture()){
ofTexture& tex = image.getTextureReference();
if(tex.bAllocated()) {
tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh);
} else {
ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated";
}
}
}
//----------------------------------------------------------
void ofGLRenderer::draw(ofShortImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){
if(image.isUsingTexture()){
ofTexture& tex = image.getTextureReference();
if(tex.bAllocated()) {
tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh);
} else {
ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated";
}
}
}
//----------------------------------------------------------
void ofGLRenderer::setCurrentFBO(ofFbo * fbo){
currentFbo = fbo;
}
//----------------------------------------------------------
void ofGLRenderer::pushView() {
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
ofRectangle currentViewport;
currentViewport.set(viewport[0], viewport[1], viewport[2], viewport[3]);
viewportHistory.push(currentViewport);
/*glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();*/
// done like this cause i was getting GL_STACK_UNDERFLOW
// should ofPush/PopMatrix work the same way, what if it's mixed with glPush/PopMatrix
ofMatrix4x4 m;
glGetFloatv(GL_PROJECTION_MATRIX,m.getPtr());
projectionStack.push(m);
glGetFloatv(GL_MODELVIEW_MATRIX,m.getPtr());
modelViewStack.push(m);
}
//----------------------------------------------------------
void ofGLRenderer::popView() {
if( viewportHistory.size() ){
ofRectangle viewRect = viewportHistory.top();
viewport(viewRect.x, viewRect.y, viewRect.width, viewRect.height,false);
viewportHistory.pop();
}
/*glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();*/
// done like this cause i was getting GL_STACK_UNDERFLOW
// should ofPush/PopMatrix work the same way, what if it's mixed with glPush/PopMatrix
glMatrixMode(GL_PROJECTION);
if(!projectionStack.empty()){
glLoadMatrixf(projectionStack.top().getPtr());
projectionStack.pop();
}else{
ofLogError() << "popView: couldn't pop projection matrix, stack empty. probably wrong anidated push/popView";
}
glMatrixMode(GL_MODELVIEW);
if(!modelViewStack.empty()){
glLoadMatrixf(modelViewStack.top().getPtr());
modelViewStack.pop();
}else{
ofLogError() << "popView: couldn't pop modelView matrix, stack empty. probably wrong anidated push/popView";
}
}
//----------------------------------------------------------
void ofGLRenderer::viewport(ofRectangle viewport_){
viewport(viewport_.x, viewport_.y, viewport_.width, viewport_.height,true);
}
//----------------------------------------------------------
void ofGLRenderer::viewport(float x, float y, float width, float height, bool invertY) {
if(width == 0) width = ofGetWindowWidth();
if(height == 0) height = ofGetWindowHeight();
if (invertY){
if(currentFbo){
y = currentFbo->getHeight() - (y + height);
}else{
y = ofGetWindowHeight() - (y + height);
}
}
glViewport(x, y, width, height);
}
//----------------------------------------------------------
ofRectangle ofGLRenderer::getCurrentViewport(){
// I am using opengl calls here instead of returning viewportRect
// since someone might use glViewport instead of ofViewport...
GLint viewport[4]; // Where The Viewport Values Will Be Stored
glGetIntegerv(GL_VIEWPORT, viewport);
ofRectangle view;
view.x = viewport[0];
view.y = viewport[1];
view.width = viewport[2];
view.height = viewport[3];
return view;
}
//----------------------------------------------------------
int ofGLRenderer::getViewportWidth(){
GLint viewport[4]; // Where The Viewport Values Will Be Stored
glGetIntegerv(GL_VIEWPORT, viewport);
return viewport[2];
}
//----------------------------------------------------------
int ofGLRenderer::getViewportHeight(){
GLint viewport[4]; // Where The Viewport Values Will Be Stored
glGetIntegerv(GL_VIEWPORT, viewport);
return viewport[3];
}
//----------------------------------------------------------
void ofGLRenderer::setCoordHandedness(ofHandednessType handedness) {
coordHandedness = handedness;
}
//----------------------------------------------------------
ofHandednessType ofGLRenderer::getCoordHandedness() {
return coordHandedness;
}
//----------------------------------------------------------
void ofGLRenderer::setupScreenPerspective(float width, float height, ofOrientation orientation, bool vFlip, float fov, float nearDist, float farDist) {
if(width == 0) width = ofGetWidth();
if(height == 0) height = ofGetHeight();
float viewW = ofGetViewportWidth();
float viewH = ofGetViewportHeight();
float eyeX = viewW / 2;
float eyeY = viewH / 2;
float halfFov = PI * fov / 360;
float theTan = tanf(halfFov);
float dist = eyeY / theTan;
float aspect = (float) viewW / viewH;
if(nearDist == 0) nearDist = dist / 10.0f;
if(farDist == 0) farDist = dist * 10.0f;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ofMatrix4x4 persp;
persp.makePerspectiveMatrix(fov, aspect, nearDist, farDist);
loadMatrix( persp );
//gluPerspective(fov, aspect, nearDist, farDist);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
ofMatrix4x4 lookAt;
lookAt.makeLookAtViewMatrix( ofVec3f(eyeX, eyeY, dist), ofVec3f(eyeX, eyeY, 0), ofVec3f(0, 1, 0) );
loadMatrix( lookAt );
//gluLookAt(eyeX, eyeY, dist, eyeX, eyeY, 0, 0, 1, 0);
//note - theo checked this on iPhone and Desktop for both vFlip = false and true
if(ofDoesHWOrientation()){
if(vFlip){
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
}
}else{
if( orientation == OF_ORIENTATION_UNKNOWN ) orientation = ofGetOrientation();
switch(orientation) {
case OF_ORIENTATION_180:
glRotatef(-180, 0, 0, 1);
if(vFlip){
glScalef(1, -1, 1);
glTranslatef(-width, 0, 0);
}else{
glTranslatef(-width, -height, 0);
}
break;
case OF_ORIENTATION_90_RIGHT:
glRotatef(-90, 0, 0, 1);
if(vFlip){
glScalef(-1, 1, 1);
}else{
glScalef(-1, -1, 1);
glTranslatef(0, -height, 0);
}
break;
case OF_ORIENTATION_90_LEFT:
glRotatef(90, 0, 0, 1);
if(vFlip){
glScalef(-1, 1, 1);
glTranslatef(-width, -height, 0);
}else{
glScalef(-1, -1, 1);
glTranslatef(-width, 0, 0);
}
break;
case OF_ORIENTATION_DEFAULT:
default:
if(vFlip){
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
}
break;
}
}
}
//----------------------------------------------------------
void ofGLRenderer::setupScreenOrtho(float width, float height, ofOrientation orientation, bool vFlip, float nearDist, float farDist) {
if(width == 0) width = ofGetWidth();
if(height == 0) height = ofGetHeight();
float viewW = ofGetViewportWidth();
float viewH = ofGetViewportHeight();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
ofSetCoordHandedness(OF_RIGHT_HANDED);
#ifndef TARGET_OPENGLES
if(vFlip) {
ofSetCoordHandedness(OF_LEFT_HANDED);
}
if(nearDist == -1) nearDist = 0;
if(farDist == -1) farDist = 10000;
glOrtho(0, viewW, 0, viewH, nearDist, farDist);
#else
if(vFlip) {
ofMatrix4x4 ortho = ofMatrix4x4::newOrthoMatrix(0, width, height, 0, nearDist, farDist);
ofSetCoordHandedness(OF_LEFT_HANDED);
}
ofMatrix4x4 ortho = ofMatrix4x4::newOrthoMatrix(0, viewW, 0, viewH, nearDist, farDist);
glMultMatrixf(ortho.getPtr());
#endif
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//note - theo checked this on iPhone and Desktop for both vFlip = false and true
if(ofDoesHWOrientation()){
if(vFlip){
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
}
}else{
if( orientation == OF_ORIENTATION_UNKNOWN ) orientation = ofGetOrientation();
switch(orientation) {
case OF_ORIENTATION_180:
glRotatef(-180, 0, 0, 1);
if(vFlip){
glScalef(1, -1, 1);
glTranslatef(-width, 0, 0);
}else{
glTranslatef(-width, -height, 0);
}
break;
case OF_ORIENTATION_90_RIGHT:
glRotatef(-90, 0, 0, 1);
if(vFlip){
glScalef(-1, 1, 1);
}else{
glScalef(-1, -1, 1);
glTranslatef(0, -height, 0);
}
break;
case OF_ORIENTATION_90_LEFT:
glRotatef(90, 0, 0, 1);
if(vFlip){
glScalef(-1, 1, 1);
glTranslatef(-width, -height, 0);
}else{
glScalef(-1, -1, 1);
glTranslatef(-width, 0, 0);
}
break;
case OF_ORIENTATION_DEFAULT:
default:
if(vFlip){
glScalef(1, -1, 1);
glTranslatef(0, -height, 0);
}
break;
}
}
}
//----------------------------------------------------------
//Resets openGL parameters back to OF defaults
void ofGLRenderer::setupGraphicDefaults(){
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
//----------------------------------------------------------
void ofGLRenderer::setupScreen(){
setupScreenPerspective(); // assume defaults
}
//----------------------------------------------------------
void ofGLRenderer::setCircleResolution(int res){
if((int)circlePolyline.size()!=res+1){
circlePolyline.clear();
circlePolyline.arc(0,0,0,1,1,0,360,res);
circlePoints.resize(circlePolyline.size());
}
}
//----------------------------------------------------------
void ofGLRenderer::setSphereResolution(int res) {
if(sphereMesh.getNumVertices() == 0 || res != ofGetStyle().sphereResolution) {
int n = res * 2;
float ndiv2=(float)n/2;
/*
Original code by Paul Bourke
A more efficient contribution by Federico Dosil (below)
Draw a point for zero radius spheres
Use CCW facet ordering
http://paulbourke.net/texture_colour/texturemap/
*/
float theta2 = TWO_PI;
float phi1 = -HALF_PI;
float phi2 = HALF_PI;
float r = 1.f; // normalize the verts //
sphereMesh.clear();
sphereMesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
int i, j;
float theta1 = 0.f;
float jdivn,j1divn,idivn,dosdivn,unodivn=1/(float)n,t1,t2,t3,cost1,cost2,cte1,cte3;
cte3 = (theta2-theta1)/n;
cte1 = (phi2-phi1)/ndiv2;
dosdivn = 2*unodivn;
ofVec3f e,p,e2,p2;
if (n < 0){
n = -n;
ndiv2 = -ndiv2;
}
if (n < 4) {n = 4; ndiv2=(float)n/2;}
if(r <= 0) r = 1;
t2=phi1;
cost2=cos(phi1);
j1divn=0;
ofVec3f vert, normal;
ofVec2f tcoord;
for (j=0;j<ndiv2;j++) {
t1 = t2;
t2 += cte1;
t3 = theta1 - cte3;
cost1 = cost2;
cost2 = cos(t2);
e.y = sin(t1);
e2.y = sin(t2);
p.y = r * e.y;
p2.y = r * e2.y;
idivn=0;
jdivn=j1divn;
j1divn+=dosdivn;
for (i=0;i<=n;i++) {
t3 += cte3;
e.x = cost1 * cos(t3);
e.z = cost1 * sin(t3);
p.x = r * e.x;
p.z = r * e.z;
normal.set( e.x, e.y, e.z );
tcoord.set( idivn, jdivn );
vert.set( p.x, p.y, p.z );
sphereMesh.addNormal(normal);
sphereMesh.addTexCoord(tcoord);
sphereMesh.addVertex(vert);
e2.x = cost2 * cos(t3);
e2.z = cost2 * sin(t3);
p2.x = r * e2.x;
p2.z = r * e2.z;
normal.set(e2.x, e2.y, e2.z);
tcoord.set(idivn, j1divn);
vert.set(p2.x, p2.y, p2.z);
sphereMesh.addNormal(normal);
sphereMesh.addTexCoord(tcoord);
sphereMesh.addVertex(vert);
idivn += unodivn;
}
}
}
}
//our openGL wrappers
//----------------------------------------------------------
void ofGLRenderer::pushMatrix(){
glPushMatrix();
}
//----------------------------------------------------------
void ofGLRenderer::popMatrix(){
glPopMatrix();
}
//----------------------------------------------------------
void ofGLRenderer::translate(const ofPoint& p){
glTranslatef(p.x, p.y, p.z);
}
//----------------------------------------------------------
void ofGLRenderer::translate(float x, float y, float z){
glTranslatef(x, y, z);
}
//----------------------------------------------------------
void ofGLRenderer::scale(float xAmnt, float yAmnt, float zAmnt){
glScalef(xAmnt, yAmnt, zAmnt);
}
//----------------------------------------------------------
void ofGLRenderer::rotate(float degrees, float vecX, float vecY, float vecZ){
glRotatef(degrees, vecX, vecY, vecZ);
}
//----------------------------------------------------------
void ofGLRenderer::rotateX(float degrees){
glRotatef(degrees, 1, 0, 0);
}
//----------------------------------------------------------
void ofGLRenderer::rotateY(float degrees){
glRotatef(degrees, 0, 1, 0);
}
//----------------------------------------------------------
void ofGLRenderer::rotateZ(float degrees){
glRotatef(degrees, 0, 0, 1);
}
//same as ofRotateZ
//----------------------------------------------------------
void ofGLRenderer::rotate(float degrees){
glRotatef(degrees, 0, 0, 1);
}
//----------------------------------------------------------
void ofGLRenderer::loadIdentityMatrix (void){
glLoadIdentity();
}
//----------------------------------------------------------
void ofGLRenderer::loadMatrix (const ofMatrix4x4 & m){
loadMatrix( m.getPtr() );
}
//----------------------------------------------------------
void ofGLRenderer::loadMatrix (const float *m){
glLoadMatrixf(m);
}
//----------------------------------------------------------
void ofGLRenderer::multMatrix (const ofMatrix4x4 & m){
multMatrix( m.getPtr() );
}
//----------------------------------------------------------
void ofGLRenderer::multMatrix (const float *m){
glMultMatrixf(m);
}
//----------------------------------------------------------
void ofGLRenderer::setColor(const ofColor & color){
setColor(color.r,color.g,color.b,color.a);
}
//----------------------------------------------------------
void ofGLRenderer::setColor(const ofColor & color, int _a){
setColor(color.r,color.g,color.b,_a);
}
//----------------------------------------------------------
void ofGLRenderer::setColor(int _r, int _g, int _b){
glColor4f(_r/255.f,_g/255.f,_b/255.f,1.f);
}
//----------------------------------------------------------
void ofGLRenderer::setColor(int _r, int _g, int _b, int _a){
glColor4f(_r/255.f,_g/255.f,_b/255.f,_a/255.f);
}
//----------------------------------------------------------
void ofGLRenderer::setColor(int gray){
setColor(gray, gray, gray);
}
//----------------------------------------------------------
void ofGLRenderer::setHexColor(int hexColor){
int r = (hexColor >> 16) & 0xff;
int g = (hexColor >> 8) & 0xff;
int b = (hexColor >> 0) & 0xff;
setColor(r,g,b);
}
//----------------------------------------------------------
void ofGLRenderer::clear(float r, float g, float b, float a) {
glClearColor(r / 255., g / 255., b / 255., a / 255.);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
//----------------------------------------------------------
void ofGLRenderer::clear(float brightness, float a) {
clear(brightness, brightness, brightness, a);
}
//----------------------------------------------------------
void ofGLRenderer::clearAlpha() {
glColorMask(0, 0, 0, 1);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glColorMask(1, 1, 1, 1);
}
//----------------------------------------------------------
void ofGLRenderer::setBackgroundAuto(bool bAuto){
bBackgroundAuto = bAuto;
}
//----------------------------------------------------------
bool ofGLRenderer::bClearBg(){
return bBackgroundAuto;
}
//----------------------------------------------------------
ofFloatColor & ofGLRenderer::getBgColor(){
return bgColor;
}
//----------------------------------------------------------
void ofGLRenderer::background(const ofColor & c){
bgColor = c;
glClearColor(bgColor[0],bgColor[1],bgColor[2], bgColor[3]);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
//----------------------------------------------------------
void ofGLRenderer::background(float brightness) {
background(brightness);
}
//----------------------------------------------------------
void ofGLRenderer::background(int hexColor, float _a){
background ( (hexColor >> 16) & 0xff, (hexColor >> 8) & 0xff, (hexColor >> 0) & 0xff, _a);
}
//----------------------------------------------------------
void ofGLRenderer::background(int r, int g, int b, int a){
background(ofColor(r,g,b,a));
}
//----------------------------------------------------------
void ofGLRenderer::setFillMode(ofFillFlag fill){
bFilled = fill;
}
//----------------------------------------------------------
ofFillFlag ofGLRenderer::getFillMode(){
return bFilled;
}
//----------------------------------------------------------
void ofGLRenderer::setRectMode(ofRectMode mode){
rectMode = mode;
}
//----------------------------------------------------------
ofRectMode ofGLRenderer::getRectMode(){
return rectMode;
}
//----------------------------------------------------------
void ofGLRenderer::setLineWidth(float lineWidth){
glLineWidth(lineWidth);
}
//----------------------------------------------------------
void ofGLRenderer::setLineSmoothing(bool smooth){
bSmoothHinted = smooth;
}
//----------------------------------------------------------
void ofGLRenderer::startSmoothing(){
#ifndef TARGET_OPENGLES
glPushAttrib(GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT);
#endif
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
//why do we need this?
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
//----------------------------------------------------------
void ofGLRenderer::endSmoothing(){
#ifndef TARGET_OPENGLES
glPopAttrib();
#endif
}
//----------------------------------------------------------
void ofGLRenderer::setBlendMode(ofBlendMode blendMode){
switch (blendMode){
case OF_BLENDMODE_ALPHA:{
glEnable(GL_BLEND);
#ifndef TARGET_OPENGLES
glBlendEquation(GL_FUNC_ADD);
#endif
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
}
case OF_BLENDMODE_ADD:{
glEnable(GL_BLEND);
#ifndef TARGET_OPENGLES
glBlendEquation(GL_FUNC_ADD);
#endif
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
}
case OF_BLENDMODE_MULTIPLY:{
glEnable(GL_BLEND);
#ifndef TARGET_OPENGLES
glBlendEquation(GL_FUNC_ADD);
#endif
glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA /* GL_ZERO or GL_ONE_MINUS_SRC_ALPHA */);
break;
}
case OF_BLENDMODE_SCREEN:{
glEnable(GL_BLEND);
#ifndef TARGET_OPENGLES
glBlendEquation(GL_FUNC_ADD);
#endif
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE);
break;
}
case OF_BLENDMODE_SUBTRACT:{
glEnable(GL_BLEND);
#ifndef TARGET_OPENGLES
glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
#else
ofLog(OF_LOG_WARNING, "OF_BLENDMODE_SUBTRACT not currently supported on OpenGL/ES");
#endif
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
}
default:
break;
}
}
//----------------------------------------------------------
void ofGLRenderer::enablePointSprites(){
#ifdef TARGET_OPENGLES
glEnable(GL_POINT_SPRITE_OES);
glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE);
// does look like this needs to be enabled in ES because
// it is always eneabled...
//glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
#else
glEnable(GL_POINT_SPRITE);
glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
#endif
}
//----------------------------------------------------------
void ofGLRenderer::disablePointSprites(){
#ifdef TARGET_OPENGLES
glDisable(GL_POINT_SPRITE_OES);
#else
glDisable(GL_POINT_SPRITE);
#endif
}
//----------------------------------------------------------
void ofGLRenderer::drawLine(float x1, float y1, float z1, float x2, float y2, float z2){
linePoints[0].set(x1,y1,z1);
linePoints[1].set(x2,y2,z2);
// use smoothness, if requested:
if (bSmoothHinted) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &linePoints[0].x);
glDrawArrays(GL_LINES, 0, 2);
// use smoothness, if requested:
if (bSmoothHinted) endSmoothing();
}
//----------------------------------------------------------
void ofGLRenderer::drawRectangle(float x, float y, float z,float w, float h){
if (rectMode == OF_RECTMODE_CORNER){
rectPoints[0].set(x,y,z);
rectPoints[1].set(x+w, y, z);
rectPoints[2].set(x+w, y+h, z);
rectPoints[3].set(x, y+h, z);
}else{
rectPoints[0].set(x-w/2.0f, y-h/2.0f, z);
rectPoints[1].set(x+w/2.0f, y-h/2.0f, z);
rectPoints[2].set(x+w/2.0f, y+h/2.0f, z);
rectPoints[3].set(x-w/2.0f, y+h/2.0f, z);
}
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &rectPoints[0].x);
glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 4);
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing();
}
//----------------------------------------------------------
void ofGLRenderer::drawTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){
triPoints[0].set(x1,y1,z1);
triPoints[1].set(x2,y2,z2);
triPoints[2].set(x3,y3,z3);
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &triPoints[0].x);
glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 3);
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing();
}
//----------------------------------------------------------
void ofGLRenderer::drawCircle(float x, float y, float z, float radius){
vector<ofPoint> & circleCache = circlePolyline.getVertices();
for(int i=0;i<(int)circleCache.size();i++){
circlePoints[i].set(radius*circleCache[i].x+x,radius*circleCache[i].y+y,z);
}
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x);
glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size());
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing();
}
//----------------------------------------------------------
void ofGLRenderer::drawSphere(float x, float y, float z, float radius) {
glEnable(GL_NORMALIZE);
glPushMatrix();
glScalef(radius, radius, radius);
if(bFilled) {
sphereMesh.draw();
} else {
sphereMesh.drawWireframe();
}
glPopMatrix();
glDisable(GL_NORMALIZE);
}
//----------------------------------------------------------
void ofGLRenderer::drawEllipse(float x, float y, float z, float width, float height){
float radiusX = width*0.5;
float radiusY = height*0.5;
vector<ofPoint> & circleCache = circlePolyline.getVertices();
for(int i=0;i<(int)circleCache.size();i++){
circlePoints[i].set(radiusX*circlePolyline[i].x+x,radiusY*circlePolyline[i].y+y,z);
}
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing();
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x);
glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size());
// use smoothness, if requested:
if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing();
}
//----------------------------------------------------------
void ofGLRenderer::drawString(string textString, float x, float y, float z, ofDrawBitmapMode mode){
// this is copied from the ofTrueTypeFont
//GLboolean blend_enabled = glIsEnabled(GL_BLEND); //TODO: this is not used?
GLint blend_src, blend_dst;
glGetIntegerv( GL_BLEND_SRC, &blend_src );
glGetIntegerv( GL_BLEND_DST, &blend_dst );
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
int len = (int)textString.length();
//float yOffset = 0;
float fontSize = 8.0f;
bool bOrigin = false;
float sx = 0;
float sy = -fontSize;
///////////////////////////
// APPLY TRANSFORM / VIEW
///////////////////////////
//
bool hasModelView = false;
bool hasProjection = false;
bool hasViewport = false;
ofRectangle rViewport;
#ifdef TARGET_OPENGLES
if(mode == OF_BITMAPMODE_MODEL_BILLBOARD) {
mode = OF_BITMAPMODE_SIMPLE;
}
#endif
switch (mode) {
case OF_BITMAPMODE_SIMPLE:
sx += x;
sy += y;
break;
case OF_BITMAPMODE_SCREEN:
hasViewport = true;
ofPushView();
rViewport = ofGetWindowRect();
ofViewport(rViewport);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-1, 1, 0);
glScalef(2/rViewport.width, -2/rViewport.height, 1);
ofTranslate(x, y, 0);
break;
case OF_BITMAPMODE_VIEWPORT:
rViewport = ofGetCurrentViewport();
hasProjection = true;
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
hasModelView = true;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslatef(-1, 1, 0);
glScalef(2/rViewport.width, -2/rViewport.height, 1);
ofTranslate(x, y, 0);
break;
case OF_BITMAPMODE_MODEL:
hasModelView = true;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
ofTranslate(x, y, z);
ofScale(1, -1, 0);
break;
case OF_BITMAPMODE_MODEL_BILLBOARD:
//our aim here is to draw to screen
//at the viewport position related
//to the world position x,y,z
// ***************
// this will not compile for opengl ES
// ***************
#ifndef TARGET_OPENGLES
//gluProject method
GLdouble modelview[16], projection[16];
GLint view[4];
double dScreenX, dScreenY, dScreenZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, view);
view[0] = 0; view[1] = 0; //we're already drawing within viewport
gluProject(x, y, z, modelview, projection, view, &dScreenX, &dScreenY, &dScreenZ);
if (dScreenZ >= 1)
return;
rViewport = ofGetCurrentViewport();
hasProjection = true;
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
hasModelView = true;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslatef(-1, -1, 0);
glScalef(2/rViewport.width, 2/rViewport.height, 1);
glTranslatef(dScreenX, dScreenY, 0);
if(currentFbo == NULL) {
glScalef(1, -1, 1);
} else {
glScalef(1, 1, 1); // invert when rendering inside an fbo
}
#endif
break;
default:
break;
}
//
///////////////////////////
// (c) enable texture once before we start drawing each char (no point turning it on and off constantly)
//We do this because its way faster
ofDrawBitmapCharacterStart(textString.size());
for(int c = 0; c < len; c++){
if(textString[c] == '\n'){
sy += bOrigin ? -1 : 1 * (fontSize*1.7);
if(mode == OF_BITMAPMODE_SIMPLE) {
sx = x;
} else {
sx = 0;
}
//glRasterPos2f(x,y + (int)yOffset);
} else if (textString[c] >= 32){
// < 32 = control characters - don't draw
// solves a bug with control characters
// getting drawn when they ought to not be
ofDrawBitmapCharacter(textString[c], (int)sx, (int)sy);
sx += fontSize;
}
}
//We do this because its way faster
ofDrawBitmapCharacterEnd();
if (hasModelView)
glPopMatrix();
if (hasProjection)
{
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
if (hasViewport)
ofPopView();
glBlendFunc(blend_src, blend_dst);
}
| 27.353317 | 151 | 0.603086 | Studio236 |
1b67d5e5998f2a27552bcc2d9fadeeb5aaf37287 | 399 | cpp | C++ | async-list/MainWindow.cpp | topecongiro/qt-toy-projects | ccf71acb0b0a896f4f231f11a5ad3b8f1f6b3e6f | [
"MIT"
] | null | null | null | async-list/MainWindow.cpp | topecongiro/qt-toy-projects | ccf71acb0b0a896f4f231f11a5ad3b8f1f6b3e6f | [
"MIT"
] | null | null | null | async-list/MainWindow.cpp | topecongiro/qt-toy-projects | ccf71acb0b0a896f4f231f11a5ad3b8f1f6b3e6f | [
"MIT"
] | null | null | null | #include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QVBoxLayout>
#include "MyWidget.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto* pLayout = new QVBoxLayout(this);
ui->centralwidget->setLayout(pLayout);
pLayout->addWidget(new MyWidget(this));
}
MainWindow::~MainWindow()
{
delete ui;
}
| 16.625 | 43 | 0.681704 | topecongiro |
1b68b4a476bbd148890f6550ab6b3c2b6e2d64b0 | 2,102 | cpp | C++ | RoboRoboPi/servo_old.cpp | vanklompf/RoboRoboPi | 344d025ae374720a88c761d97ed3010c5c577602 | [
"Beerware"
] | null | null | null | RoboRoboPi/servo_old.cpp | vanklompf/RoboRoboPi | 344d025ae374720a88c761d97ed3010c5c577602 | [
"Beerware"
] | null | null | null | RoboRoboPi/servo_old.cpp | vanklompf/RoboRoboPi | 344d025ae374720a88c761d97ed3010c5c577602 | [
"Beerware"
] | null | null | null | #include <wiringPi.h>
#include <stdio.h>
#include "servo.h"
#include "logger.h"
namespace robo
{
/*
* Clock and range values from
* http://stackoverflow.com/questions/20081286/controlling-a-servo-with-raspberry-pi-using-the-hardware-pwm-with-wiringpi
* Range tests:
* Clock: 384 Range: 30 - 115
* Clock: 500 Range: 25 - 80
* Clock: 400 Range: 29 - 111
* Clock: 250 Range: 46 - 178
* Clock: 200 Range: 57 - 223
* Clock: 100 Not working
*/
static const int SERVO_PIN = 1;
static const int MIN = 30;
static const int MAX = 115;
static const int ZERO = (MIN + MAX) / 2;
static constexpr char const * const arr[] = { "INFO", "WARNING", "ERROR", "CRASH" };
static const char * const error_values[] =
{
"SERVO_OK",
"SERVO_OUT_OF_RANGE",
"SERVO_ERROR"
};
void Servo::Init()
{
//pinMode(SERVO_PIN, PWM_OUTPUT);
//pwmSetMode(PWM_MODE_MS);
//pwmSetClock(384);
//pwmSetRange(1000);
SetAngle(0);
LogDebug("Servo Initialized.");
}
servo_status_t Servo::setGpioRegister(int16_t value)
{
auto status = servo_status_t::SERVO_ERROR;
if (value > MAX)
{
status = servo_status_t::SERVO_OUT_OF_RANGE;
value = MAX;
}
else if (value < MIN)
{
status = servo_status_t::SERVO_OUT_OF_RANGE;
value = MIN;
}
else
{
status = servo_status_t::SERVO_OK;
}
LogDebug("Setting servo gpio: %d", value);
m_gpio_value = value;
pwmWrite(SERVO_PIN, value);
return status;
}
servo_status_t Servo::SetAngle(int16_t angle)
{
return setGpioRegister(angleToGpioValue(angle));
}
int Servo::angleToGpioValue(int16_t angle) const
{
return ZERO + angle;
}
int16_t Servo::gpioValueToAngle(int value) const
{
return value - ZERO;
}
servo_status_t Servo::StepLeft()
{
return setGpioRegister(m_gpio_value - 10);
}
servo_status_t Servo::StepRight()
{
return setGpioRegister(m_gpio_value + 10);
}
const char* Servo::getStatusText(servo_status_t status) const
{
return error_values[status];
}
}
| 21.232323 | 124 | 0.639867 | vanklompf |
1b6a6df75a2234e4c07ca8fa96c8dabcc825fc54 | 293 | cpp | C++ | AtCoder/abc078/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc078/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc078/b/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int X, Y, Z; cin >> X >> Y >> Z;
int sum = 0, cnt = 0;
while(true) {
sum += Y + Z;
if (sum + Z > X) break;
cnt++;
}
printf("%d\n", cnt);
}
| 18.3125 | 36 | 0.488055 | H-Tatsuhiro |
1b6f981d5208ba3f6153bedb5c8ebd04f5f55de7 | 1,750 | cpp | C++ | Release/src/granada/util/application.cpp | htmlpuzzle/moonlynx | c098b30ab8689fc8ea25fa375c337afa9964af81 | [
"MIT"
] | null | null | null | Release/src/granada/util/application.cpp | htmlpuzzle/moonlynx | c098b30ab8689fc8ea25fa375c337afa9964af81 | [
"MIT"
] | null | null | null | Release/src/granada/util/application.cpp | htmlpuzzle/moonlynx | c098b30ab8689fc8ea25fa375c337afa9964af81 | [
"MIT"
] | null | null | null |
#include "granada/util/application.h"
namespace granada{
namespace util{
namespace application{
const std::string& get_selfpath(){
if (selfpath.empty()){
#ifdef __APPLE__
int ret;
pid_t pid;
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
pid = getpid();
ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));
if ( ret > 0 ) {
std::string totalPath = std::string(pathbuf);
selfpath = totalPath.substr(0,totalPath.find_last_of("/"));
}
#elif _WIN32
std::vector<wchar_t> pathBuf;
DWORD copied = 0;
do {
pathBuf.resize(pathBuf.size() + MAX_PATH);
copied = GetModuleFileName(0, (PWSTR)&pathBuf.at(0), pathBuf.size());
} while (copied >= pathBuf.size());
pathBuf.resize(copied);
selfpath = utility::conversions::to_utf8string(std::wstring(pathBuf.begin(), pathBuf.end()));
selfpath = selfpath.substr(0, selfpath.find_last_of("\\"));
#else
char buff[PATH_MAX];
ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
if (len != -1) {
buff[len] = '\0';
std::string totalPath = std::string(buff);
selfpath = totalPath.substr(0,totalPath.find_last_of("/"));
}
#endif
}
return selfpath;
}
const std::string GetProperty(const std::string& name){
if (property_file_ == NULL){
std::string configuration_file_path = get_selfpath() + "/server.conf";
property_file_ = std::unique_ptr<granada::util::file::PropertyFile>(new granada::util::file::PropertyFile(configuration_file_path));
}
return property_file_->GetProperty(name);
}
}
}
} | 32.407407 | 142 | 0.589143 | htmlpuzzle |
1b7520c37f1409c60529d6ab0b69a816c720f707 | 8,867 | cpp | C++ | cuda/laghos_assembly.cpp | artv3/Laghos | 64449d427349b0ca35086a63ae4e7d1ed5894f08 | [
"BSD-2-Clause"
] | 1 | 2022-03-24T07:03:23.000Z | 2022-03-24T07:03:23.000Z | cuda/laghos_assembly.cpp | jeffhammond/Laghos | 12e62aa7eb6175f27380106b40c9286d710a0f52 | [
"BSD-2-Clause"
] | null | null | null | cuda/laghos_assembly.cpp | jeffhammond/Laghos | 12e62aa7eb6175f27380106b40c9286d710a0f52 | [
"BSD-2-Clause"
] | 3 | 2020-04-12T20:07:41.000Z | 2022-03-24T07:07:52.000Z | // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project (17-SC-20-SC)
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
#include "laghos_assembly.hpp"
#ifdef MFEM_USE_MPI
using namespace std;
namespace mfem
{
namespace hydrodynamics
{
QuadratureData::QuadratureData(int dim,
int nzones,
int nqp)
{ Setup(dim, nzones, nqp); }
void QuadratureData::Setup(int dim,
int nzones,
int nqp)
{
rho0DetJ0w.SetSize(nqp * nzones);
stressJinvT.SetSize(dim * dim * nqp * nzones);
dtEst.SetSize(nqp * nzones);
}
void DensityIntegrator::AssembleRHSElementVect(const FiniteElement &fe,
ElementTransformation &Tr,
Vector &elvect)
{
const int ip_cnt = integ_rule.GetNPoints();
Vector shape(fe.GetDof());
Vector rho0DetJ0w = quad_data.rho0DetJ0w;
elvect.SetSize(fe.GetDof());
elvect = 0.0;
for (int q = 0; q < ip_cnt; q++)
{
fe.CalcShape(integ_rule.IntPoint(q), shape);
shape *= rho0DetJ0w(Tr.ElementNo*ip_cnt + q);
elvect += shape;
}
}
// *****************************************************************************
CudaMassOperator::CudaMassOperator(CudaFiniteElementSpace &fes_,
const IntegrationRule &integ_rule_,
QuadratureData *quad_data_)
: CudaOperator(fes_.GetTrueVSize()),
fes(fes_),
integ_rule(integ_rule_),
ess_tdofs_count(0),
bilinearForm(&fes),
quad_data(quad_data_),
x_gf(fes),
y_gf(fes) {}
// *****************************************************************************
CudaMassOperator::~CudaMassOperator()
{
}
// *****************************************************************************
void CudaMassOperator::Setup()
{
dim=fes.GetMesh()->Dimension();
nzones=fes.GetMesh()->GetNE();
CudaMassIntegrator &massInteg = *(new CudaMassIntegrator());
massInteg.SetIntegrationRule(integ_rule);
massInteg.SetOperator(quad_data->rho0DetJ0w);
bilinearForm.AddDomainIntegrator(&massInteg);
bilinearForm.Assemble();
bilinearForm.FormOperator(Array<int>(), massOperator);
}
// *************************************************************************
void CudaMassOperator::SetEssentialTrueDofs(Array<int> &dofs)
{
ess_tdofs_count = dofs.Size();
if (ess_tdofs.Size()==0)
{
#ifdef MFEM_USE_MPI
int global_ess_tdofs_count;
const MPI_Comm comm = fes.GetParMesh()->GetComm();
MPI_Allreduce(&ess_tdofs_count,&global_ess_tdofs_count,
1, MPI_INT, MPI_SUM, comm);
assert(global_ess_tdofs_count>0);
ess_tdofs.allocate(global_ess_tdofs_count);
#else
assert(ess_tdofs_count>0);
ess_tdofs.allocate(ess_tdofs_count);
#endif
}
else { assert(ess_tdofs_count<=ess_tdofs.Size()); }
assert(ess_tdofs.ptr());
if (ess_tdofs_count == 0) { return; }
assert(ess_tdofs_count>0);
assert(dofs.GetData());
rHtoD(ess_tdofs.ptr(),dofs.GetData(),ess_tdofs_count*sizeof(int));
}
// *****************************************************************************
void CudaMassOperator::EliminateRHS(CudaVector &b)
{
if (ess_tdofs_count > 0)
{
b.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count);
}
}
// *************************************************************************
void CudaMassOperator::Mult(const CudaVector &x, CudaVector &y) const
{
distX = x;
if (ess_tdofs_count)
{
distX.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count);
}
massOperator->Mult(distX, y);
if (ess_tdofs_count)
{
y.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count);
}
}
// *****************************************************************************
// * CudaForceOperator
// *****************************************************************************
CudaForceOperator::CudaForceOperator(CudaFiniteElementSpace &h1fes_,
CudaFiniteElementSpace &l2fes_,
const IntegrationRule &integ_rule_,
const QuadratureData *quad_data_)
: CudaOperator(l2fes_.GetTrueVSize(), h1fes_.GetTrueVSize()),
dim(h1fes_.GetMesh()->Dimension()),
nzones(h1fes_.GetMesh()->GetNE()),
h1fes(h1fes_),
l2fes(l2fes_),
integ_rule(integ_rule_),
quad_data(quad_data_),
gVecL2(l2fes.GetLocalDofs() * nzones),
gVecH1(h1fes.GetVDim() * h1fes.GetLocalDofs() * nzones) { }
// *****************************************************************************
CudaForceOperator::~CudaForceOperator() {}
// *************************************************************************
void CudaForceOperator::Setup()
{
h1D2Q = CudaDofQuadMaps::Get(h1fes, integ_rule);
l2D2Q = CudaDofQuadMaps::Get(l2fes, integ_rule);
}
// *************************************************************************
void CudaForceOperator::Mult(const CudaVector &vecL2,
CudaVector &vecH1) const
{
l2fes.GlobalToLocal(vecL2, gVecL2);
const int NUM_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1;
const IntegrationRule &ir1D = IntRules.Get(Geometry::SEGMENT,
integ_rule.GetOrder());
const int NUM_QUAD_1D = ir1D.GetNPoints();
const int L2_DOFS_1D = l2fes.GetFE(0)->GetOrder()+1;
const int H1_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1;
if (rconfig::Get().Share())
rForceMultS(dim,
NUM_DOFS_1D,
NUM_QUAD_1D,
L2_DOFS_1D,
H1_DOFS_1D,
nzones,
l2D2Q->dofToQuad,
h1D2Q->quadToDof,
h1D2Q->quadToDofD,
quad_data->stressJinvT,
gVecL2,
gVecH1);
else
rForceMult(dim,
NUM_DOFS_1D,
NUM_QUAD_1D,
L2_DOFS_1D,
H1_DOFS_1D,
nzones,
l2D2Q->dofToQuad,
h1D2Q->quadToDof,
h1D2Q->quadToDofD,
quad_data->stressJinvT,
gVecL2,
gVecH1);
h1fes.LocalToGlobal(gVecH1, vecH1);
}
// *************************************************************************
void CudaForceOperator::MultTranspose(const CudaVector &vecH1,
CudaVector &vecL2) const
{
h1fes.GlobalToLocal(vecH1, gVecH1);
const int NUM_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1;
const IntegrationRule &ir1D = IntRules.Get(Geometry::SEGMENT,
integ_rule.GetOrder());
const int NUM_QUAD_1D = ir1D.GetNPoints();
const int L2_DOFS_1D = l2fes.GetFE(0)->GetOrder()+1;
const int H1_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1;
if (rconfig::Get().Share())
rForceMultTransposeS(dim,
NUM_DOFS_1D,
NUM_QUAD_1D,
L2_DOFS_1D,
H1_DOFS_1D,
nzones,
l2D2Q->quadToDof,
h1D2Q->dofToQuad,
h1D2Q->dofToQuadD,
quad_data->stressJinvT,
gVecH1,
gVecL2);
else
rForceMultTranspose(dim,
NUM_DOFS_1D,
NUM_QUAD_1D,
L2_DOFS_1D,
H1_DOFS_1D,
nzones,
l2D2Q->quadToDof,
h1D2Q->dofToQuad,
h1D2Q->dofToQuadD,
quad_data->stressJinvT,
gVecH1,
gVecL2);
l2fes.LocalToGlobal(gVecL2, vecL2);
}
} // namespace hydrodynamics
} // namespace mfem
#endif // MFEM_USE_MPI
| 34.772549 | 81 | 0.523627 | artv3 |
1b7768553c1533a091c75d5d3e93211c2ce76500 | 849 | cpp | C++ | src/transcrLUSS/fv2id.cpp | jvitkauskas/liepa | 2a1e0d27e326a739691414b59474cd09dce16bfa | [
"0BSD"
] | null | null | null | src/transcrLUSS/fv2id.cpp | jvitkauskas/liepa | 2a1e0d27e326a739691414b59474cd09dce16bfa | [
"0BSD"
] | null | null | null | src/transcrLUSS/fv2id.cpp | jvitkauskas/liepa | 2a1e0d27e326a739691414b59474cd09dce16bfa | [
"0BSD"
] | null | null | null | #include "stdafx.h"
#include "fv2id.h"
#include <string.h>
char* strtokf(char*, const char*, char**);
unsigned short fv2id(char *fpav)
{
for (int i = 0; i < FonSk; i++)
if (strcmp(fpav, FonV[i].fv) == 0)
return FonV[i].id;
return FonV[0].id; //pauze "_"
}
char* id2fv(unsigned short id)
{
for (int i = 0; i < FonSk; i++)
if (id == FonV[i].id)
return FonV[i].fv;
return FonV[0].fv; //pauze "_"
}
int trText2UnitList(char *TrSakinys, unsigned short *units, unsigned short *unitseparators)
{
char temp[500], *pos, *newpos; //turetu pakakti 480
strcpy(temp, TrSakinys);
int i = 0;
pos = strtokf(temp, "+- ", &newpos);
while (pos != NULL)
{
units[i] = fv2id(pos);
pos = strtokf(NULL, "+- ", &newpos);
if (pos == NULL) unitseparators[i] = '+';
else unitseparators[i] = TrSakinys[pos - temp - 1];
i++;
}
return i;
}
| 19.744186 | 91 | 0.605418 | jvitkauskas |
1b797aa0c5f3b55f246455346a249c582dead4b3 | 2,385 | cpp | C++ | projects/Vk_12/src/timer.cpp | AnselmoGPP/Vulkan_samples | 9aaefcff024962b41539be70a9179e78856ff6a7 | [
"MIT"
] | null | null | null | projects/Vk_12/src/timer.cpp | AnselmoGPP/Vulkan_samples | 9aaefcff024962b41539be70a9179e78856ff6a7 | [
"MIT"
] | null | null | null | projects/Vk_12/src/timer.cpp | AnselmoGPP/Vulkan_samples | 9aaefcff024962b41539be70a9179e78856ff6a7 | [
"MIT"
] | null | null | null |
#include "timer.hpp"
#include <iostream>
#include <thread>
#include <chrono>
#include <cmath>
TimerSet::TimerSet(int maximumFPS)
: currentTime(std::chrono::system_clock::duration::zero()), maxFPS(maximumFPS)
{
startTimer();
time = 0;
deltaTime = 0;
FPS = 0;
frameCounter = 0;
}
void TimerSet::startTimer()
{
startTime = std::chrono::high_resolution_clock::now();
prevTime = startTime;
//std::this_thread::sleep_for(std::chrono::microseconds(1000)); // Avoids deltaTime == 0 (i.e. currentTime == lastTime)
}
void TimerSet::computeDeltaTime()
{
// Get deltaTime
currentTime = std::chrono::high_resolution_clock::now();
//time = std::chrono::duration_cast<std::chrono::microseconds>(currentTime - startTime).count() / 1000000.l;
//time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count();
deltaTime = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - prevTime).count();
// Add some time to deltaTime to adjust the FPS (if FPS control is enabled)
if (maxFPS > 0)
{
int waitTime = (1.l / maxFPS - deltaTime) * 1000000; // microseconds (for the sleep)
if (waitTime > 0)
{
std::this_thread::sleep_for(std::chrono::microseconds(waitTime));
currentTime = std::chrono::high_resolution_clock::now();
deltaTime = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - prevTime).count();
}
}
prevTime = currentTime;
// Get FPS
FPS = std::round(1 / deltaTime);
// Get time
time = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - startTime).count();
// Increment the frame count
++frameCounter;
}
long double TimerSet::getDeltaTime() { return deltaTime; }
long double TimerSet::getTime() { return time; }
long double TimerSet::getTimeNow()
{
std::chrono::high_resolution_clock::time_point timeNow = std::chrono::high_resolution_clock::now();
return std::chrono::duration<long double, std::chrono::seconds::period>(timeNow - startTime).count();
}
int TimerSet::getFPS() { return FPS; }
void TimerSet::setMaxFPS(int newFPS) { maxFPS = newFPS; }
size_t TimerSet::getFrameCounter() { return frameCounter; }; | 32.22973 | 126 | 0.646122 | AnselmoGPP |
1b799112689c41db6f923b8bb8dd200ae6eccc44 | 5,147 | cpp | C++ | ofApp.cpp | SJ-magic-study-oF/study__DmxToPwm | 70a27f8697b72f94652ad5c03e84f0737c8a4a2b | [
"MIT"
] | null | null | null | ofApp.cpp | SJ-magic-study-oF/study__DmxToPwm | 70a27f8697b72f94652ad5c03e84f0737c8a4a2b | [
"MIT"
] | null | null | null | ofApp.cpp | SJ-magic-study-oF/study__DmxToPwm | 70a27f8697b72f94652ad5c03e84f0737c8a4a2b | [
"MIT"
] | null | null | null | /************************************************************
************************************************************/
#include "ofApp.h"
/************************************************************
************************************************************/
char targetIP[] = "10.7.206.7";
enum LED_TYPE{
LEDTYPE_STAGELIGHT,
LEDTYPE_TAPE,
};
struct Led{
LED_TYPE LedType;
int OdeOffset;
};
/* */
Led Led[] = {
// DMX/PWM converter 1
{ LEDTYPE_TAPE , 0 }, // 0 HardOffset = 1
{ LEDTYPE_TAPE , 3 }, // 1
{ LEDTYPE_TAPE , 6 }, // 2
{ LEDTYPE_TAPE , 9 }, // 3
{ LEDTYPE_TAPE , 12 }, // 4
{ LEDTYPE_TAPE , 15 }, // 5
{ LEDTYPE_TAPE , 18 }, // 6
{ LEDTYPE_TAPE , 21 }, // 7
// DMX/PWM converter 2
{ LEDTYPE_TAPE , 24 }, // 8 HardOffset = 25
{ LEDTYPE_TAPE , 27 }, // 9
{ LEDTYPE_TAPE , 30 }, // 10
{ LEDTYPE_TAPE , 33 }, // 11
{ LEDTYPE_TAPE , 36 }, // 12
{ LEDTYPE_TAPE , 39 }, // 13
{ LEDTYPE_TAPE , 42 }, // 14
{ LEDTYPE_TAPE , 45 }, // 15
// Stage Light
{ LEDTYPE_STAGELIGHT , 48 }, // 16 HardOffset = 49
};
const int NUM_LEDS = sizeof(Led)/sizeof(Led[0]);
/************************************************************
************************************************************/
//--------------------------------------------------------------
void ofApp::setup(){
/********************
********************/
ofSetWindowShape(600, 400);
ofSetVerticalSync(false);
ofSetFrameRate(60);
//at first you must specify the Ip address of this machine
artnet.setup("10.0.0.2"); //make sure the firewall is deactivated at this point
/********************
********************/
for(int i = 0; i < DMX_SIZE; i++){
data[i] = 0;
}
/********************
********************/
ofColor initColor = ofColor(0, 0, 0, 255);
ofColor minColor = ofColor(0, 0, 0, 0);
ofColor maxColor = ofColor(255, 255, 255, 255);
/********************
********************/
gui.setup();
gui.add(LedId.setup("LedId", 0, 0, NUM_LEDS - 1));
gui.add(color.setup("color", initColor, minColor, maxColor));
}
//--------------------------------------------------------------
void ofApp::update(){
/*
// All Led on
ofColor CurrentColor = color;
for(int i = 0; i < NUM_LEDS; i++){
set_dataArray(i, CurrentColor);
}
/*/
// single Led on
for(int i = 0; i < DMX_SIZE; i++){
data[i] = 0;
}
ofColor CurrentColor = color;
set_dataArray(LedId, CurrentColor);
//*/
}
//--------------------------------------------------------------
void ofApp::set_dataArray(int id, ofColor CurrentColor){
switch(Led[id].LedType){
case LEDTYPE_STAGELIGHT:
data[Led[id].OdeOffset + 0] = CurrentColor.a;
data[Led[id].OdeOffset + 1] = CurrentColor.r;
data[Led[id].OdeOffset + 2] = CurrentColor.g;
data[Led[id].OdeOffset + 3] = CurrentColor.b;
data[Led[id].OdeOffset + 4] = 0; // w;
data[Led[id].OdeOffset + 5] = 1; // Strobe. 1-9:open
break;
case LEDTYPE_TAPE:
data[Led[id].OdeOffset + 0] = CurrentColor.r;
data[Led[id].OdeOffset + 1] = CurrentColor.g;
data[Led[id].OdeOffset + 2] = CurrentColor.b;
break;
}
}
//--------------------------------------------------------------
void ofApp::exit(){
for(int i = 0; i < DMX_SIZE; i++){
data[i] = 0;
}
artnet.sendDmx(targetIP, data, DMX_SIZE);
}
//--------------------------------------------------------------
void ofApp::draw(){
/********************
********************/
ofBackground(30);
/********************
********************/
// list nodes for sending
// with subnet / universe
// artnet.sendDmx("10.0.0.149", 0xf, 0xf, testImage.getPixels(), 512);
artnet.sendDmx(targetIP, data, DMX_SIZE);
/********************
********************/
gui.draw();
/********************
********************/
printf("%5.1f\r", ofGetFrameRate());
fflush(stdout);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 24.626794 | 83 | 0.39693 | SJ-magic-study-oF |
1b7a1fc489c7c804698a5427fec651904f781e9d | 2,162 | cpp | C++ | StateManager.cpp | JorgeAndd/NeoEngine | c83b0c21fd97fe4976c3cf142fc93814e8f0892c | [
"MIT"
] | null | null | null | StateManager.cpp | JorgeAndd/NeoEngine | c83b0c21fd97fe4976c3cf142fc93814e8f0892c | [
"MIT"
] | null | null | null | StateManager.cpp | JorgeAndd/NeoEngine | c83b0c21fd97fe4976c3cf142fc93814e8f0892c | [
"MIT"
] | null | null | null | #include "StateManager.h"
StateManager::StateManager()
{
SDLBase::initSDL();
inst = InputManager::getInstance();
currentState = new State_Splash();
currentState->load();
srand(time(NULL));
inst->update();
stack = 0;
}
StateManager::~StateManager()
{
SDLBase::exitSDL();
currentState->unload();
free(currentState);
}
void StateManager::run()
{
bool quit = false;
float accumulator, lastTime;
const float dt = TIME_STEP;
lastTime = SDL_GetTicks()/1000.f;
accumulator = 0.f;
while(!quit)
{
float nowTime = SDL_GetTicks()/1000.f;
float frameTime = nowTime - lastTime;
lastTime = nowTime;
accumulator += frameTime;
if(accumulator >= dt)
{
inst->update();
if(inst->quitGame())
{
quit = true;
continue;
}
switch(currentState->update())
{
case STATE:
break;
case STATE_SPLASH:
stack = currentState->unload();
delete(currentState);
currentState = new State_Splash();
currentState->load(stack);
break;
case STATE_GAME:
stack = currentState->unload();
delete(currentState);
currentState = new State_Game();
currentState->load(stack);
break;
case STATE_END:
stack = currentState->unload();
delete(currentState);
currentState = new State_End();
currentState->load(stack);
break;
case STATE_QUIT:
quit = true;
break;
}
accumulator -= dt;
}
currentState->render();
SDLBase::updateScreen();
/*
now = SDL_GetTicks();
if(next_time > now)
SDL_Delay(next_time - now);
next_time += TICK_INTERVAL;
*/
}
}
| 24.022222 | 54 | 0.466235 | JorgeAndd |
1b7b62adc99e85e5d461a5ffcf705f038004383b | 7,231 | hpp | C++ | src/uml/src_gen/uml/StructuralFeatureAction.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | null | null | null | src/uml/src_gen/uml/StructuralFeatureAction.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | null | null | null | src/uml/src_gen/uml/StructuralFeatureAction.hpp | dataliz9r/MDE4CPP | 9c5ce01c800fb754c371f1a67f648366eeabae49 | [
"MIT"
] | null | null | null | //********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************
#ifndef UML_STRUCTURALFEATUREACTION_HPP
#define UML_STRUCTURALFEATUREACTION_HPP
#include <map>
#include <list>
#include <memory>
#include <string>
// forward declarations
template<class T, class ... U> class Subset;
class AnyObject;
typedef std::shared_ptr<AnyObject> Any;
//*********************************
// generated Includes
#include <map>
namespace persistence
{
namespace interfaces
{
class XLoadHandler; // used for Persistence
class XSaveHandler; // used for Persistence
}
}
namespace uml
{
class UmlFactory;
}
//Forward Declaration for used types
namespace uml
{
class Action;
}
namespace uml
{
class Activity;
}
namespace uml
{
class ActivityEdge;
}
namespace uml
{
class ActivityGroup;
}
namespace uml
{
class ActivityNode;
}
namespace uml
{
class ActivityPartition;
}
namespace uml
{
class Classifier;
}
namespace uml
{
class Comment;
}
namespace uml
{
class Constraint;
}
namespace uml
{
class Dependency;
}
namespace uml
{
class Element;
}
namespace uml
{
class ExceptionHandler;
}
namespace uml
{
class InputPin;
}
namespace uml
{
class InterruptibleActivityRegion;
}
namespace uml
{
class Namespace;
}
namespace uml
{
class OutputPin;
}
namespace uml
{
class RedefinableElement;
}
namespace uml
{
class StringExpression;
}
namespace uml
{
class StructuralFeature;
}
namespace uml
{
class StructuredActivityNode;
}
// base class includes
#include "uml/Action.hpp"
// enum includes
#include "uml/VisibilityKind.hpp"
//*********************************
namespace uml
{
/*!
StructuralFeatureAction is an abstract class for all Actions that operate on StructuralFeatures.
<p>From package UML::Actions.</p> */
class StructuralFeatureAction:virtual public Action
{
public:
StructuralFeatureAction(const StructuralFeatureAction &) {}
StructuralFeatureAction& operator=(StructuralFeatureAction const&) = delete;
protected:
StructuralFeatureAction(){}
public:
virtual std::shared_ptr<ecore::EObject> copy() const = 0;
//destructor
virtual ~StructuralFeatureAction() {}
//*********************************
// Operations
//*********************************
/*!
The multiplicity of the object InputPin must be 1..1.
object.is(1,1) */
virtual bool multiplicity(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The structuralFeature must not be static.
not structuralFeature.isStatic */
virtual bool not_static(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The structuralFeature must either be an owned or inherited feature of the type of the object InputPin, or it must be an owned end of a binary Association whose opposite end had as a type to which the type of the object InputPin conforms.
object.type.oclAsType(Classifier).allFeatures()->includes(structuralFeature) or
object.type.conformsTo(structuralFeature.oclAsType(Property).opposite.type) */
virtual bool object_type(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The structuralFeature must have exactly one featuringClassifier.
structuralFeature.featuringClassifier->size() = 1 */
virtual bool one_featuring_classifier(Any diagnostics,std::map < Any, Any > context) = 0;
/*!
The visibility of the structuralFeature must allow access from the object performing the ReadStructuralFeatureAction.
structuralFeature.visibility = VisibilityKind::public or
_'context'.allFeatures()->includes(structuralFeature) or
structuralFeature.visibility=VisibilityKind::protected and
_'context'.conformsTo(structuralFeature.oclAsType(Property).opposite.type.oclAsType(Classifier)) */
virtual bool visibility(Any diagnostics,std::map < Any, Any > context) = 0;
//*********************************
// Attributes Getter Setter
//*********************************
//*********************************
// Reference
//*********************************
/*!
The InputPin from which the object whose StructuralFeature is to be read or written is obtained.
<p>From package UML::Actions.</p> */
virtual std::shared_ptr<uml::InputPin > getObject() const = 0;
/*!
The InputPin from which the object whose StructuralFeature is to be read or written is obtained.
<p>From package UML::Actions.</p> */
virtual void setObject(std::shared_ptr<uml::InputPin> _object_object) = 0;
/*!
The StructuralFeature to be read or written.
<p>From package UML::Actions.</p> */
virtual std::shared_ptr<uml::StructuralFeature > getStructuralFeature() const = 0;
/*!
The StructuralFeature to be read or written.
<p>From package UML::Actions.</p> */
virtual void setStructuralFeature(std::shared_ptr<uml::StructuralFeature> _structuralFeature_structuralFeature) = 0;
protected:
//*********************************
// Attribute Members
//*********************************
//*********************************
// Reference Members
//*********************************
/*!
The InputPin from which the object whose StructuralFeature is to be read or written is obtained.
<p>From package UML::Actions.</p> */
std::shared_ptr<uml::InputPin > m_object;
/*!
The StructuralFeature to be read or written.
<p>From package UML::Actions.</p> */
std::shared_ptr<uml::StructuralFeature > m_structuralFeature;
public:
//*********************************
// Union Getter
//*********************************
/*!
ActivityGroups containing the ActivityNode.
<p>From package UML::Activities.</p> */
virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const = 0;/*!
The ordered set of InputPins representing the inputs to the Action.
<p>From package UML::Actions.</p> */
virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const = 0;/*!
The Elements owned by this Element.
<p>From package UML::CommonStructure.</p> */
virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;/*!
The Element that owns this Element.
<p>From package UML::CommonStructure.</p> */
virtual std::weak_ptr<uml::Element > getOwner() const = 0;/*!
The RedefinableElement that is being redefined by this element.
<p>From package UML::Classification.</p> */
virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const = 0;
virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;
//*********************************
// Persistence Functions
//*********************************
virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) = 0;
virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;
};
}
#endif /* end of include guard: UML_STRUCTURALFEATUREACTION_HPP */
| 25.283217 | 241 | 0.641958 | dataliz9r |
1b7d22df872ed883508b237b1561b43faf6a288a | 18,461 | cpp | C++ | RescueMyDoggo/Classes/Enemy.cpp | furryicedragon/VTCA_F03 | c29f5ecbe461461c5ed769b7732afde8d509c117 | [
"MIT"
] | null | null | null | RescueMyDoggo/Classes/Enemy.cpp | furryicedragon/VTCA_F03 | c29f5ecbe461461c5ed769b7732afde8d509c117 | [
"MIT"
] | null | null | null | RescueMyDoggo/Classes/Enemy.cpp | furryicedragon/VTCA_F03 | c29f5ecbe461461c5ed769b7732afde8d509c117 | [
"MIT"
] | null | null | null | #include"Enemy.h"
USING_NS_CC;
using namespace std;
int hitSound = experimental::AudioEngine::play2d("sounds/hit.mp3", false, 0);
Enemy* Enemy::create(int xMapNumber, int xWaveNumber, int xBossNumber)
{
Enemy* pSprite = new Enemy();
pSprite->eeeFrames = SpriteFrameCache::getInstance();
if (pSprite && pSprite->initWithSpriteFrame(pSprite->eeeFrames->getSpriteFrameByName
(std::to_string(xMapNumber) + std::to_string(xWaveNumber) + std::to_string(xBossNumber) + "0_idle0.png")))
{
pSprite->autorelease();
pSprite->mapNumber = xMapNumber;
pSprite->waveNumber = xWaveNumber;
pSprite->bossNumber = xBossNumber;
pSprite->isSpawned = false;
return pSprite;
}
CC_SAFE_DELETE(pSprite);
return nullptr;
}
void Enemy::initOption()
{
this->direction = 0;
this->canDrop = false;
this->canChase = true;
this->canRespawn = true;
this->getHitTime = 0;
this->inviTime = 1.8;
if (this->bossNumber == 1) inviTime = 6;
if (this->bossNumber == 2) inviTime = 8;
if (this->bossNumber == 3) inviTime = 10;
this->isDead = false;
this->getLastFrameNumberOf("attack");
this->getLastFrameNumberOf("projectile");
spell = Sprite::create();
//spell->setAnchorPoint(Vec2(0.5, 0));
//if (this->waveNumber == 2 && this->mapNumber == 1) spell->setAnchorPoint(Vec2(0, 0));
spellLanded = Sprite::create();
spellLanded->setAnchorPoint(Vec2(0.5f, 0.3f));
spellLanded->setScale(2);
spell->setScale(2);
this->isOnCD = false;
this->isAttacking = false;
this->isMoving = false;
this->canDamage = false;
this->canSpawn = true;
attackHelper = Sprite::create();
if(attackHelper)
this->addChild(attackHelper);
movementHelper = Sprite::create();
if(movementHelper)
this->addChild(movementHelper);
this->hp->setVisible(false);
this->idleStatus();
this->scheduleUpdate();
}
void Enemy::setHP(int HP)
{
if (hp == nullptr)
{
hp = Label::create();
hp->setAnchorPoint(Vec2(0.5, 0));
hp->setPosition(this->getPosition().x +
(this->getContentSize().width / 2), this->getPosition().y + this->getContentSize().height);
hp->setColor(Color3B(255, 0, 0));
//hp->setColor(Color4B::RED);
hp->setSystemFontSize(16);
this->hpBar = false;
}
hp->setString(std::to_string(HP));
if (!hpBar && hp)
{
this->addChild(hp, 1);
this->hpBar = true;
}
}
void Enemy::getLastFrameNumberOf(std::string actionName)
{
for (int i = 0; i < 99; i++) {
auto frameName =
std::to_string(mapNumber) + std::to_string(waveNumber) + std::to_string(bossNumber) +std::to_string(this->direction) +"_" + actionName + std::to_string(i) + ".png";
SpriteFrame* test = eeeFrames->getSpriteFrameByName(frameName);
if (!test) {
if (actionName == "attack")
useSkillLastFN = i;
if (actionName == "projectile")
skillLastFN = i;
break;
}
}
}
void Enemy::idleStatus() {
if (!this->isIdle &&( !this->isDead || this->canRespawn)) {
this->stopAllActionsByTag(1);
this->stopAllActionsByTag(3);
//auto idleState = RepeatForever::create(animation("Idle", 0.12f));
auto idleState = RepeatForever::create(makeAnimation("idle", 0.12f));
idleState->setTag(1);
this->runAction(idleState);
this->isIdle = true;
this->canMove = true;
this->canChase = true;
}
}
void Enemy::movingAnimation()
{
if (this->mapNumber == 2 && this->waveNumber == 1) {
//what does the tree do?
}
else if (this->canMove) {
this->stopAllActionsByTag(1);
this->stopAllActionsByTag(3);
//auto anim = RepeatForever::create(animation("Moving", 0.12f));
auto anim = RepeatForever::create(makeAnimation("moving", 0.12f));
anim->setTag(3);
this->runAction(anim);
this->isMoving = true;
canMove = false;
}
}
void Enemy::chasing()
{
float howFar = std::fabsf(ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2));
if (this->canChase && !this->isMoving && !this->isAttacking &&this->isChasing && howFar>skillRange-69) {
float pppX = ppp->getPosition().x;
this->canChase = false;
this->isIdle = false;
this->isMoving = true;
this->breakTime = false;
float moveByX = pppX - (this->getPosition().x + this->getContentSize().width / 2);
if (moveByX < 0) this->direction = 0;
else this->direction = 1;
this->movingAnimation();
this->stopAllActionsByTag(4);
if (this->mapNumber == 2 && this->waveNumber == 1) {
//what a tree should do
}
else
{
auto move2 = Sequence::create(DelayTime::create(std::fabsf(moveByX)/moveSpeed),
CallFunc::create([=]()
{this->breakTime = false; this->canMove = true; this->canChase = true; this->isMoving = false;
if (std::fabsf(ppp->getPosition().x - this->getPosition().x) > visionRange + 100) this->isChasing = false; this->idleStatus(); }), nullptr);
//could need some fix?! nah
move2->setTag(4);
this->runAction(move2);
}
}
}
void Enemy::randomMoving() {
this->isMoving = true;
if((this->waveNumber==1 || this->bossNumber==1) && (this->mapNumber != 2 || (this->mapNumber == 2 && this->bossNumber == 0)))
randomX = RandomHelper::random_real(listLineX.at(0), listLineX.at(1)); //di chuyen trong 1 khoang giua line1 va line2 trong tiledMap
if((this->waveNumber==2 || this->bossNumber==2) && (this->mapNumber!=2 || (this->mapNumber==2 && this->bossNumber==0)))
randomX = RandomHelper::random_real(listLineX.at(2), listLineX.at(3));
if (this->mapNumber == 2 && this->bossNumber > 0)
randomX = RandomHelper::random_real(listLineX.at(4), listLineX.at(5));
float eX = this->getPositionX();
float moveByX = randomX - eX;
this->isIdle = false;
this->stopAllActionsByTag(4);
if (moveByX > 0) this->direction = 1; //done
else {
moveByX *= -1;
this->direction = 0;
}
this->movingAnimation();
if (this->mapNumber == 2 && this->waveNumber == 1) {
//wat a tree shoud do
}
else
{
auto seq = Sequence::create(DelayTime::create(moveByX/moveSpeed),
CallFunc::create([=]() {this->isMoving = false; this->canMove = true; this->idleStatus(); }),
DelayTime::create(RandomHelper::random_real(0.5f, 1.0f)), CallFunc::create([=]() { this->breakTime = false; }), nullptr);
seq->setTag(4);
this->runAction(seq);
}
}
void Enemy::moving() {
float howFar = std::fabsf(ppp->getPosition().x - this->getPosition().x);
auto eeePosY = this->getPositionY() - 43;
if (this->mapNumber == 3 && bossNumber != 1) {
if (this->bossNumber == 2) eeePosY -= 69;
else eeePosY -= 40;
}
if (howFar < skillRange && !this->isAttacking && !this->isOnCD
&& std::fabsf(ppp->getPosition().y - eeePosY) < 145 && (ppp->getPositionY() - eeePosY)>0 && ppp->getPositionX() > spotPlayerLineLeft && ppp->getPositionX()<spotPlayerLineRight) {
this->attack();
}
if (ppp->getPosition().y - eeePosY > 145 || ppp->getPositionX() < spotPlayerLineLeft || ppp->getPositionX() > spotPlayerLineRight)
this->isChasing = false;
if (howFar < visionRange && !this->isChasing && !this->isAttacking && std::fabsf(ppp->getPosition().y - eeePosY) < 145 && (ppp->getPositionY() - eeePosY)>0 && ppp->getPositionX() > spotPlayerLineLeft && ppp->getPositionX()<spotPlayerLineRight) {
this->isChasing = true;
}
else {
if (!this->isMoving && !this->isAttacking && !this->isChasing && !this->breakTime)
{
this->breakTime = true;
this->randomMoving();
}
else
{
this->chasing();
}
}
}
void Enemy::attack() {
if (this->isSpawned) {
float howFar = ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2);
if (howFar < skillRange) {
if (howFar < 0) this->direction = 0;
else this->direction = 1;
//if (checkFrame("projectile"))
// this->spell->setFlippedX(this->isFlippedX());
this->stopAllActions();
this->isIdle = false;
this->isAttacking = true;
this->isOnCD = true;
this->isMoving = false;
this->canMove = true;
this->breakTime = false;
//this->runAction(Sequence::create(animation("SkillUsing", castSpeed),
this->runAction(Sequence::create(makeAnimation("attack", castSpeed),
CallFunc::create([=]() {this->canDamage = false; this->isAttacking = false; this->idleStatus(); }), nullptr));
if (this->isCaster) {
this->casterSpell();
}
if (this->isSSMobility) {
this->mobilitySS();
}
if (!this->isCaster && !this->isSSMobility) {
this->runAction(Sequence::create(DelayTime::create(castSpeed*norAtkDmgAfterF), CallFunc::create([=]() {this->canDamage = true; }),
DelayTime::create(castSpeed*doneAtkAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr));
}
this->attackHelper->runAction(Sequence::create(DelayTime::create(0.12*useSkillLastFN*skillCD), CallFunc::create([=]() {this->isOnCD = false; }), nullptr));
}
}
}
void Enemy::casterSpell()
{
float range = 500.f;
if (this->direction==0) range *= -1;
float move2X = this->getPosition().x;
float move2Y = this->getPositionY();
if (this->mapNumber == 2 && this->bossNumber == 2)move2Y -= 20;
if (this->mapNumber == 1 && this->waveNumber == 1) move2Y += 10;
if (this->direction==1) {
move2X += this->getContentSize().width/2;
}
else move2X -= this->getContentSize().width / 2;
if(this->waveNumber==2 && this->mapNumber == 1)
this->spell->runAction(Sequence::create(
MoveTo::create(0, Vec2(move2X, this->getPosition().y+this->getContentSize().height/2)),
CallFunc::create([=]() {this->spell->setVisible(true); }),
makeAnimation("projectile", castSpeed), CallFunc::create([=]() {this->spell->setVisible(false); this->attackLandedEffect(); }), nullptr));
if ((this->waveNumber == 1 && this->mapNumber == 1)||(this->mapNumber==2 && this->bossNumber==2)) {
this->spell->runAction(RepeatForever::create(makeAnimation("projectile", castSpeed)));
this->spell->runAction(Sequence::create(
CallFunc::create([=]() {this->interuptable=true; }),
DelayTime::create(castSpeed * skillAtkAfterF),
CallFunc::create([=]() {
this->interuptable = false;
this->spell->setPosition(move2X, move2Y);
this->spell->setVisible(true);
}),
MoveBy::create(0.69f, Vec2(range, 0)),
CallFunc::create([=]() {this->spell->setVisible(false); this->spell->setPosition(0, 0); }), nullptr));
}
if (this->mapNumber == 2 && this->bossNumber == 1) {
this->spell->runAction(Sequence::create(CallFunc::create([=]() {this->interuptable = true; }),
DelayTime::create(castSpeed * skillAtkAfterF),
CallFunc::create([=]() {
this->interuptable = false;
this->spell->setPosition(ppp->getPositionX(), ppp->getPositionY() + 10);
this->spell->setVisible(true);
this->spell->runAction(Sequence::create(makeAnimation("projectile", castSpeed), CallFunc::create([=]() {this->spell->setVisible(false); }), nullptr));
}), DelayTime::create(castSpeed * 2), CallFunc::create([=]() {this->attackLandedEffect(); }),nullptr));
}
//this->spell->runAction(RepeatForever::create(animation("Spell", castSpeed)));
}
void Enemy::mobilitySS()
{
this->mobilityUsing = true;
this->invulnerable = true;
this->movementHelper->stopActionByTag(123);
float howFar = ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2);
if (howFar < 0) howFar *= -1;
if (this->bossNumber == 1 && this->mapNumber == 1)
this->runAction(Sequence::create(DelayTime::create(castSpeed*(mobilitySSAt + 1)),
JumpTo::create(castSpeed*mobilitySpeed, Vec2(ppp->getPosition().x - this->getContentSize().width / 2, this->getPosition().y), 72, 1), CallFunc::create([=]() {this->mobilityUsing = false; this->canDamage = true; this->invulnerable = false; }), DelayTime::create(castSpeed*mobilityDoneAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr));
else
this->runAction(Sequence::create(DelayTime::create(castSpeed*(mobilitySSAt + 1)),
MoveTo::create(castSpeed*mobilitySpeed, Vec2(ppp->getPosition().x - this->getContentSize().width / 2, this->getPosition().y)), CallFunc::create([=]() {this->mobilityUsing = false; this->canDamage = true; this->invulnerable = false; }), DelayTime::create(castSpeed*mobilityDoneAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr));
}
void Enemy::attackLandedEffect() {
if (this->checkFrame("impact")) {
this->spellLanded->setPosition(Vec2(ppp->getPosition().x, ppp->getPosition().y));
this->spellLanded->runAction(Sequence::create(
//CallFunc::create([=]() {this->canDamage = true; this->spellLanded->setVisible(true); }), animation("SkillLanded", 0.12f), CallFunc::create([=]() {this->canDamage = false; this->spellLanded->setVisible(false); this->spellLanded->setPosition(0, 0); }), nullptr));
CallFunc::create([=]() {this->canDamage = true; this->spellLanded->setVisible(true); }), makeAnimation("impact", 0.12f), CallFunc::create([=]() {this->canDamage = false; this->spellLanded->setVisible(false); this->spellLanded->setPosition(0, 0); }), nullptr));
}
}
void Enemy::getHit(int damage) {
if (!this->isDead && this->isSpawned && !this->invulnerable) {
/* if(this->mapNumber==1 || this->mapNumber==2) this->stopAllActions();
else */
this->forbidAllAction();
this->canChase = true;
this->isIdle = false;
this->isAttacking = false;
this->isMoving = false;
this->breakTime = false;
this->getHitTime++;
if (getHitTime == 3) {
getHitTime = 0;
this->invulnerable = true;
auto doIt = Sequence::create(DelayTime::create(inviTime), CallFunc::create([=]() {this->invulnerable = false; }), nullptr);
doIt->setTag(123);
this->movementHelper->runAction(doIt);
}
SpriteFrame * hit = eeeFrames->getSpriteFrameByName(std::to_string(mapNumber) + std::to_string(waveNumber)
+ std::to_string(bossNumber) + std::to_string(this->direction) + "_hurt0.png");
if(hit)
this->setSpriteFrame(hit);
int x = -16;
if (ppp->getPositionX() - 25 < this->getPositionX())
{
x *= -1;
this->direction = 0;
}
else this->direction = 1;
this->runAction(MoveBy::create(0.33f,Vec2(x, 0)));
int healthP = std::stoi(this->hp->getString());
healthP -= damage;
if (healthP < 0 || healthP == 0) {
this->hp->setString("0");
this->dead();
}
else
this->hp->setString(std::to_string(healthP));
if(!this->isDead)
this->runAction(Sequence::create(DelayTime::create(0.3f), CallFunc::create([=]() { this->idleStatus(); }), DelayTime::create(0.4f), CallFunc::create([=]() {this->isMoving=false; this->canMove = true; this->breakTime = false; }), nullptr));
}
}
void Enemy::autoRespawn()
{
if (this->canRespawn && this->bossNumber==0)
{
float timeTillRespawn = RandomHelper::random_real(5.0f, 10.0f);
//this->setVisible(true);
//this->setOpacity(0);
this->runAction(
Sequence::create(
DelayTime::create(timeTillRespawn),
CallFunc::create([=]() {this->idleStatus(); }),
FadeIn::create(1.0f), nullptr));
this->runAction(
Sequence::create(
DelayTime::create(timeTillRespawn + 1.0f),
CallFunc::create([=]() {
this->isDead = false;
this->isSpawned = true;
this->setHP(this->baseHP);
this->canRespawn = false; }), nullptr));
}
}
void Enemy::dead() {
if (this->waveNumber == 1) ppp->w1kills++;
if (this->waveNumber == 2) ppp->w2kills++;
this->isDead = true;
this->isSpawned = false;
this->canRespawn = true;
this->canDrop = true;
//this->stopAllActions();
this->forbidAllAction();
experimental::AudioEngine::play2d("sounds/monsterdie.mp3", false, 0.4f);
if(this->checkFrame("die"))
this->runAction(Sequence::create(makeAnimation("die", 0.12f), FadeOut::create(0), CallFunc::create([=]() {this->autoRespawn(); }), nullptr));
auto howFar = ppp->getPosition().x - this->getPosition().x;
auto theX = 40.f;
if (howFar > 0) theX *= -1;
this->runAction(MoveBy::create(0.5, Vec2(theX, 0)));
ppp->currentEXP += this->expReward;
}
void Enemy::forbidAllAction()
{
this->stopAllActions();
if ((this->mapNumber == 1 && this->waveNumber > 0)||this->interuptable) {
this->spell->stopAllActions();
this->spell->setVisible(false);
}
}
bool Enemy::checkFrame(std::string action)
{
action = "_" + action + "0.png";
//auto checkSprite = Sprite::create(combination +"/"+ action);
auto checkSprite = eeeFrames->getSpriteFrameByName
(std::to_string(this->mapNumber) + std::to_string(this->waveNumber) + std::to_string(this->bossNumber) + std::to_string(this->direction) + action);
if (checkSprite) return true;
else return false;
}
void Enemy::update(float elapsed)
{
if(!this->isDead && this->isSpawned)
moving();
if (this->isChasing && !this->canChase && !this->isAttacking) {
if (this->direction==0 && ppp->getPositionX() > this->getPositionX()+this->getContentSize().width)
{
this->stopAllActionsByTag(3);
this->stopAllActionsByTag(4);
if(!this->mobilityUsing)
this->direction = 1;
this->canChase = true;
this->isMoving = false;
this->idleStatus();
}
else if (this->direction==1 && ppp->getPositionX() < this->getPositionX() - this->getContentSize().width) {
this->stopAllActionsByTag(3);
this->stopAllActionsByTag(4);
if(!this->mobilityUsing)
this->direction = 0;
this->canChase = true;
this->isMoving = false;
this->idleStatus();
}
}
if (this->isMoving && (this->mapNumber!=2 || (this->mapNumber==2 && this->waveNumber!=1)))
{
this->setPositionX(this->getPositionX() + ( this->direction ? (moveSpeed * elapsed) : - (moveSpeed * elapsed) ) );
}
}
Animate* Enemy::makeAnimation(std::string actionName, float timeEachFrame)
{
std::string key = std::to_string(this->mapNumber) + std::to_string(this->waveNumber) + std::to_string(this->bossNumber)
+ std::to_string(this->direction) + "_" + actionName;
Animate* anim = listAnimations.at(key);
if (anim == nullptr)
{
Vector<SpriteFrame*> runningFrames;
for (int i = 0; i < 99; i++)
{
auto frameName = key + std::to_string(i) + ".png";
SpriteFrame* frame = eeeFrames->getSpriteFrameByName(frameName);
if (!frame)
break;
runningFrames.pushBack(frame);
}
Animation* runningAnimation = Animation::createWithSpriteFrames(runningFrames, timeEachFrame);
anim = Animate::create(runningAnimation);
listAnimations.insert(key, anim);
}
return anim;
} | 35.638996 | 361 | 0.644981 | furryicedragon |
1b810ec3f5ca1cb0bd9cfd2c2903caaed49c0e7e | 6,133 | hxx | C++ | opencascade/AdvApp2Var_ApproxF2var.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/AdvApp2Var_ApproxF2var.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/AdvApp2Var_ApproxF2var.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
// AdvApp2Var_ApproxF2var.hxx
/*---------------------------------------------------------------
| description de la macro et du prototype des routines
| de l'approximation a deux variables
| a utiliser dans AdvApp2Var
|--------------------------------------------------------------*/
#ifndef AdvApp2Var_ApproxF2var_HeaderFile
#define AdvApp2Var_ApproxF2var_HeaderFile
#include <Standard_Macro.hxx>
#include <AdvApp2Var_Data_f2c.hxx>
#include <AdvApp2Var_EvaluatorFunc2Var.hxx>
//
class AdvApp2Var_ApproxF2var {
public:
Standard_EXPORT static int mma2fnc_(integer *ndimen,
integer *nbsesp,
integer *ndimse,
doublereal *uvfonc,
const AdvApp2Var_EvaluatorFunc2Var& foncnp,
doublereal *tconst,
integer *isofav,
integer *nbroot,
doublereal *rootlg,
integer *iordre,
integer *ideriv,
integer *ndgjac,
integer *nbcrmx,
integer *ncflim,
doublereal *epsapr,
integer *ncoeff,
doublereal *courbe,
integer *nbcrbe,
doublereal *somtab,
doublereal *diftab,
doublereal *contr1,
doublereal *contr2,
doublereal *tabdec,
doublereal *errmax,
doublereal *errmoy,
integer *iercod);
Standard_EXPORT static int mma2roo_(integer *nbpntu,
integer *nbpntv,
doublereal *urootl,
doublereal *vrootl);
Standard_EXPORT static int mma2jmx_(integer *ndgjac,
integer *iordre,
doublereal *xjacmx);
Standard_EXPORT static int mmapptt_(const integer * ,
const integer * ,
const integer * ,
doublereal * ,
integer * );
Standard_EXPORT static int mma2cdi_(integer *ndimen,
integer *nbpntu,
doublereal *urootl,
integer *nbpntv,
doublereal *vrootl,
integer *iordru,
integer *iordrv,
doublereal *contr1,
doublereal *contr2,
doublereal *contr3,
doublereal *contr4,
doublereal *sotbu1,
doublereal *sotbu2,
doublereal *ditbu1,
doublereal *ditbu2,
doublereal *sotbv1,
doublereal *sotbv2,
doublereal *ditbv1,
doublereal *ditbv2,
doublereal *sosotb,
doublereal *soditb,
doublereal *disotb,
doublereal *diditb,
integer *iercod);
Standard_EXPORT static int mma2ds1_(integer *ndimen,
doublereal *uintfn,
doublereal *vintfn,
const AdvApp2Var_EvaluatorFunc2Var& foncnp,
integer *nbpntu,
integer *nbpntv,
doublereal *urootb,
doublereal *vrootb,
integer *isofav,
doublereal *sosotb,
doublereal *disotb,
doublereal *soditb,
doublereal *diditb,
doublereal *fpntab,
doublereal *ttable,
integer *iercod);
Standard_EXPORT static int mma2ce1_(integer *numdec,
integer *ndimen,
integer *nbsesp,
integer *ndimse,
integer *ndminu,
integer *ndminv,
integer *ndguli,
integer *ndgvli,
integer *ndjacu,
integer *ndjacv,
integer *iordru,
integer *iordrv,
integer *nbpntu,
integer *nbpntv,
doublereal *epsapr,
doublereal *sosotb,
doublereal *disotb,
doublereal *soditb,
doublereal *diditb,
doublereal *patjac,
doublereal *errmax,
doublereal *errmoy,
integer *ndegpu,
integer *ndegpv,
integer *itydec,
integer *iercod);
Standard_EXPORT static int mma2can_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal *,
doublereal * ,
doublereal * ,
integer * );
Standard_EXPORT static int mma1her_(const integer * ,
doublereal * ,
integer * );
Standard_EXPORT static int mma2ac2_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal * ,
const integer * ,
const doublereal * ,
const doublereal * ,
doublereal * );
Standard_EXPORT static int mma2ac3_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal * ,
const integer * ,
const doublereal * ,
const doublereal * ,
doublereal * );
Standard_EXPORT static int mma2ac1_(const integer * ,
const integer * ,
const integer * ,
const integer * ,
const integer * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
const doublereal * ,
doublereal * );
Standard_EXPORT static int mma2fx6_(integer *ncfmxu,
integer *ncfmxv,
integer *ndimen,
integer *nbsesp,
integer *ndimse,
integer *nbupat,
integer *nbvpat,
integer *iordru,
integer *iordrv,
doublereal *epsapr,
doublereal *epsfro,
doublereal *patcan,
doublereal *errmax,
integer *ncoefu,
integer *ncoefv);
};
#endif
| 27.751131 | 81 | 0.585358 | mgreminger |
1b823b8aafefca059bd3731c308007b7c4e82603 | 31,992 | cc | C++ | sources/opl3/ui/operator_editor.cc | jfrey-xx/ADLplug | 108944ab774d3bbcf5cfdc78e1df4e82a88ea522 | [
"BSL-1.0"
] | 316 | 2018-04-19T14:44:25.000Z | 2022-03-28T23:58:05.000Z | sources/opl3/ui/operator_editor.cc | jfrey-xx/ADLplug | 108944ab774d3bbcf5cfdc78e1df4e82a88ea522 | [
"BSL-1.0"
] | 81 | 2018-04-21T11:04:46.000Z | 2022-02-22T19:51:08.000Z | sources/opl3/ui/operator_editor.cc | jfrey-xx/ADLplug | 108944ab774d3bbcf5cfdc78e1df4e82a88ea522 | [
"BSL-1.0"
] | 23 | 2018-09-01T18:04:33.000Z | 2021-11-18T11:36:35.000Z | /*
==============================================================================
This is an automatically generated GUI class created by the Projucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Projucer version: 5.4.1
------------------------------------------------------------------------------
The Projucer is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
#include "ui/components/wave_label.h"
#include "ui/components/info_display.h"
#include "adl/instrument.h"
#include "parameter_block.h"
#include <cmath>
//[/Headers]
#include "operator_editor.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
Operator_Editor::Operator_Editor (unsigned op_id, Parameter_Block &pb)
{
//[Constructor_pre] You can add your own custom stuff here..
operator_id_ = op_id;
parameter_block_ = &pb;
//[/Constructor_pre]
kn_attack.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_attack.get());
kn_attack->setName ("new component");
kn_attack->setBounds (24, 3, 48, 48);
kn_decay.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_decay.get());
kn_decay->setName ("new component");
kn_decay->setBounds (96, 3, 48, 48);
kn_sustain.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_sustain.get());
kn_sustain->setName ("new component");
kn_sustain->setBounds (24, 48, 48, 48);
kn_release.reset (new Styled_Knob_Default());
addAndMakeVisible (kn_release.get());
kn_release->setName ("new component");
kn_release->setBounds (96, 48, 48, 48);
btn_prev_wave.reset (new TextButton ("new button"));
addAndMakeVisible (btn_prev_wave.get());
btn_prev_wave->setButtonText (TRANS("<"));
btn_prev_wave->setConnectedEdges (Button::ConnectedOnRight);
btn_prev_wave->addListener (this);
btn_prev_wave->setBounds (3, 96, 23, 24);
btn_next_wave.reset (new TextButton ("new button"));
addAndMakeVisible (btn_next_wave.get());
btn_next_wave->setButtonText (TRANS(">"));
btn_next_wave->setConnectedEdges (Button::ConnectedOnLeft);
btn_next_wave->addListener (this);
btn_next_wave->setBounds (132, 96, 23, 24);
btn_trem.reset (new TextButton ("new button"));
addAndMakeVisible (btn_trem.get());
btn_trem->setButtonText (String());
btn_trem->addListener (this);
btn_trem->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_trem->setBounds (168, 3, 15, 15);
btn_vib.reset (new TextButton ("new button"));
addAndMakeVisible (btn_vib.get());
btn_vib->setButtonText (String());
btn_vib->addListener (this);
btn_vib->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_vib->setBounds (168, 20, 15, 15);
btn_sus.reset (new TextButton ("new button"));
addAndMakeVisible (btn_sus.get());
btn_sus->setButtonText (String());
btn_sus->addListener (this);
btn_sus->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_sus->setBounds (168, 37, 15, 15);
btn_env.reset (new TextButton ("new button"));
addAndMakeVisible (btn_env.get());
btn_env->setButtonText (String());
btn_env->addListener (this);
btn_env->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8));
btn_env->setBounds (168, 54, 15, 15);
lbl_level.reset (new Label ("new label",
TRANS("Lv")));
addAndMakeVisible (lbl_level.get());
lbl_level->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
lbl_level->setJustificationType (Justification::centredLeft);
lbl_level->setEditable (false, false, false);
lbl_level->setColour (Label::textColourId, Colours::aliceblue);
lbl_level->setColour (TextEditor::textColourId, Colours::black);
lbl_level->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
lbl_level->setBounds (163, 72, 28, 16);
lbl_wave.reset (new Wave_Label (chip_waves_));
addAndMakeVisible (lbl_wave.get());
lbl_wave->setName ("new component");
lbl_wave->setBounds (26, 96, 106, 24);
label.reset (new Label ("new label",
TRANS("A")));
addAndMakeVisible (label.get());
label->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label->setJustificationType (Justification::centredTop);
label->setEditable (false, false, false);
label->setColour (Label::textColourId, Colours::aliceblue);
label->setColour (TextEditor::textColourId, Colours::black);
label->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label->setBounds (4, 0, 20, 16);
label2.reset (new Label ("new label",
TRANS("D")));
addAndMakeVisible (label2.get());
label2->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label2->setJustificationType (Justification::centredTop);
label2->setEditable (false, false, false);
label2->setColour (Label::textColourId, Colours::aliceblue);
label2->setColour (TextEditor::textColourId, Colours::black);
label2->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label2->setBounds (76, 0, 20, 16);
label3.reset (new Label ("new label",
TRANS("S")));
addAndMakeVisible (label3.get());
label3->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label3->setJustificationType (Justification::centredTop);
label3->setEditable (false, false, false);
label3->setColour (Label::textColourId, Colours::aliceblue);
label3->setColour (TextEditor::textColourId, Colours::black);
label3->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label3->setBounds (4, 48, 20, 16);
label4.reset (new Label ("new label",
TRANS("R")));
addAndMakeVisible (label4.get());
label4->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular"));
label4->setJustificationType (Justification::centredTop);
label4->setEditable (false, false, false);
label4->setColour (Label::textColourId, Colours::aliceblue);
label4->setColour (TextEditor::textColourId, Colours::black);
label4->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label4->setBounds (76, 48, 20, 16);
label5.reset (new Label ("new label",
TRANS("Tremolo")));
addAndMakeVisible (label5.get());
label5->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label5->setJustificationType (Justification::centredLeft);
label5->setEditable (false, false, false);
label5->setColour (Label::textColourId, Colours::aliceblue);
label5->setColour (TextEditor::textColourId, Colours::black);
label5->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label5->setBounds (184, 3, 80, 15);
label6.reset (new Label ("new label",
TRANS("Vibrato")));
addAndMakeVisible (label6.get());
label6->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label6->setJustificationType (Justification::centredLeft);
label6->setEditable (false, false, false);
label6->setColour (Label::textColourId, Colours::aliceblue);
label6->setColour (TextEditor::textColourId, Colours::black);
label6->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label6->setBounds (184, 20, 80, 15);
label7.reset (new Label ("new label",
TRANS("Sustain")));
addAndMakeVisible (label7.get());
label7->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label7->setJustificationType (Justification::centredLeft);
label7->setEditable (false, false, false);
label7->setColour (Label::textColourId, Colours::aliceblue);
label7->setColour (TextEditor::textColourId, Colours::black);
label7->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label7->setBounds (184, 37, 80, 15);
label8.reset (new Label ("new label",
TRANS("Key scaling")));
addAndMakeVisible (label8.get());
label8->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
label8->setJustificationType (Justification::centredLeft);
label8->setEditable (false, false, false);
label8->setColour (Label::textColourId, Colours::aliceblue);
label8->setColour (TextEditor::textColourId, Colours::black);
label8->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
label8->setBounds (184, 54, 80, 15);
lbl_fmul.reset (new Label ("new label",
TRANS("F*")));
addAndMakeVisible (lbl_fmul.get());
lbl_fmul->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
lbl_fmul->setJustificationType (Justification::centredLeft);
lbl_fmul->setEditable (false, false, false);
lbl_fmul->setColour (Label::textColourId, Colours::aliceblue);
lbl_fmul->setColour (TextEditor::textColourId, Colours::black);
lbl_fmul->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
lbl_fmul->setBounds (163, 88, 28, 16);
lbl_ksl.reset (new Label ("new label",
TRANS("Ksl")));
addAndMakeVisible (lbl_ksl.get());
lbl_ksl->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular"));
lbl_ksl->setJustificationType (Justification::centredLeft);
lbl_ksl->setEditable (false, false, false);
lbl_ksl->setColour (Label::textColourId, Colours::aliceblue);
lbl_ksl->setColour (TextEditor::textColourId, Colours::black);
lbl_ksl->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
lbl_ksl->setBounds (163, 104, 28, 16);
sl_level.reset (new Styled_Slider_DefaultSmall());
addAndMakeVisible (sl_level.get());
sl_level->setName ("new component");
sl_level->setBounds (195, 70, 64, 20);
sl_fmul.reset (new Styled_Slider_DefaultSmall());
addAndMakeVisible (sl_fmul.get());
sl_fmul->setName ("new component");
sl_fmul->setBounds (195, 86, 64, 20);
sl_ksl.reset (new Styled_Slider_DefaultSmall());
addAndMakeVisible (sl_ksl.get());
sl_ksl->setName ("new component");
sl_ksl->setBounds (195, 102, 64, 20);
//[UserPreSize]
sl_level->add_listener(this);
sl_level->set_range(0, 63);
sl_level->set_max_increment(1);
sl_fmul->add_listener(this);
sl_fmul->set_range(0, 15);
sl_fmul->set_max_increment(1);
sl_ksl->add_listener(this);
sl_ksl->set_range(0, 3);
sl_ksl->set_max_increment(1);
kn_attack->add_listener(this);
kn_attack->set_max_increment(1);
kn_decay->add_listener(this);
kn_decay->set_max_increment(1);
kn_sustain->add_listener(this);
kn_sustain->set_max_increment(1);
kn_release->add_listener(this);
kn_release->set_max_increment(1);
btn_trem->setClickingTogglesState(true);
btn_vib->setClickingTogglesState(true);
btn_sus->setClickingTogglesState(true);
btn_env->setClickingTogglesState(true);
//[/UserPreSize]
setSize (264, 128);
//[Constructor] You can add your own custom stuff here..
kn_attack->set_range(0, 15);
kn_decay->set_range(0, 15);
kn_sustain->set_range(0, 15);
kn_release->set_range(0, 15);
//[/Constructor]
}
Operator_Editor::~Operator_Editor()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
kn_attack = nullptr;
kn_decay = nullptr;
kn_sustain = nullptr;
kn_release = nullptr;
btn_prev_wave = nullptr;
btn_next_wave = nullptr;
btn_trem = nullptr;
btn_vib = nullptr;
btn_sus = nullptr;
btn_env = nullptr;
lbl_level = nullptr;
lbl_wave = nullptr;
label = nullptr;
label2 = nullptr;
label3 = nullptr;
label4 = nullptr;
label5 = nullptr;
label6 = nullptr;
label7 = nullptr;
label8 = nullptr;
lbl_fmul = nullptr;
lbl_ksl = nullptr;
sl_level = nullptr;
sl_fmul = nullptr;
sl_ksl = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void Operator_Editor::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
{
int x = 25, y = 96, width = 108, height = 24;
Colour strokeColour = Colour (0xff8e989b);
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (strokeColour);
g.drawRect (x, y, width, height, 1);
}
{
float x = 0.0f, y = 0.0f, width = 264.0f, height = 128.0f;
Colour fillColour = Colour (0x662e4c4d);
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (fillColour);
g.fillRoundedRectangle (x, y, width, height, 7.0f);
}
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void Operator_Editor::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
void Operator_Editor::buttonClicked (Button* buttonThatWasClicked)
{
//[UserbuttonClicked_Pre]
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
Button *btn = buttonThatWasClicked;
//[/UserbuttonClicked_Pre]
if (buttonThatWasClicked == btn_prev_wave.get())
{
//[UserButtonCode_btn_prev_wave] -- add your button handler code here..
AudioParameterChoice &p = *op.p_wave;
p.beginChangeGesture();
int wave = std::max(p.getIndex() - 1, 0);
p = wave;
p.endChangeGesture();
lbl_wave->set_wave(wave, dontSendNotification);
//[/UserButtonCode_btn_prev_wave]
}
else if (buttonThatWasClicked == btn_next_wave.get())
{
//[UserButtonCode_btn_next_wave] -- add your button handler code here..
AudioParameterChoice &p = *op.p_wave;
p.beginChangeGesture();
int wave = std::min(p.getIndex() + 1, p.choices.size() - 1);
p = wave;
p.endChangeGesture();
lbl_wave->set_wave(wave, dontSendNotification);
//[/UserButtonCode_btn_next_wave]
}
else if (buttonThatWasClicked == btn_trem.get())
{
//[UserButtonCode_btn_trem] -- add your button handler code here..
AudioParameterBool &p = *op.p_trem;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_trem]
}
else if (buttonThatWasClicked == btn_vib.get())
{
//[UserButtonCode_btn_vib] -- add your button handler code here..
AudioParameterBool &p = *op.p_vib;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_vib]
}
else if (buttonThatWasClicked == btn_sus.get())
{
//[UserButtonCode_btn_sus] -- add your button handler code here..
AudioParameterBool &p = *op.p_sus;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_sus]
}
else if (buttonThatWasClicked == btn_env.get())
{
//[UserButtonCode_btn_env] -- add your button handler code here..
AudioParameterBool &p = *op.p_env;
p.beginChangeGesture();
p = btn->getToggleState();
p.endChangeGesture();
//[/UserButtonCode_btn_env]
}
//[UserbuttonClicked_Post]
if (display_info_for_component(btn))
info_->expire_info_in();
//[/UserbuttonClicked_Post]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
static unsigned swap_ksl(unsigned ksl)
{
// OPL mapping for KSL (dB/oct): 0=>0, 1=>3, 2=>1.5, 3=>6
// for user-friendly ordering, the UI control will swap 1 and 2
switch (ksl) {
case 1: return 2;
case 2: return 1;
default: return ksl;
}
}
void Operator_Editor::set_operator_parameters(const Instrument &ins, unsigned op, NotificationType ntf)
{
kn_attack->set_value(ins.attack(op), ntf);
kn_decay->set_value(ins.decay(op), ntf);
kn_sustain->set_value(ins.sustain(op), ntf);
kn_release->set_value(ins.release(op), ntf);
sl_level->set_value(ins.level(op), ntf);
sl_fmul->set_value(ins.fmul(op), ntf);
sl_ksl->set_value(swap_ksl(ins.ksl(op)), ntf);
btn_trem->setToggleState(ins.trem(op), ntf);
btn_vib->setToggleState(ins.vib(op), ntf);
btn_sus->setToggleState(ins.sus(op), ntf);
btn_env->setToggleState(ins.env(op), ntf);
lbl_wave->set_wave(ins.wave(op), ntf);
}
void Operator_Editor::set_operator_enabled(bool b)
{
if (b == operator_enabled_)
return;
operator_enabled_ = b;
repaint();
}
void Operator_Editor::knob_value_changed(Knob *k)
{
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
if (k == sl_level.get()) {
AudioParameterInt &p = *op.p_level;
p = (int)std::lround(k->value());
}
else if (k == sl_fmul.get()) {
AudioParameterInt &p = *op.p_fmul;
p = (int)std::lround(k->value());
}
else if (k == sl_ksl.get()) {
AudioParameterInt &p = *op.p_ksl;
p = swap_ksl((int)std::lround(k->value()));
}
else if (k == kn_attack.get()) {
AudioParameterInt &p = *op.p_attack;
p = (int)std::lround(k->value());
}
else if (k == kn_decay.get()) {
AudioParameterInt &p = *op.p_decay;
p = (int)std::lround(k->value());
}
else if (k == kn_sustain.get()) {
AudioParameterInt &p = *op.p_sustain;
p = (int)std::lround(k->value());
}
else if (k == kn_release.get()) {
AudioParameterInt &p = *op.p_release;
p = (int)std::lround(k->value());
}
display_info_for_component(k);
}
void Operator_Editor::knob_drag_started(Knob *k)
{
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
if (k == sl_level.get()) {
AudioParameterInt &p = *op.p_level;
p.beginChangeGesture();
}
else if (k == sl_fmul.get()) {
AudioParameterInt &p = *op.p_fmul;
p.beginChangeGesture();
}
else if (k == sl_ksl.get()) {
AudioParameterInt &p = *op.p_ksl;
p.beginChangeGesture();
}
else if (k == kn_attack.get()) {
AudioParameterInt &p = *op.p_attack;
p.beginChangeGesture();
}
else if (k == kn_decay.get()) {
AudioParameterInt &p = *op.p_decay;
p.beginChangeGesture();
}
else if (k == kn_sustain.get()) {
AudioParameterInt &p = *op.p_sustain;
p.beginChangeGesture();
}
else if (k == kn_release.get()) {
AudioParameterInt &p = *op.p_release;
p.beginChangeGesture();
}
display_info_for_component(k);
}
void Operator_Editor::knob_drag_ended(Knob *k)
{
Parameter_Block &pb = *parameter_block_;
Parameter_Block::Part &part = pb.part[midichannel_];
Parameter_Block::Operator &op = part.nth_operator(operator_id_);
if (k == sl_level.get()) {
AudioParameterInt &p = *op.p_level;
p.endChangeGesture();
}
else if (k == sl_fmul.get()) {
AudioParameterInt &p = *op.p_fmul;
p.endChangeGesture();
}
else if (k == sl_ksl.get()) {
AudioParameterInt &p = *op.p_ksl;
p.endChangeGesture();
}
else if (k == kn_attack.get()) {
AudioParameterInt &p = *op.p_attack;
p.endChangeGesture();
}
else if (k == kn_decay.get()) {
AudioParameterInt &p = *op.p_decay;
p.endChangeGesture();
}
else if (k == kn_sustain.get()) {
AudioParameterInt &p = *op.p_sustain;
p.endChangeGesture();
}
else if (k == kn_release.get()) {
AudioParameterInt &p = *op.p_release;
p.endChangeGesture();
}
info_->expire_info_in();
}
void Operator_Editor::paintOverChildren(Graphics &g)
{
if (!operator_enabled_) {
Rectangle<int> bounds = getLocalBounds();
g.setColour(Colour(0x66777777));
g.fillRoundedRectangle(bounds.toFloat(), 7.0f);
}
}
bool Operator_Editor::display_info_for_component(Component *c)
{
String param;
int val = 0;
const char *prefixes[4] = {"Op2 ", "Op1 ", "Op4 ", "Op3 "};
String prefix = prefixes[operator_id_];
Knob *kn = static_cast<Knob *>(c);
if (c == sl_level.get()) {
param = prefix + "Level";
val = (int)std::lround(kn->value());
}
else if (c == sl_fmul.get()) {
param = prefix + "Frequency multiplier";
val = (int)std::lround(kn->value());
}
else if (c == sl_ksl.get()) {
param = prefix + "Key scale level";
val = swap_ksl((int)std::lround(kn->value()));
}
else if (c == kn_attack.get()) {
param = prefix + "Attack";
val = (int)std::lround(kn->value());
}
else if (c == kn_decay.get()) {
param = prefix + "Decay";
val = (int)std::lround(kn->value());
}
else if (c == kn_sustain.get()) {
param = prefix + "Sustain";
val = (int)std::lround(kn->value());
}
else if (c == kn_release.get()) {
param = prefix + "Release";
val = (int)std::lround(kn->value());
}
else if (c == btn_next_wave.get() || c == btn_prev_wave.get()) {
param = prefix + "Wave";
val = lbl_wave->wave();
}
if (param.isEmpty())
return false;
info_->display_info(param + " = " + String(val));
return true;
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Projucer information section --
This is where the Projucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="Operator_Editor" componentName=""
parentClasses="public Component, public Knob::Listener" constructorParams="unsigned op_id, Parameter_Block &pb"
variableInitialisers="" snapPixels="8" snapActive="1" snapShown="1"
overlayOpacity="0.33" fixedSize="0" initialWidth="264" initialHeight="128">
<BACKGROUND backgroundColour="323e44">
<RECT pos="25 96 108 24" fill="solid: 0" hasStroke="1" stroke="1, mitered, butt"
strokeColour="solid: ff8e989b"/>
<ROUNDRECT pos="0 0 264 128" cornerSize="7.0" fill="solid: 662e4c4d" hasStroke="0"/>
</BACKGROUND>
<GENERICCOMPONENT name="new component" id="7c54ff103d9f5d" memberName="kn_attack"
virtualName="" explicitFocusOrder="0" pos="24 3 48 48" class="Styled_Knob_Default"
params=""/>
<GENERICCOMPONENT name="new component" id="be39ad00dcf6efe1" memberName="kn_decay"
virtualName="" explicitFocusOrder="0" pos="96 3 48 48" class="Styled_Knob_Default"
params=""/>
<GENERICCOMPONENT name="new component" id="8d88729c124c7b16" memberName="kn_sustain"
virtualName="" explicitFocusOrder="0" pos="24 48 48 48" class="Styled_Knob_Default"
params=""/>
<GENERICCOMPONENT name="new component" id="7d576b68e9b588f" memberName="kn_release"
virtualName="" explicitFocusOrder="0" pos="96 48 48 48" class="Styled_Knob_Default"
params=""/>
<TEXTBUTTON name="new button" id="cbf65c7349d1d293" memberName="btn_prev_wave"
virtualName="" explicitFocusOrder="0" pos="3 96 23 24" buttonText="<"
connectedEdges="2" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="6fc5dc04c6c5d6b9" memberName="btn_next_wave"
virtualName="" explicitFocusOrder="0" pos="132 96 23 24" buttonText=">"
connectedEdges="1" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="f60e70ed4f10ef32" memberName="btn_trem"
virtualName="" explicitFocusOrder="0" pos="168 3 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="501ccf7ad0bc53a7" memberName="btn_vib"
virtualName="" explicitFocusOrder="0" pos="168 20 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="3e46dd6b966c40b2" memberName="btn_sus"
virtualName="" explicitFocusOrder="0" pos="168 37 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="new button" id="eb8e9dfd42dd8f57" memberName="btn_env"
virtualName="" explicitFocusOrder="0" pos="168 54 15 15" bgColOn="ff42a2c8"
buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<LABEL name="new label" id="ce54b68fc1a1f1e1" memberName="lbl_level"
virtualName="" explicitFocusOrder="0" pos="163 72 28 16" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Lv" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<GENERICCOMPONENT name="new component" id="dd16fb8d4c488877" memberName="lbl_wave"
virtualName="" explicitFocusOrder="0" pos="26 96 106 24" class="Wave_Label"
params="chip_waves_"/>
<LABEL name="new label" id="664ae98bd7a6b3a5" memberName="label" virtualName=""
explicitFocusOrder="0" pos="4 0 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="A" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="360efe252ecea296" memberName="label2" virtualName=""
explicitFocusOrder="0" pos="76 0 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="D" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="d276bb335fab1f40" memberName="label3" virtualName=""
explicitFocusOrder="0" pos="4 48 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="S" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="2ad02ec8c7135a27" memberName="label4" virtualName=""
explicitFocusOrder="0" pos="76 48 20 16" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="R" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="15.0"
kerning="0.0" bold="0" italic="0" justification="12"/>
<LABEL name="new label" id="ffcd49be138de78b" memberName="label5" virtualName=""
explicitFocusOrder="0" pos="184 3 80 15" textCol="fff0f8ff" edTextCol="ff000000"
edBkgCol="0" labelText="Tremolo" editableSingleClick="0" editableDoubleClick="0"
focusDiscardsChanges="0" fontname="Default font" fontsize="14.0"
kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="37e7947c4443e047" memberName="label6" virtualName=""
explicitFocusOrder="0" pos="184 20 80 15" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Vibrato" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="f04d949c957007e" memberName="label7" virtualName=""
explicitFocusOrder="0" pos="184 37 80 15" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Sustain" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="e8cd7412f499955d" memberName="label8" virtualName=""
explicitFocusOrder="0" pos="184 54 80 15" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Key scaling" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="e77fa8c6c00316b7" memberName="lbl_fmul"
virtualName="" explicitFocusOrder="0" pos="163 88 28 16" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="F*" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="dbcb4d45f32ea3e9" memberName="lbl_ksl" virtualName=""
explicitFocusOrder="0" pos="163 104 28 16" textCol="fff0f8ff"
edTextCol="ff000000" edBkgCol="0" labelText="Ksl" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/>
<GENERICCOMPONENT name="new component" id="d7383c8ec7f64dfc" memberName="sl_level"
virtualName="" explicitFocusOrder="0" pos="195 70 64 20" class="Styled_Slider_DefaultSmall"
params=""/>
<GENERICCOMPONENT name="new component" id="37e9a27164f2dd8e" memberName="sl_fmul"
virtualName="" explicitFocusOrder="0" pos="195 86 64 20" class="Styled_Slider_DefaultSmall"
params=""/>
<GENERICCOMPONENT name="new component" id="1836679269ce1d4f" memberName="sl_ksl"
virtualName="" explicitFocusOrder="0" pos="195 102 64 20" class="Styled_Slider_DefaultSmall"
params=""/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
//[/EndFile]
| 40.190955 | 133 | 0.624594 | jfrey-xx |
1b82c04d6fa6d0e0e0c770de4422db1b18a26c69 | 2,386 | inl | C++ | WebAssembly/fpzip/src/pcencoder.inl | jvo203/FITSWEBQLSE | 3b2b3c74d623c3510cfa81a4e30ac5bd0af48cb0 | [
"MIT"
] | 60 | 2020-01-03T20:12:39.000Z | 2022-03-14T19:46:22.000Z | src/pcencoder.inl | aras-p/fpzip | 79aa1b1bd5a0b9497b8ad4352d8561ab17113cdf | [
"BSD-3-Clause"
] | 4 | 2020-06-05T16:59:29.000Z | 2021-06-16T09:06:02.000Z | src/pcencoder.inl | aras-p/fpzip | 79aa1b1bd5a0b9497b8ad4352d8561ab17113cdf | [
"BSD-3-Clause"
] | 5 | 2020-03-13T10:18:17.000Z | 2021-08-28T18:04:41.000Z | // specialization for small alphabets -----------------------------------------
template <typename T, class M>
class PCencoder<T, M, false> {
public:
PCencoder(RCencoder* re, RCmodel*const* rm) : re(re), rm(rm) {}
T encode(T real, T pred, uint context = 0);
static const uint symbols = 2 * (1 << M::bits) - 1;
private:
static const uint bias = (1 << M::bits) - 1; // perfect prediction symbol
M map; // maps T to integer type
RCencoder*const re; // entropy encoder
RCmodel*const* rm; // probability modeler(s)
};
// encode narrow range type
template <typename T, class M>
T PCencoder<T, M, false>::encode(T real, T pred, uint context)
{
// map type T to unsigned integer type
typedef typename M::Range U;
U r = map.forward(real);
U p = map.forward(pred);
// entropy encode d = r - p
re->encode(static_cast<uint>(bias + r - p), rm[context]);
// return decoded value
return map.inverse(r);
}
// specialization for large alphabets -----------------------------------------
template <typename T, class M>
class PCencoder<T, M, true> {
public:
PCencoder(RCencoder* re, RCmodel*const* rm) : re(re), rm(rm) {}
T encode(T real, T pred, uint context = 0);
static const uint symbols = 2 * M::bits + 1;
private:
static const uint bias = M::bits; // perfect prediction symbol
M map; // maps T to integer type
RCencoder*const re; // entropy encoder
RCmodel*const* rm; // probability modeler(s)
};
// encode wide range type
template <typename T, class M>
T PCencoder<T, M, true>::encode(T real, T pred, uint context)
{
// map type T to unsigned integer type
typedef typename M::Range U;
U r = map.forward(real);
U p = map.forward(pred);
// compute (-1)^s (2^k + m) = r - p, entropy code (s, k),
// and encode the k-bit number m verbatim
if (p < r) { // underprediction
U d = r - p;
uint k = PC::bsr(d);
re->encode(bias + 1 + k, rm[context]);
re->encode(d - (U(1) << k), k);
}
else if (p > r) { // overprediction
U d = p - r;
uint k = PC::bsr(d);
re->encode(bias - 1 - k, rm[context]);
re->encode(d - (U(1) << k), k);
}
else // perfect prediction
re->encode(bias, rm[context]);
// return decoded value
return map.inverse(r);
}
| 33.138889 | 79 | 0.564962 | jvo203 |
1b875b3349081687e6b9c5fe6094e309e2713ab7 | 31,250 | cc | C++ | curv/builtin.cc | iplayfast/curv | e14ff67ba269c630b78be4708454fefcdbfc4378 | [
"Apache-2.0"
] | null | null | null | curv/builtin.cc | iplayfast/curv | e14ff67ba269c630b78be4708454fefcdbfc4378 | [
"Apache-2.0"
] | null | null | null | curv/builtin.cc | iplayfast/curv | e14ff67ba269c630b78be4708454fefcdbfc4378 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016-2018 Doug Moen
// Licensed under the Apache License, version 2.0
// See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <string>
#include <boost/math/constants/constants.hpp>
#include <boost/filesystem.hpp>
#include <curv/arg.h>
#include <curv/builtin.h>
#include <curv/program.h>
#include <curv/exception.h>
#include <curv/file.h>
#include <curv/function.h>
#include <curv/shape.h>
#include <curv/system.h>
#include <curv/gl_context.h>
#include <curv/array_op.h>
#include <curv/analyser.h>
#include <curv/math.h>
using namespace std;
using namespace boost::math::double_constants;
namespace curv {
Shared<Meaning>
Builtin_Value::to_meaning(const Identifier& id) const
{
return make<Constant>(share(id), value_);
}
struct Is_Null_Function : public Polyadic_Function
{
Is_Null_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].is_null()};
}
};
struct Is_Bool_Function : public Polyadic_Function
{
Is_Bool_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].is_bool()};
}
};
struct Is_Num_Function : public Polyadic_Function
{
Is_Num_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].is_num()};
}
};
struct Is_String_Function : public Polyadic_Function
{
Is_String_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<String>() != nullptr};
}
};
struct Is_List_Function : public Polyadic_Function
{
Is_List_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<List>() != nullptr};
}
};
struct Is_Record_Function : public Polyadic_Function
{
Is_Record_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<Structure>() != nullptr};
}
};
struct Is_Fun_Function : public Polyadic_Function
{
Is_Fun_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {args[0].dycast<Function>() != nullptr};
}
};
struct Bit_Function : public Polyadic_Function
{
Bit_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
return {double(args[0].to_bool(At_Arg(args)))};
}
GL_Value gl_call(GL_Frame& f) const override
{
auto arg = f[0];
if (arg.type != GL_Type::Bool)
throw Exception(At_GL_Arg(0, f),
"bit: argument is not a bool");
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = float("<<arg<<");\n";
return result;
}
};
struct Sqrt_Function : public Polyadic_Function
{
Sqrt_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return sqrt(x); }
static Shared<const String> callstr(Value x) {
return stringify("sqrt(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "sqrt");
}
};
// log(x) is the natural logarithm of x
struct Log_Function : public Polyadic_Function
{
Log_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return log(x); }
static Shared<const String> callstr(Value x) {
return stringify("log(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "log");
}
};
struct Abs_Function : public Polyadic_Function
{
Abs_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return abs(x); }
static Shared<const String> callstr(Value x) {
return stringify("abs(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "abs");
}
};
struct Floor_Function : public Polyadic_Function
{
Floor_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return floor(x); }
static Shared<const String> callstr(Value x) {
return stringify("floor(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "floor");
}
};
// round(x) -- round x to nearest integer.
// CPU: in case of tie, round to even.
// GPU: in case of tie, it's GPU/driver dependent.
struct Round_Function : public Polyadic_Function
{
Round_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return rint(x); }
static Shared<const String> callstr(Value x) {
return stringify("round(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "round");
}
};
struct Sin_Function : public Polyadic_Function
{
Sin_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return sin(x); }
static Shared<const String> callstr(Value x) {
return stringify("sin(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "sin");
}
};
struct Asin_Function : public Polyadic_Function
{
Asin_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return asin(x); }
static Shared<const String> callstr(Value x) {
return stringify("asin(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "asin");
}
};
struct Cos_Function : public Polyadic_Function
{
Cos_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return cos(x); }
static Shared<const String> callstr(Value x) {
return stringify("cos(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "cos");
}
};
struct Acos_Function : public Polyadic_Function
{
Acos_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x) { return acos(x); }
static Shared<const String> callstr(Value x) {
return stringify("acos(",x,")");
}
};
static Unary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
return gl_call_unary_numeric(f, "acos");
}
};
struct Atan2_Function : public Polyadic_Function
{
Atan2_Function() : Polyadic_Function(2) {}
struct Scalar_Op {
static double f(double x, double y) { return atan2(x, y); }
static const char* name() { return "atan2"; }
static Shared<const String> callstr(Value x, Value y) {
return stringify("atan2(",x,",",y,")");
}
};
static Binary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.op(args[0], args[1], At_Arg(args));
}
GL_Value gl_call(GL_Frame& f) const override
{
auto x = f[0];
auto y = f[1];
GL_Type rtype = GL_Type::Bool;
if (x.type == y.type)
rtype = x.type;
else if (x.type == GL_Type::Num)
rtype = y.type;
else if (y.type == GL_Type::Num)
rtype = x.type;
if (rtype == GL_Type::Bool)
throw Exception(At_GL_Phrase(f.call_phrase_, &f),
"GL domain error");
GL_Value result = f.gl.newvalue(rtype);
f.gl.out <<" "<<rtype<<" "<<result<<" = atan(";
gl_put_as(f, x, At_GL_Arg(0, f), rtype);
f.gl.out << ",";
gl_put_as(f, y, At_GL_Arg(1, f), rtype);
f.gl.out << ");\n";
return result;
}
};
GL_Value gl_minmax(const char* name, Operation& argx, GL_Frame& f)
{
auto list = dynamic_cast<List_Expr*>(&argx);
if (list) {
std::list<GL_Value> args;
GL_Type type = GL_Type::Num;
for (auto op : *list) {
auto val = op->gl_eval(f);
args.push_back(val);
if (val.type == GL_Type::Num)
;
else if (gl_type_count(val.type) >= 2) {
if (type == GL_Type::Num)
type = val.type;
else if (type != val.type)
throw Exception(At_GL_Phrase(op->source_, &f), stringify(
"GL: ",name,
": vector arguments of different lengths"));
} else {
throw Exception(At_GL_Phrase(op->source_, &f), stringify(
"GL: ",name,": argument has bad type"));
}
}
auto result = f.gl.newvalue(type);
if (args.size() == 0)
f.gl.out << " " << type << " " << result << " = -0.0/0.0;\n";
else if (args.size() == 1)
return args.front();
else {
f.gl.out << " " << type << " " << result << " = ";
int rparens = 0;
while (args.size() > 2) {
f.gl.out << name << "(" << args.front() << ",";
args.pop_front();
++rparens;
}
f.gl.out << name << "(" << args.front() << "," << args.back() << ")";
while (rparens > 0) {
f.gl.out << ")";
--rparens;
}
f.gl.out << ";\n";
}
return result;
} else {
auto arg = argx.gl_eval(f);
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = ";
if (arg.type == GL_Type::Vec2)
f.gl.out << name <<"("<<arg<<".x,"<<arg<<".y);\n";
else if (arg.type == GL_Type::Vec3)
f.gl.out << name<<"("<<name<<"("<<arg<<".x,"<<arg<<".y),"
<<arg<<".z);\n";
else if (arg.type == GL_Type::Vec4)
f.gl.out << name<<"("<<name<<"("<<name<<"("<<arg<<".x,"<<arg<<".y),"
<<arg<<".z),"<<arg<<".w);\n";
else
throw Exception(At_GL_Phrase(argx.source_, &f), stringify(
name,": argument is not a vector"));
return result;
}
}
struct Max_Function : public Polyadic_Function
{
Max_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x, double y) {
// return NaN if either argument is NaN.
if (x >= y) return x;
if (x < y) return y;
return 0.0/0.0;
}
static const char* name() { return "max"; }
static Shared<const String> callstr(Value x, Value y) {
return stringify("max(",x,",",y,")");
}
};
static Binary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.reduce(-INFINITY, args[0], At_Arg(args));
}
GL_Value gl_call_expr(Operation& argx, const Call_Phrase*, GL_Frame& f)
const override
{
return gl_minmax("max",argx,f);
}
};
struct Min_Function : public Polyadic_Function
{
Min_Function() : Polyadic_Function(1) {}
struct Scalar_Op {
static double f(double x, double y) {
// return NaN if either argument is NaN
if (x <= y) return x;
if (x > y) return y;
return 0.0/0.0;
}
static const char* name() { return "min"; }
static Shared<const String> callstr(Value x, Value y) {
return stringify("min(",x,",",y,")");
}
};
static Binary_Numeric_Array_Op<Scalar_Op> array_op;
Value call(Frame& args) override
{
return array_op.reduce(INFINITY, args[0], At_Arg(args));
}
GL_Value gl_call_expr(Operation& argx, const Call_Phrase*, GL_Frame& f)
const override
{
return gl_minmax("min",argx,f);
}
};
// Generalized dot product that includes vector dot product and matrix product.
// Same as Mathematica Dot[A,B]. Like APL A+.×B, Python numpy.dot(A,B)
struct Dot_Function : public Polyadic_Function
{
Dot_Function() : Polyadic_Function(2) {}
Value call(Frame& args) override
{
return dot(args[0], args[1], At_Frame(&args));
}
GL_Value gl_call(GL_Frame& f) const override
{
auto a = f[0];
auto b = f[1];
if (gl_type_count(a.type) < 2)
throw Exception(At_GL_Arg(0, f), "dot: argument is not a vector");
if (a.type != b.type)
throw Exception(At_GL_Arg(1, f), "dot: arguments have different types");
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = dot("<<a<<","<<b<<");\n";
return result;
}
};
struct Mag_Function : public Polyadic_Function
{
Mag_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
// TODO: use hypot() or BLAS DNRM2 or Eigen stableNorm/blueNorm?
// Avoids overflow/underflow due to squaring of large/small values.
// Slower. https://forum.kde.org/viewtopic.php?f=74&t=62402
auto& list = arg_to_list(args[0], At_Arg(args));
double sum = 0.0;
for (auto val : list) {
double x = val.get_num_or_nan();
sum += x * x;
}
if (sum == sum)
return {sqrt(sum)};
throw Exception(At_Arg(args), "mag: domain error");
}
GL_Value gl_call(GL_Frame& f) const override
{
auto arg = f[0];
if (gl_type_count(arg.type) < 2)
throw Exception(At_GL_Arg(0, f), "mag: argument is not a vector");
auto result = f.gl.newvalue(GL_Type::Num);
f.gl.out << " float "<<result<<" = length("<<arg<<");\n";
return result;
}
};
struct Count_Function : public Polyadic_Function
{
Count_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
if (auto list = args[0].dycast<const List>())
return {double(list->size())};
if (auto string = args[0].dycast<const String>())
return {double(string->size())};
throw Exception(At_Arg(args), "not a list or string");
}
};
struct Fields_Function : public Polyadic_Function
{
Fields_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
if (auto structure = args[0].dycast<const Structure>())
return {structure->fields()};
throw Exception(At_Arg(args), "not a record");
}
};
struct Strcat_Function : public Polyadic_Function
{
Strcat_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
if (auto list = args[0].dycast<const List>()) {
String_Builder sb;
for (auto val : *list) {
if (auto str = val.dycast<const String>())
sb << str;
else
sb << val;
}
return {sb.get_string()};
}
throw Exception(At_Arg(args), "not a list");
}
};
struct Repr_Function : public Polyadic_Function
{
Repr_Function() : Polyadic_Function(1) {}
Value call(Frame& args) override
{
String_Builder sb;
sb << args[0];
return {sb.get_string()};
}
};
struct Decode_Function : public Polyadic_Function
{
Decode_Function() : Polyadic_Function(1) {}
Value call(Frame& f) override
{
String_Builder sb;
At_Arg cx(f);
auto list = f[0].to<List>(cx);
for (size_t i = 0; i < list->size(); ++i)
sb << (char)arg_to_int((*list)[i], 1, 127, At_Index(i,cx));
return {sb.get_string()};
}
};
struct Encode_Function : public Polyadic_Function
{
Encode_Function() : Polyadic_Function(1) {}
Value call(Frame& f) override
{
List_Builder lb;
At_Arg cx(f);
auto str = f[0].to<String>(cx);
for (size_t i = 0; i < str->size(); ++i)
lb.push_back({(double)(int)str->at(i)});
return {lb.get_list()};
}
};
struct Match_Function : public Polyadic_Function
{
Match_Function() : Polyadic_Function(1) {}
Value call(Frame& f) override
{
At_Arg ctx0(f);
auto list = f[0].to<List>(ctx0);
std::vector<Shared<Function>> cases;
for (size_t i = 0; i < list->size(); ++i)
cases.push_back(list->at(i).to<Function>(At_Index(i,ctx0)));
return {make<Piecewise_Function>(cases)};
}
};
// The filename argument to "file", if it is a relative filename,
// is interpreted relative to the parent directory of the script file from
// which "file" is called.
//
// Because "file" has this hidden parameter (the name of the script file from
// which it is called), it is not a pure function. For this reason, it isn't
// a function value at all, it's a metafunction.
struct File_Expr : public Just_Expression
{
Shared<Operation> arg_;
File_Expr(Shared<const Call_Phrase> src, Shared<Operation> arg)
:
Just_Expression(std::move(src)),
arg_(std::move(arg))
{}
virtual Value eval(Frame& f) const override
{
auto& callphrase = dynamic_cast<const Call_Phrase&>(*source_);
At_Phrase cx(*callphrase.arg_, &f);
Value arg = arg_->eval(f);
auto argstr = arg.to<String>(cx);
namespace fs = boost::filesystem;
fs::path filepath;
auto caller_script_name = source_->location().script().name_;
if (caller_script_name->empty()) {
filepath = fs::path(argstr->c_str());
} else {
filepath = fs::path(caller_script_name->c_str()).parent_path()
/ fs::path(argstr->c_str());
}
auto file = make<File_Script>(make_string(filepath.c_str()), cx);
Program prog{*file, f.system_};
std::unique_ptr<Frame> f2 =
Frame::make(0, f.system_, &f, &callphrase, nullptr);
prog.compile(nullptr, &*f2);
return prog.eval();
}
};
struct File_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<File_Expr>(share(ph), analyse_op(*ph.arg_, env));
}
};
/// The meaning of a call to `print`, such as `print "foo"`.
struct Print_Action : public Just_Action
{
Shared<Operation> arg_;
Print_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
Value arg = arg_->eval(f);
if (auto str = arg.dycast<String>())
f.system_.console() << *str;
else
f.system_.console() << arg;
f.system_.console() << std::endl;
}
};
/// The meaning of the phrase `print` in isolation.
struct Print_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Print_Action>(share(ph), analyse_op(*ph.arg_, env));
}
};
struct Warning_Action : public Just_Action
{
Shared<Operation> arg_;
Warning_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
Value arg = arg_->eval(f);
Shared<String> msg;
if (auto str = arg.dycast<String>())
msg = str;
else
msg = stringify(arg);
Exception exc{At_Phrase(*source_, &f), msg};
f.system_.console() << "WARNING: " << exc << std::endl;
}
};
/// The meaning of the phrase `warning` in isolation.
struct Warning_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Warning_Action>(share(ph), analyse_op(*ph.arg_, env));
}
};
/// The meaning of a call to `error`, such as `error("foo")`.
struct Error_Operation : public Operation
{
Shared<Operation> arg_;
Error_Operation(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Operation(std::move(source)),
arg_(std::move(arg))
{}
[[noreturn]] void run(Frame& f) const
{
Value val = arg_->eval(f);
Shared<const String> msg;
if (auto s = val.dycast<String>())
msg = s;
else
msg = stringify(val);
throw Exception(At_Frame(&f), msg);
}
virtual void exec(Frame& f) const override
{
run(f);
}
virtual Value eval(Frame& f) const override
{
run(f);
}
virtual void generate(Frame& f, List_Builder&) const override
{
run(f);
}
virtual void bind(Frame& f, Record&) const override
{
run(f);
}
};
/// The meaning of the phrase `error` in isolation.
struct Error_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Error_Operation>(share(ph), analyse_op(*ph.arg_, env));
}
};
// exec(expr) -- a debug action that evaluates expr, then discards the result.
// It is used to call functions or scripts for their side effects.
struct Exec_Action : public Just_Action
{
Shared<Operation> arg_;
Exec_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
arg_->eval(f);
}
};
struct Exec_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
return make<Exec_Action>(share(ph), analyse_op(*ph.arg_, env));
}
};
struct Assert_Action : public Just_Action
{
Shared<Operation> arg_;
Assert_Action(
Shared<const Phrase> source,
Shared<Operation> arg)
:
Just_Action(std::move(source)),
arg_(std::move(arg))
{}
virtual void exec(Frame& f) const override
{
Value a = arg_->eval(f);
if (!a.is_bool())
throw Exception(At_Phrase(*source_, &f), "domain error");
bool b = a.get_bool_unsafe();
if (!b)
throw Exception(At_Phrase(*source_, &f), "assertion failed");
}
};
struct Assert_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
auto args = ph.analyse_args(env);
if (args.size() != 1)
throw Exception(At_Phrase(ph, env), "assert: expecting 1 argument");
return make<Assert_Action>(share(ph), args.front());
}
};
struct Assert_Error_Action : public Just_Action
{
Shared<Operation> expected_message_;
Shared<const String> actual_message_;
Shared<Operation> expr_;
Assert_Error_Action(
Shared<const Phrase> source,
Shared<Operation> expected_message,
Shared<const String> actual_message,
Shared<Operation> expr)
:
Just_Action(std::move(source)),
expected_message_(std::move(expected_message)),
actual_message_(std::move(actual_message)),
expr_(std::move(expr))
{}
virtual void exec(Frame& f) const override
{
Value expected_msg_val = expected_message_->eval(f);
auto expected_msg_str = expected_msg_val.to<const String>(
At_Phrase(*expected_message_->source_, &f));
if (actual_message_ != nullptr) {
if (*actual_message_ != *expected_msg_str)
throw Exception(At_Phrase(*source_, &f),
stringify("assertion failed: expected error \"",
expected_msg_str,
"\", actual error \"",
actual_message_,
"\""));
return;
}
Value result;
try {
result = expr_->eval(f);
} catch (Exception& e) {
if (*e.shared_what() != *expected_msg_str) {
throw Exception(At_Phrase(*source_, &f),
stringify("assertion failed: expected error \"",
expected_msg_str,
"\", actual error \"",
e.shared_what(),
"\""));
}
return;
}
throw Exception(At_Phrase(*source_, &f),
stringify("assertion failed: expected error \"",
expected_msg_str,
"\", got value ", result));
}
};
struct Assert_Error_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
auto parens = cast<Paren_Phrase>(ph.arg_);
Shared<Comma_Phrase> commas = nullptr;
if (parens) commas = cast<Comma_Phrase>(parens->body_);
if (parens && commas && commas->args_.size() == 2) {
auto msg = analyse_op(*commas->args_[0].expr_, env);
Shared<Operation> expr = nullptr;
Shared<const String> actual_msg = nullptr;
try {
expr = analyse_op(*commas->args_[1].expr_, env);
} catch (Exception& e) {
actual_msg = e.shared_what();
}
return make<Assert_Error_Action>(share(ph), msg, actual_msg, expr);
} else {
throw Exception(At_Phrase(ph, env),
"assert_error: expecting 2 arguments");
}
}
};
struct Defined_Expression : public Just_Expression
{
Shared<const Operation> expr_;
Atom_Expr selector_;
Defined_Expression(
Shared<const Phrase> source,
Shared<const Operation> expr,
Atom_Expr selector)
:
Just_Expression(std::move(source)),
expr_(std::move(expr)),
selector_(std::move(selector))
{
}
virtual Value eval(Frame& f) const override
{
auto val = expr_->eval(f);
auto s = val.dycast<Structure>();
if (s) {
auto id = selector_.eval(f);
return {s->hasfield(id)};
} else {
return {false};
}
}
};
struct Defined_Metafunction : public Metafunction
{
using Metafunction::Metafunction;
virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override
{
auto arg = analyse_op(*ph.arg_, env);
auto dot = cast<Dot_Expr>(arg);
if (dot != nullptr)
return make<Defined_Expression>(
share(ph), dot->base_, dot->selector_);
throw Exception(At_Phrase(*ph.arg_, env),
"defined: argument must be `expression.identifier`");
}
};
const Namespace&
builtin_namespace()
{
static const Namespace names = {
{"pi", make<Builtin_Value>(pi)},
{"tau", make<Builtin_Value>(two_pi)},
{"inf", make<Builtin_Value>(INFINITY)},
{"null", make<Builtin_Value>(Value())},
{"false", make<Builtin_Value>(Value(false))},
{"true", make<Builtin_Value>(Value(true))},
{"is_null", make<Builtin_Value>(Value{make<Is_Null_Function>()})},
{"is_bool", make<Builtin_Value>(Value{make<Is_Bool_Function>()})},
{"is_num", make<Builtin_Value>(Value{make<Is_Num_Function>()})},
{"is_string", make<Builtin_Value>(Value{make<Is_String_Function>()})},
{"is_list", make<Builtin_Value>(Value{make<Is_List_Function>()})},
{"is_record", make<Builtin_Value>(Value{make<Is_Record_Function>()})},
{"is_fun", make<Builtin_Value>(Value{make<Is_Fun_Function>()})},
{"bit", make<Builtin_Value>(Value{make<Bit_Function>()})},
{"sqrt", make<Builtin_Value>(Value{make<Sqrt_Function>()})},
{"log", make<Builtin_Value>(Value{make<Log_Function>()})},
{"abs", make<Builtin_Value>(Value{make<Abs_Function>()})},
{"floor", make<Builtin_Value>(Value{make<Floor_Function>()})},
{"round", make<Builtin_Value>(Value{make<Round_Function>()})},
{"sin", make<Builtin_Value>(Value{make<Sin_Function>()})},
{"asin", make<Builtin_Value>(Value{make<Asin_Function>()})},
{"cos", make<Builtin_Value>(Value{make<Cos_Function>()})},
{"acos", make<Builtin_Value>(Value{make<Acos_Function>()})},
{"atan2", make<Builtin_Value>(Value{make<Atan2_Function>()})},
{"max", make<Builtin_Value>(Value{make<Max_Function>()})},
{"min", make<Builtin_Value>(Value{make<Min_Function>()})},
{"dot", make<Builtin_Value>(Value{make<Dot_Function>()})},
{"mag", make<Builtin_Value>(Value{make<Mag_Function>()})},
{"count", make<Builtin_Value>(Value{make<Count_Function>()})},
{"fields", make<Builtin_Value>(Value{make<Fields_Function>()})},
{"strcat", make<Builtin_Value>(Value{make<Strcat_Function>()})},
{"repr", make<Builtin_Value>(Value{make<Repr_Function>()})},
{"decode", make<Builtin_Value>(Value{make<Decode_Function>()})},
{"encode", make<Builtin_Value>(Value{make<Encode_Function>()})},
{"match", make<Builtin_Value>(Value{make<Match_Function>()})},
{"file", make<Builtin_Meaning<File_Metafunction>>()},
{"print", make<Builtin_Meaning<Print_Metafunction>>()},
{"warning", make<Builtin_Meaning<Warning_Metafunction>>()},
{"error", make<Builtin_Meaning<Error_Metafunction>>()},
{"assert", make<Builtin_Meaning<Assert_Metafunction>>()},
{"assert_error", make<Builtin_Meaning<Assert_Error_Metafunction>>()},
{"exec", make<Builtin_Meaning<Exec_Metafunction>>()},
{"defined", make<Builtin_Meaning<Defined_Metafunction>>()},
};
return names;
}
} // namespace curv
| 31.75813 | 84 | 0.588096 | iplayfast |
1b88e855a8002879c5a18bafa21bc646d65cfc8e | 13,643 | cpp | C++ | source/lib/PccLibEncoder/source/PCCNormalsGenerator.cpp | Dinghow/mpeg-pcc-tmc2 | 1018e5467ea0d18b879272bcba8c060e1cfd97a9 | [
"BSD-3-Clause"
] | null | null | null | source/lib/PccLibEncoder/source/PCCNormalsGenerator.cpp | Dinghow/mpeg-pcc-tmc2 | 1018e5467ea0d18b879272bcba8c060e1cfd97a9 | [
"BSD-3-Clause"
] | null | null | null | source/lib/PccLibEncoder/source/PCCNormalsGenerator.cpp | Dinghow/mpeg-pcc-tmc2 | 1018e5467ea0d18b879272bcba8c060e1cfd97a9 | [
"BSD-3-Clause"
] | null | null | null | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2017, ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "PCCCommon.h"
#include "PCCKdTree.h"
#include "tbb/tbb.h"
#include "PCCNormalsGenerator.h"
using namespace pcc;
void PCCNormalsGenerator3::init( const size_t pointCount, const PCCNormalsGenerator3Parameters& params ) {
normals_.resize( pointCount );
if ( params.storeNumberOfNearestNeighborsInNormalEstimation_ ) {
numberOfNearestNeighborsInNormalEstimation_.resize( pointCount );
} else {
numberOfNearestNeighborsInNormalEstimation_.resize( 0 );
}
if ( params.storeEigenvalues_ ) {
eigenvalues_.resize( pointCount );
} else {
eigenvalues_.resize( 0 );
}
if ( params.storeCentroids_ ) {
barycenters_.resize( pointCount );
} else {
barycenters_.resize( 0 );
}
}
void PCCNormalsGenerator3::compute( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params,
const size_t nbThread ) {
nbThread_ = nbThread;
init( pointCloud.getPointCount(), params );
computeNormals( pointCloud, kdtree, params );
if ( params.numberOfIterationsInNormalSmoothing_ != 0u ) { smoothNormals( pointCloud, kdtree, params ); }
orientNormals( pointCloud, kdtree, params );
}
void PCCNormalsGenerator3::computeNormal( const size_t index,
const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params,
PCCNNResult& nNResult ) {
PCCVector3D bary( pointCloud[index][0], pointCloud[index][1], pointCloud[index][2] );
PCCVector3D normal( 0.0 );
PCCVector3D eigenval( 0.0 );
PCCMatrix3D covMat;
PCCMatrix3D Q;
PCCMatrix3D D;
kdtree.search( pointCloud[index], params.numberOfNearestNeighborsInNormalEstimation_, nNResult );
if ( nNResult.count() > 1 ) {
bary = 0.0;
for ( size_t i = 0; i < nNResult.count(); ++i ) { bary += pointCloud[nNResult.indices( i )]; }
bary /= double( nNResult.count() );
covMat = 0.0;
PCCVector3D pt;
for ( size_t i = 0; i < nNResult.count(); ++i ) {
pt = pointCloud[nNResult.indices( i )] - bary;
covMat[0][0] += pt[0] * pt[0];
covMat[1][1] += pt[1] * pt[1];
covMat[2][2] += pt[2] * pt[2];
covMat[0][1] += pt[0] * pt[1];
covMat[0][2] += pt[0] * pt[2];
covMat[1][2] += pt[1] * pt[2];
}
covMat[1][0] = covMat[0][1];
covMat[2][0] = covMat[0][2];
covMat[2][1] = covMat[1][2];
covMat /= ( nNResult.count() - 1.0 );
PCCDiagonalize( covMat, Q, D );
D[0][0] = fabs( D[0][0] );
D[1][1] = fabs( D[1][1] );
D[2][2] = fabs( D[2][2] );
if ( D[0][0] < D[1][1] && D[0][0] < D[2][2] ) {
normal[0] = Q[0][0];
normal[1] = Q[1][0];
normal[2] = Q[2][0];
eigenval[0] = D[0][0];
if ( D[1][1] < D[2][2] ) {
eigenval[1] = D[1][1];
eigenval[2] = D[2][2];
} else {
eigenval[2] = D[1][1];
eigenval[1] = D[2][2];
}
} else if ( D[1][1] < D[2][2] ) {
normal[0] = Q[0][1];
normal[1] = Q[1][1];
normal[2] = Q[2][1];
eigenval[0] = D[1][1];
if ( D[0][0] < D[2][2] ) {
eigenval[1] = D[0][0];
eigenval[2] = D[2][2];
} else {
eigenval[2] = D[0][0];
eigenval[1] = D[2][2];
}
} else {
normal[0] = Q[0][2];
normal[1] = Q[1][2];
normal[2] = Q[2][2];
eigenval[0] = D[2][2];
if ( D[0][0] < D[1][1] ) {
eigenval[1] = D[0][0];
eigenval[2] = D[1][1];
} else {
eigenval[2] = D[0][0];
eigenval[1] = D[1][1];
}
}
}
if ( normal * ( params.viewPoint_ - pointCloud[index] ) < 0.0 ) {
normals_[index] = -normal;
} else {
normals_[index] = normal;
}
if ( params.storeEigenvalues_ ) { eigenvalues_[index] = eigenval; }
if ( params.storeCentroids_ ) { barycenters_[index] = bary; }
if ( params.storeNumberOfNearestNeighborsInNormalEstimation_ ) {
numberOfNearestNeighborsInNormalEstimation_[index] = uint32_t( nNResult.count() );
}
}
void PCCNormalsGenerator3::computeNormals( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params ) {
const size_t pointCount = pointCloud.getPointCount();
normals_.resize( pointCount );
std::vector<size_t> subRanges;
const size_t chunckCount = 64;
PCCDivideRange( 0, pointCount, chunckCount, subRanges );
tbb::task_arena limited( static_cast<int>( nbThread_ ) );
limited.execute( [&] {
tbb::parallel_for( size_t( 0 ), subRanges.size() - 1, [&]( const size_t i ) {
const size_t start = subRanges[i];
const size_t end = subRanges[i + 1];
PCCNNResult nNResult;
for ( size_t ptIndex = start; ptIndex < end; ++ptIndex ) {
computeNormal( ptIndex, pointCloud, kdtree, params, nNResult );
}
} );
} );
}
void PCCNormalsGenerator3::orientNormals( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params ) {
if ( params.orientationStrategy_ == PCC_NORMALS_GENERATOR_ORIENTATION_SPANNING_TREE ) {
const size_t pointCount = pointCloud.getPointCount();
PCCNNResult nNResult;
visited_.resize( pointCount );
std::fill( visited_.begin(), visited_.end(), 0 );
PCCNNQuery3 nNQuery = {PCCPoint3D( 0.0 ),
static_cast<float>( params.radiusNormalOrientation_ ) * params.radiusNormalOrientation_,
params.numberOfNearestNeighborsInNormalOrientation_};
PCCNNQuery3 nNQuery2 = {PCCPoint3D( 0.0 ), ( std::numeric_limits<float>::max )(),
params.numberOfNearestNeighborsInNormalOrientation_};
size_t processedPointCount = 0;
for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) {
if ( visited_[ptIndex] == 0u ) {
visited_[ptIndex] = 1;
++processedPointCount;
size_t numberOfNormals;
PCCVector3D accumulatedNormals;
addNeighbors( uint32_t( ptIndex ), pointCloud, kdtree, nNQuery2, nNResult, accumulatedNormals,
numberOfNormals );
if ( numberOfNormals == 0u ) {
if ( ptIndex != 0u ) {
accumulatedNormals = normals_[ptIndex - 1];
} else {
accumulatedNormals = ( params.viewPoint_ - pointCloud[ptIndex] );
}
}
if ( normals_[ptIndex] * accumulatedNormals < 0.0 ) { normals_[ptIndex] = -normals_[ptIndex]; }
while ( !edges_.empty() ) {
PCCWeightedEdge edge = edges_.top();
edges_.pop();
uint32_t current = edge.end_;
if ( visited_[current] == 0u ) {
visited_[current] = 1;
++processedPointCount;
if ( normals_[edge.start_] * normals_[current] < 0.0 ) { normals_[current] = -normals_[current]; }
addNeighbors( current, pointCloud, kdtree, nNQuery, nNResult, accumulatedNormals, numberOfNormals );
}
}
}
}
size_t negNormalCount = 0;
for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) {
negNormalCount +=
static_cast<unsigned long long>( normals_[ptIndex] * ( params.viewPoint_ - pointCloud[ptIndex] ) < 0.0 );
}
if ( negNormalCount > ( pointCount + 1 ) / 2 ) {
for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) { normals_[ptIndex] = -normals_[ptIndex]; }
}
} else if ( params.orientationStrategy_ == PCC_NORMALS_GENERATOR_ORIENTATION_VIEW_POINT ) {
const size_t pointCount = pointCloud.getPointCount();
tbb::task_arena limited( static_cast<int>( nbThread_ ) );
limited.execute( [&] {
tbb::parallel_for( size_t( 0 ), pointCount, [&]( const size_t ptIndex ) {
if ( normals_[ptIndex] * ( params.viewPoint_ - pointCloud[ptIndex] ) < 0.0 ) {
normals_[ptIndex] = -normals_[ptIndex];
}
} );
} );
}
}
void PCCNormalsGenerator3::addNeighbors( const uint32_t current,
const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
PCCNNQuery3& nNQuery,
PCCNNResult& nNResult,
PCCVector3D& accumulatedNormals,
size_t& numberOfNormals ) {
accumulatedNormals = 0.0;
numberOfNormals = 0;
if ( nNQuery.radius > 32768.0 ) {
kdtree.search( pointCloud[current], nNQuery.nearestNeighborCount, nNResult );
} else {
kdtree.searchRadius( pointCloud[current], nNQuery.nearestNeighborCount, nNQuery.radius, nNResult );
}
PCCWeightedEdge newEdge;
uint32_t index;
for ( size_t i = 0; i < nNResult.count(); ++i ) {
index = static_cast<uint32_t>( nNResult.indices( i ) );
if ( visited_[index] == 0u ) {
newEdge.weight_ = fabs( normals_[current] * normals_[index] );
newEdge.end_ = index;
newEdge.start_ = current;
edges_.push( newEdge );
} else if ( index != current ) {
accumulatedNormals += normals_[index];
++numberOfNormals;
}
}
}
void PCCNormalsGenerator3::smoothNormals( const PCCPointSet3& pointCloud,
const PCCKdTree& kdtree,
const PCCNormalsGenerator3Parameters& params ) {
const double w2 = params.weightNormalSmoothing_;
const double w0 = ( 1 - w2 );
const size_t pointCount = pointCloud.getPointCount();
PCCVector3D n0;
PCCVector3D n1;
PCCVector3D n2;
std::vector<size_t> subRanges;
const size_t chunckCount = 64;
PCCDivideRange( 0, pointCount, chunckCount, subRanges );
const double radius = params.radiusNormalSmoothing_ * params.radiusNormalSmoothing_;
for ( size_t it = 0; it < params.numberOfIterationsInNormalSmoothing_; ++it ) {
tbb::task_arena limited( static_cast<int>( nbThread_ ) );
limited.execute( [&] {
tbb::parallel_for( size_t( 0 ), subRanges.size() - 1, [&]( const size_t i ) {
const size_t start = subRanges[i];
const size_t end = subRanges[i + 1];
PCCNNResult result;
for ( size_t ptIndex = start; ptIndex < end; ++ptIndex ) {
kdtree.searchRadius( pointCloud[ptIndex], params.numberOfNearestNeighborsInNormalSmoothing_, radius, result );
n0 = normals_[ptIndex];
n1 = 0.0;
for ( size_t i = 1; i < result.count(); ++i ) {
n2 = normals_[result.indices( i )];
if ( n0 * n2 < 0.0 ) {
n1 -= n2;
} else {
n1 += n2;
}
}
n1.normalize();
n1 = w0 * n0 + w2 * n1;
n1.normalize();
normals_[ptIndex] = n1;
}
} );
} );
}
}
| 44.152104 | 121 | 0.564978 | Dinghow |
1b8a52d6a1f2b485a9f6a9701005c7f41033b698 | 4,737 | cpp | C++ | plugins/WinVST/UltrasonX/UltrasonX.cpp | themucha/airwindows | 13bace268f2356e2a037e935c0845d91bfcb79a6 | [
"MIT"
] | null | null | null | plugins/WinVST/UltrasonX/UltrasonX.cpp | themucha/airwindows | 13bace268f2356e2a037e935c0845d91bfcb79a6 | [
"MIT"
] | null | null | null | plugins/WinVST/UltrasonX/UltrasonX.cpp | themucha/airwindows | 13bace268f2356e2a037e935c0845d91bfcb79a6 | [
"MIT"
] | null | null | null | /* ========================================
* UltrasonX - UltrasonX.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#ifndef __UltrasonX_H
#include "UltrasonX.h"
#endif
AudioEffect* createEffectInstance(audioMasterCallback audioMaster) {return new UltrasonX(audioMaster);}
UltrasonX::UltrasonX(audioMasterCallback audioMaster) :
AudioEffectX(audioMaster, kNumPrograms, kNumParameters)
{
A = 0.5;
for (int x = 0; x < fix_total; x++) {fixA[x] = 0.0;}
fixA[fix_reso] = 0.7071; //butterworth Q
fpdL = 1.0; while (fpdL < 16386) fpdL = rand()*UINT32_MAX;
fpdR = 1.0; while (fpdR < 16386) fpdR = rand()*UINT32_MAX;
//this is reset: values being initialized only once. Startup values, whatever they are.
_canDo.insert("plugAsChannelInsert"); // plug-in can be used as a channel insert effect.
_canDo.insert("plugAsSend"); // plug-in can be used as a send effect.
_canDo.insert("x2in2out");
setNumInputs(kNumInputs);
setNumOutputs(kNumOutputs);
setUniqueID(kUniqueId);
canProcessReplacing(); // supports output replacing
canDoubleReplacing(); // supports double precision processing
programsAreChunks(true);
vst_strncpy (_programName, "Default", kVstMaxProgNameLen); // default program name
}
UltrasonX::~UltrasonX() {}
VstInt32 UltrasonX::getVendorVersion () {return 1000;}
void UltrasonX::setProgramName(char *name) {vst_strncpy (_programName, name, kVstMaxProgNameLen);}
void UltrasonX::getProgramName(char *name) {vst_strncpy (name, _programName, kVstMaxProgNameLen);}
//airwindows likes to ignore this stuff. Make your own programs, and make a different plugin rather than
//trying to do versioning and preventing people from using older versions. Maybe they like the old one!
static float pinParameter(float data)
{
if (data < 0.0f) return 0.0f;
if (data > 1.0f) return 1.0f;
return data;
}
VstInt32 UltrasonX::getChunk (void** data, bool isPreset)
{
float *chunkData = (float *)calloc(kNumParameters, sizeof(float));
chunkData[0] = A;
*data = chunkData;
return kNumParameters * sizeof(float);
}
VstInt32 UltrasonX::setChunk (void* data, VstInt32 byteSize, bool isPreset)
{
float *chunkData = (float *)data;
A = pinParameter(chunkData[0]);
/* We're ignoring byteSize as we found it to be a filthy liar */
/* calculate any other fields you need here - you could copy in
code from setParameter() here. */
return 0;
}
void UltrasonX::setParameter(VstInt32 index, float value) {
switch (index) {
case kParamA: A = value; break;
default: throw; // unknown parameter, shouldn't happen!
}
}
float UltrasonX::getParameter(VstInt32 index) {
switch (index) {
case kParamA: return A; break;
default: break; // unknown parameter, shouldn't happen!
} return 0.0; //we only need to update the relevant name, this is simple to manage
}
void UltrasonX::getParameterName(VstInt32 index, char *text) {
switch (index) {
case kParamA: vst_strncpy (text, "Q", kVstMaxParamStrLen); break;
default: break; // unknown parameter, shouldn't happen!
} //this is our labels for displaying in the VST host
}
void UltrasonX::getParameterDisplay(VstInt32 index, char *text) {
switch (index) {
case kParamA: switch((VstInt32)( A * 4.999 )) //0 to almost edge of # of params
{ case kA: vst_strncpy (text, "Reso A", kVstMaxParamStrLen); break;
case kB: vst_strncpy (text, "Reso B", kVstMaxParamStrLen); break;
case kC: vst_strncpy (text, "Reso C", kVstMaxParamStrLen); break;
case kD: vst_strncpy (text, "Reso D", kVstMaxParamStrLen); break;
case kE: vst_strncpy (text, "Reso E", kVstMaxParamStrLen); break;
default: break; // unknown parameter, shouldn't happen!
} break;
default: break; // unknown parameter, shouldn't happen!
} //this displays the values and handles 'popups' where it's discrete choices
}
void UltrasonX::getParameterLabel(VstInt32 index, char *text) {
switch (index) {
case kParamA: vst_strncpy (text, "", kVstMaxParamStrLen); break;
default: break; // unknown parameter, shouldn't happen!
}
}
VstInt32 UltrasonX::canDo(char *text)
{ return (_canDo.find(text) == _canDo.end()) ? -1: 1; } // 1 = yes, -1 = no, 0 = don't know
bool UltrasonX::getEffectName(char* name) {
vst_strncpy(name, "UltrasonX", kVstMaxProductStrLen); return true;
}
VstPlugCategory UltrasonX::getPlugCategory() {return kPlugCategEffect;}
bool UltrasonX::getProductString(char* text) {
vst_strncpy (text, "airwindows UltrasonX", kVstMaxProductStrLen); return true;
}
bool UltrasonX::getVendorString(char* text) {
vst_strncpy (text, "airwindows", kVstMaxVendorStrLen); return true;
}
| 37.007813 | 104 | 0.695799 | themucha |
b8440821b6c2207c4e18a7d8705d5c5f3141435e | 9,091 | cpp | C++ | src/select/select_impl.cpp | b1nhm1nh/zsummerX | 0825d2a3b7476df614411c65a59f94df4fb927f6 | [
"MIT"
] | 343 | 2015-01-23T09:48:53.000Z | 2022-03-17T04:42:22.000Z | src/select/select_impl.cpp | zhuguang/zsummerX | 8e2e355aaa2f64d37348633ea5c2f1ec44a54152 | [
"MIT"
] | 22 | 2015-05-06T13:47:17.000Z | 2021-04-11T11:39:51.000Z | src/select/select_impl.cpp | zhuguang/zsummerX | 8e2e355aaa2f64d37348633ea5c2f1ec44a54152 | [
"MIT"
] | 178 | 2015-02-13T03:30:10.000Z | 2022-03-17T04:42:13.000Z | /*
* zsummerX License
* -----------
*
* zsummerX is licensed under the terms of the MIT license reproduced below.
* This means that zsummerX is free software and can be used for both academic
* and commercial purposes at absolutely no cost.
*
*
* ===============================================================================
*
* Copyright (C) 2010-2017 YaweiZhang <[email protected]>.
*
* 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.
*
* ===============================================================================
*
* (end of COPYRIGHT)
*/
#include <zsummerX/select/select_impl.h>
#include <zsummerX/select/tcpsocket_impl.h>
#include <zsummerX/select/tcpaccept_impl.h>
#include <zsummerX/select/udpsocket_impl.h>
using namespace zsummer::network;
bool EventLoop::initialize()
{
//////////////////////////////////////////////////////////////////////////
//create socket pair
sockaddr_in pairAddr;
memset(&pairAddr, 0, sizeof(pairAddr));
pairAddr.sin_family = AF_INET;
pairAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int acpt = socket(AF_INET, SOCK_STREAM, 0);
_sockpair[0] = socket(AF_INET, SOCK_STREAM, 0);
_sockpair[1] = socket(AF_INET, SOCK_STREAM, 0);
if (_sockpair[0] == -1 || _sockpair[1] == -1 || acpt == -1)
{
LCF("ZSummerImpl::initialize[this0x" << this << "] bind sockpair socket error. " );
return false;
}
if (::bind(acpt, (sockaddr*)&pairAddr, sizeof(pairAddr)) == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] bind sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
if (listen(acpt, 1) == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] listen sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
socklen_t len = sizeof(pairAddr);
if (getsockname(acpt, (sockaddr*)&pairAddr, &len) != 0)
{
LCF("EventLoop::initialize[this0x" << this << "] getsockname sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
if (::connect(_sockpair[0], (sockaddr*)&pairAddr, sizeof(pairAddr)) == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] connect sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
_sockpair[1] = accept(acpt, (sockaddr*)&pairAddr, &len);
if (_sockpair[1] == -1)
{
LCF("EventLoop::initialize[this0x" << this << "] accept sockpair socket error. " );
::close(acpt);
::close(_sockpair[0]);
::close(_sockpair[1]);
return false;
}
::close(acpt);
setNonBlock(_sockpair[0]);
setNonBlock(_sockpair[1]);
setNoDelay(_sockpair[0]);
setNoDelay(_sockpair[1]);
FD_ZERO(&_fdreads);
FD_ZERO(&_fdwrites);
FD_ZERO(&_fderrors);
setEvent(_sockpair[1], 0);
_arrayTcpAccept.resize(MAX_NUMBER_FD);
_arrayTcpSocket.resize(MAX_NUMBER_FD);
_arrayUdpSocket.resize(MAX_NUMBER_FD);
return true;
}
void EventLoop::setEvent(int fd, int op /*0 read, 1 write, 2 error*/)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
if (fd > _maxfd)
_maxfd = fd;
if (op == 0)
FD_SET(fd, &_fdreads);
else if(op == 1)
FD_SET(fd, &_fdwrites);
else if(op == 2)
FD_SET(fd, &_fderrors);
}
void EventLoop::unsetEvent(int fd, int op /*0 read, 1 write, 2 error*/)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
if (op == 0)
FD_CLR(fd, &_fdreads);
else if(op == 1)
FD_CLR(fd, &_fdwrites);
else if(op == 2)
FD_CLR(fd, &_fderrors);
}
void EventLoop::addTcpAccept(int fd, TcpAcceptPtr s)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
_arrayTcpAccept[fd] = s;
}
void EventLoop::addTcpSocket(int fd, TcpSocketPtr s)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
_arrayTcpSocket[fd] = s;
}
void EventLoop::addUdpSocket(int fd, UdpSocketPtr s)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
_arrayUdpSocket[fd] = s;
}
void EventLoop::clearSocket(int fd)
{
if (fd >= MAX_NUMBER_FD)
{
LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD);
return;
}
unsetEvent(fd, 0);
unsetEvent(fd, 1);
unsetEvent(fd, 2);
_arrayTcpAccept[fd].reset();
_arrayTcpSocket[fd].reset();
_arrayUdpSocket[fd].reset();
}
void EventLoop::PostMessage(_OnPostHandler &&handle)
{
_OnPostHandler * pHandler = new _OnPostHandler(std::move(handle));
bool needNotice = false;
_postQueueLock.lock();
if (_postQueue.empty()){ needNotice = true;}
_postQueue.push_back(pHandler);
_postQueueLock.unlock();
if (needNotice)
{
char c = '0';
send(_sockpair[0], &c, 1, 0);
}
}
std::string EventLoop::logSection()
{
std::stringstream os;
_postQueueLock.lock();
MessageStack::size_type msgSize = _postQueue.size();
_postQueueLock.unlock();
os << " logSection: _sockpair[2]={" << _sockpair[0] << "," << _sockpair[1] << "}"
<< " _postQueue.size()=" << msgSize << ", current total timer=" << _timer.getTimersCount()
<< " _maxfd=" << _maxfd;
return os.str();
}
void EventLoop::runOnce(bool isImmediately)
{
fd_set fdr;
fd_set fdw;
fd_set fde;
memcpy(&fdr, &_fdreads, sizeof(_fdreads));
memcpy(&fdw, &_fdwrites, sizeof(_fdwrites));
memcpy(&fde, &_fderrors, sizeof(_fderrors));
timeval tv;
if (isImmediately)
{
tv.tv_sec = 0;
tv.tv_usec = 0;
}
else
{
unsigned int ms = _timer.getNextExpireTime();
tv.tv_sec = ms / 1000;
tv.tv_usec = (ms % 1000) * 1000;
}
int retCount = ::select(_maxfd+1, &fdr, &fdw, &fde, &tv);
if (retCount == -1)
{
return;
}
//check timer
{
_timer.checkTimer();
if (retCount == 0) return;//timeout
}
if (FD_ISSET(_sockpair[1], &fdr))
{
char buf[1000];
while (recv(_sockpair[1], buf, 1000, 0) > 0);
MessageStack msgs;
_postQueueLock.lock();
msgs.swap(_postQueue);
_postQueueLock.unlock();
for (auto pfunc : msgs)
{
_OnPostHandler * p = (_OnPostHandler*)pfunc;
try
{
(*p)();
}
catch (const std::exception & e)
{
LCW("OnPostHandler have runtime_error exception. err=" << e.what());
}
catch (...)
{
LCW("OnPostHandler have unknown exception.");
}
delete p;
}
}
for (int i = 0; i <= _maxfd ; ++i)
{
//tagHandle type
if (FD_ISSET(i, &fdr) || FD_ISSET(i, &fdw) || FD_ISSET(i, &fde))
{
if (_arrayTcpAccept[i])
_arrayTcpAccept[i]->onSelectMessage();
if (_arrayTcpSocket[i])
{
_arrayTcpSocket[i]->onSelectMessage(FD_ISSET(i, &fdr), FD_ISSET(i, &fdw), FD_ISSET(i, &fde));
}
if (_arrayUdpSocket[i])
{
_arrayUdpSocket[i]->onSelectMessage(FD_ISSET(i, &fdr), FD_ISSET(i, &fdw), FD_ISSET(i, &fde));
}
}
}
}
| 29.420712 | 109 | 0.571554 | b1nhm1nh |
b84602d59cb7ef68d70b89dd04d7c07da56ae332 | 625 | ipp | C++ | libs/config/test/boost_no_std_typeinfo.ipp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 11 | 2015-07-12T13:04:52.000Z | 2021-05-30T23:23:46.000Z | libs/config/test/boost_no_std_typeinfo.ipp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | null | null | null | libs/config/test/boost_no_std_typeinfo.ipp | sdfict/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 3 | 2015-12-23T01:51:57.000Z | 2019-08-25T04:58:32.000Z | // (C) Copyright Peter Dimov 2007.
// Use, modification and distribution are 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)
// See http://www.boost.org/libs/config for most recent version.
// MACRO: BOOST_NO_STD_TYPEINFO
// TITLE: type_info not in namespace std
// DESCRIPTION: The <typeinfo> header declares type_info in the global namespace instead of std
#include <typeinfo>
namespace boost_no_std_typeinfo
{
int test()
{
std::type_info * p = 0;
return 0;
}
}
| 25 | 99 | 0.6768 | zyiacas |
b84757937bcb1064675cd86e3362120718882383 | 3,240 | cpp | C++ | labs3_17142.cpp | goongg/SamSung | d07f8ca06fa21c2c26f63f89978b79a204373262 | [
"CECILL-B"
] | null | null | null | labs3_17142.cpp | goongg/SamSung | d07f8ca06fa21c2c26f63f89978b79a204373262 | [
"CECILL-B"
] | null | null | null | labs3_17142.cpp | goongg/SamSung | d07f8ca06fa21c2c26f63f89978b79a204373262 | [
"CECILL-B"
] | null | null | null | //연구소 3 다시풀기 8시 40분
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
#define debug 0
int dx[4] ={ -1, 0, 1, 0};
int dy[4] ={ 0, 1, 0, -1 };
class lab
{
public:
int n, m;
vector<int> t;
vector<int> vis;
int blac=0;
int time;
void input()
{
cin>>n >> m;
t= vector<int>(n*n);
for(int i=0; i<n*n; i++){
cin>> t[i];
if(t[i]==2) vis.push_back(i);
if(t[i]==0) blac++;
}
}
int spread(vector<int> selected)
{
vector<int> nt =t; //퍼진 후 멥
queue<int> q_vis;
vector<int> sp_t(n*n); //각 칸에 퍼진 시간을 기록
int spread_time=0;
int sp_area=0;
#if debug
cout<<"\n selected :" ;
#endif
for(int i: selected) //활성 비이러스로 바꾸기, 활성 바이러스는 4로 표시
{
nt[i] = 4;
q_vis.push(i);
#if debug
cout<<i<<" ";
#endif
}
while(!q_vis.empty())
{
int cur = q_vis.front();
q_vis.pop();
int x = cur%n;
int y = cur/n;
for(int j=0; j<4 ;j++)//현재 위치를 기준으로 4방향 조사
{
int nx= x+dx[j];
int ny= y+dy[j];
if(nx>=n || nx<0 || ny>=n || ny<0 ) continue; //큐에 넣을 필요 없는놈들
if(nt[ny*n+nx]==1 || nt[ny*n+nx]==4) continue;
if(t[ny*n+nx]==0) sp_area++;
sp_t[ny*n+nx] = sp_t[cur]+1; // 이 칸에 최초로 퍼진 시간은, 이칸을 퍼트린 놈의 시간 +1
if( spread_time < sp_t[cur]+1 && t[ny*n+nx]==0 ) spread_time = sp_t[cur]+1 ;
// 저 조건들을 제외하면 0 또는 2(비 활성 바이러스)
nt[ny*n+nx] = 4; //활성 시켜주고
q_vis.push(ny*n+nx); //다음에 여기서부터 뻗어가도록 추가
}
#if debug
cout<<endl;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
char a;
if(t[i*n+j]==1) a='-';
else if(t[i*n+j]==2) a='*';
else a= to_string(sp_t[i*n+j])[0];
cout<< a<<" ";
}
cout<<endl;
}
cout<<endl;
#endif
}
if(sp_area == blac)
return spread_time;
else
return -1;
}
int sol()
{
input();
// if(vis.size()==0 && blac !=0) return -1;
if(blac ==0) return 0;
//vis 중에 m개를 선택
int min_time=999999;
int time;
vector<int> selected;
vector<bool> combintaion;
for(int i=0; i<m; i++)
combintaion.push_back(1);
while(combintaion.size() < vis.size()) combintaion.push_back(0);
sort(combintaion.begin(), combintaion.end());
do
{
for(int i=0; i<combintaion.size(); i++)
if(combintaion[i]) selected.push_back(vis[i]);
time= spread(selected);
if(time <min_time && time != -1) min_time=time;
selected.clear();
selected.resize(0);
}while(next_permutation(combintaion.begin(), combintaion.end()));
if(min_time != 999999)
return min_time;
else
return -1;
}
};
int main()
{
lab l;
cout<<l.sol();
return 0;
} | 21.315789 | 100 | 0.437346 | goongg |
b8478a49f898e10c0bb161004640961b96364e04 | 1,492 | cpp | C++ | platform/glfw/glfw_renderer_frontend.cpp | gomapi/gomapi-sdk-ios | e494bf0b31f612b5547e2830c1179ecd8bf350ed | [
"BSL-1.0",
"Apache-2.0"
] | 5 | 2019-12-02T07:13:06.000Z | 2019-12-02T14:34:36.000Z | platform/glfw/glfw_renderer_frontend.cpp | gomapi/gomapi-sdk-ios | e494bf0b31f612b5547e2830c1179ecd8bf350ed | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2021-05-28T03:48:40.000Z | 2021-05-28T03:48:40.000Z | platform/glfw/glfw_renderer_frontend.cpp | gomapi/gomapi-sdk-ios | e494bf0b31f612b5547e2830c1179ecd8bf350ed | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2020-02-12T14:00:22.000Z | 2020-02-12T14:00:22.000Z | #include "glfw_renderer_frontend.hpp"
#include <mbgl/renderer/renderer.hpp>
#include <mbgl/gfx/backend_scope.hpp>
GLFWRendererFrontend::GLFWRendererFrontend(std::unique_ptr<mbgl::Renderer> renderer_, GLFWView& glfwView_)
: glfwView(glfwView_)
, renderer(std::move(renderer_)) {
glfwView.setRenderFrontend(this);
}
GLFWRendererFrontend::~GLFWRendererFrontend() = default;
void GLFWRendererFrontend::reset() {
assert(renderer);
renderer.reset();
}
void GLFWRendererFrontend::setObserver(mbgl::RendererObserver& observer) {
assert(renderer);
renderer->setObserver(&observer);
}
void GLFWRendererFrontend::update(std::shared_ptr<mbgl::UpdateParameters> params) {
updateParameters = std::move(params);
glfwView.invalidate();
}
void GLFWRendererFrontend::render() {
assert(renderer);
if (!updateParameters) return;
mbgl::gfx::BackendScope guard { glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit };
// onStyleImageMissing might be called during a render. The user implemented method
// could trigger a call to MGLRenderFrontend#update which overwrites `updateParameters`.
// Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is
// still using them.
auto updateParameters_ = updateParameters;
renderer->render(*updateParameters_);
}
mbgl::Renderer* GLFWRendererFrontend::getRenderer() {
assert(renderer);
return renderer.get();
}
| 31.083333 | 114 | 0.735925 | gomapi |
b8484451cf9ee98b67f41ee32d67249456d1ea73 | 5,912 | cpp | C++ | app/application.cpp | Lut1n/Vulkan-BrickBreaker | 05b2c9a59277d2a18e4ba8085ccc77ce620a8ca8 | [
"MIT"
] | 1 | 2020-06-15T01:44:13.000Z | 2020-06-15T01:44:13.000Z | app/application.cpp | Lut1n/Vulkan-BrickBreaker | 05b2c9a59277d2a18e4ba8085ccc77ce620a8ca8 | [
"MIT"
] | null | null | null | app/application.cpp | Lut1n/Vulkan-BrickBreaker | 05b2c9a59277d2a18e4ba8085ccc77ce620a8ca8 | [
"MIT"
] | null | null | null | #include "application.h"
#include "game/brick.h"
#include "game/paddle.h"
#include "game/platform.h"
#include "game/background.h"
#include "game/camera.h"
#include "game/ball.h"
//--------------------------------------------------------------
MiniVkApplication::MiniVkApplication()
: currentFrame(0)
, framebufferResized(false)
, m_window(nullptr)
{
}
//--------------------------------------------------------------
MiniVkApplication::~MiniVkApplication()
{
}
//--------------------------------------------------------------
void MiniVkApplication::run() {
initWindow();
initVulkan();
initScene();
mainLoop();
cleanup();
}
//--------------------------------------------------------------
void MiniVkApplication::initWindow()
{
glfwInit();
// dont create OGL context
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
// special case of resizing (disable for this time)
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
m_window = glfwCreateWindow(APP_WIDTH, APP_HEIGHT, "Brick Breaker with Vulkan", nullptr, nullptr);
glfwSetWindowUserPointer(m_window, this);
glfwSetFramebufferSizeCallback(m_window, framebufferResizeCallback);
}
//--------------------------------------------------------------
void MiniVkApplication::framebufferResizeCallback(GLFWwindow* window, int /*width*/, int /*height*/)
{
auto app = reinterpret_cast<MiniVkApplication*>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
//--------------------------------------------------------------
void MiniVkApplication::initVulkan()
{
m_gcore = new GraphicsCore(m_window);
m_gcore->initialize();
m_swapchain = new SwapChainResources(m_gcore->device(), m_gcore->surface());
m_swapchain->initialize();
m_descpool = new DescriptorPool(m_gcore->device(), m_swapchain->count(), 10);
m_pipeline = new ShaderPipeline(m_gcore->device(), m_swapchain->getRenderPass(), m_swapchain->getSwapChain()->getExtent());
m_drawcmd = new DrawCommandBuffer(m_swapchain, m_pipeline->pipeline());
m_drawcmd->initialize();
m_sync = new Synchronization(m_gcore->device());
m_sync->initialize();
}
//--------------------------------------------------------------
void MiniVkApplication::initScene()
{
m_assets = new AssetsLoader(m_gcore->device(), m_descpool, m_pipeline->layout());
m_drawables = new DrawableAllocator(m_gcore->device(), m_swapchain, m_pipeline->layout(), m_descpool);
Camera* cam = new Camera(30.0, m_gcore->device(), m_descpool, m_pipeline->layout(), m_swapchain);
m_sceneObjects.setView(cam);
Paddle* paddle = new Paddle();
paddle->position.y = -6.0;
m_sceneObjects.add(paddle);
m_collisions.setPaddle(paddle);
std::srand(0);
float depf = 1.4;
for(int x=0;x<20;++x) for(int y=0;y<5;++y)
{
float xf = float(x) * depf - 13.0;
float yf = float(y) * depf + 3.5;
Brick* brick = new Brick();
brick->position.x = xf;
brick->position.y = yf;
brick->color.x = float(std::rand())/RAND_MAX;
brick->color.y = float(std::rand())/RAND_MAX;
brick->color.z = float(std::rand())/RAND_MAX;
brick->m_timeOffset = float(std::rand());
m_sceneObjects.add(brick);
m_collisions.addBrick(brick);
}
Platform* platform = new Platform();
platform->position.y = -10.0;
m_sceneObjects.add(platform);
m_collisions.setPlatform(platform);
Background* background = new Background();
background->position.z = -2.0;
m_sceneObjects.add(background);
Ball* ball = new Ball();
m_sceneObjects.add(ball);
m_collisions.setBall(ball);
}
//--------------------------------------------------------------
void MiniVkApplication::mainLoop()
{
while (!glfwWindowShouldClose(m_window))
{
glfwPollEvents();
drawFrame();
}
vkDeviceWaitIdle(m_gcore->device()->get());
}
//--------------------------------------------------------------
void MiniVkApplication::drawFrame()
{
m_sync->waitForFence();
uint32_t imageIndex = m_swapchain->getSwapChain()->acquireNextImage(m_sync->getImgAvailableSemaphore());
m_sceneObjects.updateState(m_window);
m_sceneObjects.animateScene();
m_collisions.checkCollisions();
m_sceneObjects.updateUniform(imageIndex);
m_drawcmd->beginDraw(imageIndex);
m_drawcmd->drawScene(&m_sceneObjects);
m_drawcmd->endDraw();
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = {m_sync->getImgAvailableSemaphore()};
VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &m_drawcmd->get(imageIndex)->get();
VkSemaphore signalSemaphores[] = {m_sync->getRenderFinishedSemaphore()};
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
m_sync->resetFence();
if (vkQueueSubmit(m_gcore->device()->getGraphicQueue()->get(), 1, &submitInfo, m_sync->getFence()) != VK_SUCCESS)
{
throw std::runtime_error("failed to submit draw command buffer!");
}
m_gcore->device()->getPresentQueue()->present(m_sync->getRenderFinishedSemaphore(), m_swapchain->getSwapChain(), imageIndex);
m_sync->nextFrame();
m_gcore->device()->getPresentQueue()->wait();
}
//--------------------------------------------------------------
void MiniVkApplication::cleanup()
{
glfwDestroyWindow(m_window);
glfwTerminate();
}
| 30.791667 | 130 | 0.594384 | Lut1n |
b85420fdf60791b0a6e3b9d29c2984bd67cf6921 | 2,214 | cc | C++ | test/test_fseek.cc | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | 1 | 2020-09-10T16:47:09.000Z | 2020-09-10T16:47:09.000Z | test/test_fseek.cc | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | null | null | null | test/test_fseek.cc | menonfled/menon_cpp_lib | 729bb581023e7558360fd17ac0866e20b2d7ec40 | [
"BSL-1.0"
] | null | null | null | // test_fseek.cc
#include "menon/io.hh"
#include <boost/core/lightweight_test.hpp>
#include <cstddef>
#include <vector>
#include <fstream>
// テストデータの作成
long long make_test_file(char const* path)
{
std::vector<std::byte> v(256, std::byte(123));
if (auto stream = std::fopen(path, "wb"))
{
std::fwrite(v.data(), 1, v.size(), stream);
std::fclose(stream);
}
return static_cast<long long>(v.size());
}
int main()
{
char const* path = "test.data";
[[maybe_unused]] auto n = make_test_file(path);
{ // fseek/ftell関数の基本的な使い方
auto stream = std::fopen(path, "rb");
menon::fseek(stream, 100, SEEK_SET);
BOOST_TEST_EQ(std::ftell(stream), 100);
BOOST_TEST_EQ(std::ftell(stream), menon::ftell(stream));
std::fclose(stream);
}
{ // fseek/ftell関数とfsetpos/fgetpos関数の混在
auto stream = std::fopen(path, "rb");
menon::fpos_t pos;
menon::fseek(stream, 100, SEEK_SET);
BOOST_TEST_EQ(menon::fgetpos(stream, &pos), 0);
BOOST_TEST_EQ(pos, 100);
BOOST_TEST_EQ(menon::fsetpos(stream, &pos), 0);
BOOST_TEST_EQ(std::ftell(stream), 100);
std::fclose(stream);
}
{ // istream版のfseek関数
std::ifstream ifs(path);
menon::fseek(ifs, 100, SEEK_SET);
BOOST_TEST_EQ(ifs.tellg(), 100);
}
{ // istream版のfseek関数とfsetpos/fgetos関数の混在
std::ifstream ifs(path);
menon::fpos_t pos;
menon::fseek(ifs, 100, SEEK_SET);
BOOST_TEST_EQ(menon::fgetpos(ifs, &pos), 0);
BOOST_TEST_EQ(pos, 100);
BOOST_TEST_EQ(menon::fsetpos(ifs, &pos), 0);
BOOST_TEST_EQ(ifs.tellg(), 100);
}
{ // iostream版のfseek関数
std::fstream fs(path);
menon::fseek(fs, 100, SEEK_SET);
BOOST_TEST_EQ(fs.tellp(), 100);
BOOST_TEST_EQ(fs.tellg(), 100);
}
{ // ostream版のfseek関数
std::ofstream ofs(path);
menon::fseek(ofs, 100, SEEK_SET);
BOOST_TEST_EQ(ofs.tellp(), 100);
}
{ // ostream版のfseek関数とfsetpos/fgetpos関数の混在
std::ofstream ofs(path);
menon::fpos_t pos;
menon::fseek(ofs, 100, SEEK_SET);
BOOST_TEST_EQ(menon::fgetpos(ofs, &pos), 0);
BOOST_TEST_EQ(pos, 100);
BOOST_TEST_EQ(menon::fsetpos(ofs, &pos), 0);
BOOST_TEST_EQ(ofs.tellp(), 100);
}
std::remove(path);
return boost::report_errors();
}
| 25.744186 | 60 | 0.644986 | menonfled |
b857437f1b00b85fe95cd917783c18cdff9f528a | 7,806 | cpp | C++ | system-test/fwf.cpp | 2733284198/MaxScale | b921dddbf06fcce650828ca94a3d715012b7072f | [
"BSD-3-Clause"
] | 1 | 2020-10-29T07:39:00.000Z | 2020-10-29T07:39:00.000Z | system-test/fwf.cpp | 2733284198/MaxScale | b921dddbf06fcce650828ca94a3d715012b7072f | [
"BSD-3-Clause"
] | null | null | null | system-test/fwf.cpp | 2733284198/MaxScale | b921dddbf06fcce650828ca94a3d715012b7072f | [
"BSD-3-Clause"
] | null | null | null | /**
* @file fwf - Firewall filter test (also regression test for MXS-683 "qc_mysqlembedded reports as-name
* instead of original-name")
* - setup Firewall filter to use rules from rule file fw/ruleXX, where XX - number of sub-test
* - execute queries for fw/passXX file, expect OK
* - execute queries from fw/denyXX, expect Access Denied error (mysql_error 1141)
* - repeat for all XX
* - setup Firewall filter to block queries next 2 minutes using 'at_time' statement (see template
* fw/rules_at_time)
* - start sending queries, expect Access Denied now and OK after two mintes
* - setup Firewall filter to limit a number of queries during certain time
* - start sending queries as fast as possible, expect OK for N first quries and Access Denied for next
* queries
* - wait, start sending queries again, but only one query per second, expect OK
* - try to load rules with syntax error, expect failure for all sessions and queries
*/
#include <iostream>
#include <ctime>
#include <maxtest/testconnections.hh>
#include <maxtest/sql_t1.hh>
#include <maxtest/fw_copy_rules.hh>
int main(int argc, char* argv[])
{
TestConnections::skip_maxscale_start(true);
TestConnections* Test = new TestConnections(argc, argv);
int local_result;
char str[4096];
char sql[4096];
char pass_file[4096];
char deny_file[4096];
char rules_dir[4096];
FILE* file;
sprintf(rules_dir, "%s/fw/", test_dir);
int N = 19;
int i;
for (i = 1; i < N + 1; i++)
{
Test->set_timeout(180);
local_result = 0;
sprintf(str, "rules%d", i);
copy_rules(Test, str, rules_dir);
Test->maxscales->restart_maxscale(0);
Test->maxscales->connect_rwsplit(0);
sprintf(pass_file, "%s/fw/pass%d", test_dir, i);
sprintf(deny_file, "%s/fw/deny%d", test_dir, i);
if (Test->verbose)
{
Test->tprintf("Pass file: %s", pass_file);
Test->tprintf("Deny file: %s", deny_file);
}
file = fopen(pass_file, "r");
if (file != NULL)
{
if (Test->verbose)
{
Test->tprintf("********** Trying queries that should be OK ********** ");
}
while (fgets(sql, sizeof(sql), file))
{
if (strlen(sql) > 1)
{
if (Test->verbose)
{
Test->tprintf("%s", sql);
}
int rv = execute_query(Test->maxscales->conn_rwsplit[0], "%s", sql);
Test->add_result(rv, "Query should succeed: %s", sql);
local_result += rv;
}
}
fclose(file);
}
else
{
Test->add_result(1, "Error opening query file");
}
file = fopen(deny_file, "r");
if (file != NULL)
{
if (Test->verbose)
{
Test->tprintf("********** Trying queries that should FAIL ********** ");
}
while (fgets(sql, sizeof(sql), file))
{
Test->set_timeout(180);
if (strlen(sql) > 1)
{
if (Test->verbose)
{
Test->tprintf("%s", sql);
}
execute_query_silent(Test->maxscales->conn_rwsplit[0], sql);
if (mysql_errno(Test->maxscales->conn_rwsplit[0]) != 1141)
{
Test->tprintf("Expected 1141, Access Denied but got %d, %s instead: %s",
mysql_errno(Test->maxscales->conn_rwsplit[0]),
mysql_error(Test->maxscales->conn_rwsplit[0]),
sql);
local_result++;
}
}
}
fclose(file);
}
else
{
Test->add_result(1, "Error opening query file");
}
if (local_result)
{
Test->add_result(1, "********** rules%d test FAILED", i);
}
else
{
Test->tprintf("********** rules%d test PASSED", i);
}
mysql_close(Test->maxscales->conn_rwsplit[0]);
}
Test->set_timeout(180);
// Test for at_times clause
if (Test->verbose)
{
Test->tprintf("Trying at_times clause");
}
copy_rules(Test, (char*) "rules_at_time", rules_dir);
if (Test->verbose)
{
Test->tprintf("DELETE quries without WHERE clause will be blocked during the 30 seconds");
Test->tprintf("Put time to rules.txt: %s", str);
}
Test->maxscales->ssh_node_f(0,
false,
"start_time=`date +%%T`;"
"stop_time=` date --date \"now +30 secs\" +%%T`;"
"%s sed -i \"s/###time###/$start_time-$stop_time/\" %s/rules/rules.txt",
Test->maxscales->access_sudo(0),
Test->maxscales->access_homedir(0));
Test->maxscales->restart_maxscale(0);
Test->maxscales->connect_rwsplit(0);
sleep(10);
Test->tprintf("Trying 'DELETE FROM t1' and expecting FAILURE");
execute_query_silent(Test->maxscales->conn_rwsplit[0], "DELETE FROM t1");
if (mysql_errno(Test->maxscales->conn_rwsplit[0]) != 1141)
{
Test->add_result(1,
"Query succeded, but fail expected, error is %d",
mysql_errno(Test->maxscales->conn_rwsplit[0]));
}
Test->tprintf("Waiting 30 seconds and trying 'DELETE FROM t1', expecting OK");
Test->stop_timeout();
sleep(30);
Test->set_timeout(180);
Test->try_query(Test->maxscales->conn_rwsplit[0], "DELETE FROM t1");
mysql_close(Test->maxscales->conn_rwsplit[0]);
Test->maxscales->stop_maxscale(0);
Test->tprintf("Trying limit_queries clause");
Test->tprintf("Copying rules to Maxscale machine: %s", str);
copy_rules(Test, (char*) "rules_limit_queries", rules_dir);
Test->maxscales->start_maxscale(0);
Test->maxscales->connect_rwsplit(0);
Test->tprintf("Trying 10 quries as fast as possible");
for (i = 0; i < 10; i++)
{
Test->add_result(execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1"),
"%d -query failed",
i);
}
Test->tprintf("Expecting failures during next 5 seconds");
time_t start_time_clock = time(NULL);
timeval t1, t2;
double elapsedTime;
gettimeofday(&t1, NULL);
do
{
gettimeofday(&t2, NULL);
elapsedTime = (t2.tv_sec - t1.tv_sec);
elapsedTime += (double) (t2.tv_usec - t1.tv_usec) / 1000000.0;
}
while ((execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1") != 0)
&& (elapsedTime < 10));
Test->tprintf("Quries were blocked during %f (using clock_gettime())", elapsedTime);
Test->tprintf("Quries were blocked during %lu (using time())", time(NULL) - start_time_clock);
if ((elapsedTime > 6) or (elapsedTime < 4))
{
Test->add_result(1, "Queries were blocked during wrong time");
}
Test->set_timeout(180);
Test->tprintf("Trying 12 quries, 1 query / second");
for (i = 0; i < 12; i++)
{
sleep(1);
Test->add_result(execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1"),
"query failed");
if (Test->verbose)
{
Test->tprintf("%d ", i);
}
}
int rval = Test->global_result;
delete Test;
return rval;
}
| 32.798319 | 104 | 0.532667 | 2733284198 |
b86635f2d1fb465311fb8c1e568bf312e7cece9d | 2,517 | cpp | C++ | src/lib/storage/segment_accessor.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | 1 | 2019-12-30T13:23:30.000Z | 2019-12-30T13:23:30.000Z | src/lib/storage/segment_accessor.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | 11 | 2019-12-02T20:47:52.000Z | 2020-02-04T23:19:31.000Z | src/lib/storage/segment_accessor.cpp | dey4ss/hyrise | c304b9ced36044e303eb8a4d68a05fc7edc04819 | [
"MIT"
] | 1 | 2020-11-17T19:18:58.000Z | 2020-11-17T19:18:58.000Z | #include "segment_accessor.hpp"
#include "resolve_type.hpp"
namespace opossum::detail {
template <typename T>
std::unique_ptr<AbstractSegmentAccessor<T>> CreateSegmentAccessor<T>::create(
const std::shared_ptr<const BaseSegment>& segment) {
std::unique_ptr<AbstractSegmentAccessor<T>> accessor;
resolve_segment_type<T>(*segment, [&](const auto& typed_segment) {
using SegmentType = std::decay_t<decltype(typed_segment)>;
if constexpr (std::is_same_v<SegmentType, ReferenceSegment>) {
const auto& pos_list = *typed_segment.pos_list();
if (pos_list.references_single_chunk() && !pos_list.empty()) {
// If the pos list stores a NULL value, its chunk_id references a non-existing chunk. If all entries reference
// the same chunk_id, we can safely assume that all other entries are also NULL. Instead of using an accessor
// that checks for the reference being NULL, we can simply use the NullAccessor, which always returns nullopt,
// i.e., the accessors representation of NULL values.
// Note that this is independent of the row being pointed to holding a NULL value.
if (pos_list[ChunkOffset{0}].is_null()) {
accessor = std::make_unique<NullAccessor<T>>();
} else {
auto chunk_id = pos_list[ChunkOffset{0}].chunk_id;
auto referenced_segment =
typed_segment.referenced_table()->get_chunk(chunk_id)->get_segment(typed_segment.referenced_column_id());
// If only a single segment is referenced, we can resolve it once and avoid some more expensive
// virtual method calls later.
resolve_segment_type<T>(*referenced_segment, [&](const auto& typed_referenced_segment) {
using ReferencedSegment = std::decay_t<decltype(typed_referenced_segment)>;
if constexpr (!std::is_same_v<ReferencedSegment, ReferenceSegment>) {
accessor = std::make_unique<SingleChunkReferenceSegmentAccessor<T, ReferencedSegment>>(
pos_list, chunk_id, typed_referenced_segment);
} else {
Fail("Encountered nested ReferenceSegments");
}
});
}
} else {
accessor = std::make_unique<MultipleChunkReferenceSegmentAccessor<T>>(typed_segment);
}
} else {
accessor = std::make_unique<SegmentAccessor<T, SegmentType>>(typed_segment);
}
});
return accessor;
}
EXPLICITLY_INSTANTIATE_DATA_TYPES(CreateSegmentAccessor);
} // namespace opossum::detail
| 50.34 | 119 | 0.688915 | dey4ss |
b86685f9997fc8e9371a9d5a24e56d36000d0f9e | 2,535 | cpp | C++ | OS1/Project/Code/src/Kernsem.cpp | aleksamagicka/CollegeAssignments | 59edfcf2f5782ddf2d2f3b6ed98b2e641e5fa00d | [
"Unlicense"
] | null | null | null | OS1/Project/Code/src/Kernsem.cpp | aleksamagicka/CollegeAssignments | 59edfcf2f5782ddf2d2f3b6ed98b2e641e5fa00d | [
"Unlicense"
] | null | null | null | OS1/Project/Code/src/Kernsem.cpp | aleksamagicka/CollegeAssignments | 59edfcf2f5782ddf2d2f3b6ed98b2e641e5fa00d | [
"Unlicense"
] | null | null | null | #include "kernsem.h"
#include "asystem.h"
KernelSem::KernelSem(int init, Semaphore *initSemph) :
count(init), semph(initSemph) {
System::semaphores.add(this);
}
KernelSem::~KernelSem() {
while (count < 0)
signal();
}
int KernelSem::val() const {
return count;
}
int KernelSem::wait(Time maxTimeToWait) {
lock
if (count-- > 0) {
unlock
return 1;
}
System::runningPcb->state = PCB::BLOCKED;
if (maxTimeToWait == 0) {
// Cisto blokiranje do nekog signal()-a
blockedThreads.add((PCB*) System::runningPcb);
} else {
// Vremensko blokiranje, novi SemaphoredThread se ubacuje na pravo mesto u nizu tako da poredak vremena budjenja ostane rastuci
SemaphoredThread st = SemaphoredThread((PCB*) System::runningPcb,
System::bootTimeDelta + maxTimeToWait);
if (timeBlocked.empty()) {
// Nema sta da se pretrazuje
timeBlocked.add(st);
} else {
Iterator<SemaphoredThread> t = timeBlocked.iterStart(), rightPlace = timeBlocked.iterEnd();
while (t != timeBlocked.iterEnd()
&& st.futureWakeupTime < t.current->data.futureWakeupTime) {
rightPlace = t;
t++;
}
if (rightPlace != timeBlocked.iterEnd()) {
// Nadjena je vrednost posle koje treba ubaciti ovu novu
timeBlocked.insert(rightPlace, st);
} else {
// rightPlace je ostao kraj niza, znaci da nema onog elementa POSLE koga bi ovo trebalo ubaciti
// To znaci da su svi VECI od ovog novog, i on onda ide pre svih njih
timeBlocked.addToFront(st);
}
}
}
unlock
dispatch();
// Mozda je isteklo vreme?
if (!System::runningPcb->semphTimeExceeded) {
System::runningPcb->semphTimeExceeded = false;
return 0;
}
return 1;
}
void KernelSem::releaseBlocked() {
PCB *pcb = blockedThreads.front();
blockedThreads.popFront();
pcb->state = PCB::READY;
pcb->semphTimeExceeded = true; //?
Scheduler::put(pcb);
}
void KernelSem::releaseTimed() {
PCB *pcb = timeBlocked.front().myPCB;
timeBlocked.popFront();
pcb->state = PCB::READY;
pcb->semphTimeExceeded = true;
Scheduler::put(pcb);
}
void KernelSem::signal() {
lock
if (count++ < 0) {
if (!blockedThreads.empty()) {
releaseBlocked();
} else if (!timeBlocked.empty()) {
releaseTimed();
}
}
unlock
}
void KernelSem::timerCleanup() {
lock
while (!timeBlocked.empty()) {
if (timeBlocked.front().futureWakeupTime > System::bootTimeDelta)
break;
PCB *pcb = timeBlocked.front().myPCB;
timeBlocked.popFront();
pcb->state = PCB::READY;
pcb->semphTimeExceeded = false;
Scheduler::put(pcb);
}
unlock
}
| 20.778689 | 129 | 0.677712 | aleksamagicka |
b8690a1397fcea3fa74496c86685c051198079f6 | 4,735 | hpp | C++ | libs/core/datastructures/include/hpx/datastructures/tagged_pair.hpp | AnshMishra2001/hpx | 00846a06bf2653c595b43aed3abe02c42998e230 | [
"BSL-1.0"
] | null | null | null | libs/core/datastructures/include/hpx/datastructures/tagged_pair.hpp | AnshMishra2001/hpx | 00846a06bf2653c595b43aed3abe02c42998e230 | [
"BSL-1.0"
] | null | null | null | libs/core/datastructures/include/hpx/datastructures/tagged_pair.hpp | AnshMishra2001/hpx | 00846a06bf2653c595b43aed3abe02c42998e230 | [
"BSL-1.0"
] | null | null | null | // Copyright Eric Niebler 2013-2015
// Copyright 2015-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)
//
// This was modeled after the code available in the Range v3 library
#pragma once
#include <hpx/config.hpp>
#include <hpx/assert.hpp>
#include <hpx/datastructures/tagged.hpp>
#include <hpx/datastructures/tuple.hpp>
#include <hpx/type_support/decay.hpp>
#include <cstddef>
#include <type_traits>
#include <utility>
namespace hpx { namespace util {
///////////////////////////////////////////////////////////////////////////
template <typename F, typename S>
struct tagged_pair
: tagged<std::pair<typename detail::tag_elem<F>::type,
typename detail::tag_elem<S>::type>,
typename detail::tag_spec<F>::type,
typename detail::tag_spec<S>::type>
{
typedef tagged<std::pair<typename detail::tag_elem<F>::type,
typename detail::tag_elem<S>::type>,
typename detail::tag_spec<F>::type,
typename detail::tag_spec<S>::type>
base_type;
template <typename... Ts>
tagged_pair(Ts&&... ts)
: base_type(std::forward<Ts>(ts)...)
{
}
};
///////////////////////////////////////////////////////////////////////////
template <typename Tag1, typename Tag2, typename T1, typename T2>
constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
make_tagged_pair(std::pair<T1, T2>&& p)
{
typedef tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
result_type;
return result_type(std::move(p));
}
template <typename Tag1, typename Tag2, typename T1, typename T2>
constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
make_tagged_pair(std::pair<T1, T2> const& p)
{
typedef tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
result_type;
return result_type(p);
}
template <typename Tag1, typename Tag2, typename... Ts>
constexpr HPX_FORCEINLINE tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
make_tagged_pair(hpx::tuple<Ts...>&& p)
{
static_assert(
sizeof...(Ts) >= 2, "hpx::tuple must have at least 2 elements");
typedef tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
result_type;
return result_type(std::move(get<0>(p)), std::move(get<1>(p)));
}
template <typename Tag1, typename Tag2, typename... Ts>
constexpr HPX_FORCEINLINE tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
make_tagged_pair(hpx::tuple<Ts...> const& p)
{
static_assert(
sizeof...(Ts) >= 2, "hpx::tuple must have at least 2 elements");
typedef tagged_pair<
Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type),
Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)>
result_type;
return result_type(get<0>(p), get<1>(p));
}
///////////////////////////////////////////////////////////////////////////
template <typename Tag1, typename Tag2, typename T1, typename T2>
constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
make_tagged_pair(T1&& t1, T2&& t2)
{
typedef tagged_pair<Tag1(typename decay<T1>::type),
Tag2(typename decay<T2>::type)>
result_type;
return result_type(std::forward<T1>(t1), std::forward<T2>(t2));
}
}} // namespace hpx::util
namespace hpx {
///////////////////////////////////////////////////////////////////////////
template <typename Tag1, typename Tag2>
struct tuple_size<util::tagged_pair<Tag1, Tag2>>
: std::integral_constant<std::size_t, 2>
{
};
template <std::size_t N, typename Tag1, typename Tag2>
struct tuple_element<N, util::tagged_pair<Tag1, Tag2>>
: hpx::tuple_element<N,
std::pair<typename util::detail::tag_elem<Tag1>::type,
typename util::detail::tag_elem<Tag2>::type>>
{
};
} // namespace hpx
| 35.601504 | 80 | 0.577191 | AnshMishra2001 |
b86b0d4762b5df97d94954219dcdb26dd59f2e86 | 17,882 | cpp | C++ | d3d/voxel/voxelize.cpp | minghanz/d3d | 1d08013238b300489f61be57cdd20a105d16a632 | [
"MIT"
] | 27 | 2020-04-16T22:24:47.000Z | 2022-01-12T08:23:43.000Z | d3d/voxel/voxelize.cpp | minghanz/d3d | 1d08013238b300489f61be57cdd20a105d16a632 | [
"MIT"
] | 2 | 2020-08-11T07:03:35.000Z | 2021-02-05T06:43:26.000Z | d3d/voxel/voxelize.cpp | minghanz/d3d | 1d08013238b300489f61be57cdd20a105d16a632 | [
"MIT"
] | 6 | 2020-04-16T21:49:50.000Z | 2022-01-26T15:38:47.000Z | #include "d3d/voxel/voxelize.h"
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <vector>
#include <iostream>
#include <limits>
using namespace std;
using namespace at;
using namespace pybind11::literals;
template <typename T> using toptional = torch::optional<T>;
typedef tuple<int, int, int> coord_t;
struct coord_hash : public std::unary_function<coord_t, std::size_t>
{
std::size_t operator()(const coord_t& k) const
{
constexpr int p = 997; // match this to the range of k
size_t ret = std::get<0>(k);
ret = ret * p + std::get<1>(k);
ret = ret * p + std::get<2>(k);
return ret;
}
};
struct coord_equal : public std::binary_function<coord_t, coord_t, bool>
{
bool operator()(const coord_t& v0, const coord_t& v1) const
{
return (
std::get<0>(v0) == std::get<0>(v1) &&
std::get<1>(v0) == std::get<1>(v1) &&
std::get<2>(v0) == std::get<2>(v1)
);
}
};
typedef unordered_map<coord_t, int, coord_hash, coord_equal> coord_m; // XXX: Consider use robin-map
template <ReductionType Reduction>
py::dict voxelize_3d_dense_templated(
const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound,
const int max_points, const int max_voxels
)
{
auto points_ = points.accessor<float, 2>();
auto voxel_shape_ = voxel_shape.accessor<int, 1>();
auto voxel_bound_ = voxel_bound.accessor<float, 1>();
Tensor voxels = torch::zeros({max_voxels, max_points, points_.size(1)}, torch::dtype(torch::kFloat32));
Tensor coords = torch::empty({max_voxels, 3}, torch::dtype(torch::kLong));
Tensor voxel_pmask = torch::empty({max_voxels, max_points}, torch::dtype(torch::kBool));
Tensor voxel_npoints = torch::zeros(max_voxels, torch::dtype(torch::kInt32));
auto voxels_ = voxels.accessor<float, 3>();
auto coords_ = coords.accessor<int64_t, 2>();
auto voxel_pmask_ = voxel_pmask.accessor<bool, 2>();
auto voxel_npoints_ = voxel_npoints.accessor<int, 1>();
// initialize aggregated values
Tensor aggregates;
switch(Reduction)
{
case ReductionType::NONE:
aggregates = torch::empty({0, 0});
break;
case ReductionType::MEAN:
aggregates = torch::zeros({max_voxels, points_.size(1)}, torch::dtype(torch::kFloat32));
break;
case ReductionType::MAX:
aggregates = torch::full({max_voxels, points_.size(1)}, -numeric_limits<float>::infinity(), torch::dtype(torch::kFloat32));
break;
case ReductionType::MIN:
aggregates = torch::full({max_voxels, points_.size(1)}, numeric_limits<float>::infinity(), torch::dtype(torch::kFloat32));
break;
}
auto aggregates_ = aggregates.accessor<float, 2>();
// calculate voxel sizes and other variables
float voxel_size_[3];
for (int d = 0; d < 3; ++d)
voxel_size_[d] = (voxel_bound_[(d<<1) | 1] - voxel_bound_[d<<1]) / voxel_shape_[d];
auto npoints = points_.size(0);
auto nfeatures = points_.size(1);
coord_m voxel_idmap;
int coord_temp[3];
int nvoxels = 0;
for (int i = 0; i < npoints; ++i)
{
// calculate voxel-wise coordinates
bool out_of_range = false;
for (int d = 0; d < 3; ++d)
{
int idx = int((points_[i][d] - voxel_bound_[d << 1]) / voxel_size_[d]);
if (idx < 0 || idx >= voxel_shape_[d])
{
out_of_range = true;
break;
}
coord_temp[d] = idx;
}
if (out_of_range) continue;
// assign voxel
int voxel_idx;
auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]);
auto voxel_iter = voxel_idmap.find(coord_tuple);
if (voxel_iter == voxel_idmap.end())
{
if (nvoxels >= max_voxels)
continue;
voxel_idx = nvoxels++;
voxel_idmap[coord_tuple] = voxel_idx;
for (int d = 0; d < 3; ++d)
coords_[voxel_idx][d] = coord_temp[d];
}
else
voxel_idx = voxel_iter->second;
// assign voxel mask and original features
int n = voxel_npoints_[voxel_idx]++;
if (n < max_points)
{
voxel_pmask_[voxel_idx][n] = true;
for (int d = 0; d < nfeatures; ++d)
voxels_[voxel_idx][n][d] = points_[i][d];
}
// reduce features
for (int d = 0; d < nfeatures; ++d)
{
switch (Reduction)
{
case ReductionType::MEAN: // mean
aggregates_[voxel_idx][d] += points_[i][d];
break;
case ReductionType::MAX: // max, aggregates should be initialized as positive huge numbers
aggregates_[voxel_idx][d] = max(aggregates_[voxel_idx][d], points_[i][d]);
break;
case ReductionType::MIN: // min, aggregates should be initialized as negative huge numbers
aggregates_[voxel_idx][d] = min(aggregates_[voxel_idx][d], points_[i][d]);
break;
case ReductionType::NONE:
default:
break;
}
}
}
// if aggregate is mean, divide them by the numbers now
if (Reduction == ReductionType::MEAN)
for (int i = 0; i < nvoxels; i++)
for (int d = 0; d < nfeatures; d++)
aggregates_[i][d] /= voxel_npoints_[i];
// remove unused voxel entries
if (Reduction != ReductionType::NONE)
return py::dict("voxels"_a=voxels.slice(0, 0, nvoxels),
"coords"_a=coords.slice(0, 0, nvoxels),
"voxel_pmask"_a=voxel_pmask.slice(0, 0, nvoxels),
"voxel_npoints"_a=voxel_npoints.slice(0, 0, nvoxels),
"aggregates"_a=aggregates.slice(0, 0, nvoxels)
);
else
return py::dict("voxels"_a=voxels.slice(0, 0, nvoxels),
"coords"_a=coords.slice(0, 0, nvoxels),
"voxel_pmask"_a=voxel_pmask.slice(0, 0, nvoxels),
"voxel_npoints"_a=voxel_npoints.slice(0, 0, nvoxels)
);
}
py::dict voxelize_3d_dense(
const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound,
const int max_points, const int max_voxels, const ReductionType reduction_type
)
{
#define _VOXELIZE_3D_REDUCTION_TYPE_CASE(n) case n: \
return voxelize_3d_dense_templated<n>(points, voxel_shape, voxel_bound, max_points, max_voxels)
switch (reduction_type)
{
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::NONE);
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MEAN);
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MIN);
_VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MAX);
default:
throw py::value_error("Unsupported reduction type in voxelization!");
}
#undef _VOXELIZE_3D_REDUCTION_TYPE_CASE
}
py::dict voxelize_3d_sparse(
const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound,
const toptional<int> max_points, const toptional<int> max_voxels
)
{
auto points_ = points.accessor<float, 2>();
auto voxel_shape_ = voxel_shape.accessor<int, 1>();
auto voxel_bound_ = voxel_bound.accessor<float, 1>();
// fill points mapping with -1 (unassigned)
Tensor points_mapping = torch::full(points_.size(0), -1, torch::dtype(torch::kLong));
auto points_mapping_ = points_mapping.accessor<int64_t, 1>();
// calculate voxel sizes and other variables
float voxel_size_[3];
for (int d = 0; d < 3; ++d)
voxel_size_[d] = (voxel_bound_[(d<<1) | 1] - voxel_bound_[d<<1]) / voxel_shape_[d];
auto npoints = points_.size(0);
auto nfeatures = points_.size(1);
coord_m voxel_idmap;
vector<int> voxel_npoints;
vector<Tensor> coords_list;
int coord_temp[3];
int nvoxels = 0;
bool need_mask = false;
for (int i = 0; i < npoints; ++i)
{
// calculate voxel-wise coordinates
bool out_of_range = false;
for (int d = 0; d < 3; ++d)
{
int idx = int((points_[i][d] - voxel_bound_[d << 1]) / voxel_size_[d]);
if (idx < 0 || idx >= voxel_shape_[d])
{
out_of_range = true;
break;
}
coord_temp[d] = idx;
}
if (out_of_range)
{
need_mask = true;
continue;
}
// assign voxel
int voxel_idx;
auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]);
auto voxel_iter = voxel_idmap.find(coord_tuple);
if (voxel_iter == voxel_idmap.end())
{
voxel_idx = nvoxels++;
voxel_idmap[coord_tuple] = voxel_idx;
voxel_npoints.push_back(1);
coords_list.push_back(torch::tensor({coord_temp[0], coord_temp[1], coord_temp[2]}, torch::kLong));
}
else
{
voxel_idx = voxel_iter->second;
voxel_npoints[voxel_idx] += 1;
}
points_mapping_[i] = voxel_idx;
}
// process mask
Tensor points_filtered = points;
Tensor masked;
if (need_mask)
{
masked = torch::where(points_mapping >= 0)[0];
points_filtered = torch::index_select(points, 0, masked);
points_mapping = torch::index_select(points_mapping, 0, masked);
}
else
{
masked = torch::arange(npoints);
}
return py::dict(
"points"_a=points_filtered,
"points_mask"_a=masked,
"points_mapping"_a=points_mapping,
"coords"_a=torch::stack(coords_list),
"voxel_npoints"_a=torch::tensor(voxel_npoints, torch::kInt32));
}
py::dict voxelize_sparse(
const Tensor points, const Tensor voxel_size, const toptional<int> ndim
)
{
auto points_ = points.accessor<float, 2>();
auto voxel_size_ = voxel_size.accessor<float, 1>();
int ndim_ = ndim.value_or(3);
auto npoints = points_.size(0);
Tensor points_mapping = torch::empty(npoints, torch::dtype(torch::kLong));
auto points_mapping_ = points_mapping.accessor<int64_t, 1>();
coord_m voxel_idmap; // coord to voxel id
vector<int> voxel_npoints; // number of points per voxel
vector<Tensor> coords_list; // list of coordinates
int coord_temp[ndim_]; // array to store temporary coordinate
int nvoxels = 0; // number of total voxels
for (int i = 0; i < npoints; ++i)
{
// calculate voxel-wise coordinates
for (int d = 0; d < ndim_; ++d)
coord_temp[d] = floor(points_[i][d] / voxel_size_[d]);
// assign voxel
int voxel_idx;
auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]);
auto voxel_iter = voxel_idmap.find(coord_tuple);
if (voxel_iter == voxel_idmap.end())
{
voxel_idx = nvoxels++;
voxel_idmap[coord_tuple] = voxel_idx;
voxel_npoints.push_back(1);
coords_list.push_back(torch::tensor({coord_temp[0], coord_temp[1], coord_temp[2]}, torch::kLong));
}
else
{
voxel_idx = voxel_iter->second;
voxel_npoints[voxel_idx] += 1;
}
points_mapping_[i] = voxel_idx;
}
return py::dict(
"points_mapping"_a=points_mapping,
"coords"_a=torch::stack(coords_list),
"voxel_npoints"_a=torch::tensor(voxel_npoints, torch::kInt32)
);
}
py::dict voxelize_filter(
const Tensor feats, const Tensor points_mapping,
const Tensor coords, const Tensor voxel_npoints, const toptional<Tensor> coords_bound,
const toptional<int> min_points, const toptional<int> max_points, const toptional<int> max_voxels,
const toptional<MaxPointsFilterType> max_points_filter, const toptional<MaxVoxelsFilterType> max_voxels_filter
)
{
auto feats_ = feats.accessor<float, 2>();
auto coords_ = coords.accessor<int64_t, 2>();
auto voxel_npoints_ = voxel_npoints.accessor<int, 1>();
auto points_mapping_ = points_mapping.accessor<int64_t, 1>();
Tensor coord_bound_default = coords_bound.value_or(torch::empty({0, 0}, torch::dtype(torch::kFloat)));
auto coords_bound_ = coord_bound_default.accessor<int64_t, 2>();
int nvoxels = coords_.size(0);
int ndim = coords_.size(1);
int npoints = feats_.size(0);
int nfeats = feats_.size(1);
// default values
MaxPointsFilterType max_points_filter_ = max_points_filter.value_or(MaxPointsFilterType::NONE);
MaxVoxelsFilterType max_voxels_filter_ = max_voxels_filter.value_or(MaxVoxelsFilterType::NONE);
if (max_voxels_filter != MaxVoxelsFilterType::NONE && !max_voxels.has_value())
throw py::value_error("Must specify maximum voxel count to filter voxels!");
int max_voxels_ = max_voxels.value();
if (max_points_filter != MaxPointsFilterType::NONE && !max_points.has_value())
throw py::value_error("Must specify maximum points per voxel to filter points!");
int max_points_ = max_points.value();
int min_points_ = min_points.value_or(0);
// filter out voxels at first
std::unordered_map<int, int> voxel_indices;
int nvoxel_filtered = 0;
auto test_bound = [&](int i) -> bool{
bool out_of_range = false;
for (int d = 0; d < ndim; d++)
if (coords_[i][d] < coords_bound_[d][0] ||
coords_[i][d] >= coords_bound_[d][1])
{
out_of_range = true;
break;
}
return out_of_range;
};
switch (max_voxels_filter_)
{
case MaxVoxelsFilterType::NONE:
for (int i = 0; i < nvoxels; i++)
{
if (voxel_npoints_[i] < min_points_) // skip voxels with few points
continue;
if (coords_bound.has_value() && test_bound(i))
continue;
voxel_indices[i] = nvoxel_filtered++;
}
break;
case MaxVoxelsFilterType::TRIM:
cout << "In trim" << endl;
for (int i = 0; i < nvoxels; i++)
{
if (nvoxel_filtered >= max_voxels_)
break;
if (voxel_npoints_[i] < min_points_) // skip voxels with few points
continue;
if (coords_bound.has_value() && test_bound(i))
continue;
voxel_indices[i] = nvoxel_filtered++;
}
break;
case MaxVoxelsFilterType::DESCENDING:
auto order = torch::argsort(voxel_npoints, 0, true);
auto ordered_ = order.accessor<long, 1>();
for (int i = 0; i < nvoxels; i++)
{
if (nvoxel_filtered >= max_voxels_)
break;
if (voxel_npoints_[ordered_[i]] < min_points_)
break; // skip voxels with few points
if (coords_bound.has_value() && test_bound(ordered_[i]))
continue;
voxel_indices[ordered_[i]] = nvoxel_filtered++;
}
break;
}
// filter coordinates
Tensor coords_filtered = torch::empty({nvoxel_filtered, ndim}, coords.options());
auto coords_filtered_ = coords_filtered.accessor<int64_t, 2>();
for (auto iter = voxel_indices.begin(); iter != voxel_indices.end(); iter++)
for (int d = 0; d < ndim; d++)
coords_filtered_[iter->second][d] = coords_[iter->first][d];
// filter out points, first create output tensors
Tensor points_mapping_filtered = torch::empty_like(points_mapping);
Tensor voxel_npoints_filtered = torch::zeros({nvoxel_filtered}, voxel_npoints.options());
auto points_mapping_filtered_ = points_mapping_filtered.accessor<int64_t, 1>();
auto voxel_npoints_filtered_ = voxel_npoints_filtered.accessor<int, 1>();
switch(max_points_filter_)
{
case MaxPointsFilterType::NONE:
for (int i = 0; i < npoints; i++)
{
auto new_id = voxel_indices.find(points_mapping_[i]);
if (new_id != voxel_indices.end())
{
int vid = new_id->second;
points_mapping_filtered_[i] = vid;
voxel_npoints_filtered_[vid]++;
}
else points_mapping_filtered_[i] = -1;
}
break;
case MaxPointsFilterType::TRIM:
for (int i = 0; i < npoints; i++)
{
auto new_id = voxel_indices.find(points_mapping_[i]);
if (new_id != voxel_indices.end())
{
int vid = new_id->second;
if (voxel_npoints_filtered_[vid] >= max_points_)
{
points_mapping_filtered_[i] = -1;
continue;
}
points_mapping_filtered_[i] = vid;
voxel_npoints_filtered_[vid]++;
}
else points_mapping_filtered_[i] = -1;
}
break;
case MaxPointsFilterType::FARTHEST_SAMPLING:
throw py::value_error("Farthest Sampling not implemented!");
break;
}
Tensor masked = torch::where(points_mapping_filtered >= 0)[0];
Tensor feats_filtered = torch::index_select(feats, 0, masked);
points_mapping_filtered = torch::index_select(points_mapping_filtered, 0, masked);
return py::dict(
"points"_a=feats_filtered, // FIXME: use consistent name for point features (`points` or `feats`)
"points_mask"_a=masked,
"points_mapping"_a=points_mapping_filtered,
"voxel_npoints"_a=voxel_npoints_filtered,
"coords"_a=coords_filtered
);
} | 36.946281 | 135 | 0.593054 | minghanz |
b86fdf20471ea8badf2b98ef3174f590d96188a9 | 6,852 | cpp | C++ | Mario_Game/title.cpp | Rossterrrr/Qt | 3e5c2934ce19675390d2ad6d513a14964d8cbe50 | [
"MIT"
] | 3 | 2019-09-02T05:17:08.000Z | 2021-01-07T11:21:34.000Z | QtMario_Youtube-master/QtMario_Original Code/title.cpp | Jhongesell/Qt | 3fc548731435d3f6fffbaec1bdfd19371232088e | [
"MIT"
] | null | null | null | QtMario_Youtube-master/QtMario_Original Code/title.cpp | Jhongesell/Qt | 3fc548731435d3f6fffbaec1bdfd19371232088e | [
"MIT"
] | null | null | null | #include "title.h"
#include "loginwindow.h"
#include <QMessageBox>
Title::Title(View *view, QWidget *parent) : QGraphicsScene(parent){
viewer = view;
scroll = new QScrollBar;
scroll = viewer->horizontalScrollBar();
background = new AnimatedGraphicsItem;
background->setPixmap(QPixmap(":/images/background.png"));
foreground = new QGraphicsPixmapItem(QPixmap(":/images/title.png"));
//cursor = new QGraphicsPixmapItem(QPixmap(":/images/cursor.png"));
logo = new QGraphicsPixmapItem(QPixmap(":/images/logo.png"));
animation = new QPropertyAnimation(background, "pos");
animation->setLoopCount(-1);
animation->setDuration(150000);
animation->setStartValue(QPoint(-width,0));
animation->setEndValue(QPoint(0,0));
animation->start();
logo->setPos((width - logo->boundingRect().width()) / 2, height / 12);
addItem(background);
addItem(foreground);
addItem(logo);
this->setFocus();
this->setSceneRect(0,0,1280,720);
view->sceneSet(this);
//Push Button for login
loginButton = new QPushButton(viewer);
loginButton->setText("Login");
loginButton->setObjectName(QString("loginButton"));
loginButton->setToolTip("Click to login");
loginButton->setGeometry(QRect(540, 500, 100, 32));
connect(loginButton, SIGNAL(clicked()), this, SLOT(login()));
//Push Button for developer login
developerButton = new QPushButton(viewer);
developerButton->setText("Guest Login");
developerButton->setObjectName(QString("developerButton"));
developerButton->setToolTip("Login as a guest");
developerButton->setGeometry(QRect(540, 535, 100, 32));
connect(developerButton, SIGNAL(clicked()), this, SLOT(developerLogin()));
//Push Button to quit
quitButton = new QPushButton(viewer);
quitButton->setText("Quit");
quitButton->setObjectName(QString("quitButton"));
quitButton->setToolTip("Quit program");
quitButton->setGeometry(QRect(642, 535, 100, 32));
connect(quitButton, SIGNAL(clicked()), this, SLOT(quitProgram()));
//Push Button for new user
newUserButton = new QPushButton(viewer);
newUserButton->setText("New User");
newUserButton->setObjectName(QString("newUserButton"));
newUserButton->setToolTip("Click to create a login");
newUserButton->setGeometry(QRect(642, 500, 100, 32));
connect(newUserButton, SIGNAL(clicked()), this, SLOT(newUser()));
//Add line edit for username, set tooltip
userLine = new QLineEdit(viewer);
//userLine->setObjectName(QString("userLine"));
userLine->setToolTip("Enter an email address");
userLine->setGeometry(QRect(540, 420, 200, 25));
//Add Label for username
QFont font("MV Boli", 15, QFont::Bold);
userName = new QLabel(viewer);
userName->setFont(font);
userName->setText("Username");
userName->setObjectName(QString("username"));
userName->setGeometry(QRect(430, 420, 100, 25));
//Add line edit for password, set tooltip
passLine = new QLineEdit(viewer);
passLine->setEchoMode(QLineEdit::Password);
passLine->setObjectName(QString("passLine"));
passLine->setToolTip("Enter password");
passLine->setGeometry(QRect(540, 450, 200, 25));
//Add Label For password
password = new QLabel(viewer);
password->setFont(font);
password->setText("Password");
password->setObjectName(QString("password"));
password->setGeometry(QRect(430, 450, 100, 25));
//Add radio button and connect signal to slot,set tooltip
radioButton = new QRadioButton(viewer);
radioButton->setObjectName(QString("radioButton"));
radioButton->setToolTip("Click to show password text");
radioButton->setGeometry(QRect(760, 450, 100, 25));
connect(radioButton, SIGNAL(toggled(bool)), this, SLOT(on_radioButton_toggled(bool)));
//add radio button text
radioText = new QLabel(viewer);
radioText->setText("Show Password");
radioText->setToolTip("Click to show password text");
radioText->setGeometry(QRect(780, 450, 100, 25));
}
bool Title::regExUserTest(){
bool accessGranted = false;
usernameRegEx = new QRegularExpression("^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$");
usernamenameMatch = new QRegularExpressionMatch(usernameRegEx->match(userLine->text()));
accessGranted = usernamenameMatch->hasMatch();
if(accessGranted){
return true;
}
else
return false;
}
void Title::on_radioButton_toggled(bool checked)
{
if(checked){
passLine->setEchoMode(QLineEdit::Normal);
}
else{
passLine->setEchoMode(QLineEdit::Password);
}
}
void Title::quitProgram(){
qApp->quit();
}
void Title::login(){
//Connect to Database
DataB::DBConnect(DBase);
//Error for lack of input
if(userLine->text().isEmpty()){
QMessageBox msgBox;
msgBox.setText("You must enter a username. ");
msgBox.setWindowTitle("Warning");
msgBox.exec();
return;
}
if(regExUserTest()== false){
QMessageBox msgBoxFail;
msgBoxFail.setText("That is not a valid email address. ");
msgBoxFail.setWindowTitle("Warning");
msgBoxFail.exec();
return;
}
if(passLine->text().isEmpty()){
QMessageBox msgBox2;
msgBox2.setText("You must enter a password. ");
msgBox2.setWindowTitle("Warning");
msgBox2.exec();
return;
}
//Gather Input
Query uInput;
uInput.uName=userLine->text();
uInput.pass=passLine->text();
qDebug() << uInput.uName;
qDebug() << uInput.pass;
//Try to check User
if(DataB::cUsrPas(uInput,DBase.db)){
//Then it worked
loginButton->close();
newUserButton->close();
passLine->close();
userLine->close();
userName->close();
password->close();
radioButton->close();
radioText->close();
developerButton->close();
quitButton->close();
scene = new MyScene(scroll,this);
viewer->sceneSet(scene);
}
else{
//Then it didnt
QMessageBox msgBox3;
msgBox3.setText(" Combination of username and/or password incorrect. ");
msgBox3.setWindowTitle("Warning");
msgBox3.exec();
return;
}
}
void Title::newUser(){
loginWindow = new LoginWindow();
loginWindow->exec();
}
void Title::developerLogin(){
loginButton->close();
newUserButton->close();
passLine->close();
userLine->close();
userName->close();
password->close();
radioButton->close();
radioText->close();
developerButton->close();
quitButton->close();
scene = new MyScene(scroll,this);
viewer->sceneSet(scene);
}
| 31.004525 | 95 | 0.641419 | Rossterrrr |
b87b3292e0d300a7a0f343d67544309a72d3470b | 2,005 | cc | C++ | src/q_1251_1300/q1288.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | null | null | null | src/q_1251_1300/q1288.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | 2 | 2021-12-15T10:51:15.000Z | 2022-01-26T17:03:16.000Z | src/q_1251_1300/q1288.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <iostream>
#include <vector>
using namespace std;
/**
* This file is generated by leetcode_add.py
*
* 1288.
* Remove Covered Intervals
*
* ––––––––––––––––––––––––––––– Description –––––––––––––––––––––––––––––
*
* Given an array ‘intervals’ where ‘intervals[i] = [lᵢ, rᵢ]’ represent
* the interval ‘[lᵢ, rᵢ)’ , remove all intervals that are covered by
* another interval in the
* The interval ‘[a, b)’ is covered by the interval ‘[c, d)’ if and only
* if ‘c ≤ a’ and ‘b ≤ d’
* Return “the number of remaining intervals” .
*
* ––––––––––––––––––––––––––––– Constraints –––––––––––––––––––––––––––––
*
* • ‘1 ≤ intervals.length ≤ 1000’
* • ‘intervals[i].length = 2’
* • ‘0 ≤ lᵢ ≤ rᵢ ≤ 10⁵’
* • All the given intervals are “unique” .
*
*/
struct q1288 : public ::testing::Test {
// Leetcode answer here
class Solution {
public:
int removeCoveredIntervals(vector<vector<int>> &intervals) {
sort(intervals.begin(), intervals.end(), [](const vector<int> &x, const vector<int> &y) {
return x[0] == y[0] ? x[1] > y[1] : x[0] < y[0];
});
int res = intervals.size();
vector<int> curr = intervals.front();
for (auto it = intervals.begin() + 1; it != intervals.end(); ++it) {
int l = curr[0],
r = curr[1];
if (l <= (*it)[0] && r >= (*it)[1]) {
--res;
} else {
curr = *it;
}
}
return res;
}
};
class Solution *solution;
};
TEST_F(q1288, sample_input01) {
solution = new Solution();
vector<vector<int>> intervals = {{1, 4}, {3, 6}, {2, 8}};
int exp = 2;
int act = solution->removeCoveredIntervals(intervals);
EXPECT_EQ(act, exp);
delete solution;
}
TEST_F(q1288, sample_input02) {
solution = new Solution();
vector<vector<int>> intervals = {{1, 4}, {2, 3}};
int exp = 1;
int act = solution->removeCoveredIntervals(intervals);
EXPECT_EQ(act, exp);
delete solution;
} | 27.465753 | 95 | 0.539651 | vNaonLu |
b87f61a901338830bacddd80b689d591cb5bddb3 | 25,904 | cpp | C++ | builder/llpcBuilder.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | builder/llpcBuilder.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | builder/llpcBuilder.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2019 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
* 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.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcBuilder.cpp
* @brief LLPC source file: implementation of Llpc::Builder
***********************************************************************************************************************
*/
#include "llpcBuilderImpl.h"
#include "llpcPipelineState.h"
#include "llpcContext.h"
#include "llpcInternal.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Support/CommandLine.h"
#include <set>
#define DEBUG_TYPE "llpc-builder"
using namespace Llpc;
using namespace llvm;
// -use-builder-recorder
static cl::opt<uint32_t> UseBuilderRecorder("use-builder-recorder",
cl::desc("Do lowering via recording and replaying LLPC builder:\n"
"0: Generate IR directly; no recording\n"
"1: Do lowering via recording and replaying LLPC builder (default)\n"
"2: Do lowering via recording; no replaying"),
cl::init(1));
// =====================================================================================================================
// Create a Builder object
// If -use-builder-recorder is 0, this creates a BuilderImpl. Otherwise, it creates a BuilderRecorder.
Builder* Builder::Create(
LLVMContext& context) // [in] LLVM context
{
if (UseBuilderRecorder == 0)
{
// -use-builder-recorder=0: generate LLVM IR directly without recording
return CreateBuilderImpl(context);
}
// -use-builder-recorder=1: record with BuilderRecorder and replay with BuilderReplayer
// -use-builder-recorder=2: record with BuilderRecorder and do not replay
return CreateBuilderRecorder(context, UseBuilderRecorder == 1 /*wantReplay*/);
}
// =====================================================================================================================
// Create a BuilderImpl object
Builder* Builder::CreateBuilderImpl(
LLVMContext& context) // [in] LLVM context
{
return new BuilderImpl(context);
}
// =====================================================================================================================
Builder::Builder(
LLVMContext& context) // [in] LLPC context
:
IRBuilder<>(context)
{
m_pPipelineState = new PipelineState(&context);
}
// =====================================================================================================================
Builder::~Builder()
{
delete m_pPipelineState;
}
// =====================================================================================================================
// Get the type pElementTy, turned into a vector of the same vector width as pMaybeVecTy if the latter
// is a vector type.
Type* Builder::GetConditionallyVectorizedTy(
Type* pElementTy, // [in] Element type
Type* pMaybeVecTy) // [in] Possible vector type to get number of elements from
{
if (auto pVecTy = dyn_cast<VectorType>(pMaybeVecTy))
{
return VectorType::get(pElementTy, pVecTy->getNumElements());
}
return pElementTy;
}
// =====================================================================================================================
// Set the resource mapping nodes for the given shader stage.
// This stores the nodes as IR metadata.
void Builder::SetUserDataNodes(
ArrayRef<ResourceMappingNode> nodes, // The resource mapping nodes
ArrayRef<DescriptorRangeValue> rangeValues) // The descriptor range values
{
m_pPipelineState->SetUserDataNodes(nodes, rangeValues);
}
// =====================================================================================================================
// Base implementation of linking shader modules into a pipeline module.
Module* Builder::Link(
ArrayRef<Module*> modules, // Array of modules indexed by shader stage, with nullptr entry
// for any stage not present in the pipeline
bool linkNativeStages) // Whether to link native shader stage modules
{
// Add IR metadata for the shader stage to each function in each shader, and rename the entrypoint to
// ensure there is no clash on linking.
if (linkNativeStages)
{
uint32_t metaKindId = getContext().getMDKindID(LlpcName::ShaderStageMetadata);
for (uint32_t stage = 0; stage < modules.size(); ++stage)
{
Module* pModule = modules[stage];
if (pModule == nullptr)
{
continue;
}
auto pStageMetaNode = MDNode::get(getContext(), { ConstantAsMetadata::get(getInt32(stage)) });
for (Function& func : *pModule)
{
if (func.isDeclaration() == false)
{
func.setMetadata(metaKindId, pStageMetaNode);
if (func.getLinkage() != GlobalValue::InternalLinkage)
{
func.setName(Twine(LlpcName::EntryPointPrefix) +
GetShaderStageAbbreviation(static_cast<ShaderStage>(stage), true) +
"." +
func.getName());
}
}
}
}
}
// If there is only one shader, just change the name on its module and return it.
Module* pPipelineModule = nullptr;
for (auto pModule : modules)
{
if (pPipelineModule == nullptr)
{
pPipelineModule = pModule;
}
else if (pModule != nullptr)
{
pPipelineModule = nullptr;
break;
}
}
if (pPipelineModule != nullptr)
{
pPipelineModule->setModuleIdentifier("llpcPipeline");
// Record pipeline state into IR metadata.
if (m_pPipelineState != nullptr)
{
m_pPipelineState->RecordState(pPipelineModule);
}
}
else
{
// Create an empty module then link each shader module into it. We record pipeline state into IR
// metadata before the link, to avoid problems with a Constant for an immutable descriptor value
// disappearing when modules are deleted.
bool result = true;
pPipelineModule = new Module("llpcPipeline", getContext());
static_cast<Llpc::Context*>(&getContext())->SetModuleTargetMachine(pPipelineModule);
Linker linker(*pPipelineModule);
if (m_pPipelineState != nullptr)
{
m_pPipelineState->RecordState(pPipelineModule);
}
for (int32_t shaderIndex = 0; shaderIndex < modules.size(); ++shaderIndex)
{
if (modules[shaderIndex] != nullptr)
{
// NOTE: We use unique_ptr here. The shader module will be destroyed after it is
// linked into pipeline module.
if (linker.linkInModule(std::unique_ptr<Module>(modules[shaderIndex])))
{
result = false;
}
}
}
if (result == false)
{
delete pPipelineModule;
pPipelineModule = nullptr;
}
}
return pPipelineModule;
}
// =====================================================================================================================
// Create a map to i32 function. Many AMDGCN intrinsics only take i32's, so we need to massage input data into an i32
// to allow us to call these intrinsics. This helper takes a function pointer, massage arguments, and passthrough
// arguments and massages the mappedArgs into i32's before calling the function pointer. Note that all massage
// arguments must have the same type.
Value* Builder::CreateMapToInt32(
PFN_MapToInt32Func pfnMapFunc, // [in] The function to call on each provided i32.
ArrayRef<Value*> mappedArgs, // The arguments to be massaged into i32's and passed to function.
ArrayRef<Value*> passthroughArgs) // The arguments to be passed through as is (no massaging).
{
// We must have at least one argument to massage.
LLPC_ASSERT(mappedArgs.size() > 0);
Type* const pType = mappedArgs[0]->getType();
// Check the massage types all match.
for (uint32_t i = 1; i < mappedArgs.size(); i++)
{
LLPC_ASSERT(mappedArgs[i]->getType() == pType);
}
if (mappedArgs[0]->getType()->isVectorTy())
{
// For vectors we extract each vector component and map them individually.
const uint32_t compCount = pType->getVectorNumElements();
SmallVector<Value*, 4> results;
for (uint32_t i = 0; i < compCount; i++)
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
newMappedArgs.push_back(CreateExtractElement(pMappedArg, i));
}
results.push_back(CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs));
}
Value* pResult = UndefValue::get(VectorType::get(results[0]->getType(), compCount));
for (uint32_t i = 0; i < compCount; i++)
{
pResult = CreateInsertElement(pResult, results[i], i);
}
return pResult;
}
else if (pType->isIntegerTy() && pType->getIntegerBitWidth() == 1)
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
newMappedArgs.push_back(CreateZExt(pMappedArg, getInt32Ty()));
}
Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
return CreateTrunc(pResult, getInt1Ty());
}
else if (pType->isIntegerTy() && pType->getIntegerBitWidth() < 32)
{
SmallVector<Value*, 4> newMappedArgs;
Type* const pVectorType = VectorType::get(pType, (pType->getPrimitiveSizeInBits() == 16) ? 2 : 4);
Value* const pUndef = UndefValue::get(pVectorType);
for (Value* const pMappedArg : mappedArgs)
{
Value* const pNewMappedArg = CreateInsertElement(pUndef, pMappedArg, static_cast<uint64_t>(0));
newMappedArgs.push_back(CreateBitCast(pNewMappedArg, getInt32Ty()));
}
Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
return CreateExtractElement(CreateBitCast(pResult, pVectorType), static_cast<uint64_t>(0));
}
else if (pType->getPrimitiveSizeInBits() == 64)
{
SmallVector<Value*, 4> castMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
castMappedArgs.push_back(CreateBitCast(pMappedArg, VectorType::get(getInt32Ty(), 2)));
}
Value* pResult = UndefValue::get(castMappedArgs[0]->getType());
for (uint32_t i = 0; i < 2; i++)
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pCastMappedArg : castMappedArgs)
{
newMappedArgs.push_back(CreateExtractElement(pCastMappedArg, i));
}
Value* const pResultComp = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
pResult = CreateInsertElement(pResult, pResultComp, i);
}
return CreateBitCast(pResult, pType);
}
else if (pType->isFloatingPointTy())
{
SmallVector<Value*, 4> newMappedArgs;
for (Value* const pMappedArg : mappedArgs)
{
newMappedArgs.push_back(CreateBitCast(pMappedArg, getIntNTy(pMappedArg->getType()->getPrimitiveSizeInBits())));
}
Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs);
return CreateBitCast(pResult, pType);
}
else if (pType->isIntegerTy(32))
{
return pfnMapFunc(*this, mappedArgs, passthroughArgs);
}
else
{
LLPC_NEVER_CALLED();
return nullptr;
}
}
// =====================================================================================================================
// Gets new matrix type after doing matrix transposing.
Type* Builder::GetTransposedMatrixTy(
Type* const pMatrixType // [in] The matrix type to get the transposed type from.
) const
{
LLPC_ASSERT(pMatrixType->isArrayTy());
Type* const pColumnVectorType = pMatrixType->getArrayElementType();
LLPC_ASSERT(pColumnVectorType->isVectorTy());
const uint32_t columnCount = pMatrixType->getArrayNumElements();
const uint32_t rowCount = pColumnVectorType->getVectorNumElements();
return ArrayType::get(VectorType::get(pColumnVectorType->getVectorElementType(), columnCount), rowCount);
}
// =====================================================================================================================
// Get the LLPC context. This overrides the IRBuilder method that gets the LLVM context.
Context& Builder::getContext() const
{
return *static_cast<Llpc::Context*>(&IRBuilder<>::getContext());
}
// =====================================================================================================================
// Get the type of pointer returned by CreateLoadBufferDesc.
PointerType* Builder::GetBufferDescTy(
Type* pPointeeTy) // [in] Type that the returned pointer should point to.
{
return PointerType::get(pPointeeTy, ADDR_SPACE_BUFFER_FAT_POINTER);
}
// =====================================================================================================================
// Get the type of an image descriptor
VectorType* Builder::GetImageDescTy()
{
return VectorType::get(getInt32Ty(), 8);
}
// =====================================================================================================================
// Get the type of an fmask descriptor
VectorType* Builder::GetFmaskDescTy()
{
return VectorType::get(getInt32Ty(), 8);
}
// =====================================================================================================================
// Get the type of a texel buffer descriptor
VectorType* Builder::GetTexelBufferDescTy()
{
return VectorType::get(getInt32Ty(), 4);
}
// =====================================================================================================================
// Get the type of a sampler descriptor
VectorType* Builder::GetSamplerDescTy()
{
return VectorType::get(getInt32Ty(), 4);
}
// =====================================================================================================================
// Get the type of pointer to image descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetImageDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetImageDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of pointer to fmask descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetFmaskDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetFmaskDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of pointer to texel buffer descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetTexelBufferDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetTexelBufferDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of pointer to sampler descriptor.
// This is in fact a struct containing the pointer itself plus the stride in dwords.
Type* Builder::GetSamplerDescPtrTy()
{
return StructType::get(getContext(), { PointerType::get(GetSamplerDescTy(), ADDR_SPACE_CONST), getInt32Ty() });
}
// =====================================================================================================================
// Get the type of a built-in. Where the built-in has a shader-defined array size (ClipDistance,
// CullDistance, SampleMask), inOutInfo.GetArraySize() is used as the array size.
Type* Builder::GetBuiltInTy(
BuiltInKind builtIn, // Built-in kind
InOutInfo inOutInfo) // Extra input/output info (shader-defined array size)
{
enum TypeCode: uint32_t
{
a2f32,
a4f32,
af32,
ai32,
f32,
i1,
i32,
i64,
mask,
v2f32,
v3f32,
v3i32,
v4f32,
v4i32,
a4v3f32
};
uint32_t arraySize = inOutInfo.GetArraySize();
TypeCode typeCode = TypeCode::i32;
switch (builtIn)
{
#define BUILTIN(name, number, out, in, type) \
case BuiltIn ## name: \
typeCode = TypeCode:: type; \
break;
#include "llpcBuilderBuiltIns.h"
#undef BUILTIN
default:
LLPC_NEVER_CALLED();
break;
}
switch (typeCode)
{
case TypeCode::a2f32: return ArrayType::get(getFloatTy(), 2);
case TypeCode::a4f32: return ArrayType::get(getFloatTy(), 4);
// For ClipDistance and CullDistance, the shader determines the array size.
case TypeCode::af32: return ArrayType::get(getFloatTy(), arraySize);
// For SampleMask, the shader determines the array size.
case TypeCode::ai32: return ArrayType::get(getInt32Ty(), arraySize);
case TypeCode::f32: return getFloatTy();
case TypeCode::i1: return getInt1Ty();
case TypeCode::i32: return getInt32Ty();
case TypeCode::i64: return getInt64Ty();
case TypeCode::v2f32: return VectorType::get(getFloatTy(), 2);
case TypeCode::v3f32: return VectorType::get(getFloatTy(), 3);
case TypeCode::v4f32: return VectorType::get(getFloatTy(), 4);
case TypeCode::v3i32: return VectorType::get(getInt32Ty(), 3);
case TypeCode::v4i32: return VectorType::get(getInt32Ty(), 4);
case TypeCode::a4v3f32: return ArrayType::get(VectorType::get(getFloatTy(), 3), 4);
default:
LLPC_NEVER_CALLED();
return nullptr;
}
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type from the given APFloat, converting APFloat semantics where necessary
Constant* Builder::GetFpConstant(
Type* pTy, // [in] FP scalar or vector type
APFloat value) // APFloat value
{
const fltSemantics* pSemantics = &APFloat::IEEEdouble();
Type* pScalarTy = pTy->getScalarType();
if (pScalarTy->isHalfTy())
{
pSemantics = &APFloat::IEEEhalf();
}
else if (pScalarTy->isFloatTy())
{
pSemantics = &APFloat::IEEEsingle();
}
bool ignored = true;
value.convert(*pSemantics, APFloat::rmNearestTiesToEven, &ignored);
return ConstantFP::get(pTy, value);
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type for the value PI/180, for converting radians to degrees.
Constant* Builder::GetPiOver180(
Type* pTy) // [in] FP scalar or vector type
{
// PI/180, 0.017453292
// TODO: Use a value that works for double as well.
return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, 0x3F91DF46A0000000)));
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type for the value 180/PI, for converting degrees to radians.
Constant* Builder::Get180OverPi(
Type* pTy) // [in] FP scalar or vector type
{
// 180/PI, 57.29577951308232
// TODO: Use a value that works for double as well.
return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, 0x404CA5DC20000000)));
}
// =====================================================================================================================
// Get a constant of FP or vector of FP type for the value 1/(2^n - 1)
Constant* Builder::GetOneOverPower2MinusOne(
Type* pTy, // [in] FP scalar or vector type
uint32_t n) // Power of two to use
{
// We could calculate this here, using knowledge that 1(2^n - 1) in binary has a repeating bit pattern
// of {n-1 zeros, 1 one}. But instead we just special case the values of n that we know are
// used from the frontend.
uint64_t bits = 0;
switch (n) {
case 7: // 1/127
bits = 0x3F80204081020408;
break;
case 8: // 1/255
bits = 0x3F70101010101010;
break;
case 15: // 1/32767
bits = 0x3F00002000400080;
break;
case 16: // 1/65535
bits = 0x3EF0001000100010;
break;
default:
LLPC_NEVER_CALLED();
}
return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, bits)));
}
// =====================================================================================================================
// Create a call to the specified intrinsic with one operand, mangled on its type.
// This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math
// flags from the Builder if none are specified by pFmfSource.
CallInst* Builder::CreateUnaryIntrinsic(
Intrinsic::ID id, // Intrinsic ID
Value* pValue, // [in] Input value
Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder
const Twine& instName) // [in] Name to give instruction
{
CallInst* pResult = IRBuilder<>::CreateUnaryIntrinsic(id, pValue, pFmfSource, instName);
if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult))
{
// There are certain intrinsics with an FP result that we do not want FMF on.
switch (id)
{
case Intrinsic::amdgcn_wqm:
case Intrinsic::amdgcn_wwm:
break;
default:
pResult->setFastMathFlags(getFastMathFlags());
break;
}
}
return pResult;
}
// =====================================================================================================================
// Create a call to the specified intrinsic with two operands of the same type, mangled on that type.
// This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math
// flags from the Builder if none are specified by pFmfSource.
CallInst* Builder::CreateBinaryIntrinsic(
Intrinsic::ID id, // Intrinsic ID
Value* pValue1, // [in] Input value 1
Value* pValue2, // [in] Input value 2
Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder
const Twine& name) // [in] Name to give instruction
{
CallInst* pResult = IRBuilder<>::CreateBinaryIntrinsic(id, pValue1, pValue2, pFmfSource, name);
if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult))
{
pResult->setFastMathFlags(getFastMathFlags());
}
return pResult;
}
// =====================================================================================================================
// Create a call to the specified intrinsic with the specified operands, mangled on the specified types.
// This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math
// flags from the Builder if none are specified by pFmfSource.
CallInst* Builder::CreateIntrinsic(
Intrinsic::ID id, // Intrinsic ID
ArrayRef<Type*> types, // [in] Types
ArrayRef<Value*> args, // [in] Input values
Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder
const Twine& name) // [in] Name to give instruction
{
CallInst* pResult = IRBuilder<>::CreateIntrinsic(id, types, args, pFmfSource, name);
if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult))
{
pResult->setFastMathFlags(getFastMathFlags());
}
return pResult;
}
| 40.72956 | 123 | 0.552617 | hustwarhd |
b8820d698f9791ef3cae05f9ed6ee384fa697210 | 4,324 | tcc | C++ | libcross2d/include/cross2d/skeleton/tweeny/tweenpoint.tcc | minkcv/pinballnx | 2a911c144c97278abcff00c237766380908031de | [
"MIT"
] | 6 | 2019-07-01T03:21:02.000Z | 2021-09-13T17:15:01.000Z | libcross2d/include/cross2d/skeleton/tweeny/tweenpoint.tcc | minkcv/pinballnx | 2a911c144c97278abcff00c237766380908031de | [
"MIT"
] | 3 | 2019-07-01T03:53:56.000Z | 2020-06-17T09:14:27.000Z | libcross2d/include/cross2d/skeleton/tweeny/tweenpoint.tcc | minkcv/pinballnx | 2a911c144c97278abcff00c237766380908031de | [
"MIT"
] | 1 | 2019-07-23T12:28:30.000Z | 2019-07-23T12:28:30.000Z | /*
This file is part of the Tweeny library.
Copyright (c) 2016-2018 Leonardo G. Lucena de Freitas
Copyright (c) 2016 Guilherme R. Costa
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* This file implements the tweenpoint class
*/
#ifndef TWEENY_TWEENPOINT_TCC
#define TWEENY_TWEENPOINT_TCC
#include <algorithm>
#include <type_traits>
#include "tweenpoint.h"
#include "tweentraits.h"
#include "easing.h"
#include "easingresolve.h"
#include "int2type.h"
namespace tweeny {
namespace detail {
template<typename TypeTupleT, typename EasingCollectionT, typename EasingT, size_t I>
void easingfill(EasingCollectionT &f, EasingT easing, int2type<I>) {
easingresolve<I, TypeTupleT, EasingCollectionT, EasingT>::impl(f, easing);
easingfill<TypeTupleT, EasingCollectionT, EasingT>(f, easing, int2type<I - 1>{});
}
template<typename TypeTupleT, typename EasingCollectionT, typename EasingT>
void easingfill(EasingCollectionT &f, EasingT easing, int2type<0>) {
easingresolve<0, TypeTupleT, EasingCollectionT, EasingT>::impl(f, easing);
}
template<class ...T>
struct are_same;
template<class A, class B, class ...T>
struct are_same<A, B, T...> {
static const bool value = std::is_same<A, B>::value && are_same<B, T...>::value;
};
template<class A>
struct are_same<A> {
static const bool value = true;
};
template<typename... Ts>
inline tweenpoint<Ts...>::tweenpoint(Ts... vs) : values{vs...} {
during(static_cast<uint16_t>(0));
via(easing::linear);
}
template<typename... Ts>
template<typename D>
inline void tweenpoint<Ts...>::during(D milis) {
for (uint16_t &t : durations) { t = static_cast<uint16_t>(milis); }
}
template<typename... Ts>
template<typename... Ds>
inline void tweenpoint<Ts...>::during(Ds... milis) {
static_assert(sizeof...(Ds) == sizeof...(Ts),
"Amount of durations should be equal to the amount of values in a currentPoint");
std::array<int, sizeof...(Ts)> list = {{milis...}};
std::copy(list.begin(), list.end(), durations.begin());
}
template<typename... Ts>
template<typename... Fs>
inline void tweenpoint<Ts...>::via(Fs... fs) {
static_assert(sizeof...(Fs) == sizeof...(Ts),
"Number of functions passed to via() must be equal the number of values.");
detail::easingresolve<0, std::tuple<Ts...>, typename traits::easingCollection, Fs...>::impl(easings, fs...);
}
template<typename... Ts>
template<typename F>
inline void tweenpoint<Ts...>::via(F f) {
easingfill<typename traits::valuesType>(easings, f, int2type<sizeof...(Ts) - 1>{});
}
template<typename... Ts>
inline uint16_t tweenpoint<Ts...>::duration() const {
return *std::max_element(durations.begin(), durations.end());
}
template<typename... Ts>
inline uint16_t tweenpoint<Ts...>::duration(size_t i) const {
return durations.at(i);
}
}
}
#endif //TWEENY_TWEENPOINT_TCC
| 37.275862 | 120 | 0.641304 | minkcv |
b888b9126c171245de259d7cefe90c151647eead | 4,532 | cpp | C++ | app/src/main/cpp/zqcnn_mtcnn_nchwc4_jni.cpp | zhu260824/ZQCNN_Android | 337fab2b58f14d118b59072d9469646cdba43d57 | [
"Apache-2.0"
] | 8 | 2019-06-18T14:38:56.000Z | 2020-09-14T07:23:08.000Z | app/src/main/cpp/zqcnn_mtcnn_nchwc4_jni.cpp | zhu260824/ZQCNN_Android | 337fab2b58f14d118b59072d9469646cdba43d57 | [
"Apache-2.0"
] | 1 | 2019-06-26T09:10:21.000Z | 2019-06-26T09:10:21.000Z | app/src/main/cpp/zqcnn_mtcnn_nchwc4_jni.cpp | zhu260824/ZQCNN_Android | 337fab2b58f14d118b59072d9469646cdba43d57 | [
"Apache-2.0"
] | 3 | 2019-06-27T00:49:48.000Z | 2020-04-17T02:21:50.000Z | //
// Created by ZL on 2019-06-13.
//
#include "zqcnn_mtcnn_nchwc4.h"
#include <android/log.h>
#include <jni.h>
#include <string>
#include <vector>
#include <imgproc/types_c.h>
#define TAG "ZQCNN"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
using namespace std;
using namespace cv;
using namespace ZQ;
static MTCNNNCHWC *mtcnnnchwc;
extern "C" {
JNIEXPORT jboolean JNICALL
Java_com_zl_demo_MTCNNNCHWC_initModelPath(JNIEnv *env, jobject instance, jstring modelPath_) {
if (NULL == modelPath_) {
return false;
}
//获取MTCNN模型的绝对路径的目录(不是/aaa/bbb.bin这样的路径,是/aaa/)
const char *modelPath = env->GetStringUTFChars(modelPath_, 0);
if (NULL == modelPath) {
return false;
}
string tFaceModelDir = modelPath;
string tLastChar = tFaceModelDir.substr(tFaceModelDir.length() - 1, 1);
//目录补齐/
if ("\\" == tLastChar) {
tFaceModelDir = tFaceModelDir.substr(0, tFaceModelDir.length() - 1) + "/";
} else if (tLastChar != "/") {
tFaceModelDir += "/";
}
LOGD("init, tFaceModelDir=%s", tFaceModelDir.c_str());
mtcnnnchwc = new MTCNNNCHWC(tFaceModelDir);
return true;
}
JNIEXPORT jfloatArray JNICALL
Java_com_zl_demo_MTCNNNCHWC_detectFace(JNIEnv *env, jobject instance, jstring imgPath_) {
const char *imgPath = env->GetStringUTFChars(imgPath_, 0);
vector<ZQ_CNN_BBox> faceInfo = mtcnnnchwc->detect(imgPath);
int32_t num_face = static_cast<int32_t>(faceInfo.size());
LOGD("检测到的人脸数目:%d\n", num_face);
int out_size = 1 + num_face * 29;
float *faces = new float[out_size];
faces[0] = num_face;
for (int i = 0; i < num_face; i++) {
float score = faceInfo[i].score;
int row1 = faceInfo[i].row1;
int col1 = faceInfo[i].col1;
int row2 = faceInfo[i].row2;
int col2 = faceInfo[i].col2;
LOGD("faceInfo:score=%.3f;row1=%d,col1=%d,row2=%d,col2=%d\n", score, row1, col1, row2,
col2);
}
jfloatArray tFaces = env->NewFloatArray(out_size);
env->SetFloatArrayRegion(tFaces, 0, out_size, faces);
return tFaces;
}
JNIEXPORT jobjectArray JNICALL
Java_com_zl_demo_MTCNNNCHWC_detect(JNIEnv *env, jobject instance, jbyteArray yuv, jint width,
jint height) {
jobjectArray faceArgs = nullptr;
jbyte *pBuf = (jbyte *) env->GetByteArrayElements(yuv, 0);
Mat image(height + height / 2, width, CV_8UC1, (unsigned char *) pBuf);
Mat mBgr;
cvtColor(image, mBgr, CV_YUV2BGR_NV21);
vector<ZQ_CNN_BBox> faceInfo = mtcnnnchwc->detectMat(mBgr);
int32_t num_face = static_cast<int32_t>(faceInfo.size());
/**
* 获取Face类以及其对于参数的签名
*/
jclass faceClass = env->FindClass("com/zl/demo/FaceInfo");//获取Face类
jmethodID faceClassInitID = (env)->GetMethodID(faceClass, "<init>", "()V");
jfieldID faceScore = env->GetFieldID(faceClass, "score",
"F");//获取int类型参数confidence
jfieldID faceRect = env->GetFieldID(faceClass, "faceRect",
"Landroid/graphics/Rect;");//获取faceRect的签名
/**
* 获取RECT类以及对应参数的签名
*/
jclass rectClass = env->FindClass("android/graphics/Rect");//获取到RECT类
jmethodID rectClassInitID = (env)->GetMethodID(rectClass, "<init>", "()V");
jfieldID rect_left = env->GetFieldID(rectClass, "left", "I");//获取x的签名
jfieldID rect_top = env->GetFieldID(rectClass, "top", "I");//获取y的签名
jfieldID rect_right = env->GetFieldID(rectClass, "right", "I");//获取width的签名
jfieldID rect_bottom = env->GetFieldID(rectClass, "bottom", "I");//获取height的签名
faceArgs = (env)->NewObjectArray(num_face, faceClass, 0);
LOGD("检测到的人脸数目:%d\n", num_face);
for (int i = 0; i < num_face; i++) {
float score = faceInfo[i].score;
int row1 = faceInfo[i].row1;
int col1 = faceInfo[i].col1;
int row2 = faceInfo[i].row2;
int col2 = faceInfo[i].col2;
jobject newFace = (env)->NewObject(faceClass, faceClassInitID);
jobject newRect = (env)->NewObject(rectClass, rectClassInitID);
(env)->SetIntField(newRect, rect_left, row1);
(env)->SetIntField(newRect, rect_top, col1);
(env)->SetIntField(newRect, rect_right, row2);
(env)->SetIntField(newRect, rect_bottom, col2);
(env)->SetObjectField(newFace, faceRect, newRect);
(env)->SetFloatField(newFace, faceScore, score);
(env)->SetObjectArrayElement(faceArgs, i, newFace);
}
free(pBuf);
return faceArgs;
}
} | 36.845528 | 94 | 0.644748 | zhu260824 |
b8912f7577b1ff9fb94ab1de217144dd547167b8 | 2,449 | cpp | C++ | addStrings/main.cpp | DaveKerk/Cloud-Code | 37db3f7e203b909271bfcdd0df331904fd17c412 | [
"MIT"
] | null | null | null | addStrings/main.cpp | DaveKerk/Cloud-Code | 37db3f7e203b909271bfcdd0df331904fd17c412 | [
"MIT"
] | 1 | 2017-01-26T04:11:23.000Z | 2017-02-03T01:14:41.000Z | addStrings/main.cpp | DaveKerk/Cloud-Code | 37db3f7e203b909271bfcdd0df331904fd17c412 | [
"MIT"
] | null | null | null | // 00000011111111112222222222333333333344444444445555555555666666666677777777778
// 45678901234567890123456789012345678901234567890123456789012345678901234567890
//
// File Name : addStrings.cpp
// File Type : Source code
// Purpose : Main program (Adding two strings).
//
// Date : 2017-02-23
// Version : 1.0.0
// Copyrights : FRCC
//
// Author : Mohammad Huwaidi
// E-Mail : [email protected]
// Style : http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
// Document : http://www.stack.nl/~dimitri/doxygen/index.html
//
// 00000011111111112222222222333333333344444444445555555555666666666677777777778
// 45678901234567890123456789012345678901234567890123456789012345678901234567890
//
//
// Define the PAUSE depending on the operating system:
// Do not worry about this code until where HERE is written
#if defined(_WIN32) || defined(WIN32) // Windows machine
#include <windows.h>
#define PAUSE "pause" // The pause command for DOS window.
#else // Unix-based machines
// Following is the pause command for the BASH script that runs on UNIX:
#define PAUSE "read -p 'Press [Enter] key to continue ...'"
#endif
// HERE
// C++ include files:
#include <iostream> // I/O manipulation; e.g., cout.
#include <string> // String types and operations.
using namespace std;
// 0000001111111111222222222233333333334444444444555555555566666666667777777777
// 4567890123456789012345678901234567890123456789012345678901234567890123456789
//
// The main function that is invoked by the operating system.
//
int main(int argc, char * argv[])
{
// Define some variables. It is a good idea to make them constants if they
// will not be modified later in the program.
string fname;
string lname;
cout << "What is your first name?" << endl;
cin >> fname;
cout << "Now your last name." << endl;
cin >> lname;
const string first_name = fname; // Define and initialize the 1st name.
const string last_name = lname; // Define and initialize the last name.
const string full_name = first_name + string(" ") + last_name; // Combine the two names
cout << "Your name is " << first_name + last_name << endl;
cout << "Full name is " << full_name << endl;
//system(PAUSE); // Pause for the user so the window doesn't disappear.
return 0; // Since nothing went wrong, go back to the OS normally.
}
| 38.265625 | 92 | 0.705186 | DaveKerk |
b892545b8861da99b61befca57cb6746ced83e6c | 648 | cpp | C++ | CtCI-6th-Edition-cpp/04_Trees_and_Graphs/04_Check_Balanced/isBalanced.test.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | CtCI-6th-Edition-cpp/04_Trees_and_Graphs/04_Check_Balanced/isBalanced.test.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | CtCI-6th-Edition-cpp/04_Trees_and_Graphs/04_Check_Balanced/isBalanced.test.cpp | longztian/cpp | 59203f41162f40a46badf69093d287250e5cbab6 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "isBalanced.hpp"
namespace BT = BinaryTreeUnique;
TEST_CASE("isBalanced test", "[isBalanced]") {
auto tree = BT::create("[]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1,2]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1,null,2]");
REQUIRE(isBalanced(tree) == true);
tree = BT::create("[1,2,3]");
REQUIRE(isBalanced(tree) == false);
tree = BT::create("[1,2,3,null,null,4]");
REQUIRE(isBalanced(tree) == false);
tree = BT::create("[1,2,3,null,null,null,4]");
REQUIRE(isBalanced(tree) == true);
}
| 23.142857 | 48 | 0.617284 | longztian |
b89400e94f3467a599d91ccfb19b79fe41f67548 | 2,901 | hpp | C++ | engine/gtp/Engine.hpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | engine/gtp/Engine.hpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | engine/gtp/Engine.hpp | imalerich/imgo | 1dc999b62d95b74dd992fd1daf1cb0d974bba8a7 | [
"MIT"
] | null | null | null | #ifndef ENGINE_HPP
#define ENGINE_HPP
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include "Command.hpp"
#include "Argument.hpp"
namespace gtp {
/**
* Defines a function that may be registered to the GTP Engine.
* When an engine recives the corresponding Command, the registered
* function will be called. This function should return the string
* representing the result of the function, it will then be output by the
* Engine (including any additional data needed by the controller).
*/
typedef std::string (*ProcCmd)(const ARG_LIST&);
/**
* An engine for the Go Text Protocol.
* An instance of this class may be used to communicate between
* with the go server that maintains the current game.
*/
class Engine {
public:
/**
* Constructs an Engine by registering the default implementation
* for each supported command.
*/
Engine();
/**
* Main game loop for the engine.
* This will read and execute commands from the given input stream
* until either an EOF is sent or the 'quit' command is given.
* \param is Input stream to read commands from.
*/
void play(std::istream &is);
/**
* Read and execute a single command from the input stream.
* \param is Input stream to read a command from.
*/
void proc_command(std::istream &is);
/**
* Registers the input proc to the given command.
* Whenever that command is received from the controller,
* the proc function will be executed with the arguments
* as supplied by the controller.
* If a proccess is already registered to the input Command,
* that process will be overridden.
* \param cmd Command to register the input proc to.
* \param proc The process to execute on receiving the given command.
*/
void register_proc(Command cmd, const ProcCmd &proc);
private:
std::map<Command,ProcCmd> commands;
/**
* Parse all arguments from the input line, given the type of argument that will be parsed.
* \param cmd Type of command to parse arguments for.
* \param iss Input string stream of the line being parsed.
* \return Array of pointers to argument objects.
*/
ARG_LIST args_for_cmd(const Command &cmd, std::istringstream &iss);
/**
* Performs preprocessing on a line of text.
* The following operation are performed in accordance with the GTP specification.
* 1. Remove all occurences of CR and other control characters except for HT and LF.
* 2. For each line with a hash sign (#), remove all text following and including this characeter.
* 3. Convert all occurences of HT to SPACE.
* 4. Discard any empty or white-space only lines.
* \param line to the line to be processed.
* \return Processed version of the input string.
*/
std::string preproc_line(const std::string &line);
/**
* \param The line in question.
* \return Should this line be ignored?
*/
bool ignore_line(const std::string &line);
};
}
#endif
| 30.536842 | 99 | 0.722509 | imalerich |
b895c774ee235f0a32ab770b51cc581514e2e94f | 4,524 | cpp | C++ | Job-0/Job-0/Job-1-main.cpp | xiliangjianke/GAMES101 | 251f285d21f00dd542ebc326d47b9daddb0c6753 | [
"MIT"
] | null | null | null | Job-0/Job-0/Job-1-main.cpp | xiliangjianke/GAMES101 | 251f285d21f00dd542ebc326d47b9daddb0c6753 | [
"MIT"
] | null | null | null | Job-0/Job-0/Job-1-main.cpp | xiliangjianke/GAMES101 | 251f285d21f00dd542ebc326d47b9daddb0c6753 | [
"MIT"
] | null | null | null | //#include "Triangle.hpp"
//#include "rasterizer.hpp"
//#include <eigen3/Eigen/Eigen>
//#include <iostream>
//#include <opencv2/opencv.hpp>
///*
//constexpr double MY_PI = 3.1415926;
//
//Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
//{
// Eigen::Matrix4f view = Eigen::Matrix4f::Identity();
//
// Eigen::Matrix4f translate;
// translate << 1, 0, 0, -eye_pos[0],
// 0, 1, 0, -eye_pos[1],
// 0, 0, 1, -eye_pos[2],
// 0, 0, 0, 1;
//
// view = translate * view;
//
// return view;
//}
//
//Eigen::Matrix4f get_model_matrix(float rotation_angle)
//{
// Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
//
// // TODO: Implement this function
// // Create the model matrix for rotating the triangle around the Z axis.
// // Then return it.
// double theta = rotation_angle / 180.0 * MY_PI;
//
// model << std::cos(theta), std::sin(theta), 0, 0,
// -std::sin(theta), std::cos(theta), 0, 0,
// 0, 0, 1, 0,
// 0, 0, 0, 1;
//
// return model;
//}
//
//Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
// float zNear, float zFar)
//{
// // Students will implement this function
//
// Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
//
// // TODO: Implement this function
// // Create the projection matrix for the given parameters.
// // Then return it.
//
// // Transformation matrix of perspective projection to orthographic projection
// Eigen::Matrix4f PerspToOrth;
// PerspToOrth << zNear, 0, 0, 0,
// 0, zNear, 0, 0,
// 0, 0, zNear + zFar, -zNear * zFar,
// 0, 0, 0, 1;
//
// // Tan(fov/2) = height/2, aspect = weight / height
// float Height = std::atan(eye_fov / 2 / 180 * MY_PI) * 2;
// float Width = aspect_ratio * Height;
//
// Eigen::Matrix4f ViewPort;
// ViewPort << Width / 2, 0, 0, Width / 2,
// 0, Height / 2, 0, Height / 2,
// 0, 0, 1, 0,
// 0, 0, 0, 1;
//
// projection = ViewPort * PerspToOrth;
//
// return projection;
//}
//
//Eigen::Matrix4f get_rotation(Vector3f axis, float angle)
//{
// // https://www.bilibili.com/read/cv11925407
// Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
// angle = angle / 180.f * MY_PI;
// axis.normalize();
// /*
// float = square = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2];
// axis[0] /= std::sqrt(square);
// axis[1] /= std::sqrt(square);
// axis[2] /= std::sqrt(square);
//
// Eigen::Matrix3f k;
// k << 0.f, -axis[2], axis[1],
// axis[2], 0.f, -axis[0],
// -axis[1], axis[0], 0.f;
// Eigen::Matrix3f E = Eigen::Matrix3f::Identity();
// Eigen::Matrix3f rotation_matrix;
// rotation_matrix = E * std::cos(angle) + std::sin(angle) * k + (1 - std::cos(angle)) * axis * axis.transpose();
//
// model.block<3, 3>(0, 0) = rotation_matrix;
// return model;
//
//}
//
//
//int main(int argc, const char** argv)
//{
// float angle = 45.0f;
// Eigen::Vector3f axis(0, 0, 1);
// bool command_line = false;
// std::string filename = "output.png";
//
// if (argc >= 3) {
// command_line = true;
// angle = std::stof(argv[2]); // -r by default
// if (argc == 4) {
// filename = std::string(argv[3]);
// }
// }
//
// rst::rasterizer r(700, 700);
//
// Eigen::Vector3f eye_pos = { 0, 0, 5 };
//
// std::vector<Eigen::Vector3f> pos{ {2, 0, -2}, {0, 2, -2}, {-2, 0, -2} };
//
// std::vector<Eigen::Vector3i> ind{ {0, 1, 2} };
//
// auto pos_id = r.load_positions(pos);
// auto ind_id = r.load_indices(ind);
//
// int key = 0;
// int frame_count = 0;
//
// if (command_line) {
// r.clear(rst::Buffers::Color | rst::Buffers::Depth);
//
// r.set_model(get_model_matrix(angle));
// r.set_view(get_view_matrix(eye_pos));
// r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
//
// r.draw(pos_id, ind_id, rst::Primitive::Triangle);
// cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
// image.convertTo(image, CV_8UC3, 1.0f);
//
// cv::imwrite(filename, image);
//
// return 0;
// }
//
// while (key != 27) {
// r.clear(rst::Buffers::Color | rst::Buffers::Depth);
//
// //r.set_model(get_rotation(axis, angle));
//
// r.set_model(get_model_matrix(angle));
// r.set_view(get_view_matrix(eye_pos));
// r.set_projection(get_projection_matrix(45, 1, 0.1, 50));
//
// r.draw(pos_id, ind_id, rst::Primitive::Triangle);
//
// cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
// image.convertTo(image, CV_8UC3, 1.0f);
// cv::imshow("image", image);
// key = cv::waitKey(10);
//
// std::cout << "frame count: " << frame_count++ << '\n';
//
// if (key == 'a') {
// angle += 10;
// }
// else if (key == 'd') {
// angle -= 10;
// }
// }
//
// return 0;
//}
//*/
| 26 | 113 | 0.596596 | xiliangjianke |
b897659ed171f916cfb637567e47fb13868eff3c | 2,040 | cpp | C++ | parrlibgl/spritebatch.cpp | AlessandroParrotta/parrlibgl | 2d0a27a16bb17be8d4554bfcdc4f5e2a4946db96 | [
"MIT"
] | null | null | null | parrlibgl/spritebatch.cpp | AlessandroParrotta/parrlibgl | 2d0a27a16bb17be8d4554bfcdc4f5e2a4946db96 | [
"MIT"
] | null | null | null | parrlibgl/spritebatch.cpp | AlessandroParrotta/parrlibgl | 2d0a27a16bb17be8d4554bfcdc4f5e2a4946db96 | [
"MIT"
] | null | null | null | #include "SpriteBatch.h"
namespace prb {
void SpriteBatch::init() {
vao = { { { {}, 4 } } }; //this probably leaks memory if you reinitialize the spritebatch
sh = { "assets/shaders/spritebatch.vert", "assets/shaders/spritebatch.frag" };
}
SpriteBatch::SpriteBatch() {}
SpriteBatch::SpriteBatch(Sprite const& atlas) : atlas(atlas) { init(); }
void SpriteBatch::draw(Sprite const& s, vec2 const& txmin, vec2 const& txmax, mat3 const& transform) {
if (s.tex.texID != atlas.tex.texID) flushAndClear();
vec2 v0 = transform * vec2(-1.f, -1.f);
vec2 v1 = transform * vec2(-1.f, 1.f);
vec2 v2 = transform * vec2(1.f, 1.f);
vec2 v3 = transform * vec2(1.f, -1.f);
if (data.size() < curFloat + 3 * 2 * 4) data.resize(curFloat + 3 * 2 * 4);
data[curFloat++] = v0.x; data[curFloat++] = v0.y; data[curFloat++] = txmin.x; data[curFloat++] = txmin.y;
data[curFloat++] = v1.x; data[curFloat++] = v1.y; data[curFloat++] = txmin.x; data[curFloat++] = txmax.y;
data[curFloat++] = v2.x; data[curFloat++] = v2.y; data[curFloat++] = txmax.x; data[curFloat++] = txmax.y;
data[curFloat++] = v2.x; data[curFloat++] = v2.y; data[curFloat++] = txmax.x; data[curFloat++] = txmax.y;
data[curFloat++] = v3.x; data[curFloat++] = v3.y; data[curFloat++] = txmax.x; data[curFloat++] = txmin.y;
data[curFloat++] = v0.x; data[curFloat++] = v0.y; data[curFloat++] = txmin.x; data[curFloat++] = txmin.y;
}
void SpriteBatch::draw(Sprite const& s, Sprite::AnimationPlayer const& sa, mat3 const& transform) { vec2 offset = s.getOffset(sa) / s.tex.size; draw(s, offset, offset + s.size / s.tex.size, transform); }
void SpriteBatch::draw(Sprite const& s, mat3 const& transform) { draw(s, 0.f, 1.f, transform); }
void SpriteBatch::flush() {
vao.vbos[0].setData(data, curFloat);
sh.use();
sh.setUniform("transform", transform);
sh.setUniform("tex", 0);
util::bindTexture(0, atlas.tex.texID);
vao.draw();
sh.release();
}
void SpriteBatch::clear() { curFloat = 0; }
void SpriteBatch::flushAndClear() { flush(); clear(); }
}
| 43.404255 | 204 | 0.640686 | AlessandroParrotta |
b89a06c8554e9d0b604c6516bfd664f640294d99 | 1,413 | hpp | C++ | src/game/sys/sound/sound_sys.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | src/game/sys/sound/sound_sys.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | src/game/sys/sound/sound_sys.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | /** System that manages sound effects ****************************************
* *
* Copyright (c) 2016 Florian Oetke *
* This file is distributed under the MIT License *
* See LICENSE file for details. *
\*****************************************************************************/
#pragma once
#include <core/audio/audio_ctx.hpp>
#include <core/audio/sound.hpp>
#include <core/engine.hpp>
#include <core/utils/str_id.hpp>
#include <core/utils/messagebus.hpp>
#include <core/units.hpp>
#include <core/ecs/ecs.hpp>
namespace lux {
namespace renderer {
struct Animation_event;
}
namespace sys {
namespace sound {
struct Sound_mappings;
class Sound_sys {
public:
Sound_sys(Engine&, ecs::Entity_manager& ecs);
~Sound_sys();
void update(Time dt);
private:
struct Sound_effect {
audio::Sound_ptr sound;
bool loop = false;
};
audio::Audio_ctx& _audio_ctx;
asset::Asset_manager& _assets;
ecs::Entity_manager& _ecs;
asset::Ptr<Sound_mappings> _mappings;
util::Mailbox_collection _mailbox;
int _last_rev = 0;
std::unordered_map<util::Str_id, Sound_effect> _event_sounds;
void _reload();
void _on_anim_event(const renderer::Animation_event& event);
};
}
}
}
| 23.55 | 79 | 0.55414 | lowkey42 |
b8a20d7bcb754876f1238a5299cb7c9ca05accdf | 5,970 | hpp | C++ | src/astrolabe_exception.hpp | jose-navarro/ASTROLABE | 95482bf4ecd7c22e0bcef18aeae0d8b828b3327c | [
"MIT"
] | null | null | null | src/astrolabe_exception.hpp | jose-navarro/ASTROLABE | 95482bf4ecd7c22e0bcef18aeae0d8b828b3327c | [
"MIT"
] | 3 | 2019-05-28T05:34:50.000Z | 2019-12-09T12:58:22.000Z | src/astrolabe_exception.hpp | jose-navarro/astrolabe | 95482bf4ecd7c22e0bcef18aeae0d8b828b3327c | [
"MIT"
] | null | null | null | /** \file astrolabe_exception.hpp
\brief Definition of the topmost, general ASTROLABE exception.
\ingroup ASTROLABE_exceptions_group
*/
#ifndef ASTROLABE_EXCEPTION_HPP
#define ASTROLABE_EXCEPTION_HPP
#include <stdexcept>
#include <string>
using namespace std;
class astrolabe_time;
/**
\brief ASTROLABE's topmost, general exception.
\ingroup ASTROLABE_exceptions_group
*/
class astrolabe_exception : public exception
{
public:
/// \brief Default constructor.
astrolabe_exception (void);
/// \brief Copy constructor.
/**
\param other The other exception from which the values
will be copied.
*/
astrolabe_exception (const astrolabe_exception & other);
/// \brief Destructor.
virtual ~astrolabe_exception (void);
public:
/// \brief Print the exception.
/**
\param the_stream The stream to print the exception to.
*/
virtual void print (ostream & the_stream) const;
/// \brief Set the description of the exception.
/**
\param the_description The description of the exception.
*/
virtual void set_description (const string & the_description);
/// \brief Get the description of the exception.
/**
\return The description of the exception.
*/
virtual string _description (void) const;
/// \brief Set the name of the source file where the exception takes place.
/**
\param the_file The name of the file to set.
*/
virtual void set_file (const string & the_file);
/// \brief Get the name of the file where the exception takes place.
/**
\return The name of the file where the exception takes place.
*/
virtual string _file (void) const;
/// \brief Set the line number (in the source file) where the exception takes place.
/**
\param the_line The line number to set.
*/
virtual void set_line (int the_line);
/// \brief Ge the line number (in the source file) where the exception takes place.
/**
\return The line number (in the source file) where the exception takes place.
*/
virtual int _line (void) const;
/// \brief Set the name of the class where the exception takes place.
/**
\param the_class The name of the class to set.
*/
virtual void set_class_in (const string & the_class);
/// \brief Retrieve the name of the class where the exception takes place.
/**
\return The name of the class where the exception takes place.
*/
virtual string _class_in (void) const;
/// \brief Set the name of the method where the exception takes place.
/**
\param the_method The name of the method to set.
*/
virtual void set_method_in (const string & the_method);
/// \brief Retrieve the name of the method where the exception takes place.
/**
\return The name of the method where the exception takes place.
*/
virtual string _method_in (void) const;
/// \brief Set the severity level of the exception.
/**
\param The severity level to set. It must be coded as follows:
- Severity = 000 -> INFORMATIONAL (simply information to user)
- Severity = 1000 -> WARNING (it makes sense to continue with the execution)
- Severity = 2000 -> FATAL ERROR (execution was broken)
*/
virtual void set_severity (int the_sever);
/// \brief Retrieve the severity level of the exception.
/**
\return The severity level of the exception. The meaning of the
numerical code returned is:
- Severity = 000 -> INFORMATIONAL (simply information to user)
- Severity = 1000 -> WARNING (it makes sense to continue with the execution)
- Severity = 2000 -> FATAL ERROR (execution was broken)
*/
virtual string _severity (void) const;
/// \brief Set the time when the exception takes place.
/**
\param Time The time when the exception takes place.
*/
virtual void set_time (const astrolabe_time Time);
/// \brief Retrieve the time when the exception takes place.
/**
\param Time The object to which the time when the exception
takes placw will be copied.
*/
virtual void _time ( astrolabe_time & Time) const;
/// \brief Retrieve the exception's alphanumeric code.
/**
\return The exception's alphanumeric code.
*/
virtual string _name_code (void) const;
/// \brief Retrieve the exception's numeric code.
/**
\return The exception's numeric code.
*/
virtual int _num_code (void) const;
protected:
/// \brief Source file where the exception took place.
string file_;
/// \brief Line number within the source file where the exception took place.
int line_;
/// \brief Class of the object throwing the exception.
string class_;
/// \brief Method of the object throwing the exception.
string method_;
/// \brief Short description.
string description_;
/// \brief Error degree.
/**
Three severity levels are allowed:
- Severity = 000 -> INFORMATIONAL (simply information to user)
- Severity = 1000 -> WARNING (it makes sense to continue with the execution)
- Severity = 2000 -> FATAL ERROR (execution was broken)
*/
int severity_;
/// \brief Time of event: year.
int yy_;
/// \brief Time of event: month.
int mm_;
/// \brief Time of event: day.
int dd_;
/// \brief Time of event: hour.
int ho_;
/// \brief Time of event: minute.
int mi_;
/// \brief Time of event: second.
long double se_;
};
ostream & operator << (ostream & result, const astrolabe_exception & the_exception);
#endif
| 25.622318 | 90 | 0.627303 | jose-navarro |
b8a321eb384a8c56db31894ac2698db5a374dc2e | 1,990 | cpp | C++ | Sources/engine/assetdatabase/private/assetdatabase/PathTree.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 20 | 2019-12-22T20:40:22.000Z | 2021-07-06T00:23:45.000Z | Sources/engine/assetdatabase/private/assetdatabase/PathTree.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 32 | 2020-07-11T15:51:13.000Z | 2021-06-07T10:25:07.000Z | Sources/engine/assetdatabase/private/assetdatabase/PathTree.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 3 | 2019-12-19T17:04:04.000Z | 2021-05-17T01:49:59.000Z | #include "PathTree.h"
#include <sstream>
#include "StringUtil.h"
namespace ze::assetdatabase
{
void PathTree::add(const std::filesystem::path& path)
{
ZE_CHECK(path.is_relative());
/** Check if path already exists */
if (has_path(path))
return;
/** Insert the path in the map if it is a directory */
if (!path.has_extension())
paths.insert({ path, PathDirectory() });
/** Now scan each part to build a tree */
std::vector<std::string> tokens = stringutil::split(path.string(),
std::filesystem::path::preferred_separator);
/** Insert at root */
if (tokens.size() == 1)
{
paths[""].childs.insert(path);
}
else
{
std::filesystem::path final_path;
std::filesystem::path parent = "";
for (size_t i = 0; i < tokens.size() - 1; ++i)
{
const auto& token = tokens[i];
final_path = final_path / token;
if (paths[parent].childs.find(token) == paths[parent].childs.end())
{
paths[parent / token].parent = parent;
paths[parent].childs.insert(token);
}
/** Insert file */
if (i == tokens.size() - 2)
{
paths[parent / token].childs.insert(tokens[tokens.size() - 1]);
}
parent /= token;
}
}
}
std::vector<std::filesystem::path> PathTree::get_childs(const std::filesystem::path& path,
const bool& include_files)
{
std::vector<std::filesystem::path> childs;
if (paths.find(path) == paths.end())
return childs;
childs.reserve(paths[path].childs.size());
for (const auto& child : paths[path].childs)
{
if (!include_files && child.has_extension())
continue;
childs.emplace_back(child);
}
return childs;
}
bool PathTree::has_path(const std::filesystem::path& path) const
{
if (path.has_filename())
{
/** Check to the parent of the file */
auto parent_it = paths.find(path.parent_path());
if (parent_it != paths.end())
{
return parent_it->second.childs.find(path.filename()) != parent_it->second.childs.end();
}
return false;
}
else
{
return paths.find(path) != paths.end();
}
}
} | 21.170213 | 91 | 0.647236 | Zino2201 |
b8a79a4bbf613fa1c526f04b1ca6fcb0c4677904 | 520 | cpp | C++ | tute04.cpp | SLIIT-FacultyOfComputing/tutorial-02b-IT21191688 | 4dea9fc2c31d6761332971e8e310c79f4da778bd | [
"MIT"
] | null | null | null | tute04.cpp | SLIIT-FacultyOfComputing/tutorial-02b-IT21191688 | 4dea9fc2c31d6761332971e8e310c79f4da778bd | [
"MIT"
] | null | null | null | tute04.cpp | SLIIT-FacultyOfComputing/tutorial-02b-IT21191688 | 4dea9fc2c31d6761332971e8e310c79f4da778bd | [
"MIT"
] | null | null | null | #include <iostream>
long Factorial(int no);
long nCr(int n, int r);
int main() {
int n, r;
std::cout << "Enter a value for n ";
std::cin >> n;
std::cout << "Enter a value for r ";
std::cin >> r;
std::cout << "nCr = ";
std::cout << nCr(n, r);
std::cout << std::endl;
return 0;
}
long Factorial(int no)
{
long sum;
int i;
sum = 1;
for (i = no; i >= 1; i--)
{
sum = i * sum;
}
return sum;
}
long nCr(int n, int r)
{
long ncr;
ncr = Factorial(n) / (Factorial(r) * Factorial((n-r)));
return ncr;
}
| 14.054054 | 56 | 0.546154 | SLIIT-FacultyOfComputing |
b8acd63d07bc0f2c52e871117bc6e61b11be11d0 | 5,655 | cpp | C++ | tests/src/unit/detail/record.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 193 | 2015-01-05T08:48:05.000Z | 2022-01-31T22:04:01.000Z | tests/src/unit/detail/record.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 135 | 2015-01-13T13:02:49.000Z | 2022-01-12T15:06:48.000Z | tests/src/unit/detail/record.cpp | JakariaBlaine/blackhole | e340329c6e2e3166858d8466656ad12300b686bd | [
"MIT"
] | 40 | 2015-01-21T16:37:30.000Z | 2022-01-25T15:54:04.000Z | #include <memory>
#include <src/recordbuf.hpp>
#include <gtest/gtest.h>
namespace blackhole {
inline namespace v1 {
namespace {
TEST(recordbuf_t, FromRecordMessage) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_pack pack;
const record_t record(0, message, pack);
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(string_view("GET"), result->into_view().message());
}
TEST(owned, FromRecordFormattedMessage) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET: {}");
const attribute_pack pack;
record_t record(0, message, pack);
record.activate("GET: 42");
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(string_view("GET: 42"), result->into_view().formatted());
}
TEST(owned, FromRecordSeverity) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("");
const attribute_pack pack;
const record_t record(42, message, pack);
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(42, result->into_view().severity());
}
TEST(owned, FromRecordTimestamp) {
std::unique_ptr<recordbuf_t> result;
record_t::clock_type::time_point min = {};
record_t::clock_type::time_point max = {};
{
const string_view message("");
const attribute_pack pack;
min = record_t::clock_type::now();
record_t record(0, message, pack);
record.activate();
max = record_t::clock_type::now();
result.reset(new recordbuf_t(record));
}
EXPECT_TRUE(min <= result->into_view().timestamp());
EXPECT_TRUE(max >= result->into_view().timestamp());
}
TEST(owned, FromRecordThreadId) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("");
const attribute_pack pack;
const record_t record(0, message, pack);
result.reset(new recordbuf_t(record));
}
EXPECT_EQ(::pthread_self(), result->into_view().tid());
}
TEST(owned, FromRecordAttributes) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(0, message, pack);
result.reset(new recordbuf_t(record));
}
const attribute_list attributes{{"key#1", "value#1"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(owned, MoveConstructor) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(42, message, pack);
recordbuf_t own(record);
result.reset(new recordbuf_t(std::move(own)));
}
EXPECT_EQ(string_view("GET"), result->into_view().message());
EXPECT_EQ(42, result->into_view().severity());
const attribute_list attributes{{"key#1", "value#1"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(owned, MoveAssignment) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(42, message, pack);
result.reset(new recordbuf_t(record));
}
{
const string_view message("POST");
const attribute_list attributes{{"key#2", "value#2"}};
const attribute_pack pack{attributes};
const record_t record(10, message, pack);
recordbuf_t own(record);
*result = std::move(own);
}
EXPECT_EQ(string_view("POST"), result->into_view().message());
EXPECT_EQ(10, result->into_view().severity());
const attribute_list attributes{{"key#2", "value#2"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(owned, MoveAssignmentWithDifferentSizes) {
std::unique_ptr<recordbuf_t> result;
{
const string_view message("GET");
const attribute_list attributes{{"key#1", "value#1"}};
const attribute_pack pack{attributes};
const record_t record(42, message, pack);
result.reset(new recordbuf_t(record));
}
{
const string_view message("POST");
const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}};
const attribute_pack pack{attributes};
const record_t record(10, message, pack);
recordbuf_t own(record);
*result = std::move(own);
}
EXPECT_EQ(string_view("POST"), result->into_view().message());
EXPECT_EQ(10, result->into_view().severity());
const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}};
ASSERT_EQ(1, result->into_view().attributes().size());
EXPECT_EQ(attributes, result->into_view().attributes().at(0).get());
}
TEST(recordbuf_t, DefaultMove) {
recordbuf_t recordbuf;
const string_view message("POST");
const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}};
const attribute_pack pack{attributes};
const record_t record(10, message, pack);
recordbuf = recordbuf_t(record);
recordbuf_t destroyer;
destroyer = std::move(recordbuf);
}
} // namespace
} // namespace v1
} // namespace blackhole
| 27.1875 | 84 | 0.640318 | JakariaBlaine |
b8adc7d8895a94058707a407ed9472316f79e0d6 | 128 | cpp | C++ | engine/src/core/Allocator.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | 2 | 2018-12-19T01:52:39.000Z | 2022-03-29T16:04:15.000Z | engine/src/core/Allocator.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | engine/src/core/Allocator.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | #include "../../include/core/Allocator.h"
using namespace PhysicsEngine;
Allocator::Allocator()
{
}
Allocator::~Allocator(){}; | 16 | 41 | 0.710938 | jsandham |
b8afaf9523b596a374f84040ad7f91f6b5cc68e1 | 495 | hpp | C++ | src/totem.hpp | Hazematman/Ultrabrew2021 | 934d8609179effcf26ce2f5d53361031d8a1aa01 | [
"WTFPL"
] | 3 | 2021-12-14T00:14:53.000Z | 2022-03-30T04:08:34.000Z | src/totem.hpp | Hazematman/Ultrabrew2021 | 934d8609179effcf26ce2f5d53361031d8a1aa01 | [
"WTFPL"
] | null | null | null | src/totem.hpp | Hazematman/Ultrabrew2021 | 934d8609179effcf26ce2f5d53361031d8a1aa01 | [
"WTFPL"
] | 1 | 2021-12-09T10:21:11.000Z | 2021-12-09T10:21:11.000Z | #ifndef TOTEM_HPP
#define TOTEM_HPP
#include "gameobject.hpp"
class Totem : public GameObject
{
public:
Totem(btVector3 origin, btDiscreteDynamicsWorld *dyn_world);
virtual bool collide(btManifoldPoint &cp,
const btCollisionObjectWrapper *obj1, int id1, int index1);
virtual void update(float dt);
GameObject *carried;
private:
btDiscreteDynamicsWorld *dyn_world;
btCollisionShape *ghost_shape;
btPairCachingGhostObject *ghost;
};
#endif
| 23.571429 | 84 | 0.723232 | Hazematman |
b8b3288e128db7300c87f650925b3f87918bb5fc | 3,840 | cpp | C++ | src/compositor/scenegraph/input/singlebonetracker.cpp | Quora-Users/motorcar | e1cb943d2874a4716556c314190a48294e2bf53a | [
"BSD-2-Clause"
] | 216 | 2015-01-20T17:14:01.000Z | 2022-03-05T16:14:25.000Z | src/compositor/scenegraph/input/singlebonetracker.cpp | Quora-Users/motorcar | e1cb943d2874a4716556c314190a48294e2bf53a | [
"BSD-2-Clause"
] | 12 | 2015-07-09T06:46:09.000Z | 2017-04-13T05:41:08.000Z | src/compositor/scenegraph/input/singlebonetracker.cpp | Quora-Users/motorcar | e1cb943d2874a4716556c314190a48294e2bf53a | [
"BSD-2-Clause"
] | 29 | 2015-03-14T03:19:52.000Z | 2021-01-29T13:43:51.000Z | /****************************************************************************
**This file is part of the Motorcar 3D windowing framework
**
**
**Copyright (C) 2014 Forrest Reiling
**
**
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** 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 <scenegraph/input/singlebonetracker.h>
using namespace motorcar;
SingleBoneTracker::SingleBoneTracker(Bone *trackedBone, glm::mat4 boneTrackTransform, Skeleton *skeleton, PhysicalNode *parent, const glm::mat4 &transform)
:BoneSensor(skeleton, parent, transform)
,m_trackedBone(trackedBone)
,m_boneTrackTransform(boneTrackTransform)
{
}
glm::mat4 SingleBoneTracker::trackerParentSpaceToBoneParentSpaceTransform()
{
//define tracker parent space in bone space
glm::mat4 workingTransform = trackedBone()->inverseWorldTransform() * this->parentNode()->worldTransform();
//apply inverse bone track transform in the bone space
//this makes sure that the bone's orientation is taken into account when applying translation
workingTransform = glm::inverse(boneTrackTransform()) * workingTransform;
//bring into bone parent space
workingTransform = trackedBone()->transform() * workingTransform;
return workingTransform;
}
void SingleBoneTracker::setTransformFromTrackedBone()
{
this->setTransform(this->parentNode()->inverseWorldTransform() * trackedBone()->worldTransform() * boneTrackTransform());
}
void SingleBoneTracker::setPosition(const glm::vec3 &position)
{
glm::vec4 parentSpaceBonePos = trackerParentSpaceToBoneParentSpaceTransform() * glm::vec4(position, 1);
trackedBone()->setPosition(glm::vec3(parentSpaceBonePos));
setTransformFromTrackedBone();
}
void SingleBoneTracker::setOrientation(const glm::mat3 &orientation)
{
glm::mat4 orientation4X4 = glm::mat4(orientation);
glm::mat4 boneOrientation4X4 = trackerParentSpaceToBoneParentSpaceTransform() * orientation4X4 ;
trackedBone()->setOrientation(glm::mat3(boneOrientation4X4));
setTransformFromTrackedBone();
}
Bone *SingleBoneTracker::trackedBone() const
{
return m_trackedBone;
}
void SingleBoneTracker::setTrackedBone(Bone *trackedBone)
{
m_trackedBone = trackedBone;
}
glm::mat4 SingleBoneTracker::boneTrackTransform() const
{
return m_boneTrackTransform;
}
void SingleBoneTracker::setBoneTrackTransform(const glm::mat4 &boneTrackTransform)
{
m_boneTrackTransform = boneTrackTransform;
}
| 33.684211 | 155 | 0.732292 | Quora-Users |
b8b4c69573bb9151f2bc9c7f4a7039e88c727175 | 383 | cpp | C++ | C++/oj1337.cpp | muinocriz/hfutoj | 9c6b0602f1b155cd9cec38e673b064c64f1dc7d6 | [
"Apache-2.0"
] | 18 | 2018-03-22T14:33:14.000Z | 2021-11-07T07:05:32.000Z | C++/oj1337.cpp | muinocriz/hfutoj | 9c6b0602f1b155cd9cec38e673b064c64f1dc7d6 | [
"Apache-2.0"
] | null | null | null | C++/oj1337.cpp | muinocriz/hfutoj | 9c6b0602f1b155cd9cec38e673b064c64f1dc7d6 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int t,i,j,k;
int sum;
char a,b;
cin >>t;
while(t--)
{
sum=0;
cin>>i>>a>>j>>b>>k;
if(a=='+')
sum = i+j;
else
sum = i-j;
if(b=='+')
sum = sum + k;
else
sum=sum-k;
cout <<sum<<endl;
}
return 0;
}
| 15.32 | 27 | 0.355091 | muinocriz |
b8be8de72b7b10648fe75e002dc639285ea5ece9 | 4,978 | cpp | C++ | RayTracer/RayTracer/src/Graphics/Primitives/BoundingBox.cpp | cristi191096/RayTracer | 4065fc86e3445bb6f57b494e02298f12ec3e4da1 | [
"Apache-2.0"
] | null | null | null | RayTracer/RayTracer/src/Graphics/Primitives/BoundingBox.cpp | cristi191096/RayTracer | 4065fc86e3445bb6f57b494e02298f12ec3e4da1 | [
"Apache-2.0"
] | null | null | null | RayTracer/RayTracer/src/Graphics/Primitives/BoundingBox.cpp | cristi191096/RayTracer | 4065fc86e3445bb6f57b494e02298f12ec3e4da1 | [
"Apache-2.0"
] | null | null | null | #include "pch.h"
#include "BoundingBox.h"
BoundingBox::BoundingBox(glm::vec3 min, glm::vec3 max)
{
m_Params[0] = min;
m_Params[1] = max;
m_Centre = (min + max) * 0.5f;
//Split(0);
}
BoundingBox::~BoundingBox()
{
}
void BoundingBox::Split(int level)
{
//if (level == MAX_DEPTH) return;
glm::vec3 min;
glm::vec3 max;
//if (m_Triangles.size() > MAX_TRIANGLES_PER_BOX)
//{
float epsilon = 1e-1;
BoundingBox* temp[NUMBER_OF_CHILDREN];
//Make children
temp[0]= new BoundingBox(this->m_Params[0] - epsilon, this->m_Centre + epsilon);
min = glm::vec3(this->m_Centre.x - epsilon, this->m_Params[0].y - epsilon, this->m_Params[0].z - epsilon);
max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Centre.y + epsilon, this->m_Centre.z + epsilon);
temp[1] = new BoundingBox(min, max);
min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Centre.y - epsilon, this->m_Params[0].z - epsilon);
max = glm::vec3(this->m_Centre.x + epsilon, this->m_Params[1].y + epsilon, this->m_Centre.z + epsilon);
temp[2] = new BoundingBox(min, max);
min = glm::vec3(this->m_Centre.x - epsilon, this->m_Centre.y - epsilon, this->m_Params[0].z - epsilon);
max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Params[1].y + epsilon, this->m_Centre.z + epsilon);
temp[3] = new BoundingBox(min, max);
min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Params[0].y - epsilon, this->m_Centre.z- epsilon);
max = glm::vec3(this->m_Centre.x + epsilon, this->m_Centre.y + epsilon, this->m_Params[1].z + epsilon);
temp[4] = new BoundingBox(min, max);
min = glm::vec3(this->m_Centre.x - epsilon, this->m_Params[0].y - epsilon, this->m_Centre.z - epsilon);
max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Centre.y + epsilon, this->m_Params[1].z + epsilon);
temp[5] = new BoundingBox(min, max);
min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Centre.y - epsilon, this->m_Centre.z - epsilon);
max = glm::vec3(this->m_Centre.x + epsilon, this->m_Params[1].y + epsilon, this->m_Params[1].z + epsilon);
temp[6] = new BoundingBox(min, max);
temp[7] = new BoundingBox(this->m_Centre - epsilon, this->m_Params[1] + epsilon);
//if (level < MAX_DEPTH) {
for (int i = 0; i < NUMBER_OF_CHILDREN; i++) {
for (int j = 0; j < m_Triangles.size(); j++) {
temp[i]->Add(m_Triangles[j]); //Try and add this triangle -> push_back(t)
if (j == m_Triangles.size() - 1) {
if (temp[i]->m_Triangles.size() <= 0) {
delete temp[i];
break;
}
if (temp[i]->m_Triangles.size() > MAX_TRIANGLES_PER_BOX)
{
temp[i]->Split(0);
temp[i]->m_Triangles.clear();
children.push_back(temp[i]);
break;
}
children.push_back(temp[i]);
}
}
}
//m_Triangles.clear();
/*for (int i = 0; i < NUMBER_OF_CHILDREN; i++) {
if()
}*/
/* for (int i = 0; i < children.size(); i++) {
if (this->children[i]->m_Triangles.size() > 0)
{
this->children[i]->Split(level + 1);
}
}*/
//}
//}
//else
//{
//// if (m_Triangles.size() == 0) delete this;
// WARN("Triangles On leaf: {0}", m_Triangles.size());
// isLeaf = true;
//}
}
bool BoundingBox::Intersect(Ray & ray)
{
float txmin, txmax, tymin, tymax, tzmin, tzmax;
txmin = (m_Params[ray.sign[0]].x - ray.Origin.x) * ray.Inv_Direction.x;
txmax = (m_Params[1 - ray.sign[0]].x - ray.Origin.x) * ray.Inv_Direction.x;
tymin = (m_Params[ray.sign[1]].y - ray.Origin.y) * ray.Inv_Direction.y;
tymax = (m_Params[1 - ray.sign[1]].y - ray.Origin.y) * ray.Inv_Direction.y;
if (txmin > txmax) swap(txmin, txmax);
if (tymin > tymax) swap(tymin, tymax);
if ((txmin > tymax) || (tymin > txmax))
return false;
if (tymin > txmin)
txmin = tymin;
if (tymax < txmax)
txmax = tymax;
tzmin = (m_Params[ray.sign[2]].z - ray.Origin.z) * ray.Inv_Direction.z;
tzmax = (m_Params[1 - ray.sign[2]].z - ray.Origin.z) * ray.Inv_Direction.z;
if (tzmin > tzmax) swap(tzmin, tzmax);
if ((txmin > tzmax) || (tzmin > txmax))
return false;
if (tzmin > txmin)
txmin = tzmin;
if (tzmax < txmax)
txmax = tzmax;
bool intersect = false;
if (children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
this->children[i]->Intersect(ray);
}
}
else
{
for (int i = 0; i < m_Triangles.size(); i++) {
if (m_Triangles[i]->Intersect(ray))
{
intersect = true;
}
}
}
return intersect;
}
void BoundingBox::swap(float& first, float& second)
{
float temp;
temp = first;
first = second;
second = temp;
}
void BoundingBox::Add(Triangle * t)
{
if (IsVertexInside(t->A()) || IsVertexInside(t->B()) || IsVertexInside(t->C()))
{
m_Triangles.push_back(t);
}
}
bool BoundingBox::IsVertexInside(const glm::vec3& vert)
{
if (vert.x >= m_Params[0].x &&
vert.y >= m_Params[0].y &&
vert.z >= m_Params[0].z &&
vert.x <= m_Params[1].x &&
vert.y <= m_Params[1].y &&
vert.z <= m_Params[1].z )
{
return true;
}
return false;
}
| 24.766169 | 108 | 0.608076 | cristi191096 |
b8bf8b4ada3e129d4729be4ae6939433e0c5d4b3 | 216 | cpp | C++ | src/main.cpp | DomonkosSuranyi/neural-glider | e131d9a91337fd42e5d827556ac3c1e2b21dbc4d | [
"MIT"
] | null | null | null | src/main.cpp | DomonkosSuranyi/neural-glider | e131d9a91337fd42e5d827556ac3c1e2b21dbc4d | [
"MIT"
] | null | null | null | src/main.cpp | DomonkosSuranyi/neural-glider | e131d9a91337fd42e5d827556ac3c1e2b21dbc4d | [
"MIT"
] | null | null | null | #include <negli/NeuralGliderGame.hpp>
#include <negli/ConsolePrint.hpp>
using namespace negli;
int main()
{
NeuralGliderGame game = NeuralGliderGame(20, 20, 5, 5);
negli::printGame(game);
return 0;
}
| 15.428571 | 59 | 0.699074 | DomonkosSuranyi |
b8bfb109ed59d7e98bbe354fd1fc27e4ab7e8636 | 4,611 | cpp | C++ | src/main.cpp | n-ari/c91-tsp | f760582269a7e7c645e414fa4b89c06e99f03c35 | [
"MIT"
] | null | null | null | src/main.cpp | n-ari/c91-tsp | f760582269a7e7c645e414fa4b89c06e99f03c35 | [
"MIT"
] | null | null | null | src/main.cpp | n-ari/c91-tsp | f760582269a7e7c645e414fa4b89c06e99f03c35 | [
"MIT"
] | null | null | null | #include <iostream>
#include "util.hpp"
#include "tsp.hpp"
#include "nearest_neighbor.hpp"
#include "nearest_insertion.hpp"
#include "farthest_insertion.hpp"
#include "double_mst.hpp"
#include "greedy.hpp"
#include "quick_boruvka.hpp"
#include "two_opt.hpp"
// main routine
int main(int argc, char **argv){
if(argc<2){
std::cerr << "Error: need input filename." << std::endl;
return 1;
}
// input
{
std::string s(argv[1]);
s = "in/" + s + ".in";
TSP::input(s);
}
// nearest neighbor
{
Util::resettime();
Util::timestamp("Nearest Neighbor");
TSP::Tour tour_nn = TSP::NearestNeighbor::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_nn.out";
TSP::output(tour_nn,s);
tour_nn.clear();
}
// nearest insertion
{
Util::resettime();
Util::timestamp("Nearest Insertion");
TSP::Tour tour_ni = TSP::NearestInsertion::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_ni.out";
TSP::output(tour_ni,s);
tour_ni.clear();
}
// farthest insertion
{
Util::resettime();
Util::timestamp("Farthest Insertion");
TSP::Tour tour_fi = TSP::FarthestInsertion::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_fi.out";
TSP::output(tour_fi,s);
tour_fi.clear();
}
// double mst
{
Util::resettime();
Util::timestamp("Double Minimum Spanning Tree");
TSP::Tour tour_dmst = TSP::DoubleMST::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_dmst.out";
TSP::output(tour_dmst,s);
tour_dmst.clear();
}
// greedy
{
Util::resettime();
Util::timestamp("Greedy");
TSP::Tour tour_gr = TSP::Greedy::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_gr.out";
TSP::output(tour_gr,s);
tour_gr.clear();
}
// quick boruvka
{
Util::resettime();
Util::timestamp("Quick Boruvka");
TSP::Tour tour_qb = TSP::QuickBoruvka::calc();
Util::timestamp("End");
std::string s(argv[1]);
s = "out/" + s + "_qb.out";
TSP::output(tour_qb,s);
tour_qb.clear();
}
// nearest neighbor & 2-opt
{
Util::resettime();
Util::timestamp("Nearest Neighbor & 2-opt");
TSP::Tour tour_nn_2opt = TSP::NearestNeighbor::calc();
Util::timestamp("End(NN)");
TSP::TwoOpt::improve(tour_nn_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_nn_2opt.out";
TSP::output(tour_nn_2opt,s);
tour_nn_2opt.clear();
}
// nearest insertion & 2-opt
{
Util::resettime();
Util::timestamp("Nearest Insertion & 2-opt");
TSP::Tour tour_ni_2opt = TSP::NearestInsertion::calc();
Util::timestamp("End(NI)");
TSP::TwoOpt::improve(tour_ni_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_ni_2opt.out";
TSP::output(tour_ni_2opt,s);
tour_ni_2opt.clear();
}
// farthest insertion & 2-opt
{
Util::resettime();
Util::timestamp("Farthest Insertion & 2-opt");
TSP::Tour tour_fi_2opt = TSP::FarthestInsertion::calc();
Util::timestamp("End(FI)");
TSP::TwoOpt::improve(tour_fi_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_fi_2opt.out";
TSP::output(tour_fi_2opt,s);
tour_fi_2opt.clear();
}
// double mst & 2-opt
{
Util::resettime();
Util::timestamp("Double Minimum Spanning Tree & 2-opt");
TSP::Tour tour_dmst_2opt = TSP::DoubleMST::calc();
Util::timestamp("End(DMST)");
TSP::TwoOpt::improve(tour_dmst_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_dmst_2opt.out";
TSP::output(tour_dmst_2opt,s);
tour_dmst_2opt.clear();
}
// greedy & 2-opt
{
Util::resettime();
Util::timestamp("Greedy & 2-opt");
TSP::Tour tour_gr_2opt = TSP::Greedy::calc();
Util::timestamp("End(GR)");
TSP::TwoOpt::improve(tour_gr_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_gr_2opt.out";
TSP::output(tour_gr_2opt,s);
tour_gr_2opt.clear();
}
// quick boruvka & 2-opt
{
Util::resettime();
Util::timestamp("Quick Boruvka & 2-opt");
TSP::Tour tour_qb_2opt = TSP::QuickBoruvka::calc();
Util::timestamp("End(QB)");
TSP::TwoOpt::improve(tour_qb_2opt);
Util::timestamp("End(2-opt)");
std::string s(argv[1]);
s = "out/" + s + "_qb_2opt.out";
TSP::output(tour_qb_2opt,s);
tour_qb_2opt.clear();
}
TSP::halt();
return 0;
}
| 24.657754 | 60 | 0.589243 | n-ari |
b8c1d6eaf8bd946b16d2f0fffc01aea65bc662a3 | 370 | hpp | C++ | Common/GameEngine/component/graphical/Drawable.hpp | Pierre-Narcisi/r-type | ac1b10e404313fef56eaea52e0252d85b7feae05 | [
"Unlicense"
] | null | null | null | Common/GameEngine/component/graphical/Drawable.hpp | Pierre-Narcisi/r-type | ac1b10e404313fef56eaea52e0252d85b7feae05 | [
"Unlicense"
] | null | null | null | Common/GameEngine/component/graphical/Drawable.hpp | Pierre-Narcisi/r-type | ac1b10e404313fef56eaea52e0252d85b7feae05 | [
"Unlicense"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** rtype
** File description:
** Created by seb,
*/
#pragma once
namespace ecs {namespace component {
struct Drawable {
Drawable() {
this->layer = 0;
this->visible = false;
}
Drawable(unsigned int layer, bool visible) {
this->layer = layer;
this->visible = visible;
}
unsigned int layer;
bool visible;
};
}} | 16.086957 | 46 | 0.627027 | Pierre-Narcisi |
fef74a3ee35c0682f94ffc385d97330afa35efc7 | 3,442 | cpp | C++ | tests/op/test_tensorrt_op_clip.cpp | sunnycase/Tengine | fe1b148f64ffe0546fc18000293aa7abd6308fb3 | [
"Apache-2.0"
] | 2 | 2021-07-29T02:02:33.000Z | 2022-03-02T08:56:52.000Z | tests/op/test_tensorrt_op_clip.cpp | sunnycase/Tengine | fe1b148f64ffe0546fc18000293aa7abd6308fb3 | [
"Apache-2.0"
] | null | null | null | tests/op/test_tensorrt_op_clip.cpp | sunnycase/Tengine | fe1b148f64ffe0546fc18000293aa7abd6308fb3 | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: [email protected]
*/
#include "test_op.h"
int create_test_clip_node(graph_t graph, const char* input_name, const char* node_name, int data_type, int layout, int n, int c, int h, int w)
{
(void)layout;
(void)n;
(void)c;
(void)h;
(void)w;
/* create the test node */
struct node* test_node = (struct node*)create_graph_node(graph, node_name, "Clip");
tensor_t input_tensor = get_graph_tensor(graph, input_name);
if (NULL == input_tensor)
{
fprintf(stderr, "create test node failed.\n");
return -1;
}
/* input tensors of test node */
set_node_input_tensor(test_node, 0, input_tensor);
/* output tensors of test node */
tensor_t output_tensor = create_graph_tensor(graph, node_name, data_type);
set_node_output_tensor(test_node, 0, output_tensor, TENSOR_TYPE_VAR);
return 0;
}
float input_fp32[5] = {-3.0f, 3.0f, 8.0f, 1.0f, -2.0f};
float reference_out[5] = {0.0f, 3.0f, 6.0f, 1.0f, 0.0f};
int main(int argc, char* argv[])
{
int n = 1, c = 1, h = 5, w = 1;
const char* test_node_name = "clip";
int data_type = TENGINE_DT_FP32;
int layout = TENGINE_LAYOUT_NCHW;
// init
int ret = test_graph_init();
if (0 != ret)
fprintf(stderr, "Tengine init failed.\n");
// create
graph_t graph = create_tensorrt_test_graph(test_node_name, data_type, layout, n, c, h, w, &create_test_clip_node);
if (NULL == graph)
return -1;
set_log_level(LOG_INFO);
dump_graph(graph);
// set quantize params
struct tensor* input_tensor = (struct tensor*)get_graph_input_tensor(graph, 0, 0);
struct tensor* output_tensor = (struct tensor*)get_graph_output_tensor(graph, 0, 0);
// set input data
set_tensor_buffer(input_tensor, input_fp32, 5 * 4);
// graph run
ret = test_graph_run(graph);
if (0 != ret)
{
fprintf(stderr, "Run graph error. ERRNO: %d.\n", ret);
test_graph_release(graph);
return -1;
}
// get output and dequant
float* output_data = (float*)output_tensor->data;
int output_size = output_tensor->elem_num;
// check the result
ret = 0;
for (int i = 0; i < output_size; i++)
{
if (fabsf(output_data[i] - reference_out[i]) > 0.1)
{
fprintf(stderr, "index:%d, a:%f, b:%f\n", i, output_data[i], reference_out[i]);
ret = -1;
}
}
if (ret == 0)
fprintf(stderr, "test pass.\n");
else
fprintf(stderr, "test failed.\n");
// exit
test_graph_release(graph);
return ret;
}
| 28.446281 | 142 | 0.647298 | sunnycase |
fef932d3d5f0b6ea85389a95dfd62345c79ead4f | 1,368 | cpp | C++ | Graphs/NumberOfIslands.cpp | diivyya/DSA_codes | e50de5a863d52cc70f29b81e45c9301cf002ba2b | [
"MIT"
] | null | null | null | Graphs/NumberOfIslands.cpp | diivyya/DSA_codes | e50de5a863d52cc70f29b81e45c9301cf002ba2b | [
"MIT"
] | null | null | null | Graphs/NumberOfIslands.cpp | diivyya/DSA_codes | e50de5a863d52cc70f29b81e45c9301cf002ba2b | [
"MIT"
] | null | null | null | //No of islands (only 4 neighbours)
//Time: O(M*N)
//Space: O(M*N)
#include <bits/stdc++.h>
using namespace std;
bool isInside(int n, int m, int i, int j)
{
if(i<0||j<0||i>n-1||j>m-1) return false;
return true;
}
void dfs(vector<vector<char>>&grid, vector<vector<bool>>&vis, int n, int m, int i, int j)
{
vis[i][j]=true;
int dx[] = { 0, -1, 0, 1 };
int dy[] = { -1, 0, 1, 0 };
for(int k=0;k<4;k++)
{
int x=dx[k]+i;
int y=dy[k]+j;
if(isInside(n,m,x,y) && !vis[x][y] && grid[x][y]=='X') dfs(grid,vis,n,m,x,y);
}
return;
}
int solve(vector<vector<char>>& grid)
{
int n=grid.size();
int m=grid[0].size();
int ans=0;
vector<vector<bool>>vis(n,vector<bool>(m,false));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(!vis[i][j] && grid[i][j]=='X')
{
dfs(grid,vis,n,m,i,j);
ans++;
}
}
}
return ans;
}
int main()
{
int n,m;
cin>>n>>m;
vector<vector<char>>grid(n,vector<char>(m));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>grid[i][j];
}
}
int ans = solve(grid);
cout<<ans;
}
| 22.8 | 93 | 0.407164 | diivyya |
fefece9337b6ae3bafc108b2e17cdbdebe7a00da | 4,485 | cpp | C++ | source/samples/BLETest.cpp | danielstl/microbit-v2-samples | bdf296781b736b858f453b06ff7324ccc194a3ae | [
"MIT"
] | 23 | 2020-11-18T00:27:57.000Z | 2022-03-20T17:50:14.000Z | source/samples/BLETest.cpp | danielstl/microbit-v2-samples | bdf296781b736b858f453b06ff7324ccc194a3ae | [
"MIT"
] | 37 | 2020-10-19T16:15:27.000Z | 2022-03-20T12:21:22.000Z | source/samples/BLETest.cpp | danielstl/microbit-v2-samples | bdf296781b736b858f453b06ff7324ccc194a3ae | [
"MIT"
] | 40 | 2020-10-14T15:26:13.000Z | 2022-02-21T12:41:44.000Z | /*
The MIT License (MIT)
Copyright (c) 2021 Lancaster University.
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 "MicroBit.h"
#include "Tests.h"
extern MicroBit uBit;
MicroBitUARTService *uart;
// we use events abd the 'connected' variable to keep track of the status of the Bluetooth connection
void onConnected(MicroBitEvent)
{
uBit.display.print("C");
}
void onDisconnected(MicroBitEvent)
{
uBit.display.print("D");
}
void onDelim(MicroBitEvent)
{
ManagedString r = uart->readUntil("\r\n");
uart->send(r);
}
void ble_test()
{
// Configuration Tips
//
// An example codal.json is provided in the root directory: codal.ble.json
// Rename codal.ble.json to codal.json to use this BLE sample
//
// codal.json contains various Bluetooth related properties some of which are explained here:
//
// "SOFTDEVICE_PRESENT": 1 Determines whether the build contains softdevice
// "DEVICE_BLE": 1 Determines whether BLE is enabled
// "MICROBIT_BLE_ENABLED" : 1 Determines whether BLE is enabled
// "MICROBIT_BLE_PAIRING_MODE": 1 Determines whether Pairing Mode is enabled
// "MICROBIT_BLE_DFU_SERVICE": 1 Determines whether the Nordic DFU Service is enabled
// "MICROBIT_BLE_DEVICE_INFORMATION_SERVICE": 1 Determines whether the DIS is enabled
// "MICROBIT_BLE_EVENT_SERVICE" : 1, Determines whether the Event Service is enabled
// "MICROBIT_BLE_PARTIAL_FLASHING" : 0 Determines whether Partial Flashing is enabled (Needs MakeCode/Python)
// "MICROBIT_BLE_SECURITY_LEVEL": "SECURITY_MODE_ENCRYPTION_WITH_MITM" Determines security mode
//
// Options for MICROBIT_BLE_SECURITY_LEVEL are:
// SECURITY_MODE_ENCRYPTION_WITH_MITM, enables pairing with a passcode
// SECURITY_MODE_ENCRYPTION_NO_MITM, enables pairing without a passcode
// SECURITY_MODE_ENCRYPTION_OPEN_LINK, pairing is no required
//
// A cunning code to indicate during start-up the particular Bluetooth configuration in the build
//
// SERVICE CODES
// A: Accelerometer Service
// B: Button Service
// D: Device Information Service
// E: Event Service
// F: DFU Service
// I: IO Pin Service
// L: LED Service
// M: Magnetometer Service
// T: Temperature Service
// U: UART Service
//
// P: PASSKEY
// J: Just Works
// N: No Pairing Required
// Services/Pairing Config/Power Level
uBit.display.scroll("BLE ABDILMTU/P");
uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected);
uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected);
uBit.messageBus.listen(MICROBIT_ID_BLE_UART, MICROBIT_UART_S_EVT_DELIM_MATCH, onDelim);
new MicroBitAccelerometerService(*uBit.ble, uBit.accelerometer);
new MicroBitButtonService(*uBit.ble);
new MicroBitIOPinService(*uBit.ble, uBit.io);
new MicroBitLEDService(*uBit.ble, uBit.display);
new MicroBitMagnetometerService(*uBit.ble, uBit.compass);
new MicroBitTemperatureService(*uBit.ble, uBit.thermometer);
uart = new MicroBitUARTService(*uBit.ble, 32, 32);
uart->eventOn("\r\n");
// If main exits, there may still be other fibers running or registered event handlers etc.
// Simply release this fiber, which will mean we enter the scheduler. Worse case, we then
// sit in the idle task forever, in a power efficient sleep.
release_fiber();
}
| 38.663793 | 113 | 0.733333 | danielstl |
feff010f88248ab5fc0827a993aeb88f49ad90ee | 438 | cpp | C++ | HFMidiLib/port.cpp | hefsoftware/HFMidiLib | e816d92a6effe8b70420a7db431c7197e0c4f727 | [
"MIT"
] | null | null | null | HFMidiLib/port.cpp | hefsoftware/HFMidiLib | e816d92a6effe8b70420a7db431c7197e0c4f727 | [
"MIT"
] | null | null | null | HFMidiLib/port.cpp | hefsoftware/HFMidiLib | e816d92a6effe8b70420a7db431c7197e0c4f727 | [
"MIT"
] | null | null | null | /*
* Copyright 2021 Marzocchi Alessandro
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "port.h"
using namespace HFMidi;
Port::Port()
{
}
void Port::sendEvent(const QByteArray &data)
{
sendData(data);
}
bool Port::sendData(const QByteArray &data)
{
Q_UNUSED(data);
return false;
}
void Port::receivedData(const QByteArray &data)
{
// qDebug()<<data.toHex();
emit midiEvent(data);
}
| 14.6 | 71 | 0.696347 | hefsoftware |
3a020dd3dd9621e2d1d76204c4720f5446e4407f | 2,338 | cpp | C++ | node/src/ops/Pad.cpp | wangli69087/webnn-native | 8fc751ee87dd797137a6443a28b8dd34d0a4d692 | [
"Apache-2.0"
] | null | null | null | node/src/ops/Pad.cpp | wangli69087/webnn-native | 8fc751ee87dd797137a6443a28b8dd34d0a4d692 | [
"Apache-2.0"
] | null | null | null | node/src/ops/Pad.cpp | wangli69087/webnn-native | 8fc751ee87dd797137a6443a28b8dd34d0a4d692 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The WebNN-native Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ops/Pad.h"
#include "Utils.h"
namespace node::op {
Napi::Value Pad::Build(const Napi::CallbackInfo& info, wnn::GraphBuilder builder) {
// Operand pad(Operand input, Operand padding, optional PadOptions options = {});
WEBNN_NODE_ASSERT(info.Length() == 2 || info.Length() == 3,
"The number of arguments is invalid.");
std::vector<napi_value> args;
wnn::Operand input;
WEBNN_NODE_ASSERT(GetOperand(info[0], input, args), "The input parameter is invalid.");
wnn::Operand padding;
WEBNN_NODE_ASSERT(GetOperand(info[1], padding, args), "The padding parameter is invalid.");
// dictionary PadOptions {
// PaddingMode mode;
// float value = false;
// };
wnn::PadOptions options;
if (info.Length() == 3 && !info[2].IsUndefined()) {
WEBNN_NODE_ASSERT(info[2].IsObject(), "The options must be an object.");
Napi::Object jsOptions = info[2].As<Napi::Object>();
if (HasOptionMember(jsOptions, "mode")) {
WEBNN_NODE_ASSERT(GetPaddingMode(jsOptions.Get("mode"), options.mode),
"The mode parameter is invalid.");
}
if (HasOptionMember(jsOptions, "value")) {
WEBNN_NODE_ASSERT(GetValue(jsOptions.Get("value"), options.value),
"The value parameter is invalid.");
}
}
Napi::Object object = Operand::constructor.New(args);
Operand* operand = Napi::ObjectWrap<Operand>::Unwrap(object);
operand->SetImpl(builder.Pad(input, padding, &options));
return object;
}
} // namespace node::op
| 41.017544 | 99 | 0.61976 | wangli69087 |
3a024a78147f0f1d108a91d8d73eb54493c718e8 | 1,259 | cpp | C++ | ControlWindow.cpp | pipmix/WinUI2 | d5f897aa58c9d0024ff45e3a8a562bcf925ca361 | [
"MIT"
] | null | null | null | ControlWindow.cpp | pipmix/WinUI2 | d5f897aa58c9d0024ff45e3a8a562bcf925ca361 | [
"MIT"
] | null | null | null | ControlWindow.cpp | pipmix/WinUI2 | d5f897aa58c9d0024ff45e3a8a562bcf925ca361 | [
"MIT"
] | null | null | null | #include "ControlWindow.h"
void CreateControlWindow(WinDat& wd){
wd._handle = CreateWindowEx(0, wd._className, NULL, wd._style, wd._x, wd._y, wd._w, wd._h, wd._parent, 0, NULL, NULL);
HTREEITEM hRoot;
TV_INSERTSTRUCT tvins;
tvins = { 0 };
tvins.hInsertAfter = TVI_ROOT;
tvins.item.mask = TVIF_TEXT;
tvins.item.pszText = L"Root";
tvins.item.cchTextMax = 10;
hRoot = TreeView_InsertItem(wd._handle, &tvins);
//tvins.hInsertAfter = TVI_LAST;
//tvins.item.pszText = "Child";
//hChild = TreeView_InsertItem(hSidePanel, &tvins);
ListViewAddItem(wd._handle, hRoot, L"test");
ListViewAddItem(wd._handle, hRoot, L"cat");
ListViewAddItem(wd._handle, ListViewAddItem(wd._handle, hRoot, L"murder"), L"more");
tvins.hInsertAfter = TVI_ROOT;
tvins.item.mask = TVIF_TEXT;
tvins.item.pszText = L"Root2";
tvins.item.cchTextMax = 10;
hRoot = TreeView_InsertItem(wd._handle, &tvins);
}
HTREEITEM ListViewAddItem(HWND hWnd, HTREEITEM hItem, LPWSTR lpstr) {
TVINSERTSTRUCT insert;
insert = { 0 };
insert.hParent = hItem;
insert.hInsertAfter = TVI_LAST;
insert.item.mask = TVIF_TEXT;
insert.item.pszText = lpstr;
insert.item.cchTextMax = 10;
//HTREEITEM test = TVM_INSERTITEM(0, &insert);
return TreeView_InsertItem(hWnd, &insert);
} | 23.754717 | 119 | 0.72359 | pipmix |
3a05ddb3d8d3e19c15db99ecac35e8450db1259a | 5,885 | cpp | C++ | Modules/US/USModel/mitkUSDeviceWriterXML.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/US/USModel/mitkUSDeviceWriterXML.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/US/USModel/mitkUSDeviceWriterXML.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// MITK
#include "mitkUSDeviceReaderWriterConstants.h"
#include "mitkUSDeviceWriterXML.h"
#include <mitkIGTMimeTypes.h>
#include <mitkLocaleSwitch.h>
#include <mitkUSDevice.h>
// Third Party
#include <tinyxml.h>
#include <itksys/SystemTools.hxx>
#include <fstream>
#include <iostream>
mitk::USDeviceWriterXML::USDeviceWriterXML() : AbstractFileWriter(USDevice::GetStaticNameOfClass(),
mitk::IGTMimeTypes::USDEVICEINFORMATIONXML_MIMETYPE(),
"MITK USDevice Writer (XML)"), m_Filename("")
{
RegisterService();
}
mitk::USDeviceWriterXML::USDeviceWriterXML(const mitk::USDeviceWriterXML& other) : AbstractFileWriter(other)
{
}
mitk::USDeviceWriterXML::~USDeviceWriterXML()
{
}
mitk::USDeviceWriterXML* mitk::USDeviceWriterXML::Clone() const
{
return new USDeviceWriterXML(*this);
}
void mitk::USDeviceWriterXML::Write()
{
if (m_Filename == "")
{
MITK_WARN << "Cannot write to file - empty filename!";
return;
}
}
void mitk::USDeviceWriterXML::SetFilename(std::string filename)
{
m_Filename = filename;
}
bool mitk::USDeviceWriterXML::WriteUltrasoundVideoDeviceConfiguration(mitk::USDeviceReaderXML::USVideoDeviceConfigData & config)
{
TiXmlDocument document;
TiXmlDeclaration* xmlDeclaration = new TiXmlDeclaration("1.0", "", "");
document.LinkEndChild(xmlDeclaration);
//Create the xml information of the ULTRASOUNDDEVICE-Tag:
TiXmlElement *ultrasoundDeviceTag = new TiXmlElement(TAG_ULTRASOUNDDEVICE);
this->CreateXmlInformationOfUltrasoundDeviceTag(document, ultrasoundDeviceTag, config);
//Create the xml information of the GENERALSETTINGS-Tag:
TiXmlElement *generalSettingsTag = new TiXmlElement(TAG_GENERALSETTINGS);
this->CreateXmlInformationOfGeneralSettingsTag(ultrasoundDeviceTag, generalSettingsTag, config);
//Create the xml information of the PROBES-Tag:
this->CreateXmlInformationOfProbesTag(ultrasoundDeviceTag, config);
return document.SaveFile(m_Filename);
}
void mitk::USDeviceWriterXML::CreateXmlInformationOfUltrasoundDeviceTag(
TiXmlDocument &document, TiXmlElement * ultrasoundDeviceTag,
mitk::USDeviceReaderXML::USVideoDeviceConfigData &config)
{
ultrasoundDeviceTag->SetAttribute(ATTR_FILEVERS, config.fileversion);
ultrasoundDeviceTag->SetAttribute(ATTR_TYPE, config.deviceType);
ultrasoundDeviceTag->SetAttribute(ATTR_NAME, config.deviceName);
ultrasoundDeviceTag->SetAttribute(ATTR_MANUFACTURER, config.manufacturer);
ultrasoundDeviceTag->SetAttribute(ATTR_MODEL, config.model);
ultrasoundDeviceTag->SetAttribute(ATTR_COMMENT, config.comment);
ultrasoundDeviceTag->SetAttribute(ATTR_IMAGESTREAMS, config.numberOfImageStreams);
document.LinkEndChild(ultrasoundDeviceTag);
}
void mitk::USDeviceWriterXML::CreateXmlInformationOfGeneralSettingsTag(TiXmlElement *parentTag, TiXmlElement *generalSettingsTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData & config)
{
std::string value = config.useGreyscale ? "true" : "false";
generalSettingsTag->SetAttribute(ATTR_GREYSCALE, value);
value = config.useResolutionOverride ? "true" : "false";
generalSettingsTag->SetAttribute(ATTR_RESOLUTIONOVERRIDE, value);
generalSettingsTag->SetAttribute(ATTR_RESOLUTIONWIDTH, config.resolutionWidth);
generalSettingsTag->SetAttribute(ATTR_RESOLUTIONHEIGHT, config.resolutionHeight);
generalSettingsTag->SetAttribute(ATTR_SOURCEID, config.sourceID);
generalSettingsTag->SetAttribute(ATTR_FILEPATH, config.filepathVideoSource);
generalSettingsTag->SetAttribute(ATTR_OPENCVPORT, config.opencvPort);
parentTag->LinkEndChild(generalSettingsTag);
}
void mitk::USDeviceWriterXML::CreateXmlInformationOfProbesTag(TiXmlElement * parentTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData & config)
{
if (config.probes.size() != 0)
{
TiXmlElement *probesTag = new TiXmlElement(TAG_PROBES);
parentTag->LinkEndChild(probesTag);
for (size_t index = 0; index < config.probes.size(); ++index)
{
TiXmlElement *probeTag = new TiXmlElement(TAG_PROBE);
probesTag->LinkEndChild(probeTag);
mitk::USProbe::Pointer probe = config.probes.at(index);
probeTag->SetAttribute(ATTR_NAME, probe->GetName());
std::map<int, mitk::Vector3D> depthsAndSpacing = probe->GetDepthsAndSpacing();
if (depthsAndSpacing.size() != 0)
{
TiXmlElement *depthsTag = new TiXmlElement(TAG_DEPTHS);
probeTag->LinkEndChild(depthsTag);
for (std::map<int, mitk::Vector3D>::iterator it = depthsAndSpacing.begin(); it != depthsAndSpacing.end(); it++)
{
TiXmlElement *depthTag = new TiXmlElement(TAG_DEPTH);
depthTag->SetAttribute(ATTR_DEPTH, it->first);
depthsTag->LinkEndChild(depthTag);
TiXmlElement *spacingTag = new TiXmlElement(TAG_SPACING);
spacingTag->SetDoubleAttribute(ATTR_X, it->second[0], 6);
spacingTag->SetDoubleAttribute(ATTR_Y, it->second[1], 6);
depthTag->LinkEndChild(spacingTag);
}
TiXmlElement *croppingTag = new TiXmlElement(TAG_CROPPING);
probeTag->LinkEndChild(croppingTag);
croppingTag->SetAttribute(ATTR_TOP, probe->GetProbeCropping().top);
croppingTag->SetAttribute(ATTR_BOTTOM, probe->GetProbeCropping().bottom);
croppingTag->SetAttribute(ATTR_LEFT, probe->GetProbeCropping().left);
croppingTag->SetAttribute(ATTR_RIGHT, probe->GetProbeCropping().right);
}
}
}
}
| 37.246835 | 188 | 0.746814 | wyyrepo |
3a087fceb1f9cb99e6e419ac33c956794e78c256 | 9,122 | cpp | C++ | include/oled.cpp | va3wam/pentaBot | 76c94e405a8c1b773a5b6ed30eaff8f126a47629 | [
"MIT"
] | null | null | null | include/oled.cpp | va3wam/pentaBot | 76c94e405a8c1b773a5b6ed30eaff8f126a47629 | [
"MIT"
] | 97 | 2021-08-30T13:35:39.000Z | 2022-03-31T02:51:47.000Z | include/oled.cpp | va3wam/pentaBot | 76c94e405a8c1b773a5b6ed30eaff8f126a47629 | [
"MIT"
] | 1 | 2021-10-29T19:09:33.000Z | 2021-10-29T19:09:33.000Z | /*******************************************************************************
* @file oled.cpp
* @brief File containing all OLED functions.
*******************************************************************************/
#ifndef oled_cpp // Start of precompiler check to avoid dupicate inclusion of this code block.
#define oled_cpp // Precompiler macro used for precompiler check.
#include <main.h> // Header file for all libraries needed by this program.
/**
* @brief Hardware Interrupt Service Routine for Button A on OLED display.
* ==========================================================================*/
void IRAM_ATTR ButtonA_ISR()
{
buttonA_flag = true;
} // ButtonA_ISR()
/**
* @brief Hardware Interrupt Service Routine for Button B on OLED display.
* ==========================================================================*/
void IRAM_ATTR ButtonB_ISR()
{
buttonB_flag = true;
} // ButtonB_ISR()
/**
* @brief Hardware Interrupt Service Routine for Button C on OLED display.
* ==========================================================================*/
void IRAM_ATTR ButtonC_ISR()
{
buttonC_flag = true;
} // ButtonC_ISR()
/**
* @brief Places a text message centrered vertically and horizontally.
*
* @param msg A text message to be displayed.
* @param fontSize Multiplier of base text size (6px X 8px). Usually 1-3.
* @param fontColour SH110X_WHITE is the usual choice here.
* ==========================================================================*/
void placeTextVHcentre(String msg, uint8_t fontSize, uint16_t fontColour)
{
display.setTextSize(fontSize);
display.setTextColor(fontColour);
uint8_t x = (oledX - (textBaseX * fontSize * msg.length())) / 2;
uint8_t y = (oledY - (textBaseY * fontSize)) / 2;
display.setCursor(x, y);
display.print(msg);
} // placeTextVHcentre
/**
* @brief Places a text message centrered horizontally.
*
* @param msg A text message to be displayed.
* @param fontSize Multiplier of base text size (6px X 8px). Usually 1-3.
* @param fontColour SH110X_WHITE is the usual choice here.
* ==========================================================================*/
void placeTextHcentre(String msg, uint8_t fontSize, uint16_t fontColour)
{
display.setTextSize(fontSize);
display.setTextColor(fontColour);
uint8_t x = (oledX - (textBaseX * fontSize * msg.length())) / 2;
display.setCursor(x, display.getCursorY());
display.println(msg);
} // placeTextHcentre()
/**
* @brief Rotate the display.
* @details Does not rotate the current screen content but will affect all
* new content sent t the OLED. Note that the the setRotation() function
* orients the content displayed on the OLED screen using a 1 byte parameter
* which has does the following:
* 0 sets the orietation so that the top is where the buttons are.
* 1 rotates the top of the display 90 degrees clockwise from position 0.
* 2 rotates the top of the display 180 degrees clockwise from position 0.
* 3 rotates the top of the display 270 degrees clockwise from position 0.
* @param newOrientation which of the 4 valid orientations to use.
* ==========================================================================*/
void rotateDisplay(int8_t newOrientation)
{
switch(newOrientation)
{
case 0:
Log.verboseln("<rotateDisplay> OLED top is now where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
case 1:
Log.verboseln("<rotateDisplay> OLED top is now 90 degrees clockwise from where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
case 2:
Log.verboseln("<rotateDisplay> OLED top is now 180 degrees clockwise from where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
case 3:
Log.verboseln("<rotateDisplay> OLED top is now 270 degrees clockwise from where the buttons are.");
oledOrientation = newOrientation;
display.setRotation(oledOrientation); // Orient screen content.
break;
default:
Log.errorln("<rotateDisplay> Invalid OLED orientation request of %d. Only values 0-3 are allowed.", newOrientation);
break;
} // switch
} // rotateDisplay()
/**
* @brief Display the splash screen.
* @details Clear the OLED display, set the orientation then display the
* splash screen. Note that the the setRotation() function orients the content
* displayed on the OLED screen using a 1 byte parameter which has does the
* following:
* 0 sets the orietation so that the top is where the buttons are.
* 1 rotates the top of the display 90 degrees clockwise from position 0.
* 2 rotates the top of the display 180 degrees clockwise from position 0.
* 3 rotates the top of the display 270 degrees clockwise from position 0.
* @param msg Text message to add as tag line to splash screen.
* ==========================================================================*/
void displaySplashScreen(String msg)
{
if(oledConnected == false)
{
Log.warningln("<displaySplashScreen> OLED missing. Message suppressed.");
return;
} // if
int8_t headingSize = 3;
int8_t subMsgSize = 1;
display.clearDisplay(); // Clear the buffer.
if(msg == "") // No sub heading message
{
placeTextVHcentre("HEXBOT", headingSize, SH110X_WHITE);
} // if
else
{
placeTextVHcentre("HEXBOT", headingSize, SH110X_WHITE);
placeTextHcentre(msg, subMsgSize, SH110X_WHITE);
} // else
delay(10); // Wait for buffer.
yield(); // Periodic yield call to avoid watchdog reset.
display.display(); // Actually display all of the above
} // displaySplashScreen()
/**
* @brief Display what the legs are doing.
* ==========================================================================*/
void displayStatusScreen()
{
if(oledConnected == false)
{
Log.warningln("<displayStatusScreen> OLED missing. Message suppressed.");
return;
} // if
display.clearDisplay();
display.setCursor(0, 0);
placeTextHcentre("Robot Status", 1, SH110X_WHITE);
display.print("\nWifi: ");
// Wifi status.
if(networkConnected == true)
{
display.println("OK");
} // if
else
{
display.println("ERR");
} // else
// MQTT broker connection status.
display.print("MQTT: ");
if(mqttBrokerConnected == true)
{
display.println("OK");
} // if
else
{
display.println("ERR");
} // else
// Mobility status (if leg servo controllers are detected on I2C).
display.print("Legs: ");
if(mobilityStatus == true)
{
display.println("OK");
} // if
else
{
display.println("ERR");
} // else
// Current robot goal.
display.print("Goal: ");
display.println(legDirExpl[legDirIndex]);
delay(10);
yield();
display.display(); // actually display all of the above
} // displayStatusScreen()
/**
* @brief Check to see if any of the OLED buttons have been pressed.
* ==========================================================================*/
void checkOledButtons()
{
if(buttonA_flag == true)
{
buttonA_flag = false;
display.clearDisplay();
display.setCursor(0, 0);
placeTextHcentre("Configuration", 1, SH110X_WHITE);
display.print("\nRobot: ");
display.println(WiFi.localIP());
display.print("Broker: ");
display.println(getMqttBrokerIP());
delay(10);
yield();
display.display(); // actually display all of the above
} // if
if(buttonB_flag == true)
{
buttonB_flag = false;
displayStatusScreen();
} // if
if(buttonC_flag == true)
{
buttonC_flag = false;
displaySplashScreen("");
} // if
} // loop()
/**
* @brief Initiaize OLED display.
* ==========================================================================*/
void initOled()
{
if(oledConnected == false)
{
Log.warningln("<initOled> OLED missing. Skipping initialization.");
return;
} // if
Log.verboseln("<initOled> 128x64 OLED FeatherWing setup.");
display.begin(0x3C, true); // Address 0x3C default
Log.verboseln("<initOled> OLED begun.");
pinMode(G_BUTTON_A, INPUT_PULLUP); // Make button A pin input with weak pullup.
pinMode(G_BUTTON_B, INPUT_PULLUP); // Make button B pin input with weak pullup.
pinMode(G_BUTTON_C, INPUT_PULLUP); // Make button C pin input with weak pullup.
attachInterrupt(G_BUTTON_A, ButtonA_ISR, RISING); // Assign ISR for button A.
attachInterrupt(G_BUTTON_B, ButtonB_ISR, RISING); // Assign ISR for button B.
attachInterrupt(G_BUTTON_C, ButtonC_ISR, RISING); // Assign ISR for button C.
rotateDisplay(oledOrientation); // Orient OLED text.
displaySplashScreen("");
} // setup()
#endif // End of precompiler protected code block | 36.342629 | 125 | 0.60513 | va3wam |
3a0f2adc46d8eee62126b5f74997a8b066ebb1eb | 2,607 | cpp | C++ | SAD-3D/Source/PanelAbout.cpp | t3m1X/SAD-3D | 129973f9c15eac62cd1e868224190a961f0684bd | [
"MIT"
] | null | null | null | SAD-3D/Source/PanelAbout.cpp | t3m1X/SAD-3D | 129973f9c15eac62cd1e868224190a961f0684bd | [
"MIT"
] | null | null | null | SAD-3D/Source/PanelAbout.cpp | t3m1X/SAD-3D | 129973f9c15eac62cd1e868224190a961f0684bd | [
"MIT"
] | null | null | null | #include "PanelAbout.h"
#include "Application.h"
#include "ModuleGui.h"
#include "Imgui/imgui.h"
#include "mmgr/mmgr.h"
PanelAbout::PanelAbout(char * name) : Panel(name)
{
}
PanelAbout::~PanelAbout()
{
}
bool PanelAbout::Draw()
{
ImGuiWindowFlags settingsFlags = 0;
settingsFlags = ImGuiWindowFlags_NoFocusOnAppearing;
if (ImGui::Begin(name, &enabled, settingsFlags))
{
// --- Introduction ---
ImGui::Separator();
ImGui::Text("SAD 3D");
ImGui::SameLine();
ImGui::Text("Version 2.0");
ImGui::SameLine();
if (ImGui::Button("GitHub")) { App->gui->RequestBrowser("https://github.com/t3m1X/SAD-3D"); }
ImGui::Text("A fork of Central 3D");
ImGui::Text("By: ");
ImGui::SameLine();
if (ImGui::Button("Sergi Parra")) { App->gui->RequestBrowser("https://github.com/t3m1X"); }
ImGui::Text("Central 3D by:");
ImGui::SameLine();
if (ImGui::Button("Aitor Simona")) { App->gui->RequestBrowser("https://github.com/AitorSimona"); }
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
// --- License ---
ImGui::TextWrapped("MIT License");
ImGui::TextWrapped("Copyright(c) 2019 Aitor Simona Bouzas");
ImGui::TextWrapped("Copyright (c) 2021 Sergi Parra Ramirez");
ImGui::TextWrapped("Copyright for portions of SAD 3D are held by Aitor Simona Bouzas, 2019 as part of project CENTRAL 3D (Version 2.0).");
ImGui::TextWrapped("All other copyright for project SAD 3D are held by Sergi Parra Ramirez, 2021.");
ImGui::TextWrapped("");
ImGui::TextWrapped("Permission is hereby granted, free of charge, to any person obtaining a copyof 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 : ");
ImGui::TextWrapped("The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.");
ImGui::TextWrapped("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.");
}
ImGui::End();
return true;
}
| 42.737705 | 485 | 0.726506 | t3m1X |
3a1333267ba4408a140f01de409b239e004253b3 | 1,987 | cc | C++ | src/devices/temperature/drivers/tmp112/tmp112-test.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | src/devices/temperature/drivers/tmp112/tmp112-test.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | src/devices/temperature/drivers/tmp112/tmp112-test.cc | csrpi/fuchsia | 2f015594dcb4c13aa51eee305ad561078f1f9b7f | [
"BSD-2-Clause"
] | null | null | null | // 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 "tmp112.h"
#include <lib/fake_ddk/fake_ddk.h>
#include <lib/mock-i2c/mock-i2c.h>
#include <zxtest/zxtest.h>
namespace {
bool FloatNear(float a, float b) { return std::abs(a - b) < 0.001f; }
} // namespace
namespace temperature {
using TemperatureClient = fidl::WireSyncClient<fuchsia_hardware_temperature::Device>;
class Tmp112DeviceTest : public zxtest::Test {
public:
Tmp112DeviceTest() {}
void SetUp() override {
dev_ = std::make_unique<Tmp112Device>(fake_ddk::kFakeParent,
ddk::I2cChannel(mock_i2c_.GetProto()));
const auto message_op = [](void* ctx, fidl_incoming_msg_t* msg,
fidl_txn_t* txn) -> zx_status_t {
return static_cast<Tmp112Device*>(ctx)->DdkMessage(msg, txn);
};
ASSERT_OK(messenger_.SetMessageOp(dev_.get(), message_op));
}
protected:
mock_i2c::MockI2c mock_i2c_;
std::unique_ptr<Tmp112Device> dev_;
fake_ddk::FidlMessenger messenger_;
};
TEST_F(Tmp112DeviceTest, Init) {
uint8_t initial_config_val[2] = {kConfigConvertResolutionSet12Bit, 0};
mock_i2c_.ExpectWrite({kConfigReg}).ExpectReadStop({0x0, 0x0});
mock_i2c_.ExpectWriteStop({kConfigReg, initial_config_val[0], initial_config_val[1]});
dev_->Init();
mock_i2c_.VerifyAndClear();
}
TEST_F(Tmp112DeviceTest, GetTemperatureCelsius) {
mock_i2c_.ExpectWrite({kTemperatureReg}).ExpectReadStop({0x34, 0x12});
TemperatureClient client(std::move(messenger_.local()));
auto result = client.GetTemperatureCelsius();
EXPECT_OK(result->status);
EXPECT_TRUE(FloatNear(result->temp, dev_->RegToTemperatureCelsius(0x1234)));
mock_i2c_.VerifyAndClear();
}
TEST_F(Tmp112DeviceTest, RegToTemperature) {
EXPECT_TRUE(FloatNear(dev_->RegToTemperatureCelsius(0x1234), 52.0625));
}
} // namespace temperature
| 29.220588 | 88 | 0.717665 | csrpi |
3a14283ea57ebe466e1b4e7b69e3e3d93b97efbc | 1,186 | cc | C++ | platform/epoll_platform_impl/quic_epoll_clock.cc | MacroLau/quiche | 21b1a63ead0a03497127d7f9ae74c3f0eed07e58 | [
"Apache-2.0"
] | 102 | 2021-05-18T10:31:57.000Z | 2022-03-29T04:25:42.000Z | platform/epoll_platform_impl/quic_epoll_clock.cc | MacroLau/quiche | 21b1a63ead0a03497127d7f9ae74c3f0eed07e58 | [
"Apache-2.0"
] | 9 | 2021-06-02T06:44:30.000Z | 2022-03-14T07:52:34.000Z | platform/epoll_platform_impl/quic_epoll_clock.cc | MacroLau/quiche | 21b1a63ead0a03497127d7f9ae74c3f0eed07e58 | [
"Apache-2.0"
] | 23 | 2021-05-18T13:07:50.000Z | 2022-02-24T02:16:02.000Z | // NOLINT(namespace-quic)
//
// This file is part of the QUICHE platform implementation, and is not to be
// consumed or referenced directly by other Envoy code. It serves purely as a
// porting layer for QUICHE.
#include "platform/epoll_platform_impl/quic_epoll_clock.h"
namespace quic {
QuicEpollClock::QuicEpollClock(epoll_server::SimpleEpollServer* epoll_server)
: epoll_server_(epoll_server), largest_time_(QuicTime::Zero()) {}
QuicTime QuicEpollClock::ApproximateNow() const {
return CreateTimeFromMicroseconds(epoll_server_->ApproximateNowInUsec());
}
QuicTime QuicEpollClock::Now() const {
QuicTime now = CreateTimeFromMicroseconds(epoll_server_->NowInUsec());
if (now <= largest_time_) {
// Time not increasing, return |largest_time_|.
return largest_time_;
}
largest_time_ = now;
return largest_time_;
}
QuicWallTime QuicEpollClock::WallNow() const {
return QuicWallTime::FromUNIXMicroseconds(epoll_server_->ApproximateNowInUsec());
}
QuicTime QuicEpollClock::ConvertWallTimeToQuicTime(const QuicWallTime& walltime) const {
return QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(walltime.ToUNIXMicroseconds());
}
} // namespace quic
| 30.410256 | 93 | 0.77403 | MacroLau |
3a14418b5b63b643fa73d0de8cdf04438e409c98 | 12,922 | cpp | C++ | plugins/monitor/pluginsrc/cpu_stats_linux.cpp | pretty-wise/link | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | [
"Unlicense"
] | null | null | null | plugins/monitor/pluginsrc/cpu_stats_linux.cpp | pretty-wise/link | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | [
"Unlicense"
] | 5 | 2019-12-27T05:51:10.000Z | 2022-02-12T02:24:58.000Z | plugins/monitor/pluginsrc/cpu_stats_linux.cpp | pretty-wise/link | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | [
"Unlicense"
] | null | null | null | /*
* Copywrite 2014-2015 Krzysztof Stasik. All rights reserved.
*/
#include "monitor_plugin.h"
#include "base/io/base_file.h"
#include "common/json/json_writer.h"
#include "link/plugin_log.h"
#include "base/core/time_utils.h"
#include "base/core/assert.h"
#include <unistd.h>
namespace Link {
static const streamsize kProcBufferSize = 1024;
struct CPUSample {
u32 timestamp; // sample time.
u32 user; // normal processes executing in user mode.
u32 nice; // niced processes executing in user mode.
u32 system; // processes executing in krenel mode.
u32 idle; // twiddling thumbs.
u32 iowait; // waiting for I/O to complete.
u32 irq; // servicing interrupts.
u32 softirq; // servicing softirqs.
void InitMax() {
timestamp = (u32)-1;
user = (u32)-1;
nice = (u32)-1;
system = (u32)-1;
idle = (u32)-1;
iowait = (u32)-1;
irq = (u32)-1;
softirq = (u32)-1;
}
void GetMax(const CPUSample &a) {
if(a.timestamp > timestamp)
timestamp = a.timestamp;
if(a.user > user)
user = a.user;
if(a.nice > nice)
nice = a.nice;
if(a.system > system)
system = a.system;
if(a.idle > idle)
idle = a.idle;
if(a.iowait > iowait)
iowait = a.iowait;
if(a.irq > irq)
irq = a.irq;
if(a.softirq > softirq)
softirq = a.softirq;
}
void GetMin(const CPUSample &a) {
if(a.timestamp < timestamp)
timestamp = a.timestamp;
if(a.user < user)
user = a.user;
if(a.nice < nice)
nice = a.nice;
if(a.system < system)
system = a.system;
if(a.idle < idle)
idle = a.idle;
if(a.iowait < iowait)
iowait = a.iowait;
if(a.irq < irq)
irq = a.irq;
if(a.softirq < softirq)
softirq = a.softirq;
}
CPUSample &operator+=(const CPUSample &rhs) {
timestamp += rhs.timestamp;
user += rhs.user;
nice += rhs.nice;
system += rhs.system;
idle += rhs.idle;
iowait += rhs.iowait;
irq += rhs.irq;
softirq += rhs.softirq;
return *this;
}
};
struct ProcessSample {
u32 timestamp;
u32 user;
u32 system;
};
float ToPercent(u32 stat, u32 time, u32 hz) {
float dt_sec = static_cast<float>(time) * 0.001f;
float denom = dt_sec * static_cast<float>(hz);
if(denom == 0.f) {
return 0.f;
}
return static_cast<float>(stat) / denom;
}
struct ProcessPercent {
float user;
float system;
void Calculate(const ProcessSample &delta, u32 hz) {
user = ToPercent(delta.user, delta.timestamp, hz);
system = ToPercent(delta.system, delta.timestamp, hz);
}
};
template <> inline void JsonWriter::AppendValue(const ProcessPercent &info) {
JsonWriter writer(m_destination);
writer.Write("user", info.user);
writer.Write("system", info.system);
writer.Finalize();
}
struct ProcessHistory {
u32 num_samples;
u32 current_sample;
ProcessSample *data;
ProcessHistory() : num_samples(0), current_sample(0), data(nullptr) {}
~ProcessHistory() { delete[] data; }
void Resize(u32 _num_samples) {
BASE_ASSERT(_num_samples > 0);
num_samples = _num_samples;
current_sample = 0;
delete[] data;
data = new ProcessSample[num_samples];
}
ProcessSample *GetNextSample() {
BASE_ASSERT(current_sample < num_samples, "sample out of range");
ProcessSample *res = &data[current_sample];
current_sample = (++current_sample) % num_samples;
return res;
}
void LastSampleStats(u32 tick_per_sec, ProcessPercent *out) {
ProcessSample diff;
Diff(data[(current_sample - 1) % num_samples],
data[(current_sample - 2) % num_samples], &diff);
out->Calculate(diff, tick_per_sec);
}
void Diff(const ProcessSample &a, const ProcessSample &b,
ProcessSample *res) {
res->user = a.user - b.user;
res->system = a.system - b.system;
}
};
struct CPUPercent {
float user;
float nice;
float system;
float idle;
float iowait;
float irq;
float softirq;
void InitMax() {
user = 1.f;
nice = 1.f;
system = 1.f;
idle = 1.f;
iowait = 1.f;
irq = 1.f;
softirq = 1.f;
}
void GetMin(const CPUPercent &d) {
if(d.user < user)
user = d.user;
if(d.nice < nice)
nice = d.nice;
if(d.system < system)
system = d.system;
if(d.idle < idle)
idle = d.idle;
if(d.iowait < iowait)
iowait = d.iowait;
if(d.irq < irq)
irq = d.irq;
if(d.softirq < softirq)
softirq = d.softirq;
}
void GetMax(const CPUPercent &d) {
if(d.user > user)
user = d.user;
if(d.nice > nice)
nice = d.nice;
if(d.system > system)
system = d.system;
if(d.idle > idle)
idle = d.idle;
if(d.iowait > iowait)
iowait = d.iowait;
if(d.irq > irq)
irq = d.irq;
if(d.softirq > softirq)
softirq = d.softirq;
}
void Calculate(const CPUSample &delta, u32 hz) {
user = ToPercent(delta.user, delta.timestamp, hz);
nice = ToPercent(delta.nice, delta.timestamp, hz);
system = ToPercent(delta.system, delta.timestamp, hz);
idle = ToPercent(delta.idle, delta.timestamp, hz);
iowait = ToPercent(delta.iowait, delta.timestamp, hz);
irq = ToPercent(delta.irq, delta.timestamp, hz);
softirq = ToPercent(delta.softirq, delta.timestamp, hz);
}
};
template <> inline void JsonWriter::AppendValue(const CPUPercent &info) {
JsonWriter writer(m_destination);
writer.Write("user", info.user);
writer.Write("nice", info.nice);
writer.Write("system", info.system);
writer.Write("idle", info.idle);
writer.Write("iowait", info.iowait);
writer.Write("irq", info.irq);
writer.Write("softirq", info.softirq);
writer.Finalize();
}
struct CPUHistory {
u32 num_samples;
u32 current_sample;
struct CPUSample *data;
struct CPUPercent min, max, avg;
CPUHistory() : num_samples(0), current_sample(0), data(0) {}
~CPUHistory() { delete[] data; }
void Resize(u32 _num_samples) {
BASE_ASSERT(_num_samples > 0);
num_samples = _num_samples;
current_sample = 0;
delete[] data;
data = new CPUSample[num_samples];
}
CPUSample *GetNextSample() {
BASE_ASSERT(current_sample < num_samples, "sample out of range");
CPUSample *res = &data[current_sample];
current_sample = (++current_sample) % num_samples;
return res;
}
void LastSampleStats(u32 tick_per_sec, CPUPercent *out) {
CPUSample diff;
Diff(data[(current_sample - 1) % num_samples],
data[(current_sample - 2) % num_samples], &diff);
out->Calculate(diff, tick_per_sec);
}
void Calculate(u32 tick_per_sec) {
CPUSample sum = {}, diff;
min.InitMax();
for(u32 i = 0; i < num_samples; ++i) {
Diff(data[(i - 1) % num_samples], data[(i - 2) % num_samples], &diff);
sum += diff;
CPUPercent tmp;
tmp.Calculate(diff, tick_per_sec);
min.GetMin(tmp);
max.GetMax(tmp);
}
avg.Calculate(sum, tick_per_sec);
}
void Diff(const CPUSample &a, const CPUSample &b, CPUSample *res) {
res->timestamp = a.timestamp - b.timestamp;
res->user = a.user - b.user;
res->nice = a.nice - b.nice;
res->system = a.system - b.system;
res->idle = a.idle - b.idle;
res->iowait = a.iowait - b.iowait;
res->irq = a.irq - b.irq;
res->softirq = a.softirq - b.softirq;
}
};
template <> inline void JsonWriter::AppendValue(const CPUSample &info) {
JsonWriter writer(m_destination);
writer.Write("timestamp", info.timestamp);
writer.Write("user", info.user);
writer.Write("nice", info.nice);
writer.Write("system", info.system);
writer.Write("idle", info.idle);
writer.Write("iowait", info.iowait);
writer.Write("irq", info.irq);
writer.Write("softirq", info.softirq);
writer.Finalize();
}
char *GoToNextValue(char *cur) {
// skip current value.
while(*cur != ' ' && *cur != '\t') {
++cur;
}
// skip whitespaces.
while(*cur == ' ' || *cur == '\t') {
++cur;
}
return cur;
}
char *GoToNextLine(char *cur) {
while(*cur != '\n' && *cur != 0) {
++cur;
}
if(*cur == '\n') {
++cur;
}
return cur;
}
bool ReadCPUStatus(char *&pointer, struct CPUSample *stats, u32 timestamp) {
// field definition: http://man7.org/linux/man-pages/man5/proc.5.html
if(pointer[0] != 'c' || pointer[1] != 'p' || pointer[2] != 'u') {
return false;
}
stats->timestamp = timestamp;
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->user);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->nice);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->system);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->idle);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->iowait);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->irq);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, stats->softirq);
pointer = GoToNextLine(pointer);
return true;
}
bool ReadCPUStats(struct CPUHistory *total, struct CPUHistory **cpu,
int num_cpu) {
Base::FileHandle file = Base::Open("/proc/stat", Base::OM_Read);
if(file == -1) {
PLUGIN_ERROR("failed opeining proc stat");
return false;
}
char buffer[kProcBufferSize];
size_t nbytes = Base::Read(file, buffer, kProcBufferSize);
if(nbytes == static_cast<size_t>(-1)) {
PLUGIN_ERROR("problem reading proc stat");
return false;
}
u32 timestamp = Base::Time::GetTimeMs();
char *pointer = buffer;
if(!ReadCPUStatus(pointer, total->GetNextSample(), timestamp)) {
PLUGIN_ERROR("problem reading cpu stats");
Base::Close(file);
return false;
}
for(int i = 0; i < num_cpu; ++i) {
if(!pointer ||
!ReadCPUStatus(pointer, cpu[i]->GetNextSample(), timestamp)) {
PLUGIN_ERROR("problem reading %d cpu stats", i);
Base::Close(file);
return false;
}
}
Base::Close(file);
return true;
}
bool ReadProcessStats(struct ProcessHistory *hist) {
Base::FileHandle file = Base::Open("/proc/self/stat", Base::OM_Read);
char buffer[kProcBufferSize];
size_t nbytes = Base::Read(file, buffer, kProcBufferSize);
if(nbytes == static_cast<size_t>(-1)) {
PLUGIN_ERROR("problem reading proc stat");
return false;
}
char *pointer = buffer;
for(int i = 0; i < 13; ++i) {
pointer = GoToNextValue(pointer);
}
ProcessSample *sample = hist->GetNextSample();
Base::String::FromString(pointer, sample->user);
pointer = GoToNextValue(pointer);
Base::String::FromString(pointer, sample->system);
Base::Close(file);
return true;
}
struct CPUStatsCmd::PIMPL {
u32 m_num_cpu; // number of processors
u32 m_ticks_per_sec; // clock speed.
ProcessHistory m_process; // process stat data.
CPUHistory m_total; // all cpu stat data.
CPUHistory *m_cpu; // stat data per cpu.
u32 m_last_read_time; // last time stats were read.
bool m_error; // true if there was a processing error
PIMPL(u32 sample_count) : m_error(false) {
m_num_cpu = sysconf(_SC_NPROCESSORS_ONLN);
m_ticks_per_sec = sysconf(_SC_CLK_TCK);
m_cpu = new CPUHistory[m_num_cpu];
m_total.Resize(sample_count);
for(u32 i = 0; i < m_num_cpu; ++i) {
m_cpu[i].Resize(sample_count);
}
m_process.Resize(sample_count);
// init stats.
ReadStats();
}
~PIMPL() { delete[] m_cpu; }
void ReadStats() {
ReadCPUStats(&m_total, &m_cpu, m_num_cpu);
ReadProcessStats(&m_process);
m_last_read_time = Base::Time::GetTimeMs();
}
void Recalculate() {
m_total.Calculate(m_ticks_per_sec);
for(u32 i = 0; i < m_num_cpu; ++i) {
m_cpu[i].Calculate(m_ticks_per_sec);
}
}
};
CPUStatsCmd::CPUStatsCmd() {
u32 sample_count = 10;
m_pimpl = new PIMPL(sample_count);
}
CPUStatsCmd::~CPUStatsCmd() { delete m_pimpl; }
void CPUStatsCmd::Sample() {}
bool CPUStatsCmd::OnCommand(const std::string &query_string,
const std::string &post_data,
std::string *response_data) {
u32 prev_read_time = m_pimpl->m_last_read_time;
m_pimpl->ReadStats();
m_pimpl->Recalculate();
CPUPercent total;
m_pimpl->m_total.LastSampleStats(m_pimpl->m_ticks_per_sec, &total);
ProcessPercent process;
m_pimpl->m_process.LastSampleStats(m_pimpl->m_ticks_per_sec, &process);
JsonWriter writer(*response_data);
writer.Write("platform", "linux");
writer.Write("error", m_pimpl->m_error);
writer.Write("cpu_num", m_pimpl->m_num_cpu);
writer.Write("ticks_per_sec", m_pimpl->m_ticks_per_sec);
writer.Write("timestamp", m_pimpl->m_last_read_time);
writer.Write("timeslice", m_pimpl->m_last_read_time - prev_read_time);
writer.Write("total", total);
writer.Write("process", process);
writer.Finalize();
return true;
}
} // namespace Link
| 26.157895 | 77 | 0.638291 | pretty-wise |
3a14d40d59d1c1ddd94b4c01a08c6c40475e01e6 | 150 | cpp | C++ | old/AtCoder/arc056/A.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | old/AtCoder/arc056/A.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | old/AtCoder/arc056/A.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "template.hpp"
int main() {
int64_t a, b, k, l;
cin >> a >> b >> k >> l;
cout << min(k % l * a + k / l * b, k / l * b + b) << endl;
}
| 18.75 | 60 | 0.426667 | not522 |
3a15141528e6dda2f9bf0ab28c793d143c7a5f14 | 5,380 | cpp | C++ | avk/internal/main.cpp | hanxingyixue-arch/AVK | 0a19ba3e71bac1c5944b084311669f23ff5fda72 | [
"BSD-2-Clause"
] | 1 | 2021-03-09T02:39:45.000Z | 2021-03-09T02:39:45.000Z | avk/internal/main.cpp | hanxingyixue-arch/AVK | 0a19ba3e71bac1c5944b084311669f23ff5fda72 | [
"BSD-2-Clause"
] | null | null | null | avk/internal/main.cpp | hanxingyixue-arch/AVK | 0a19ba3e71bac1c5944b084311669f23ff5fda72 | [
"BSD-2-Clause"
] | null | null | null | #include "../external_dependencies/cmts/include/cmts.h"
#include "algorithm_thread.h"
#include "graphics/vulkan_state.h"
#include "windows-specific/framework.h"
#include "windows-specific/Resource.h"
#include <atomic>
#include <chrono>
#define MAX_LOADSTRING 100
HINSTANCE hinstance;
HWND hwnd;
static HACCEL accel;
std::atomic<bool> should_continue_global = true;
std::atomic<bool> should_continue_sort;
TCHAR window_title_buffer[4096];
extern LRESULT CALLBACK window_callbacks(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
extern int init_vulkan();
extern void draw_main_array();
namespace cmts_checks
{
const int count = 65536;
alignas(64) std::atomic_int counter_a;
alignas(64) std::atomic_int counter_b;
static void count_test_task_a(void* unused)
{
counter_a.fetch_add(1, std::memory_order_relaxed);
}
static void count_test_task_b(void* unused)
{
counter_b.fetch_add(1, std::memory_order_relaxed);
}
static void count_test()
{
cmts_init_options_t options = {};
options.task_stack_size = cmts_default_task_stack_size();
options.max_tasks = count;
options.thread_count = cmts_processor_count();
auto code = cmts_lib_init(&options);
assert(code == CMTS_OK);
code = cmts_dispatch([](void* unused)
{
cmts_counter_t ca, cb;
cmts_counter_init(&ca, count);
cmts_counter_init(&cb, count);
cmts_dispatch_options_t options = {};
options.flags = CMTS_DISPATCH_FLAGS_FORCE;
options.sync_type = CMTS_SYNC_TYPE_COUNTER;
options.sync_object = &ca;
for (int i = 0; i != count; ++i)
cmts_dispatch(count_test_task_a, &options);
options.sync_object = &cb;
for (int i = 0; i != count; ++i)
cmts_dispatch(count_test_task_b, &options);
cmts_counter_await(&ca);
cmts_counter_await(&cb);
cmts_lib_exit_signal();
}, nullptr);
assert(code == CMTS_OK);
code = cmts_lib_exit_await(nullptr);
assert(code == CMTS_OK);
}
static void run()
{
count_test();
}
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
//cmts_checks::run();
constexpr TCHAR class_name[] = TEXT("AVKClassName");
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = window_callbacks;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ARRAYVK));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = CreateSolidBrush(0);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_MAIN_MENU);
wcex.lpszClassName = class_name;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
constexpr auto base_counter = __COUNTER__;
if (RegisterClassEx(&wcex) == INVALID_ATOM)
return -(__COUNTER__ - base_counter);
hinstance = hInstance;
constexpr TCHAR title[] = TEXT("AVK - Sorting Algorithm Visualizer");
hwnd = CreateWindow(
class_name,
title,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0,
CW_USEDEFAULT, 0,
nullptr, nullptr,
hInstance, nullptr);
if (hwnd == nullptr)
return -(__COUNTER__ - base_counter);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
accel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MAIN_MENU));
const int res = init_vulkan();
if (res < 0)
return (1 << 30) | res;
algorithm_thread::launch();
using namespace std::chrono;
auto last = high_resolution_clock::now();
auto delay = std::chrono::milliseconds(1);
main_array::set_compare_delay(delay);
main_array::set_read_delay(delay);
main_array::set_write_delay(delay);
main_array::resize(1 << 8);
constexpr TCHAR title_format[] = TEXT("AVK - Sorting Algorithm Visualizer - [ %u elements ]");
#ifdef UNICODE
wsprintf(window_title_buffer, title_format, main_array::size());
SetWindowText(hwnd, window_title_buffer);
#else
sprintf(window_title_buffer, title_format, main_array::size());
SetWindowTextA(hwnd, window_title_buffer);
#endif
main_array::for_each([&](item& e, uint32_t position)
{
e.value = position;
e.original_position = position;
e.color = item_color::white();
});
constexpr auto framerrate = duration<long double>(1.0 / 60.0);
auto last_draw = high_resolution_clock::now();
MSG msg = {};
while (should_continue_global.load(std::memory_order_acquire))
{
while (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE))
{
if (!TranslateAccelerator(msg.hwnd, accel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
const auto now = high_resolution_clock::now();
if (now - last_draw > framerrate)
{
draw_main_array();
last_draw = now;
}
}
algorithm_thread::terminate();
return (int)msg.message;
} | 28.167539 | 123 | 0.64684 | hanxingyixue-arch |
3a1588c32aae4d242d82280d4d2868edde1df202 | 999 | hpp | C++ | PP/tuple/concept.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | 3 | 2019-07-12T23:12:24.000Z | 2019-09-05T07:57:45.000Z | PP/tuple/concept.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | PP/tuple/concept.hpp | Petkr/PP | 646cc156603a6a9461e74d8f54786c0d5a9c32d2 | [
"MIT"
] | null | null | null | #pragma once
#include <PP/declval.hpp>
#include <PP/get_type.hpp>
#include <PP/macros/simple_concept.hpp>
#include <PP/value_t.hpp>
#include <PP/tuple/count.hpp>
#include <PP/tuple/element.hpp>
#include <PP/tuple/get.hpp>
#include <PP/tuple/value_sequence_for.hpp>
namespace PP::detail
{
template <typename T, auto I>
concept tuple_access = requires
{
::PP::declval_impl<T>()[::PP::value<I>];
::PP::tuple::element(::PP::value<I>, ::PP::declval_impl<T>());
};
template <typename T, auto... I>
concept tuple_accesses = (tuple_access<T, I> && ...);
template <auto... I>
constexpr auto is_tuple_helper(concepts::type auto&& t,
value_sequence<I...>) noexcept
{
return tuple_accesses<PP_GT(t), I...>;
}
}
namespace PP::concepts
{
template <typename T>
concept tuple = requires
{
::PP::tuple::count_value_t(::PP::declval_impl<T>());
}
&&PP::detail::is_tuple_helper(PP::type<T>,
tuple::type_value_sequence_for(PP::type<T>));
}
| 24.975 | 75 | 0.648649 | Petkr |
3a1afcbceeae17911fc911949ede0b302f08f7a5 | 1,485 | cpp | C++ | double_comparison.cpp | TyeolRik/CodingProblems_CPP | 1b4d42dd1b24200b8da073948070e65c556f98b4 | [
"MIT"
] | null | null | null | double_comparison.cpp | TyeolRik/CodingProblems_CPP | 1b4d42dd1b24200b8da073948070e65c556f98b4 | [
"MIT"
] | null | null | null | double_comparison.cpp | TyeolRik/CodingProblems_CPP | 1b4d42dd1b24200b8da073948070e65c556f98b4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#define EPSILON 1e-10
bool is_same(double __x, double __y) {
if(std::abs(__x - __y) < EPSILON) {
std::cout << std::fixed << "IN Function __x\t\t" << __x << "\n";
std::cout << std::fixed << "IN Function __y\t\t" << __y << "\n";
std::cout << std::fixed << "std::abs(__x - __y)\t" << std::abs(__x - __y) << "\n";
return true;
} else {
return false;
}
}
double distance(double x1, double y1, double x2, double y2) {
return std::sqrt(std::pow((x2 - x1), 2) + std::pow((y2 - y1), 2));
}
int main() {
std::cout.precision(17); // maximum precision : https://stackoverflow.com/a/554134/7105963
std::cout << std::fixed << "dist (0, 0) ~ (3, 4)\t" << distance(0, 0, 3, 4) << "\n";
std::cout << std::fixed << "EPSILON(small)\t\t" << EPSILON << "\n";
std::cout << std::fixed << "distance + EPSILON\t" << (distance(0, 0, 3, 4) + EPSILON) << "\n";
std::cout << std::fixed << "distance - EPSILON\t" << (distance(0, 0, 3, 4) - EPSILON) << "\n";
// std::cout << is_same(distance(0, 0, 3, 4), (distance(0, 0, 3, 4) + __DBL_EPSILON__)) << "\n";
std::cout << is_same(distance(0, 0, 3, 4), (distance(0, 0, 3, 4) + EPSILON)) << "\n";
std::cout << std::fixed << "5.0 + EPSILON\t\t" << (5.0 + EPSILON) << "\n";
std::cout << std::fixed << "5.0 - EPSILON\t\t" << (5.0 - EPSILON) << "\n";
std::cout << std::fixed << "5.0 - EPSILON\t\t" << (5.0 - EPSILON) << "\n";
} | 46.40625 | 101 | 0.517845 | TyeolRik |
3a1c6f6e95f6544ea309810f31d4d1da239734b4 | 1,731 | hpp | C++ | src/standard/bits/DD_ReferenceCounter.hpp | iDingDong/libDDCPP-old | 841260fecc84330ff3bfffba7263f5318f0b4655 | [
"BSD-3-Clause"
] | 1 | 2018-06-01T03:29:34.000Z | 2018-06-01T03:29:34.000Z | src/standard/bits/DD_ReferenceCounter.hpp | iDingDong/libDDCPP-old | 841260fecc84330ff3bfffba7263f5318f0b4655 | [
"BSD-3-Clause"
] | null | null | null | src/standard/bits/DD_ReferenceCounter.hpp | iDingDong/libDDCPP-old | 841260fecc84330ff3bfffba7263f5318f0b4655 | [
"BSD-3-Clause"
] | null | null | null | // DDCPP/standard/bits/DD_ReferenceCounter.hpp
#ifndef DD_REFERENCE_COUNTER_HPP_INCLUDED_
# define DD_REFERENCE_COUNTER_HPP_INCLUDED_ 1
# include "DD_global_definitions.hpp"
DD_DETAIL_BEGIN_
struct ReferenceCounter {
public:
DD_ALIAS(ThisType, ReferenceCounter);
public:
DD_ALIAS(LengthType, ::DD::LengthType);
public:
Pair<LengthType> m_reference_count_;
public:
Pair<LengthType> const& get_reference_count() const DD_NOEXCEPT {
return m_reference_count_;
}
public:
LengthType get_strong_reference_count() const DD_NOEXCEPT {
return get_reference_count().first;
}
public:
LengthType get_weak_reference_count() const DD_NOEXCEPT {
return get_reference_count().second;
}
public:
ValidityType is_unique_strong_reference() const DD_NOEXCEPT {
return get_strong_reference_count() == LengthType(1);
}
public:
ValidityType is_unique_weak_reference() const DD_NOEXCEPT {
return get_weak_reference_count() == LengthType(1);
}
public:
ValidityType has_strong_reference() const DD_NOEXCEPT {
return get_strong_reference_count();
}
public:
ValidityType has_weak_reference() const DD_NOEXCEPT {
return get_weak_reference_count();
}
public:
ValidityType is_expired() const DD_NOEXCEPT {
return !has_strong_reference();
}
public:
ProcessType strongly_referred() DD_NOEXCEPT {
++m_reference_count_.first;
}
public:
ProcessType weakly_referred() DD_NOEXCEPT {
++m_reference_count_.second;
}
public:
ProcessType strongly_released() DD_NOEXCEPT {
--m_reference_count_.first;
}
public:
ProcessType weakly_released() DD_NOEXCEPT {
--m_reference_count_.second;
}
};
DD_DETAIL_END_
DD_BEGIN_
using detail_::ReferenceCounter;
DD_END_
#endif
| 15.184211 | 66 | 0.770075 | iDingDong |
3a2381a6feef0b1e2ee4cc37c366668b20ff1bd6 | 2,111 | cpp | C++ | src/utils/test/lock.std.cpp | acelyc111/rdsn | 298769147750167949af800b96d5b9dcdfab0aeb | [
"MIT"
] | 149 | 2017-10-16T03:24:58.000Z | 2022-03-25T02:29:13.000Z | src/utils/test/lock.std.cpp | acelyc111/rdsn | 298769147750167949af800b96d5b9dcdfab0aeb | [
"MIT"
] | 297 | 2017-10-19T03:23:34.000Z | 2022-03-17T08:00:12.000Z | src/utils/test/lock.std.cpp | acelyc111/rdsn | 298769147750167949af800b96d5b9dcdfab0aeb | [
"MIT"
] | 63 | 2017-10-19T01:55:27.000Z | 2022-03-09T11:09:00.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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 "utils/lockp.std.h"
#include <gtest/gtest.h>
using namespace dsn;
using namespace dsn::tools;
TEST(tools_common, std_lock_provider)
{
std_lock_provider *lock = new std_lock_provider(nullptr);
lock->lock();
EXPECT_TRUE(lock->try_lock());
lock->unlock();
lock->unlock();
std_lock_nr_provider *nr_lock = new std_lock_nr_provider(nullptr);
nr_lock->lock();
EXPECT_FALSE(nr_lock->try_lock());
nr_lock->unlock();
std_rwlock_nr_provider *rwlock = new std_rwlock_nr_provider(nullptr);
rwlock->lock_read();
rwlock->unlock_read();
rwlock->lock_write();
rwlock->unlock_write();
std_semaphore_provider *sema = new std_semaphore_provider(0, nullptr);
std::thread t([](std_semaphore_provider *s) { s->wait(1000000); }, sema);
sema->signal(1);
t.join();
delete lock;
delete nr_lock;
delete rwlock;
delete sema;
}
| 34.048387 | 80 | 0.721459 | acelyc111 |
3a251cf8b33df88740c77ff1a81064a1549e37c1 | 664 | cpp | C++ | src/lib/AST/UnaryOperator.cpp | NCTU-Homework/compiler-hw4 | 343db48644e4a53759a602983aaf3a4030eeb986 | [
"MIT"
] | null | null | null | src/lib/AST/UnaryOperator.cpp | NCTU-Homework/compiler-hw4 | 343db48644e4a53759a602983aaf3a4030eeb986 | [
"MIT"
] | null | null | null | src/lib/AST/UnaryOperator.cpp | NCTU-Homework/compiler-hw4 | 343db48644e4a53759a602983aaf3a4030eeb986 | [
"MIT"
] | null | null | null | #include "AST/UnaryOperator.hpp"
#include "visitor/AstNodeVisitor.hpp"
UnaryOperatorNode::UnaryOperatorNode(const uint32_t line, const uint32_t col,
Operator op, ExpressionNode *p_operand)
: ExpressionNode{line, col}, op(op), operand(p_operand) {}
const char *UnaryOperatorNode::getOpCString() const {
return kOpString[static_cast<size_t>(op)];
}
void UnaryOperatorNode::accept(AstNodeVisitor &p_visitor) {
p_visitor.visit(*this);
}
void UnaryOperatorNode::visitChildNodes(AstNodeVisitor &p_visitor) {
operand->accept(p_visitor);
}
const Operator& UnaryOperatorNode::getOperator() const {
return op;
}
| 28.869565 | 77 | 0.71988 | NCTU-Homework |
3a2da50fe195f8d35967c867c7fcb115d765edbf | 5,560 | hpp | C++ | contracts/relay.token/relay.token.hpp | eosforce/FORCEIO | b8dc334db53a66f8913027bc396eee852f6fe770 | [
"MIT"
] | 10 | 2019-01-17T11:56:40.000Z | 2019-12-23T11:08:13.000Z | contracts/relay.token/relay.token.hpp | eosforce/FORCEIO | b8dc334db53a66f8913027bc396eee852f6fe770 | [
"MIT"
] | null | null | null | contracts/relay.token/relay.token.hpp | eosforce/FORCEIO | b8dc334db53a66f8913027bc396eee852f6fe770 | [
"MIT"
] | 6 | 2019-04-24T11:16:02.000Z | 2020-11-29T05:41:07.000Z | //
// Created by fy on 2019-01-29.
//
#ifndef FORCEIO_CONTRACT_RELAY_TOKEN_HPP
#define FORCEIO_CONTRACT_RELAY_TOKEN_HPP
#pragma once
#include <eosiolib/eosio.hpp>
#include "force.relay/force.relay.hpp"
#include "sys.match/sys.match.hpp"
namespace relay {
using namespace eosio;
using std::string;
struct sys_bridge_addmort {
name trade_name;
account_name trade_maker;
uint64_t type;
void parse(const string memo);
};
struct sys_bridge_exchange {
name trade_name;
account_name trade_maker;
account_name recv;
uint64_t type;
void parse(const string memo);
};
enum class trade_type:uint64_t {
match=1,
bridge_addmortgage,
bridge_exchange,
trade_type_count
};
#ifdef BEFORE_ONLINE_TEST
static constexpr uint32_t UPDATE_CYCLE = 126;
#else
static constexpr uint32_t UPDATE_CYCLE = 315;
#endif
static constexpr uint64_t OTHER_COIN_WEIGHT = 500;
#define COIN_REWARD_RECORD_SIZE 360
class token : public eosio::contract {
public:
using contract::contract;
token( account_name self ) : contract(self) {}
struct action {
account_name from;
account_name to;
asset quantity;
std::string memo;
EOSLIB_SERIALIZE(action, (from)(to)(quantity)(memo))
};
/// @abi action
void on( name chain, const checksum256 block_id, const force::relay::action& act );
/// @abi action
void create( account_name issuer,
name chain,
account_name side_account,
action_name side_action,
asset maximum_supply );
/// @abi action
void issue( name chain, account_name to, asset quantity, string memo );
/// @abi action
void destroy( name chain, account_name from, asset quantity, string memo );
/// @abi action
void transfer( account_name from,
account_name to,
name chain,
asset quantity,
string memo );
inline asset get_supply( name chain, symbol_name sym )const;
/// @abi action
void trade( account_name from,
account_name to,
name chain,
asset quantity,
trade_type type,
string memo);
/// @abi action
void addreward(name chain,asset supply,int32_t reward_now);
/// @abi action
void rewardmine(asset quantity);
/// @abi action
void claim(name chain,asset quantity,account_name receiver);
/// @abi action
void settlemine(account_name system_account);
/// @abi action
void activemine(account_name system_account);
private:
inline static uint128_t get_account_idx(const name& chain, const asset& a) {
return (uint128_t(uint64_t(chain)) << 64) + uint128_t(a.symbol.name());
}
struct account {
uint64_t id;
asset balance;
name chain;
int128_t mineage = 0; // asset.amount * block height
uint32_t mineage_update_height = 0;
asset reward = asset(0);
uint64_t primary_key() const { return id; }
uint128_t get_index_i128() const { return get_account_idx(chain, balance); }
};
struct account_next_id {
uint64_t id;
account_name account;
uint64_t primary_key() const { return account; }
};
struct reward_mine_info {
int128_t total_mineage = 0;
asset reward_pool = asset(0);
int32_t reward_block_num = 0;
uint64_t primary_key() const { return reward_block_num; }
};
struct currency_stats {
asset supply;
asset max_supply;
account_name issuer;
name chain;
account_name side_account;
action_name side_action;
int128_t total_mineage = 0; // asset.amount * block height
uint32_t total_mineage_update_height = 0;
uint64_t reward_scope;
int32_t reward_size = 0;
// vector<reward_mine_info> reward_mine;
uint64_t primary_key() const { return supply.symbol.name(); }
};
struct reward_currency {
uint64_t id;
name chain;
asset supply;
bool reward_now = true; //记录是否是立刻进行挖矿的代币
uint64_t primary_key() const { return id; }
uint128_t get_index_i128() const { return get_account_idx(chain, supply); }
};
typedef multi_index<N(accounts), account,
indexed_by< N(bychain),
const_mem_fun<account, uint128_t, &account::get_index_i128 >>> accounts;
typedef multi_index<N(stat), currency_stats> stats;
typedef multi_index<N(accountid), account_next_id> account_next_ids ;
typedef multi_index<N(reward), reward_currency,
indexed_by< N(bychain),
const_mem_fun<reward_currency, uint128_t, &reward_currency::get_index_i128 >>> rewards;
typedef multi_index<N(minereward), reward_mine_info> reward_mine ;
void sub_balance( account_name owner, name chain, asset value );
void add_balance( account_name owner, name chain, asset value, account_name ram_payer );
void settle_user(account_name owner, name chain, asset value);
public:
struct transfer_args {
account_name from;
account_name to;
name chain;
asset quantity;
string memo;
};
};
asset token::get_supply( name chain, symbol_name sym )const
{
stats statstable( _self, chain );
const auto& st = statstable.get( sym );
return st.supply;
}
};
#endif //FORCEIO_CONTRACT_RELAY_TOKEN_HPP
| 26.990291 | 105 | 0.641187 | eosforce |
3a35abe378de5385c0ca8d71446f0be43146accb | 6,813 | cpp | C++ | src/loop050.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | 4 | 2016-11-07T12:50:14.000Z | 2020-04-30T19:48:05.000Z | src/loop050.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | 1 | 2017-04-17T12:00:16.000Z | 2017-04-17T12:00:16.000Z | src/loop050.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | null | null | null |
#include "demoloop.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include "graphics/shader.h"
using namespace std;
using namespace demoloop;
const uint32_t CYCLE_LENGTH = 10;
const static std::string shaderCode = R"===(
uniform mediump float cycle_ratio;
#define DEMOLOOP_M_PI 3.1459
#ifdef VERTEX
vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) {
return transform_proj * model * vertpos;
}
#endif
#ifdef PIXEL
highp vec3 mod289(highp vec3 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
highp vec2 mod289(highp vec2 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
highp vec3 permute(highp vec3 x) {
return mod289(((x*34.0)+1.0)*x);
}
float snoise( vec2 v)
{
const highp vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
-0.577350269189626, // -1.0 + 2.0 * C.x
0.024390243902439); // 1.0 / 41.0
// First corner
highp vec2 i = floor(v + dot(v, C.yy) );
highp vec2 x0 = v - i + dot(i, C.xx);
// Other corners
highp vec2 i1;
//i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
//i1.y = 1.0 - i1.x;
i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
// x0 = x0 - 0.0 + 0.0 * C.xx ;
// x1 = x0 - i1 + 1.0 * C.xx ;
// x2 = x0 - 1.0 + 2.0 * C.xx ;
highp vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
highp vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
+ i.x + vec3(0.0, i1.x, 1.0 ));
highp vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
m = m*m ;
m = m*m ;
// Gradients: 41 points uniformly over a line, mapped onto a diamond.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
highp vec3 x = 2.0 * fract(p * C.www) - 1.0;
highp vec3 h = abs(x) - 0.5;
highp vec3 ox = floor(x + 0.5);
highp vec3 a0 = x - ox;
// Normalise gradients implicitly by scaling m
// Approximation of: m *= inversesqrt( a0*a0 + h*h );
m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );
// Compute final noise value at P
highp vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
float snoise(float x, float y) {
return snoise(vec2(x, y));
}
float noise(float x, float y, float a, float b) {
return snoise(x * a / 256.0, y * b / 256.0);
}
vec3 mix(float a, vec3 v1, vec3 v2) { return v1 * (1.0 - a) + v2 * a; }
float smoothStep(float w, float a, float b) {
if (w>=b) return 1.0;
if (w<=a) return 0.0;
float d = b-a;
return (w-a)/d;
}
vec3 colsca(vec3 c, float s) {
return c * s;
}
vec3 eye(float x, float y, float b) {
float rx = 2.0*(x-0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y;
float ry = 2.0*(y-0.5);
float a = atan(ry, rx);
float e = rx*rx + ry*ry;
float r = sqrt(e);
vec3 fue = vec3(1.0, 1.0, 1.0);
vec3 den = vec3(0.3, 0.7, 0.4 + e);
// veins
// float ven = noise(24 * x, 24 * y, 128, 128);
// ven = smoothStep(ven, -0.2, 0.0) - smoothStep(ven, 0.0, 0.2);
// ven += x + pow(x, 6) * 10;
// fue.r += 0.04 - 0.00*ven;
// fue.g += 0.04 - 0.05*ven;
// fue.b += 0.04 - 0.05*ven;
// circular pattern
float noiseOffset = pow(sin(cycle_ratio * DEMOLOOP_M_PI), 2.0) * 1.0;
float no = 0.8 + 0.2 * noise(4.0*r + noiseOffset, 32.0*a/DEMOLOOP_M_PI + noiseOffset, 256.0, 256.0);
den = colsca(den, no);
// iris
float irisSize = 0.025 - (1.0 - pow(sin((cycle_ratio) * DEMOLOOP_M_PI), 3.0)) * 0.02;
float f2 = smoothStep(e, irisSize, irisSize + 0.01);
den = colsca(den, f2);
vec3 mixed = mix(smoothStep(e, 0.35, 0.36), den, fue);
// ring
float ri = smoothStep(e, 0.31, 0.35) - smoothStep(e, 0.35, 0.36);
ri = 1.0 - 0.35 * ri;
mixed = colsca(mixed, ri);
// reflection
// float r3 = sqrt(r*r*r);
// float re = noise(2.0+4.0*r3*cos(a), 4.0*r3*sin(a), 128.0, 128.0);
// re = 0.4 * smoothStep(re, 0.1, 0.5);
// mixed += re * (1.0 - mixed);
// eye contours
mixed=colsca(mixed,0.8+0.15*smoothStep(-b,0.0,0.2));
mixed=colsca(mixed,0.8+0.2*smoothStep(-b,0.0,0.05));
return mixed;
}
vec3 skin(float x, float y, float b) {
float rx = 2.0*(x - 0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y;
float ry = 2.0*(y - 0.5);
vec3 skinColor = vec3(0.75, 0.69, 0.6);
// float cel = 0.95 + 0.05 * noise(64.0*x, 64.0*y, 256.0, 256.0);
// skinColor = colsca(skinColor, cel);
// skinColor.r += 0.03 * rx;
// skinColor.g += 0.03 * ry;
// skinColor = colsca(skinColor, y * 0.1 + 0.9);
// float bri = noise(128.0 * x, 128.0 * y, 256.0, 256.0);
// bri = 0.2 + 0.8 * smoothStep(bri, 0.0, 0.3);
// skinColor = mix(bri*0.08*y, skinColor, vec3(1, 1, 1));
// float san = 0.50*noise(16.0*x,16.0*y,256.0,256.0);
// san+= 0.25*noise(32.0*x,32.0*y,256.0,256.0);
// skinColor.g*=1-0.1*san;
// float osc = 0.500*noise(16.0*x,16.0*y,256.0,256.0);
// osc+= 0.250*noise(24.0*x,24.0*y,256.0,256.0);
// osc+= 0.125*noise(48.0*x,48.0*y,256.0,256.0);
// skinColor=colsca(skinColor,0.9+0.1*osc);
// skinColor.r+=0.08*x;
// skinColor.g+=0.01;
// float pecas = noise(32.0*x,32.0*y,256.0,256.0);
// pecas=smoothStep(pecas,0.80,0.8001);
// skinColor *= 1.0 - 0.16*pecas;
float g = smoothStep(1.0 - b, 0.2, 0.7);
g -= smoothStep(1.0 - b, 0.8, 1.0) * 3.0;
skinColor += g * 0.1;
// skinColor = mix(0.14, skinColor, vec3(1.0, 1.0, 1.0));
// skinColor *= 1.23;
// skinColor += 0.21;
skinColor=colsca(skinColor,(1.0-(b*0.5)));
return skinColor;
}
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) {
float t = cycle_ratio;
float r = 0.0, g = 0.0, b = 0.0;
float x = tc.x;
float y = tc.y;
float rx = 2.0*(x - 0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y;
float ry = 2.0*(y - 0.5);
// float h = 3.0*sqrt(x*x*x)*(1.0-x);
float h = (2.0*(1.0 - pow(sin(cycle_ratio * DEMOLOOP_M_PI), 5.0)) + 1.0)*sqrt(x*x*x)*(1.0-x);
float e = abs(ry) - h;
float f = smoothStep( e, 0.0, 0.01 );
float eyeX = x + cos(cycle_ratio * DEMOLOOP_M_PI * 2.0) * 0.1 - 0.1;
// y += sin(cycle_ratio * DEMOLOOP_M_PI * 2) * 0.1;
vec3 skinColor = skin(x, y, e);
vec3 eyeColor = eye(eyeX, y, e);
return vec4(mix(f, eyeColor, skinColor), 1.0);
}
#endif
)===";
class Loop050 : public Demoloop {
public:
Loop050() : Demoloop(CYCLE_LENGTH, 150, 150, 150), shader({shaderCode, shaderCode}) {
}
void Update() {
const float cycle_ratio = getCycleRatio();
shader.attach();
shader.sendFloat("cycle_ratio", 1, &cycle_ratio, 1);
renderTexture(gl.getDefaultTexture(), 0, 0, width, height);
shader.detach();
}
private:
Shader shader;
};
int main(int, char**){
Loop050 test;
test.Run();
return 0;
}
| 27.582996 | 102 | 0.577866 | TannerRogalsky |
3a37bdced5e0efee4020441b1398b40eafd176e2 | 1,797 | hpp | C++ | src/network/credentials_manager.hpp | Natureshadow/biboumi | b70136b96e579e8d38a30a298f885899cb80514c | [
"Zlib"
] | null | null | null | src/network/credentials_manager.hpp | Natureshadow/biboumi | b70136b96e579e8d38a30a298f885899cb80514c | [
"Zlib"
] | null | null | null | src/network/credentials_manager.hpp | Natureshadow/biboumi | b70136b96e579e8d38a30a298f885899cb80514c | [
"Zlib"
] | null | null | null | #pragma once
#include "biboumi.h"
#ifdef BOTAN_FOUND
#include <botan/credentials_manager.h>
#include <botan/certstor.h>
#include <botan/tls_client.h>
class TCPSocketHandler;
/**
* If the given cert isn’t valid, based on the given hostname
* and fingerprint, then throws the exception if it’s non-empty.
*
* Must be called after the standard (from Botan) way of
* checking the certificate, if we want to also accept certificates based
* on a trusted fingerprint.
*/
void check_tls_certificate(const std::vector<Botan::X509_Certificate>& certs,
const std::string& hostname, const std::string& trusted_fingerprint,
const std::exception_ptr& exc);
class BasicCredentialsManager: public Botan::Credentials_Manager
{
public:
BasicCredentialsManager(const TCPSocketHandler* const socket_handler);
BasicCredentialsManager(BasicCredentialsManager&&) = delete;
BasicCredentialsManager(const BasicCredentialsManager&) = delete;
BasicCredentialsManager& operator=(const BasicCredentialsManager&) = delete;
BasicCredentialsManager& operator=(BasicCredentialsManager&&) = delete;
std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type,
const std::string& context) override final;
void set_trusted_fingerprint(const std::string& fingerprint);
const std::string& get_trusted_fingerprint() const;
private:
const TCPSocketHandler* const socket_handler;
static bool try_to_open_one_ca_bundle(const std::vector<std::string>& paths);
static void load_certs();
static Botan::Certificate_Store_In_Memory certificate_store;
static bool certs_loaded;
std::string trusted_fingerprint;
};
#endif //BOTAN_FOUND
| 34.557692 | 116 | 0.734001 | Natureshadow |
3a3c737e177e79caa3dd9fb3ffa71b10e4190155 | 1,583 | hpp | C++ | EFI/CLOVER/kexts/Other/Lilu_v1.4.3-Debug.kext/Contents/Resources/Headers/kern_policy.hpp | zhujinle/Lenovo-yoga-c930-hackintosh | 679ec3efe7e63b102e5a2ad7a3f5a1cd48a949ca | [
"MIT"
] | 56 | 2019-11-07T01:57:38.000Z | 2021-06-07T21:09:52.000Z | EFI/CLOVER/kexts/Other/Lilu_v1.4.3-Debug.kext/Contents/Resources/Headers/kern_policy.hpp | zhujinle/Lenovo-yoga-c930-hackintosh | 679ec3efe7e63b102e5a2ad7a3f5a1cd48a949ca | [
"MIT"
] | 10 | 2020-07-27T01:59:55.000Z | 2021-03-02T02:17:04.000Z | EFI/CLOVER/kexts/Other/Lilu_v1.4.3-Debug.kext/Contents/Resources/Headers/kern_policy.hpp | zhujinle/Lenovo-yoga-c930-hackintosh | 679ec3efe7e63b102e5a2ad7a3f5a1cd48a949ca | [
"MIT"
] | 11 | 2020-07-10T07:03:08.000Z | 2021-05-14T06:44:19.000Z | //
// kern_policy.hpp
// Lilu
//
// Copyright © 2016-2017 vit9696. All rights reserved.
//
#ifndef kern_policy_hpp
#define kern_policy_hpp
#include <Headers/kern_config.hpp>
#include <sys/types.h>
#include <sys/proc.h>
#include <Library/security/mac_framework.h>
#include <Library/security/mac_policy.h>
#include <Headers/kern_util.hpp>
class Policy {
/**
* TrustedBSD Policy handle
*/
mac_policy_handle_t policyHandle {0};
/**
* TrustedBSD policy configuration
*/
mac_policy_conf policyConf;
public:
/**
* May be used at TrustedBSD policy initialisation
*
* @param conf policy configuration
*/
static void dummyPolicyInitBSD(mac_policy_conf *conf) {
DBGLOG("policy", "init bsd");
}
/**
* Compile-time policy constructor
*
* @param name policy name literal
* @param descr policy description literal
* @param ops policy functions
*/
constexpr Policy(const char *name, const char *descr, struct mac_policy_ops *ops) : policyConf{
.mpc_name = name,
.mpc_fullname = descr,
.mpc_labelnames = nullptr,
.mpc_labelname_count = 0,
.mpc_ops = ops,
// Our policies are loaded very early and are static. We cannot unload them.
.mpc_loadtime_flags = 0 /*MPC_LOADTIME_FLAG_UNLOADOK*/,
.mpc_field_off = nullptr,
.mpc_runtime_flags = 0
} { }
/**
* Registers TrustedBSD policy
*
* @return true on success
*/
EXPORT bool registerPolicy();
/**
* Unregisters TrustedBSD policy if allowed
*
* @return true on success
*/
EXPORT bool unregisterPolicy();
};
#endif /* kern_policy_hpp */
| 21.106667 | 96 | 0.689829 | zhujinle |
3a3e2f2b818c38b1c01f390ef641f9e3b0f0b91b | 1,066 | cpp | C++ | Cplusplus_Study/array_vector.cpp | SuperBruceJia/paper-reading | ccfa34706fd525b1c47ec2476896efbd020c7210 | [
"MIT"
] | 11 | 2020-11-13T02:47:56.000Z | 2022-03-25T06:13:06.000Z | Cplusplus_Study/array_vector.cpp | SuperBruceJia/paper-reading | ccfa34706fd525b1c47ec2476896efbd020c7210 | [
"MIT"
] | null | null | null | Cplusplus_Study/array_vector.cpp | SuperBruceJia/paper-reading | ccfa34706fd525b1c47ec2476896efbd020c7210 | [
"MIT"
] | 2 | 2021-10-10T13:42:20.000Z | 2021-12-14T09:59:23.000Z | #include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
char vowels [] {'a', 'e','i', 'w', 'r'};
cout << "The first vowels is " << vowels[0] << endl;
cout << "The last vowels is " << vowels[4] << endl;
double hi_temps [] {90.1, 89.7, 77.5, 81.6};
cout << "The first high temperature is " << hi_temps[0] << endl;
hi_temps[0] = 100.7;
for (int i=0; i<=3; i++)
cout << hi_temps[i] << endl;
int test_score [] {};
cout << "Input 5 test scores: " << endl;
cin >> test_score[0];
cin >> test_score[1];
cin >> test_score[2];
cin >> test_score[3];
cin >> test_score[4];
cout << "First score at index 0 is " << test_score[0] << endl;
cout << "Second score at index 1 is " << test_score[1] << endl;
cout << "Third score at index 2 is " << test_score[2] << endl;
cout << "Fourth score at index 3 is " << test_score[3] << endl;
cout << "Fifth score at index 4 is " << test_score[4] << endl;
cout << test_score << endl;
return 0;
}
| 29.611111 | 68 | 0.532833 | SuperBruceJia |
3a4c78ac435cd30a3fef99b13b1afeeb82e2d4e0 | 15,981 | cpp | C++ | software/controller/lib/hal/i2c.cpp | RespiraWorks/Ventilator | 2b431b96d988a5d88cc60525470277757c2b88f4 | [
"Apache-2.0"
] | 47 | 2020-07-05T03:06:25.000Z | 2022-03-14T16:59:24.000Z | software/controller/lib/hal/i2c.cpp | RespiraWorks/Ventilator | 2b431b96d988a5d88cc60525470277757c2b88f4 | [
"Apache-2.0"
] | 545 | 2020-07-01T22:25:42.000Z | 2022-03-31T04:07:28.000Z | software/controller/lib/hal/i2c.cpp | RespiraWorks/Ventilator | 2b431b96d988a5d88cc60525470277757c2b88f4 | [
"Apache-2.0"
] | 19 | 2020-07-16T18:48:28.000Z | 2022-02-09T10:20:21.000Z | /* Copyright 2020, RespiraWorks
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.
*/
////////////////////////////////////////////////////////////////////
//
// This file contains code to setup, send and receive data on the I²C channel
// See header file for implementation philosophy.
//
////////////////////////////////////////////////////////////////////
#include "i2c.h"
#include <cstring>
#include "clocks.h"
#include "gpio.h"
#if defined(BARE_STM32)
I2C::STM32Channel i2c1;
#else
I2C::Channel i2c1;
#endif // BARE_STM32
namespace I2C {
// Reference abbreviations ([RM], [PCB], etc) are defined in hal/README.md
void initialize() {
// Enable I2C1 and DMA2 peripheral clocks (we use DMA2 to send/receive data)
enable_peripheral_clock(PeripheralID::I2C1);
enable_peripheral_clock(PeripheralID::DMA2);
// The following pins are used as i2c1 bus on the rev-1 PCB (see [PCB]):
// Set Pin Function to I²C, [DS] Table 17 (pg 77)
GPIO::alternate_function(GPIO::Port::B, /*pin =*/8,
GPIO::AlternativeFuncion::AF4); // I2C1_SCL
GPIO::alternate_function(GPIO::Port::B, /*pin =*/9,
GPIO::AlternativeFuncion::AF4); // I2C1_SDA
// Set output speed to Fast
GPIO::output_speed(GPIO::Port::B, 8, GPIO::OutSpeed::Fast);
GPIO::output_speed(GPIO::Port::B, 9, GPIO::OutSpeed::Fast);
// Set open drain mode
GPIO::output_type(GPIO::Port::B, 8, GPIO::OutType::OpenDrain);
GPIO::output_type(GPIO::Port::B, 9, GPIO::OutType::OpenDrain);
// Set Pull Up resistors
GPIO::pull_up(GPIO::Port::B, 8);
GPIO::pull_up(GPIO::Port::B, 9);
Interrupts::singleton().EnableInterrupt(InterruptVector::I2c1Event, IntPriority::Low);
Interrupts::singleton().EnableInterrupt(InterruptVector::I2c1Error, IntPriority::Low);
Interrupts::singleton().EnableInterrupt(InterruptVector::Dma2Channel6, IntPriority::Low);
Interrupts::singleton().EnableInterrupt(InterruptVector::Dma2Channel7, IntPriority::Low);
// init i2c1
#if defined(BARE_STM32)
i2c1.Init(I2C1Base, DMA::Base::DMA2, I2C::Speed::Fast);
#endif
}
bool Channel::SendRequest(const Request &request) {
*(request.processed) = false;
// We need to ensure thread safety as this function might be
// called from a timer interrupt as well as the main loop.
// Also, because our ISR change the transfer_in_progress_ member variable.
BlockInterrupts block;
// Queue the request if possible: check that there is room in the index
// buffer
if (buffer_.IsFull()) {
return false;
}
// Add the current queue_ index into the buffer
if (buffer_.Put(ind_queue_)) {
queue_[ind_queue_] = request;
} else {
return false;
}
// In case of a write request, copy data to our write buffer
if (request.direction == ExchangeDirection::Write) {
if (!CopyDataToWriteBuffer(request.data, request.size)) {
return false;
}
// update the request's data pointer to the write buffer instead of the
// caller's scope variable
queue_[ind_queue_].data = &write_buffer_[write_buffer_index_];
// update the write buffer index
write_buffer_index_ += request.size;
}
// increment ind_queue_, which is the index at which the next request will
// be put in the queue, with wrapping around the queue.
if (++ind_queue_ >= QueueLength) {
ind_queue_ = 0;
}
if (!transfer_in_progress_) {
StartTransfer();
}
// if a transfer is already in progress, this request will be initiated by
// the interrupt handlers, our work is done!
return true;
}
bool Channel::CopyDataToWriteBuffer(const void *data, const uint16_t size) {
// This protected function is only called from an already thread safe
// function, but leaning on the safe side here, I am disabling interrupts
// for this one anyway, in case someone changes the design of the I²C class.
BlockInterrupts block;
// Check if the empty space at the end of the buffer is big enough to
// store all of the data
if (write_buffer_index_ + size > WriteBufferSize) {
// It isn't ==> Check if the empty space at the beginning of the buffer
// is big enough to store all of the data instead
if (size >= write_buffer_start_) {
// There is no contiguous space left in buffer that is big enough,
// we can't safely send this Write request.
return false;
}
// We can write at the beginning of the buffer, need to remember that we
// wrap at that index in order to properly wrap when updating
// write_buffer_start_ when the (previous) transfer will end.
wrapping_index_ = write_buffer_index_;
write_buffer_index_ = 0;
}
memcpy(&write_buffer_[write_buffer_index_], data, size);
return true;
}
void Channel::StartTransfer() {
transfer_in_progress_ = true;
// In DMA mode, a single request can lead to several transfers, when it is
// longer than 255 bytes. Therefore we need to check whether this call is a
// continuation of a long request or a new request.
// Also in case of transfer error, we may need to re-send the last request
if (remaining_size_ == 0) {
// Ensure thread safety
BlockInterrupts block;
// This indicates the last request has been successfully sent, hence we
// will send the next request in the queue.
std::optional<uint8_t> index = buffer_.Get();
if (index == std::nullopt) {
// no request in the queue
transfer_in_progress_ = false;
return;
}
last_request_ = queue_[*index];
next_data_ = reinterpret_cast<uint8_t *>(last_request_.data);
remaining_size_ = last_request_.size;
error_retry_ = MaxRetries;
}
SetupI2CTransfer();
}
// Method called by interrupt handler when dma is disabled. This method
// transfers data to/from the tx/rx registers from/to *request.data
void Channel::TransferByte() {
if (remaining_size_ == 0) {
// this shouldn't happen, but just to be safe, we stop here.
return;
}
if (last_request_.direction == ExchangeDirection::Read) {
ReceiveByte();
} else {
SendByte();
}
if (--remaining_size_ > 0) {
// increment next_data_ pointer only in case we are still expecting more
// data to prevent unwarranted memory access
next_data_ += sizeof(uint8_t);
};
}
void Channel::EndTransfer() {
// Ensure thread safety
BlockInterrupts block;
*last_request_.processed = true;
if (last_request_.direction == ExchangeDirection::Write) {
// free the part of the write buffer that was dedicated to this request
write_buffer_start_ += last_request_.size;
if (write_buffer_start_ >= wrapping_index_) {
// We don't allow data in the same request to wrap around, so we
// must detect that the next write data actually starts at index 0
// to properly free the end of the buffer as well
write_buffer_start_ = 0;
}
}
transfer_in_progress_ = false;
}
void Channel::I2CEventHandler() {
if (!transfer_in_progress_) {
return;
}
// resend the request in case the slave NACK'd our request
if (NackDetected()) {
// clear the nack
ClearNack();
// the slave is non-responsive --> start the request anew
next_data_ = reinterpret_cast<uint8_t *>(last_request_.data);
remaining_size_ = last_request_.size;
StartTransfer();
}
// When we are using DMA, NACK is the only I²C event we are dealing with
if (dma_enable_) {
return;
}
if (NextByteNeeded()) {
// carry on with the current transfer
TransferByte();
}
if (TransferReload()) {
// To continue a request that is longer than 255 bits, all we need to do
// is write a non-zero transfer size, and set the reload byte
// accordingly (see [RM] p1151 (Write request) and 1155 (Read request))
WriteTransferSize();
}
if (TransferComplete()) {
// Send stop condition
StopTransfer();
// Clean necessary states
EndTransfer();
// And start the next one (if any)
StartTransfer();
}
}
void Channel::I2CErrorHandler() {
// I²C error --> clear all error flags (except those that are SMBus only)
ClearErrors();
// and restart the request up to error_retry_ times
if (--error_retry_ > 0) {
next_data_ = reinterpret_cast<uint8_t *>(last_request_.data);
remaining_size_ = last_request_.size;
} else {
// skip this request and go to next one;
remaining_size_ = 0;
}
StartTransfer();
}
void STM32Channel::Init(I2CReg *i2c, DMA::Base dma, Speed speed) {
i2c_ = i2c;
dma_ = dma;
// Disable I²C peripheral
i2c_->control_reg1.enable = 0;
// Set I²C speed using timing values from [RM] table 182
i2c_->timing.full_reg = static_cast<uint32_t>(speed);
// Setup DMA channels
// if (dma != nullptr) {
SetupDMAChannels(dma);
// }
// enable I²C peripheral
i2c_->control_reg1.enable = 1;
// configure I²C interrupts
i2c_->control_reg1.nack_interrupts = 1;
i2c_->control_reg1.error_interrupts = 1;
// in DMA mode, we do not treat the transfer-specific ones
if (!dma_enable_) {
i2c_->control_reg1.rx_interrupts = 1;
i2c_->control_reg1.tx_interrupts = 1;
i2c_->control_reg1.tx_complete_interrupts = 1;
} else {
i2c_->control_reg1.rx_interrupts = 0;
i2c_->control_reg1.tx_interrupts = 0;
i2c_->control_reg1.tx_complete_interrupts = 0;
}
}
void STM32Channel::SetupI2CTransfer() {
// set transfer-specific registers per [RM] p1149 to 1158
i2c_->control2.slave_addr_7b = last_request_.slave_address & 0x7f;
i2c_->control2.transfer_direction = static_cast<bool>(last_request_.direction);
if (dma_enable_) {
SetupDMATransfer();
}
WriteTransferSize();
i2c_->control2.start = 1;
}
// Write the remaining size to the appropriate register with reload logic
void STM32Channel::WriteTransferSize() {
if (remaining_size_ <= 255) {
i2c_->control2.n_bytes = static_cast<uint8_t>(remaining_size_);
i2c_->control2.reload = 0;
} else {
i2c_->control2.n_bytes = 255;
// Transfer reload is not currently supported by our HAL in DMA mode,
// we will treat a reload as a new transfer. In effect this means we
// will have to reissue the I²C header and start condition.
// It also means that any request that has a (functional) header inside
// its data and is longer than 255 bytes may not be processed correctly
// by the I²C slave, as it will be split (this is referred to as a
// Restart condition rather than Reload)
if (!dma_enable_) {
i2c_->control2.reload = 1;
} else {
i2c_->control2.reload = 0;
}
}
}
// DMA functions are only meaningful in BARE_STM32
void STM32Channel::SetupDMAChannels(const DMA::Base dma) {
// DMA mapping for I²C (see [RM] p299)
static struct {
DMA::Base dma_base;
volatile void *i2c_base;
DMA::Channel tx_channel_id;
DMA::Channel rx_channel_id;
uint8_t request_number;
} DmaMap[] = {
{DMA::Base::DMA1, I2C1Base, DMA::Channel::Chan6, DMA::Channel::Chan7, 3},
{DMA::Base::DMA1, I2C2Base, DMA::Channel::Chan4, DMA::Channel::Chan5, 3},
{DMA::Base::DMA1, I2C3Base, DMA::Channel::Chan2, DMA::Channel::Chan3, 3},
{DMA::Base::DMA2, I2C1Base, DMA::Channel::Chan7, DMA::Channel::Chan6, 5},
{DMA::Base::DMA2, I2C4Base, DMA::Channel::Chan2, DMA::Channel::Chan1, 0},
};
for (auto &map : DmaMap) {
if (dma == map.dma_base && i2c_ == map.i2c_base) {
auto *dma_register = DMA::get_register(dma);
dma_ = dma;
tx_channel_ = &dma_register->channel[static_cast<uint8_t>(map.tx_channel_id)];
rx_channel_ = &dma_register->channel[static_cast<uint8_t>(map.rx_channel_id)];
// Tell the STM32 that those two DMA channels are used for I2C
DMA::SelectChannel(dma, map.rx_channel_id, map.request_number);
DMA::SelectChannel(dma, map.tx_channel_id, map.request_number);
// configure both DMA channels to handle I²C transfers
ConfigureDMAChannel(rx_channel_, ExchangeDirection::Read);
ConfigureDMAChannel(tx_channel_, ExchangeDirection::Write);
dma_enable_ = true;
i2c_->control_reg1.dma_rx = 1;
i2c_->control_reg1.dma_tx = 1;
break;
}
}
}
void I2C::STM32Channel::ConfigureDMAChannel(volatile DmaReg::ChannelRegs *channel,
ExchangeDirection direction) {
channel->config.priority = 0b01; // medium priority
channel->config.tx_error_interrupt = 1; // interrupt on error
channel->config.half_tx_interrupt = 0; // no half-transfer interrupt
channel->config.tx_complete_interrupt = 1; // interrupt on DMA complete
channel->config.mem2mem = 0; // memory-to-memory mode disabled
channel->config.memory_size = static_cast<uint8_t>(DMA::TransferSize::Byte);
channel->config.peripheral_size = static_cast<uint8_t>(DMA::TransferSize::Byte);
channel->config.memory_increment = 1; // increment dest address
channel->config.peripheral_increment = 0; // don't increment source address
channel->config.circular = 0;
if (direction == ExchangeDirection::Read) {
channel->config.direction = static_cast<uint8_t>(DMA::ChannelDir::PeripheralToMemory);
channel->peripheral_address = &(i2c_->rx_data);
} else {
channel->config.direction = static_cast<uint8_t>(DMA::ChannelDir::MemoryToPeripheral);
channel->peripheral_address = &(i2c_->tx_data);
}
}
void STM32Channel::SetupDMATransfer() {
if (!dma_enable_) {
return;
}
// to be on the safe size, disable both channels in case they weren't
// (likely when this is called as a "retry after error")
rx_channel_->config.enable = 0;
tx_channel_->config.enable = 0;
volatile DmaReg::ChannelRegs *channel{nullptr};
if (last_request_.direction == ExchangeDirection::Read) {
channel = rx_channel_;
} else {
channel = tx_channel_;
}
channel->memory_address = next_data_;
if (remaining_size_ <= 255) {
channel->count = remaining_size_;
} else {
channel->count = 255;
}
// when using DMA, we need to use autoend, otherwise the STOP condition
// which we issue at the end of the DMA transfer (which means the last byte
// has been written to the register) may arrive before the last byte is
// actually written on the line. Tests with both DMA and I2C interrupts
// enabled to send Stop at the end of the I2C transfer were inconclusive.
i2c_->control2.autoend = 1;
channel->config.enable = 1;
}
void STM32Channel::DMAIntHandler(DMA::Channel chan) {
if (!dma_enable_ || !transfer_in_progress_) return;
auto *dma_register = DMA::get_register(dma_);
dma_register->channel[static_cast<uint8_t>(chan)].config.enable = 0;
if (DMA::IntStatus(dma_, chan, DMA::Interrupt::TransferComplete)) {
if (remaining_size_ > 255) {
// decrement remaining size by 255 (the size of the DMA transfer)
remaining_size_ = static_cast<uint16_t>(remaining_size_ - 255);
next_data_ += 255 * sizeof(uint8_t);
} else {
remaining_size_ = 0;
EndTransfer();
}
} else if (DMA::IntStatus(dma_, chan, DMA::Interrupt::TransferError)) {
// we are dealing with an error --> reset transfer (up to MaxRetries
// times)
if (--error_retry_ > 0) {
next_data_ = reinterpret_cast<uint8_t *>(last_request_.data);
remaining_size_ = last_request_.size;
} else {
// skip this request and go to next request;
remaining_size_ = 0;
}
}
// clear all interrupts and (re-)start the current or next transfer
DMA::ClearInt(dma_, chan, DMA::Interrupt::Global);
StartTransfer();
}
} // namespace I2C
| 34.969365 | 91 | 0.686315 | RespiraWorks |
3a521542ae98bdc5e7ffce1afcd79026d128886c | 7,124 | cpp | C++ | src/condor_utils/hibernator.tools.cpp | zhangzhehust/htcondor | e07510d62161f38fa2483b299196ef9a7b9f7941 | [
"Apache-2.0"
] | 1 | 2017-02-13T01:25:34.000Z | 2017-02-13T01:25:34.000Z | src/condor_utils/hibernator.tools.cpp | zhangzhehust/htcondor | e07510d62161f38fa2483b299196ef9a7b9f7941 | [
"Apache-2.0"
] | 1 | 2021-04-06T04:19:40.000Z | 2021-04-06T04:19:40.000Z | src/condor_utils/hibernator.tools.cpp | zhangzhehust/htcondor | e07510d62161f38fa2483b299196ef9a7b9f7941 | [
"Apache-2.0"
] | 2 | 2016-05-24T17:12:13.000Z | 2017-02-13T01:25:35.000Z | /***************************************************************
*
* Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
/***************************************************************
* Headers
***************************************************************/
#include "condor_common.h"
#include "condor_config.h"
#include "condor_uid.h"
#include "hibernator.tools.h"
#include "path_utils.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
/***************************************************************
* UserDefinedToolsHibernator class
***************************************************************/
UserDefinedToolsHibernator::UserDefinedToolsHibernator () throw ()
: HibernatorBase (),
m_keyword ( "HIBERNATE" ),
m_reaper_id ( -1 )
{
for ( unsigned i = 0; i <= 10; ++i ) {
m_tool_paths[i] = NULL;
}
configure ();
}
UserDefinedToolsHibernator::UserDefinedToolsHibernator ( const MyString &keyword ) throw ()
: HibernatorBase (),
m_keyword ( keyword ),
m_reaper_id ( -1 )
{
for ( unsigned i = 0; i <= 10; ++i ) {
m_tool_paths[i] = NULL;
}
configure ();
}
UserDefinedToolsHibernator::~UserDefinedToolsHibernator () throw ()
{
for ( unsigned i = 1; i <= 10; ++i ) {
if ( NULL != m_tool_paths[i] ) {
free ( m_tool_paths[i] );
m_tool_paths[i] = NULL;
}
}
if ( -1 != m_reaper_id ) {
daemonCore->Cancel_Reaper ( m_reaper_id );
}
}
const char*
UserDefinedToolsHibernator::getMethod ( void ) const
{
return "user defined tools";
}
/** We define a 'C' style Reaper for use in configure() to eliminate
the problem of a cast being made between different pointer to
member representations (because of multiple inheritance--C++
Reapers require the object to be of type Service); If we used a
C++ style Reaper the compiler may generate incorrect code. */
int UserDefinedToolsHibernator::userDefinedToolsHibernatorReaper ( int pid, int )
{
/** Make sure the hibernator didn't leak any processes */
daemonCore->Kill_Family ( pid );
return TRUE;
}
void UserDefinedToolsHibernator::configure ()
{
MyString name,
error;
unsigned states = HibernatorBase::NONE;
const char *description = NULL;
char *arguments = NULL;
HibernatorBase::SLEEP_STATE state = HibernatorBase::NONE;
bool ok = false;
/** There are no tools for S0, or "NONE" */
m_tool_paths[0] = NULL;
/** Pull the paths for the rest of the sleep states from
the configuration file */
for ( unsigned i = 1; i <= 10; ++i ) {
/** Clean out the old path information */
if ( NULL != m_tool_paths[i] ) {
free ( m_tool_paths[i] );
m_tool_paths[i] = NULL;
}
/** Convert the current index to the sleep state equivalent */
state = HibernatorBase::intToSleepState ( i );
if ( HibernatorBase::NONE == state ) {
continue;
}
/** Convert the sleep state to a human consumable description */
description = HibernatorBase::sleepStateToString ( state );
if ( NULL == description ) {
continue;
}
dprintf (
D_FULLDEBUG,
"UserDefinedToolsHibernator: state = %d, desc = %s\n",
state,
"S1" );
/** Build the tool look-up parameter for the tool's path */
name.formatstr (
"%s_USER_%s_TOOL",
"HIBERNATE",
"S1" );
/** Grab the user defined executable path */
m_tool_paths[i] = validateExecutablePath ( name.Value () );
if ( NULL != m_tool_paths[i] ) {
/** Make the path the first argument to Create_Process */
m_tool_args[i].AppendArg ( m_tool_paths[i] );
/** Build the tool look-up parameter for the tool's
argument list */
name.formatstr (
"%s_USER_%s_ARGS",
m_keyword.Value(),
description );
/** Grab the command's arguments */
arguments = param ( name.Value () );
if ( NULL != arguments ) {
/** Parse the command-line arguments */
ok = m_tool_args[i].AppendArgsV1WackedOrV2Quoted (
arguments,
&error );
if ( !ok ) {
dprintf (
D_FULLDEBUG,
"UserDefinedToolsHibernator::configure: failed "
"to parse the tool arguments defined in the "
"configuration file: %s\n",
error.Value() );
}
/** Dump the param'd value */
free ( arguments );
}
/** Tally the supported state */
states |= state;
} else {
dprintf (
D_FULLDEBUG,
"UserDefinedToolsHibernator::configure: the executable "
"(%s) defined in the configuration file is invalid.\n",
m_tool_paths[i] );
}
}
/** Now set the supported states */
setStates ( states );
/** Finally, register the reaper that will clean up after the
user defined tool and its children */
m_reaper_id = daemonCore->Register_Reaper (
"UserDefinedToolsHibernator Reaper",
(ReaperHandlercpp) &UserDefinedToolsHibernator::userDefinedToolsHibernatorReaper,
"UserDefinedToolsHibernator Reaper",
NULL );
}
HibernatorBase::SLEEP_STATE
UserDefinedToolsHibernator::enterState ( HibernatorBase::SLEEP_STATE state ) const
{
/** Make sure a tool for this sleep state has been defined */
unsigned index = sleepStateToInt ( state );
if ( NULL == m_tool_paths[index] ) {
dprintf (
D_FULLDEBUG,
"Hibernator::%s tool not configured.\n",
HibernatorBase::sleepStateToString ( state ) );
return HibernatorBase::NONE;
}
/** Tell DaemonCore to register the process family so we can
safely kill everything from the reaper */
FamilyInfo fi;
fi.max_snapshot_interval = param_integer (
"PID_SNAPSHOT_INTERVAL",
15 );
/** Run the user tool */
int pid = daemonCore->Create_Process (
m_tool_paths[index],
m_tool_args[index],
PRIV_CONDOR_FINAL,
m_reaper_id,
FALSE,
FALSE,
NULL,
NULL,
&fi );
if ( FALSE == pid ) {
dprintf (
D_ALWAYS,
"UserDefinedToolsHibernator::enterState: Create_Process() "
"failed\n" );
return HibernatorBase::NONE;
}
return state;
}
HibernatorBase::SLEEP_STATE
UserDefinedToolsHibernator::enterStateStandBy ( bool /*force*/ ) const
{
return enterState ( HibernatorBase::S1 );
}
HibernatorBase::SLEEP_STATE
UserDefinedToolsHibernator::enterStateSuspend ( bool /*force*/ ) const
{
return enterState ( HibernatorBase::S3 );
}
HibernatorBase::SLEEP_STATE
UserDefinedToolsHibernator::enterStateHibernate ( bool /*force*/ ) const
{
return enterState ( HibernatorBase::S4 );
}
HibernatorBase::SLEEP_STATE
UserDefinedToolsHibernator::enterStatePowerOff ( bool /*force*/ ) const
{
return enterState ( HibernatorBase::S5 );
}
| 25.905455 | 92 | 0.643739 | zhangzhehust |
3a52b2a578ca59420a71cd1263fc45435d0b181a | 1,263 | cpp | C++ | erts/emulator/asmjit/arm/a64builder.cpp | williamthome/otp | c4f24d6718ac56c431f0fccf240c5b15482792ed | [
"Apache-2.0"
] | null | null | null | erts/emulator/asmjit/arm/a64builder.cpp | williamthome/otp | c4f24d6718ac56c431f0fccf240c5b15482792ed | [
"Apache-2.0"
] | null | null | null | erts/emulator/asmjit/arm/a64builder.cpp | williamthome/otp | c4f24d6718ac56c431f0fccf240c5b15482792ed | [
"Apache-2.0"
] | 2 | 2015-10-18T22:36:46.000Z | 2022-01-26T14:01:57.000Z | // This file is part of AsmJit project <https://asmjit.com>
//
// See asmjit.h or LICENSE.md for license and copyright information
// SPDX-License-Identifier: Zlib
#include "../core/api-build_p.h"
#if !defined(ASMJIT_NO_AARCH64) && !defined(ASMJIT_NO_BUILDER)
#include "../arm/a64assembler.h"
#include "../arm/a64builder.h"
#include "../arm/a64emithelper_p.h"
ASMJIT_BEGIN_SUB_NAMESPACE(a64)
// a64::Builder - Construction & Destruction
// =========================================
Builder::Builder(CodeHolder* code) noexcept : BaseBuilder() {
_archMask = uint64_t(1) << uint32_t(Arch::kAArch64);
assignEmitterFuncs(this);
if (code)
code->attach(this);
}
Builder::~Builder() noexcept {}
// a64::Builder - Events
// =====================
Error Builder::onAttach(CodeHolder* code) noexcept {
return Base::onAttach(code);
}
Error Builder::onDetach(CodeHolder* code) noexcept {
return Base::onDetach(code);
}
// a64::Builder - Finalize
// =======================
Error Builder::finalize() {
ASMJIT_PROPAGATE(runPasses());
Assembler a(_code);
a.addEncodingOptions(encodingOptions());
a.addDiagnosticOptions(diagnosticOptions());
return serializeTo(&a);
}
ASMJIT_END_SUB_NAMESPACE
#endif // !ASMJIT_NO_AARCH64 && !ASMJIT_NO_BUILDER
| 24.288462 | 67 | 0.673001 | williamthome |
3a53f1275b70afb6575f74ab168e6b3406d7aff7 | 7,629 | cpp | C++ | NxS Info Tool Source/nxstabpages.cpp | saivert/winamp-plugins | 5dae16e80bb63e3de258b4279c444bf2434de564 | [
"MIT"
] | 3 | 2019-06-14T12:03:23.000Z | 2022-02-12T18:15:38.000Z | NxS Info Tool Source/nxstabpages.cpp | saivert/winamp-plugins | 5dae16e80bb63e3de258b4279c444bf2434de564 | [
"MIT"
] | null | null | null | NxS Info Tool Source/nxstabpages.cpp | saivert/winamp-plugins | 5dae16e80bb63e3de258b4279c444bf2434de564 | [
"MIT"
] | null | null | null | /* NxS Tabpages - written by Saivert */
//#include "StdAfx.h"
#include "nxstabpages.h"
NxS_TabPages::~NxS_TabPages()
{
Clear();
}
HWND NxS_TabPages::SetTabCtrl(HWND NewTabCtrl)
{
HWND tmp;
tmp = m_hwTab;
if (IsWindow(NewTabCtrl))
{
if (GetCount()>0)
TabCtrl_DeleteAllItems(m_hwTab);
m_hwTab = NewTabCtrl;
if (GetCount()>0)
TabCtrl_DeleteAllItems(m_hwTab);
TabCtrl_SetItemExtra(m_hwTab, NXSTABPAGES_TABITEMSIZE);
}
return tmp;
}
bool NxS_TabPages::DelPage(int index)
{
TABITEM item;
if (TabCtrl_GetItem(m_hwTab, index, &item))
{
if (item.dlghandle)
{
NMHDR hdr;
hdr.code = PSN_RESET;
hdr.hwndFrom = (HWND)this;
hdr.idFrom = 0;
if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr))
{
if (TRUE==GetWindowLong(item.dlghandle, DWL_MSGRESULT))
return false;
}
DestroyWindow(item.dlghandle);
}
TabCtrl_DeleteItem(m_hwTab, index);
return true;
}
return false;
}
bool NxS_TabPages::GetPage(int index, TABITEM &tp)
{
return TabCtrl_GetItem(m_hwTab, index, &tp)>0;
}
NxS_TabPages::TABITEM& NxS_TabPages::Pages(int index)
{
TabCtrl_GetItem(m_hwTab, index, &m_tptemp);
return m_tptemp;
}
bool NxS_TabPages::SendApply()
{
bool res=true;
TABITEM item;
//First we check if the active page wants to loose activation
if (m_curwnd)
{
NMHDR hdr;
hdr.code = PSN_KILLACTIVE;
hdr.hwndFrom = (HWND)this;
hdr.idFrom = 0;
if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr))
{
if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT))
return false;
}
}
//If the active page said OK, we send a PSN_APPLY notification message to
//all the pages. Any one of the pages can return PSNRET_INVALID_NOCHANGEPAGE
//to make SendApply() return false. This is a clue to keep the host dialog open.
for (int i=0; i<GetCount(); i++)
{
if (TabCtrl_GetItem(m_hwTab, i, &item))
{
if (item.dlghandle)
{
NMHDR hdr;
hdr.code = PSN_APPLY;
hdr.hwndFrom = (HWND)this;
hdr.idFrom = 0;
if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr))
{
if (PSNRET_INVALID_NOCHANGEPAGE==GetWindowLong(item.dlghandle, DWL_MSGRESULT))
res=false;
}
}
}
}
return res;
}
bool NxS_TabPages::Clear(void)
{
int i;
while ((i = GetCount()) > 0)
{
if (!DelPage(i-1)) return false;
}
m_curwnd=NULL; //There's no longer an active dialog now...
return true;
}
bool NxS_TabPages::HandleNotifications(WPARAM wParam, LPARAM lParam)
{
int idTabCtl = (int) LOWORD(wParam);
LPNMHDR lpnmhdr = (LPNMHDR) lParam;
if (lpnmhdr->hwndFrom == m_hwTab)
{
if (lpnmhdr->code == TCN_SELCHANGING)
{
NMHDR hdr;
hdr.code = PSN_KILLACTIVE;
hdr.hwndFrom = (HWND)this;
hdr.idFrom = 0;
if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr))
{
if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT))
return true;
}
}
if (lpnmhdr->code == TCN_SELCHANGE)
{
return SelectPage(GetSelPage());
}
}
if (lpnmhdr->code == TTN_NEEDTEXT)
{
LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT) lParam;
TABITEM item;
//Make sure it's our tab control's tooltip calling in...
if (lpnmhdr->hwndFrom != TabCtrl_GetToolTips(m_hwTab)) return false;
TabCtrl_GetItem(m_hwTab, lpttt->hdr.idFrom, &item);
lpttt->hinst = IS_INTRESOURCE(item.tip)?m_hinst:NULL;
lpttt->lpszText = item.tip;
}
return false;
}
int NxS_TabPages::AddPage(char* lpszTitle, char* lpszDlgRes, DLGPROC lpfnDlgProc, char* lpszTip)
{
TABITEM i;
if (!lpszDlgRes) return 0;
if (IS_INTRESOURCE(lpszDlgRes))
i.dialog = lpszDlgRes;
else
i.SetDlgRes(lpszDlgRes);
if (IS_INTRESOURCE(lpszTip))
i.tip = lpszTip;
else
i.SetTip(lpszTip);
if (!lpszTitle)
{
int len;
HWND hwTemp;
hwTemp = CreateDialog(m_hinst,(LPCTSTR)lpszDlgRes,
GetDesktopWindow(), lpfnDlgProc);
len = GetWindowTextLength(hwTemp)+1;
i.title = new char[len];
GetWindowText(hwTemp, i.title, len);
DestroyWindow(hwTemp);
}
else
i.SetTitle(lpszTitle);
i.dlgproc = lpfnDlgProc;
i.dlghandle = NULL; //Dialog not created yet...
i.itemhdr.mask = TCIF_TEXT|TCIF_PARAM;
i.itemhdr.pszText = i.title;
return TabCtrl_InsertItem(m_hwTab, GetCount(), &i);
}
bool NxS_TabPages::SelectPage(int index)
{
HWND hwndDlg;
TABITEM item;
hwndDlg = GetParent(m_hwTab);
if (index >= 0)
{
if (m_curwnd)
{
NMHDR hdr;
hdr.code = PSN_KILLACTIVE;
hdr.hwndFrom = (HWND)this;
hdr.idFrom = 0;
if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr))
{
if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT))
return false;
}
ShowWindow(m_curwnd, SW_HIDE);
}
if (!TabCtrl_GetItem(m_hwTab, index, &item)) return false;
if (NULL==item.dlghandle)
{
item.SetDlgHandle(
CreateDialogParam(m_hinst, item.dialog,
hwndDlg, item.dlgproc, LPARAM(&item))
);
SetWindowLong(item.dlghandle, GWL_STYLE, WS_CHILD);
SetWindowLong(item.dlghandle, GWL_EXSTYLE, WS_EX_CONTROLPARENT);
SetParent(item.dlghandle, hwndDlg);
EnableThemeDlgTexture(item.dlghandle,
m_UseDlgTexture?ETDT_ENABLETAB:ETDT_DISABLE);
//Update item.dlghandle (application data item)
TabCtrl_SetItem(m_hwTab, index, &item);
}
{
NMHDR hdr;
hdr.code = PSN_SETACTIVE;
hdr.hwndFrom = (HWND)this;
hdr.idFrom = 0;
if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr))
{
if (0==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) return false;
}
}
if (m_curwnd=item.dlghandle)
{
RECT r;
GetWindowRect(m_hwTab,&r);
TabCtrl_AdjustRect(m_hwTab, FALSE, &r);
MapWindowPoints(HWND_DESKTOP, hwndDlg, LPPOINT(&r), 2);
//Make right & bottom be the width & height
r.right -= r.left;
r.bottom -= r.top;
SetWindowPos(item.dlghandle, 0, r.left, r.top, r.right, r.bottom,
SWP_NOACTIVATE|SWP_NOZORDER);
ShowWindow(item.dlghandle,SW_SHOWNA);
}
TabCtrl_SetCurSel(m_hwTab, index);
}
return true;
}
void NxS_TabPages::AdjustPageSize(void)
{
RECT r;
GetWindowRect(m_hwTab,&r);
TabCtrl_AdjustRect(m_hwTab, FALSE, &r);
MapWindowPoints(HWND_DESKTOP, GetParent(m_hwTab), LPPOINT(&r), 2);
//Make right & bottom be the width & height
r.right -= r.left;
r.bottom -= r.top;
SetWindowPos(m_curwnd, 0, r.left, r.top, r.right, r.bottom,
SWP_NOACTIVATE|SWP_NOZORDER);
}
bool NxS_TabPages::SetUseThemedDlgTexture(bool use)
{
bool prev=m_UseDlgTexture;
// If there are already some pages added,
// change the state for these pages' dialogs.
if (int count=GetCount())
{
for (int i=0;i<count;i++)
{
if (HWND hwndDlg=Pages(i).dlghandle)
EnableThemeDlgTexture(hwndDlg, use?ETDT_ENABLETAB:ETDT_DISABLE);
}
}
return prev;
}
// A wrapper for the "EnableThemeDialogTexture" function located in
// UXTHEME.DLL. When you call this with the handle of a dialog, the
// dialog's background get a texture that matches the current theme.
// This only works on a Windows XP machine.
HRESULT NxS_TabPages::EnableThemeDlgTexture(HWND hwnd, DWORD flags)
{
typedef HRESULT (WINAPI * ENABLETHEMEDIALOGTEXTURE)(HWND, DWORD);
ENABLETHEMEDIALOGTEXTURE pfnETDT;
HINSTANCE hDll;
HRESULT res=-1;
if (NULL != (hDll = LoadLibrary(TEXT("uxtheme.dll"))))
{
if (NULL != (pfnETDT = (ENABLETHEMEDIALOGTEXTURE)GetProcAddress(hDll, "EnableThemeDialogTexture")))
{
res = pfnETDT(hwnd, ETDT_ENABLETAB);
}
FreeLibrary(hDll);
}
return res;
}
//#EOF | 23.048338 | 102 | 0.661555 | saivert |
3a5770ed7e9e6ae6bd585b7832f2b8c092249fa0 | 2,525 | hpp | C++ | src/lib/optimizer/strategy/abstract_rule.hpp | mrcl-tst/hyrise | eec50b39de9f530b0a1732ceb5822b7222f3fe17 | [
"MIT"
] | 583 | 2015-01-10T00:55:32.000Z | 2022-03-25T12:24:30.000Z | src/lib/optimizer/strategy/abstract_rule.hpp | mrcl-tst/hyrise | eec50b39de9f530b0a1732ceb5822b7222f3fe17 | [
"MIT"
] | 1,573 | 2015-01-07T15:47:22.000Z | 2022-03-31T11:48:03.000Z | src/lib/optimizer/strategy/abstract_rule.hpp | mrcl-tst/hyrise | eec50b39de9f530b0a1732ceb5822b7222f3fe17 | [
"MIT"
] | 145 | 2015-03-09T16:26:07.000Z | 2022-02-15T12:53:23.000Z | #pragma once
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
namespace opossum {
class AbstractCardinalityEstimator;
class AbstractCostEstimator;
class AbstractLQPNode;
class LogicalPlanRootNode;
class LQPSubqueryExpression;
class AbstractRule {
public:
virtual ~AbstractRule() = default;
/**
* This function applies the concrete Optimizer Rule to an LQP.
* The default implementation
* (1) optimizes the root LQP
* (2) optimizes all (nested) subquery LQPs of the optimized root LQP, one-by-one.
*
* IMPORTANT NOTES ON OPTIMIZING SUBQUERY LQPS:
*
* Multiple Expressions in different nodes might reference the same LQP. Most commonly this will be the case
* for a ProjectionNode computing a subquery and a subsequent PredicateNode filtering based on it.
* We do not WANT to optimize the LQP twice (optimization takes time after all) and we CANNOT optimize it
* twice, since, e.g., a non-deterministic rule, could produce two different LQPs while optimizing and then the
* SubqueryExpression in the PredicateNode couldn't be resolved to a column anymore. There are more subtle
* ways LQPs might break in this scenario, and frankly, this is one of the weak links in the expression system...
*
* ...long story short:
* !!!
* EACH UNIQUE SUB-LQP IS ONLY OPTIMIZED ONCE, EVEN IF IT OCCURS IN DIFFERENT NODES/EXPRESSIONS.
* !!!
*
* Rules can define their own strategy of optimizing subquery LQPs by overriding this function. See, for example, the
* StoredTableColumnAlignmentRule.
*/
virtual void apply_to_plan(const std::shared_ptr<LogicalPlanRootNode>& lqp_root) const;
virtual std::string name() const = 0;
std::shared_ptr<AbstractCostEstimator> cost_estimator;
protected:
/**
* This function applies the concrete rule to the given plan, but not to its subquery plans.
*
* DO NOT CALL THIS FUNCTION RECURSIVELY!
* The reason for this can be found in diamond LQPs: When using "trivial" recursion, we would go down both on the
* left and the right side of the diamond. On both sides, we would reach the bottom of the diamond. From there, we
* would look at each node twice. visit_lqp prevents this by tracking which nodes have already been visited and
* avoiding visiting a node twice.
*/
virtual void _apply_to_plan_without_subqueries(const std::shared_ptr<AbstractLQPNode>& lqp_root) const = 0;
};
} // namespace opossum
| 40.079365 | 120 | 0.726733 | mrcl-tst |
3a5ac902c963d1d7d4d5174d9dc0c7e5ea6c8491 | 122 | hxx | C++ | src/Providers/UNIXProviders/SwapSpaceCheck/UNIX_SwapSpaceCheck_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/SwapSpaceCheck/UNIX_SwapSpaceCheck_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/SwapSpaceCheck/UNIX_SwapSpaceCheck_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_AIX
#ifndef __UNIX_SWAPSPACECHECK_PRIVATE_H
#define __UNIX_SWAPSPACECHECK_PRIVATE_H
#endif
#endif
| 10.166667 | 39 | 0.844262 | brunolauze |
3a6076681f32c7e0ff074420433601df4c840244 | 1,215 | cpp | C++ | src/core/Processor.cpp | ASxa86/azule | 9bf89dfc5a80f296b02edd3ac608d9a90e4ea26b | [
"MIT"
] | 1 | 2018-10-19T18:00:19.000Z | 2018-10-19T18:00:19.000Z | src/core/Processor.cpp | ASxa86/azule | 9bf89dfc5a80f296b02edd3ac608d9a90e4ea26b | [
"MIT"
] | 7 | 2019-06-13T00:48:55.000Z | 2020-05-05T00:18:42.000Z | src/core/Processor.cpp | ASxa86/AGE | 9bf89dfc5a80f296b02edd3ac608d9a90e4ea26b | [
"MIT"
] | null | null | null | #include <azule/core/Processor.h>
#include <azule/utilities/PimplImpl.h>
using namespace azule;
class Processor::Impl
{
public:
std::vector<std::function<void(std::chrono::microseconds)>> fixedFunctions;
std::vector<std::function<void(std::chrono::microseconds)>> variableFunctions;
std::vector<std::function<void(std::chrono::microseconds)>> renderFunctions;
};
Processor::Processor()
{
}
Processor::~Processor()
{
}
void Processor::fixed(std::chrono::microseconds x)
{
for(const auto& f : this->pimpl->fixedFunctions)
{
f(x);
}
}
void Processor::variable(std::chrono::microseconds x)
{
for(const auto& f : this->pimpl->variableFunctions)
{
f(x);
}
}
void Processor::render(std::chrono::microseconds x)
{
for(const auto& f : this->pimpl->renderFunctions)
{
f(x);
}
}
void Processor::addFixedFunction(const std::function<void(std::chrono::microseconds)>& x)
{
this->pimpl->fixedFunctions.push_back(x);
}
void Processor::addVariableFunction(const std::function<void(std::chrono::microseconds)>& x)
{
this->pimpl->variableFunctions.push_back(x);
}
void Processor::addRenderFunction(const std::function<void(std::chrono::microseconds)>& x)
{
this->pimpl->renderFunctions.push_back(x);
}
| 20.25 | 92 | 0.723457 | ASxa86 |
3a611f0e25da9757510cd0d85febd4c131a8df8c | 3,793 | cc | C++ | src/baldr/compression_utils.cc | mixvit/valhalla | 65d56caf85103f267452e7b79e49ec66a9bf480e | [
"MIT"
] | 1 | 2020-01-12T21:14:45.000Z | 2020-01-12T21:14:45.000Z | src/baldr/compression_utils.cc | Bolaxax/valhalla | f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb | [
"MIT"
] | 3 | 2020-08-24T18:48:12.000Z | 2021-01-05T21:18:44.000Z | src/baldr/compression_utils.cc | Bolaxax/valhalla | f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb | [
"MIT"
] | 1 | 2021-01-24T16:46:01.000Z | 2021-01-24T16:46:01.000Z | #include "baldr/compression_utils.h"
namespace valhalla {
namespace baldr {
/* Deflates data with gzip or zlib wrapper
* @param src_func function which modifies the stream to read more input
* @param dst_func function which modifies the stream to write more output
* @param level what compression level to use
* @param gzip whether or not to write a gzip header instead of a zlib one
* @return returns true if the stream was successfully inflated, false otherwise
*/
bool deflate(const std::function<int(z_stream&)>& src_func,
const std::function<void(z_stream&)>& dst_func,
int level,
bool gzip) {
// initialize the stream
// add 16 to window bits for gzip header instead of zlib header, 9 is max speed
z_stream stream{};
if (deflateInit2(&stream, level, Z_DEFLATED, gzip ? 15 + 16 : 15, 9, Z_DEFAULT_STRATEGY) != Z_OK)
return false;
int flush = Z_NO_FLUSH;
int code = Z_OK;
do {
// if we need more src material
try {
if (stream.avail_in == 0)
flush = src_func(stream);
} catch (...) {
deflateEnd(&stream);
return false;
}
do {
// if we need more space in the dst
try {
if (stream.avail_out == 0)
dst_func(stream);
} catch (...) {
deflateEnd(&stream);
return false;
}
// only one fatal error to worry about
code = deflate(&stream, flush);
if (code == Z_STREAM_ERROR) {
deflateEnd(&stream);
return false;
}
// only stop when we've got nothing more to put in the dst buffer
} while (stream.avail_out == 0);
// only stop when we signaled that we have no more input
} while (flush != Z_FINISH);
// hand back the final buffer
dst_func(stream);
// if we got here we expected to finish but weren't thats not good
deflateEnd(&stream);
return true;
}
/* Inflates gzip or zlib wrapped deflated data
* @param src_func function which modifies the stream to read more input
* @param dst_func function which modifies the stream to write more output
* @return returns true if the stream was successfully inflated, false otherwise
*/
bool inflate(const std::function<void(z_stream&)>& src_func,
const std::function<int(z_stream&)>& dst_func) {
// initialize the stream
// MAX_WBITS is the max size of the window and should be 15, this will work with headerless
// defalted streams to work with gzip add 16, to work with both gzip and libz add 32
z_stream stream{};
if (inflateInit2(&stream, MAX_WBITS + 32) != Z_OK)
return false;
int flush = Z_NO_FLUSH;
int code = Z_OK;
do {
// if we need more src material
try {
if (stream.avail_in == 0)
src_func(stream);
if (stream.avail_in == 0)
throw;
} catch (...) {
inflateEnd(&stream);
return false;
}
do {
// if we need more space in the dst
try {
if (stream.avail_out == 0)
flush = dst_func(stream);
} catch (...) {
inflateEnd(&stream);
return false;
}
// several fatal errors to worry about
code = inflate(&stream, flush);
switch (code) {
case Z_STREAM_ERROR:
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&stream);
return false;
}
// only stop when we've got nothing more to put in the dst buffer
} while (stream.avail_out == 0);
// only stop when we reached the end of the stream
} while (code != Z_STREAM_END);
// hand back the final buffer
dst_func(stream);
// if we got here we expected to finish but weren't thats not good
inflateEnd(&stream);
return true;
}
} // namespace baldr
} // namespace valhalla | 30.344 | 99 | 0.627472 | mixvit |
3a61736a725e8c08f3f43de560bde183998f7e7d | 9,905 | cpp | C++ | src/utils2d/axisalignedboundingbox2d.cpp | AlessandroParrotta/parrlib | d1679ee8a7cff7d14b2d93e898ed58fecff13159 | [
"MIT"
] | 2 | 2020-05-08T20:27:14.000Z | 2021-01-21T10:28:19.000Z | src/utils2d/axisalignedboundingbox2d.cpp | AlessandroParrotta/parrlib | d1679ee8a7cff7d14b2d93e898ed58fecff13159 | [
"MIT"
] | null | null | null | src/utils2d/axisalignedboundingbox2d.cpp | AlessandroParrotta/parrlib | d1679ee8a7cff7d14b2d93e898ed58fecff13159 | [
"MIT"
] | 1 | 2020-05-08T20:27:16.000Z | 2020-05-08T20:27:16.000Z | #include <parrlib/utils2d/AxisAlignedBoundingBox2D.h>
#include <iostream>
#include <parrlib/Matrix3f.h>
#include <parrlib/otherutil.h>
#include <parrlib/stringutils.h>
AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(){}
//AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(float v) { vmax = v; vmin = v; }
AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 v) : vmin(v), vmax(v) {}
AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 min, vec2 max) : vmin(min), vmax(max) { align(); }
AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 min, vec2 max, bool doalign) : vmin(min), vmax(max), doalign(doalign) { align(); }
bool AxisAlignedBoundingBox2D::intersects(AxisAlignedBoundingBox2D const& bb) const {
return vmin.x < bb.maxx() &&
vmax.x > bb.minx() &&
vmin.y < bb.maxy() &&
vmax.y > bb.miny();
}
void AxisAlignedBoundingBox2D::rescale(vec2 const& v) {
if (v.x < vmin.x) vmin.x = v.x;
else if (v.x > vmax.x) vmax.x = v.x;
if (v.y < vmin.y) vmin.y = v.y;
else if (v.y > vmax.y) vmax.y = v.y;
}
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::rescaled(vec2 const& v) const { aabb2 bb = *this; bb.rescale(v); return bb; }
void AxisAlignedBoundingBox2D::narrow(AxisAlignedBoundingBox2D const& bb) {
if (vmin.x < bb.fmin().x) vmin.x = bb.fmin().x;
if (vmin.y < bb.fmin().y) vmin.y = bb.fmin().y;
if (vmax.x > bb.fmax().x) vmax.x = bb.fmax().x;
if (vmax.y > bb.fmax().y) vmax.y = bb.fmax().y;
}
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::narrowed(AxisAlignedBoundingBox2D const& bb) const { aabb2 tbb = *this; tbb.narrow(bb); return tbb; }
void AxisAlignedBoundingBox2D::fit(AxisAlignedBoundingBox2D const& bb) {
*this = fitted(bb);
}
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fitted(AxisAlignedBoundingBox2D const& bb) {
vec2 p = bb.size() / size();
float scale = outl::minfabs(p.x, p.y);
return (centered() * scale + bb.center());
}
bool AxisAlignedBoundingBox2D::inside(AxisAlignedBoundingBox2D const& bb) const {
return vmin.x >= bb.minx() && vmin.y >= bb.miny() &&
vmax.x <= bb.maxx() && vmax.y <= bb.maxy();
}
bool AxisAlignedBoundingBox2D::pointInside(vec2 const& v) const {
return v.x >= vmin.x && v.x <= vmax.x &&
v.y >= vmin.y && v.y <= vmax.y;
}
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+(vec2 const& v) const { return aabb2(vmin + v, vmax + v); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-(vec2 const& v) const { return aabb2(vmin - v, vmax - v); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*(vec2 const& v) const { return aabb2(vmin * v, vmax * v); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/(vec2 const& v) const { return aabb2(vmin / v, vmax / v); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin + bb.fmin(), vmax + bb.fmax()); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin - bb.fmin(), vmax - bb.fmax()); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin * bb.fmin(), vmax * bb.fmax()); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin / bb.fmin(), vmax / bb.fmax()); }
AxisAlignedBoundingBox2D operator+ (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v + bb.fmin(), v + bb.fmax() }; }
AxisAlignedBoundingBox2D operator- (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v - bb.fmin(), v - bb.fmax() }; }
AxisAlignedBoundingBox2D operator* (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v * bb.fmin(), v * bb.fmax() }; }
AxisAlignedBoundingBox2D operator/ (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v / bb.fmin(), v / bb.fmax() }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+=(vec2 const& v) { vmin += v; vmax += v; return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-=(vec2 const& v) { vmin -= v; vmax -= v; return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*=(vec2 const& v) { vmin *= v; vmax *= v; return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/=(vec2 const& v) { vmin /= v; vmax /= v; return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+=(AxisAlignedBoundingBox2D const& bb) { vmin += bb.fmin(); vmax += bb.fmax(); return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-=(AxisAlignedBoundingBox2D const& bb) { vmin -= bb.fmin(); vmax -= bb.fmax(); return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*=(AxisAlignedBoundingBox2D const& bb) { vmin *= bb.fmin(); vmax *= bb.fmax(); return *this; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/=(AxisAlignedBoundingBox2D const& bb) { vmin /= bb.fmin(); vmax /= bb.fmax(); return *this; }
bool AxisAlignedBoundingBox2D::operator==(float f) const { return vmin == f && vmax == f; }
bool AxisAlignedBoundingBox2D::operator!=(float f) const { return vmin != f && vmax != f; }
bool AxisAlignedBoundingBox2D::operator==(AxisAlignedBoundingBox2D const& f) const { return vmin == f.fmin() && vmax == f.fmax(); }
bool AxisAlignedBoundingBox2D::operator!=(AxisAlignedBoundingBox2D const& f) const { return vmin != f.fmin() && vmax != f.fmax(); }
void AxisAlignedBoundingBox2D::align() {
if (!doalign) return;
if (vmin.x > vmax.x) std::swap(vmin.x, vmax.x);
if (vmin.y > vmax.y) std::swap(vmin.y, vmax.y);
}
void AxisAlignedBoundingBox2D::fmaxr(vec2 max) { this->vmax = max; align(); }
vec2 AxisAlignedBoundingBox2D::fmax() const { return vmax; }
void AxisAlignedBoundingBox2D::fminr(vec2 min) { this->vmin = min; align(); }
vec2 AxisAlignedBoundingBox2D::fmin() const { return vmin; }
vec2 AxisAlignedBoundingBox2D::center() const { return (vmin + vmax) / 2.f; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::centered() const { return *this - center(); }
float AxisAlignedBoundingBox2D::minx() const { return vmin.x; }
float AxisAlignedBoundingBox2D::miny() const { return vmin.y; }
float AxisAlignedBoundingBox2D::maxx() const { return vmax.x; }
float AxisAlignedBoundingBox2D::maxy() const { return vmax.y; }
void AxisAlignedBoundingBox2D::maxxr(float f) { vmax.x = f; }
void AxisAlignedBoundingBox2D::maxyr(float f) { vmax.y = f; }
void AxisAlignedBoundingBox2D::minxr(float f) { vmin.x = f; }
void AxisAlignedBoundingBox2D::minyr(float f) { vmin.y = f; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::maxx(float f) const { return aabb2{ vmin, {f, vmax.y} }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::maxy(float f) const { return aabb2{ vmin, {vmax.x, f} }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::minx(float f) const { return aabb2{ { f, vmin.y }, vmax }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::miny(float f) const { return aabb2{ { vmin.x, f }, vmax }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fmax(vec2 vmax) const { return aabb2{ vmin, vmax }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fmin(vec2 vmin) const { return aabb2{ vmin, vmax }; }
vec2 AxisAlignedBoundingBox2D::get(int i) const {
switch (i) {
case 0: return {vmin.x, vmin.y};
case 1: return {vmin.x, vmax.y};
case 2: return {vmax.x, vmax.y};
case 3: return {vmax.x, vmin.y};
}
return 0.f;
}
float AxisAlignedBoundingBox2D::getSingle(int i) const {
return i == 0 ? vmin.x : i == 1 ? vmin.y : i == 2 ? vmax.x : i == 3 ? vmax.y : 0.f;
}
vec2 AxisAlignedBoundingBox2D::operator[](int const& i) const { return get(i); }
std::array<vec2, 4> AxisAlignedBoundingBox2D::toVerts() const { return { get(0), get(1), get(2), get(3) }; }
vec2 AxisAlignedBoundingBox2D::edgeCenter(int i) const {
return ((*this)[i] + (*this)[(i+1)%4])/2.f;
}
vec2 AxisAlignedBoundingBox2D::size() const { return vmax - vmin; }
float AxisAlignedBoundingBox2D::sizex() const { return vmax.x - vmin.x; }
float AxisAlignedBoundingBox2D::sizey() const { return vmax.y - vmin.y; }
void AxisAlignedBoundingBox2D::scale(vec2 const& scale) { *this = scaled(scale); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::scaled(vec2 const& scale) const { return centered()*scale + center(); }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::movedIn(vec2 const& delta) const { return { vmin + delta, vmax - delta }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::movedOut(vec2 const& delta) const { return { vmin - delta, vmax + delta }; }
AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::forcedIn(AxisAlignedBoundingBox2D const& bb) const{
if (inside(bb)) return *this; //just return if it's already inside
if (size() > bb.size()) return bb;
aabb2 resbb = *this;
if (sizex() > bb.sizex()) resbb = resbb.scaled(vec2(bb.sizex()/sizex() , 1.f));
if (sizey() > bb.sizey()) resbb = resbb.scaled(vec2(1.f, bb.sizey()/sizey()));
//translate along x axis if necessary
bool xtrasl = false;
if (resbb.minx() < bb.minx()) { resbb += vec2x(bb.minx() - resbb.minx()); xtrasl = true; }
if (!xtrasl && resbb.maxx() > bb.maxx()) { resbb += vec2x(bb.maxx() - resbb.maxx()); xtrasl = true; }
bool ytrasl = false;
if (resbb.miny() < bb.fmin().y) { resbb += vec2y(bb.miny() - resbb.miny()); ytrasl = true; }
if (!ytrasl && resbb.maxy() > bb.maxy()) { resbb += vec2y(bb.maxy() - resbb.maxy()); ytrasl = true; }
return resbb;
}
std::string AxisAlignedBoundingBox2D::toString() const {
std::stringstream ss;
ss << "(" << vmin << ", " << vmax << ")";
return ss.str();
}
std::ostream& operator<<(std::ostream& os, AxisAlignedBoundingBox2D const& bb) { return os << bb.toString(); }
std::wostream& operator<<(std::wostream& os, AxisAlignedBoundingBox2D const& bb) { return os << stru::towstr(bb.toString()); }
AxisAlignedBoundingBox2D aabb2s(vec2 const& size) { return { -size/2.f, size/2.f }; }
| 52.407407 | 156 | 0.713074 | AlessandroParrotta |
3a61efccacd3085e4acf1b2c007aa4dd998acc73 | 1,982 | cpp | C++ | src/game.cpp | kvbc/space_shooter | 6e9e689d23c5b8570fb791ace938eab09d1b477b | [
"MIT"
] | 1 | 2022-03-14T09:35:11.000Z | 2022-03-14T09:35:11.000Z | src/game.cpp | kvbc/space_shooter | 6e9e689d23c5b8570fb791ace938eab09d1b477b | [
"MIT"
] | null | null | null | src/game.cpp | kvbc/space_shooter | 6e9e689d23c5b8570fb791ace938eab09d1b477b | [
"MIT"
] | null | null | null | #include <windows.h>
#include <thread>
#include "game.h"
#include "particles.h"
#include "math.h"
#define pressed(c) GetAsyncKeyState(c)
void Game::update() {
Option BSIZE_X = value(m_op[OP_BSIZE_X]);
Option BSIZE_Y = value(m_op[OP_BSIZE_Y]);
Option PSPEED = value(m_op[OP_PSPEED]);
if(m_plr.health() > 0) {
m_plr.display_healthbar(m_board, {1, BSIZE_Y - 1}, PLAYER_HBARS);
m_plr.display_health(m_board, {1 + PLAYER_HBARS, BSIZE_Y - 1});
if(m_enemies.size() > 0)
for(int i = 0; i < m_enemies.size(); i++) {
Entity &enemy = m_enemies[i];
if(enemy.health() > 0) {
int _rand = rand();
std::thread([&]() {
enemy.display(m_board);
if(m_frame % 20 == 0)
enemy.move({1, 0});
else if(m_frame % 10 == 0)
enemy.move({-1, 0});
if(m_frame % (_rand % ENEMY_FIRERATE + 1) == 0)
enemy.fire(m_board, DBULLET);
}).detach();
}
else
m_enemies.m_data.erase(m_enemies.begin() + i);
}
else {
m_board.clear(true);
Sprite YouWon = {{{ SPRITE_YOUWON }}, m_op};
YouWon.write(m_board, { (BSIZE_X - YOUWON_SIZE_X) / 2, (BSIZE_Y - YOUWON_SIZE_Y) / 2});
m_board.display();
throw 0;
}
}
else {
m_board.clear(true);
Sprite GameOver = {{{ SPRITE_GAMEOVER }}, m_op};
GameOver.write(m_board, { (BSIZE_X - GAMEOVER_SIZE_X) / 2, (BSIZE_Y - GAMEOVER_SIZE_Y) / 2});
m_board.display();
throw 0;
}
m_plr.display(m_board);
for(Particle *particle : m_particles)
particle->update(this);
m_board.display(this);
if (
pressed(VK_LEFT) ||
pressed('a') ||
pressed('A')
)
m_plr.move({-PSPEED, 0});
else if (
pressed(VK_RIGHT) ||
pressed('d') ||
pressed('D')
)
m_plr.move({PSPEED, 0});
if (
(pressed(VK_UP) ||
pressed('w') ||
pressed('W') ||
pressed(' ')) &&
m_frame % PLAYER_FIRERATE == 0
)
m_plr.fire(m_board, UBULLET);
m_board.clear();
m_frame++;
} | 22.781609 | 96 | 0.573663 | kvbc |
3a68688cd7a6ef9505f3322babca5e768d9c8691 | 3,377 | cpp | C++ | src/PBN.cpp | lanctot/dds | 06c1b31795ca2db2f268ea81a1029b03c8c37872 | [
"Apache-2.0"
] | 93 | 2015-01-23T01:56:02.000Z | 2022-02-21T22:56:41.000Z | src/PBN.cpp | lanctot/dds | 06c1b31795ca2db2f268ea81a1029b03c8c37872 | [
"Apache-2.0"
] | 57 | 2015-01-15T15:01:01.000Z | 2021-06-25T08:36:19.000Z | src/PBN.cpp | online-bridge-hackathon/libdds | 19db9cf99bee85074884f628cdd5a5faf79bc766 | [
"Apache-2.0"
] | 76 | 2015-04-11T10:22:47.000Z | 2022-03-29T09:51:03.000Z | /*
DDS, a bridge double dummy solver.
Copyright (C) 2006-2014 by Bo Haglund /
2014-2018 by Bo Haglund & Soren Hein.
See LICENSE and README.
*/
#include "dds.h"
#include "PBN.h"
int IsCard(const char cardChar);
int ConvertFromPBN(
char const * dealBuff,
unsigned int remainCards[DDS_HANDS][DDS_SUITS])
{
for (int h = 0; h < DDS_HANDS; h++)
for (int s = 0; s < DDS_SUITS; s++)
remainCards[h][s] = 0;
int bp = 0;
while (((dealBuff[bp] != 'W') && (dealBuff[bp] != 'N') &&
(dealBuff[bp] != 'E') && (dealBuff[bp] != 'S') &&
(dealBuff[bp] != 'w') && (dealBuff[bp] != 'n') &&
(dealBuff[bp] != 'e') && (dealBuff[bp] != 's')) && (bp < 3))
bp++;
if (bp >= 3)
return 0;
int first;
if ((dealBuff[bp] == 'N') || (dealBuff[bp] == 'n'))
first = 0;
else if ((dealBuff[bp] == 'E') || (dealBuff[bp] == 'e'))
first = 1;
else if ((dealBuff[bp] == 'S') || (dealBuff[bp] == 's'))
first = 2;
else
first = 3;
bp++;
bp++;
int handRelFirst = 0;
int suitInHand = 0;
int card, hand;
while ((bp < 80) && (dealBuff[bp] != '\0'))
{
card = IsCard(dealBuff[bp]);
if (card)
{
switch (first)
{
case 0:
hand = handRelFirst;
break;
case 1:
if (handRelFirst == 0)
hand = 1;
else if (handRelFirst == 3)
hand = 0;
else
hand = handRelFirst + 1;
break;
case 2:
if (handRelFirst == 0)
hand = 2;
else if (handRelFirst == 1)
hand = 3;
else
hand = handRelFirst - 2;
break;
default:
if (handRelFirst == 0)
hand = 3;
else
hand = handRelFirst - 1;
}
remainCards[hand][suitInHand] |=
static_cast<unsigned>((bitMapRank[card] << 2));
}
else if (dealBuff[bp] == '.')
suitInHand++;
else if (dealBuff[bp] == ' ')
{
handRelFirst++;
suitInHand = 0;
}
bp++;
}
return RETURN_NO_FAULT;
}
int IsCard(const char cardChar)
{
switch (cardChar)
{
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'T':
case 't':
return 10;
case 'J':
case 'j':
return 11;
case 'Q':
case 'q':
return 12;
case 'K':
case 'k':
return 13;
case 'A':
case 'a':
return 14;
default:
return 0;
}
}
int ConvertPlayFromPBN(
const playTracePBN& playPBN,
playTraceBin& playBin)
{
const int n = playPBN.number;
if (n < 0 || n > 52)
return RETURN_PLAY_FAULT;
playBin.number = n;
for (int i = 0; i < 2 * n; i += 2)
{
char suit = playPBN.cards[i];
int s;
if (suit == 's' || suit == 'S')
s = 0;
else if (suit == 'h' || suit == 'H')
s = 1;
else if (suit == 'd' || suit == 'D')
s = 2;
else if (suit == 'c' || suit == 'C')
s = 3;
else
return RETURN_PLAY_FAULT;
playBin.suit[i >> 1] = s;
int rank = IsCard(playPBN.cards[i+1]);
if (rank == 0)
return RETURN_PLAY_FAULT;
playBin.rank[i >> 1] = rank;
}
return RETURN_NO_FAULT;
}
| 18.761111 | 70 | 0.472017 | lanctot |
3a6c3309915e86f8f0e6a5f15317d7c7aea24d23 | 3,336 | cpp | C++ | src/logger_asynchronous.cpp | babidev/logging | f53db4cbdd5ed831dad0b673752d4bef7629eb98 | [
"BSD-3-Clause"
] | null | null | null | src/logger_asynchronous.cpp | babidev/logging | f53db4cbdd5ed831dad0b673752d4bef7629eb98 | [
"BSD-3-Clause"
] | null | null | null | src/logger_asynchronous.cpp | babidev/logging | f53db4cbdd5ed831dad0b673752d4bef7629eb98 | [
"BSD-3-Clause"
] | null | null | null | #include "logging/logger_asynchronous.h"
#include <chrono>
#include "logging/manager.h"
namespace logging {
logger_asynchronous::logger_asynchronous()
: state_{static_cast<unsigned>(state::off)}
{
start();
}
logger_asynchronous::~logger_asynchronous()
{
stop();
}
void logger_asynchronous::start()
{
unsigned state = state_.load(std::memory_order_acquire);
if (state == static_cast<unsigned>(state::working) ||
state == static_cast<unsigned>(state::starting)) {
return;
}
while (state == static_cast<unsigned>(state::stopping)) {
std::this_thread::sleep_for(std::chrono::microseconds(100));
state = state_.load(std::memory_order_acquire);
}
if (state == static_cast<unsigned>(state::off)) {
if (state_.compare_exchange_strong(
state, static_cast<unsigned>(state::starting),
std::memory_order_release, std::memory_order_relaxed)) {
worker_ = std::move(std::thread{[this](){ work(); }});
while(state_.load(std::memory_order_acquire) !=
static_cast<unsigned>(state::working)) {
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
}
}
}
void logger_asynchronous::stop()
{
unsigned state = state_.load(std::memory_order_acquire);
if (state == static_cast<unsigned>(state::off) ||
state == static_cast<unsigned>(state::stopping)) {
return;
}
while (state == static_cast<unsigned>(state::starting)) {
std::this_thread::sleep_for(std::chrono::microseconds(100));
state = state_.load(std::memory_order_acquire);
}
if (state == static_cast<unsigned>(state::working)) {
if (state_.compare_exchange_strong(
state, static_cast<unsigned>(state::stopping),
std::memory_order_release, std::memory_order_relaxed)) {
write_condition_.notify_one();
while(state_.load(std::memory_order_acquire) !=
static_cast<unsigned>(state::off)) {
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
if (worker_.joinable()) {
worker_.join();
}
}
}
}
void logger_asynchronous::dispatch(const logging::record& record)
{
auto state = state_.load(std::memory_order_acquire);
if (state == static_cast<unsigned>(state::off) ||
state == static_cast<unsigned>(state::stopping)) {
return;
}
{
std::unique_lock<std::mutex> lock(mutex_);
records_.emplace(record);
}
write_condition_.notify_one();
}
void logger_asynchronous::work()
{
state_.store(static_cast<unsigned>(state::working), std::memory_order_release);
bool is_records_queue_empty{true};
while(state_.load(std::memory_order_acquire) !=
static_cast<unsigned>(state::stopping) ||
is_records_queue_empty == false) {
std::queue<logging::record> buffer;
std::unique_lock<std::mutex> lock(mutex_);
if (records_.empty()) {
write_condition_.wait(lock);
}
std::swap(records_, buffer);
lock.unlock();
while(!buffer.empty()) {
auto item = buffer.front();
if (auto sink{manager::instance().find_sink(item.sink_name)}) {
if (sink->check_level(item.level)) {
sink->write(item);
}
}
buffer.pop();
}
lock.lock();
is_records_queue_empty = records_.empty();
}
state_.store(static_cast<unsigned>(state::off), std::memory_order_release);
}
}
| 29.263158 | 81 | 0.66247 | babidev |
3a6ff74e04828bc6bcb690735b7aec220f1e3a1b | 29,800 | cpp | C++ | SOURCES/graphics/bspbuild/mgif.cpp | IsraelyFlightSimulator/Negev-Storm | 86de63e195577339f6e4a94198bedd31833a8be8 | [
"Unlicense"
] | 1 | 2021-02-19T06:06:31.000Z | 2021-02-19T06:06:31.000Z | src/graphics/bspbuild/mgif.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | null | null | null | src/graphics/bspbuild/mgif.cpp | markbb1957/FFalconSource | 07b12e2c41a93fa3a95b912a2433a8056de5bc4d | [
"BSD-2-Clause"
] | 2 | 2019-08-20T13:35:13.000Z | 2021-04-24T07:32:04.000Z | #include <mgapiall.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <stddef.h>
#include <math.h>
static int lasterr = 0;
static void Normalize (double *xp, double *yp, double *zp)
{
// normalize
double x = *xp, y = *yp, z = *zp;
double mag = sqrt(x*x + y*y + z*z);
x /= mag;
y /= mag;
z /= mag;
*xp = x;
*yp = y;
*zp = z;
}
static void freenode (mgrec *db)
{
if (db->next) freenode (db->next);
if (db->child) freenode (db->child);
free (db);
}
inline void exch_char (char *a, char *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
inline short swap_short (short num)
{
short data = num;
char *cnum = (char *) &data;
exch_char (&cnum[1], &cnum[0]);
return data;
}
inline int swap_int (int num)
{
int data = num;
char *cnum = (char *) &data;
exch_char (&cnum[3], &cnum[0]);
exch_char (&cnum[2], &cnum[1]);
return data;
}
inline float swap_float (float num)
{
float data = num;
char *cnum = (char *) &data;
exch_char (&cnum[3], &cnum[0]);
exch_char (&cnum[2], &cnum[1]);
return data;
}
inline double swap_double (double num)
{
double data = num;
char *cnum = (char *) &data;
exch_char (&cnum[7], &cnum[0]);
exch_char (&cnum[6], &cnum[1]);
exch_char (&cnum[5], &cnum[2]);
exch_char (&cnum[4], &cnum[3]);
return data;
}
struct {
FltTypes type;
const char *name;
} FltNames[] = {
#define MKENT(x) { x, #x }
MKENT(fltHeader),
MKENT(fltGroup),
MKENT(fltIcoord),
MKENT(fltVU),
MKENT(fltVV),
MKENT(fltVertex),
MKENT(fltPolyMaterial),
MKENT(fltDiffuse),
MKENT(fltMatAlpha),
MKENT(fltPolygon),
MKENT(fltBsp),
MKENT(fltSwitch),
MKENT(fltDof),
MKENT(fltLightPoint),
MKENT(fltPolyTransparency),
MKENT(fltGcLightMode),
MKENT(fltPolyTexture),
MKENT(fltMatrix),
MKENT(fltVColor),
MKENT(fltLpDirectionalityType),
MKENT(fltLpBackColor),
MKENT(fltPolyMgTemplate),
MKENT(fltPolyLineStyle),
MKENT(fltPolyDrawType),
MKENT(fltDPlaneA),
MKENT(fltDPlaneB),
MKENT(fltDPlaneC),
MKENT(fltDPlaneD),
MKENT(fltDofPutAnchorX),
MKENT(fltDofPutAnchorY),
MKENT(fltDofPutAnchorZ),
MKENT(fltDofPutAlignX),
MKENT(fltDofPutAlignY),
MKENT(fltDofPutAlignZ),
MKENT(fltDofPutTrackX),
MKENT(fltDofPutTrackY),
MKENT(fltDofPutTrackZ),
MKENT(fltDofMaxX),
MKENT(fltDofMinX),
MKENT(fltXref),
MKENT(fltLodSwitchIn),
MKENT(fltXrefFilename),
MKENT(fltLod)
};
static const int FltSize = sizeof(FltNames) / sizeof(FltNames[0]);
static int mgIgnoreRec (OpCode type)
{
#if 1
return 0;
#else
switch (type) {
case OPCODE_POLYGON:
case OPCODE_BINARY_SEPARATING_PLANE:
case OPCODE_SWITCH_BEAD:
case OPCODE_DEGREE_OF_FREEDOM:
case OPCODE_LIGHT_SOURCE_RECORD:
case OPCODE_LEVEL_OF_DETAIL:
case OPCODE_VERTEX_LIST:
case OPCODE_COLOR_TABLE:
case OPCODE_HEADER:
case OPCODE_TEXT_COMMENT:
case OPCODE_TEXTURE_REFERENCE_RECORD:
case OPCODE_VERTEX_PALETTE:
case OPCODE_VERTEX_WITH_NORMAL:
case OPCODE_VERTEX_WITH_NORMAL_AND_UV:
case OPCODE_VERTEX_WITH_UV:
case OPCODE_MATERIAL_TABLE:
case OPCODE_PUSH_LEVEL:
case OPCODE_POP_LEVEL:
case OPCODE_MATERIAL_PALETTE:
case OPCODE_VERTEX_COORDINATE:
return 0;
default:
return 1;
}
#endif
}
static int mgIsAncillary (OpCode type)
{
switch (type) {
case OPCODE_TEXT_COMMENT:
case OPCODE_LONG_IDENTIFIER:
case OPCODE_REPLICATE_CODE:
case OPCODE_ROAD_ZONE:
case OPCODE_TRANSFORMATION_MATRIX:
case OPCODE_VECTOR:
case OPCODE_BOUNDING_BOX:
case OPCODE_CAT_DATA:
case OPCODE_EXTENSION:
case OPCODE_VERTEX_COORDINATE:
case OPCODE_VERTEX_WITH_NORMAL:
case OPCODE_VERTEX_WITH_NORMAL_AND_UV:
case OPCODE_VERTEX_WITH_UV:
return 1;
default:
return 0;
}
}
static int mgIsPalette (OpCode type)
{
switch (type) {
case OPCODE_VERTEX_PALETTE:
case OPCODE_COLOR_TABLE:
case OPCODE_COLOR_NAME_PALETTE:
case OPCODE_MATERIAL_PALETTE:
case OPCODE_TEXTURE_REFERENCE_RECORD:
case OPCODE_EYEPOINT_AND_TRACKPLANE_POSITION:
case OPCODE_LINKAGE_RECORD:
case OPCODE_SOUND_PALETTE:
case OPCODE_LIGHT_SOURCE_PALETTE:
case OPCODE_LINE_STYLE_RECORD:
case OPCODE_TEXTURE_MAPPING_PALETTE:
case OPCODE_MATERIAL_TABLE:
return 1;
default:
return 0;
}
}
const char *FindFltName (FltTypes f)
{
for (int i = 0; i < FltSize; i++) {
if (FltNames[i].type == f) return FltNames[i].name;
}
return 0;
}
static int mgGetColorInd (mgrec *rec, int ind, int *rgb)
{
mgrec *pbase = rec;
while (pbase -> parent) {
pbase = pbase -> parent;
}
while (pbase && pbase -> type != OPCODE_COLOR_TABLE) {
pbase = mgGetNext (pbase);
}
if (pbase == NULL) return MG_FALSE;
if (rec->vrsn > 1500) {
if ((unsigned)ind > (pbase -> len - offsetof(struct aflt_ColorRecord, rgb))/4)
return MG_FALSE;
struct aflt_ColorRecord *cr;
cr = (struct aflt_ColorRecord *)pbase->data;
*rgb = swap_int(cr -> rgb[ind]);
return MG_TRUE;
}
else {
if ((unsigned)ind > (pbase -> len - offsetof(struct flt_ColorRecord, rgb))/4)
return MG_FALSE;
struct flt_ColorRecord *cr;
cr = (struct flt_ColorRecord *)pbase->data;
*rgb = swap_int(cr -> rgb[ind]);
return MG_TRUE;
}
}
void
mgInit (int type, void *param)
{
}
char *mgGetName (mgrec *rec)
{
mgrec *p;
for (p = rec->next; p && mgIsAncillary(p->type); p = p -> next) {
if (p->type == OPCODE_LONG_IDENTIFIER) {
char *comm = (char *)malloc (p->len - 4 + 1);
memcpy (comm, p->data+4, p->len - 4);
comm[p->len - 4] = '\0';
return comm;
}
}
char *comm = (char *)malloc (8);
memcpy (comm, rec->data+4, 8);
return comm;
}
char *
mgRec2Filename (mgrec *rec)
{
char *comm = (char *)malloc (9);
strcpy (comm, "filename");
return comm;
}
mgrec *mgGetChild (mgrec *rec)
{
if (rec -> child) return rec->child;
mgrec *p;
for (p = rec->next; p && (mgIsAncillary(p->type) || mgIsPalette(p->type)); p = p->next)
if (p->child)
return p->child;
return 0;
}
mgrec *mgGetParent (mgrec *rec)
{
return rec -> parent;
}
void mgExit ()
{
}
mgrec *mgGetNext (mgrec *rec)
{
mgrec *p;
for (p = rec->next;
p && (mgIsAncillary(p->type) || mgIsPalette(p->type));
p = p->next)
continue;
return p;
}
int mgIsCode (mgrec *rec, FltTypes type)
{
char buf[1024];
switch (type) {
case fltPolygon:
return rec->type == OPCODE_POLYGON;
case fltBsp:
return rec->type == OPCODE_BINARY_SEPARATING_PLANE;
case fltSwitch:
return rec->type == OPCODE_SWITCH_BEAD;
case fltDof:
return rec->type == OPCODE_DEGREE_OF_FREEDOM;
case fltLightPoint:
return rec->type == OPCODE_LIGHT_SOURCE_RECORD;
case fltLod:
return rec->type == OPCODE_LEVEL_OF_DETAIL;
case fltVertex:
return rec->type == OPCODE_VERTEX_LIST;
default:
sprintf (buf, "Unknown FltType %d %s\n", type, FindFltName(type));
OutputDebugString(buf);
break;
}
return MG_FALSE;
}
void mgGetLastError (char *err, int size)
{
sprintf (err, "Error number %d", lasterr);
}
void mgFree (char *data)
{
free (data);
}
char *mgGetComment (mgrec *record)
{
while (record && record -> type != OPCODE_TEXT_COMMENT) {
record = record -> next;
}
if (record) {
char *comm = (char *)malloc (record -> len - 4);
memcpy (comm, record -> data, record -> len - 4);
return comm;
}
return 0;
}
int mgGetFirstTexture (mgrec *record, int *texind, char *texname)
{
return MG_FALSE;
while (record && record -> type != OPCODE_TEXTURE_REFERENCE_RECORD) {
record = record -> next;
}
if (record) {
#if 0
if (record->vrsn > 1500) {
OutputDebugString ("Version 1500 textures not supported yet\n");
return MG_FALSE;
}
#endif
struct flt_TexturePatternRecord *tr = (struct flt_TexturePatternRecord *)record -> data;
*texind = swap_int(tr -> patternIndex);
strcpy (texname, tr -> filename);
return MG_TRUE;
}
return MG_FALSE;
}
int
mgGetNextTexture (mgrec *record, int *texind, char *texname)
{
if (record->vrsn > 1500) {
OutputDebugString ("Version 1500 textures not supported yet\n");
return MG_FALSE;
}
while (record && record -> type != OPCODE_TEXTURE_REFERENCE_RECORD) {
record = record -> next;
}
if (record == NULL) return MG_FALSE;
while (record && record -> type == OPCODE_TEXTURE_REFERENCE_RECORD) {
struct flt_TexturePatternRecord *tr = (struct flt_TexturePatternRecord *)record -> data;
int ind = swap_int(tr -> patternIndex);
if (ind > *texind) {
*texind = ind;
strcpy (texname, tr -> filename);
return MG_TRUE;
}
record = record->next;
}
return MG_FALSE;
}
static mgrec *GetVertex (mgrec *rec, int n)
{
while (rec -> parent) rec = rec->parent;
while (rec && rec -> type != OPCODE_VERTEX_PALETTE)
rec = rec->next;
if (rec == 0) return 0;
int voff = rec->len;
rec = rec->next;
for (int i = 0; rec && voff < n; i++) {
if (voff == n) return rec;
voff += rec -> len;
rec = rec->next;
}
return rec;
}
static int mgGetVertexNormal (mgrec *rec, double *i, double *j, double *k)
{
if (rec -> type != OPCODE_VERTEX_LIST) {
OutputDebugString("GetVertexNormal not a vertex list\n");
return MG_FALSE;
}
int *vtx = (int *)rec->data;
mgrec *vr = GetVertex (rec, *vtx);
if (vr == NULL) {
OutputDebugString("GetVertexNormal no vertex list\n");
return MG_FALSE;
}
switch (vr -> type) {
case OPCODE_VERTEX_WITH_NORMAL:
{
struct flt_VertexCoordinateNormal *vn = (struct flt_VertexCoordinateNormal *)vr->data;
*i = swap_float (vn->nx);
*j = swap_float (vn->ny);
*k = swap_float (vn->nz);
return MG_TRUE;
}
case OPCODE_VERTEX_WITH_NORMAL_AND_UV:
{
struct flt_VertexCoordinateTextureNormal *vn = (struct flt_VertexCoordinateTextureNormal *)vr->data;
*i = swap_float (vn->nx);
*j = swap_float (vn->ny);
*k = swap_float (vn->nz);
return MG_TRUE;
}
default:
return MG_FALSE;
}
}
int mgGetVtxNormal (mgrec *rec, float *i, float *j, float *k)
{
double i1, j1, k1;
if (mgGetVertexNormal (rec, &i1, &j1, &k1) == MG_TRUE) {
*i = (float)i1;
*j = (float)j1;
*k = (float)k1;
return MG_TRUE;
}
return MG_FALSE;
}
int mgGetVtxColorRGB (mgrec *rec, short *r, short *g, short *b)
{
if (rec -> type != OPCODE_VERTEX_LIST) {
OutputDebugString("mgGetVtxColorRGB not a vertex list\n");
}
int *vtx = (int *)rec->data;
mgrec *vr = GetVertex (rec, *vtx);
if (vr == NULL) {
char buf[1024];
sprintf (buf, "No vertex reference found for %d\n", *vtx);
OutputDebugString (buf);
return MG_FALSE;
}
struct flt_VertexCoordinate *vc = (struct flt_VertexCoordinate *)vr->data;
int pc= swap_short(vc -> vertexColor);
int colind = pc >> 7;
int colint = pc & 0x7f;
int rgb;
if (mgGetColorInd (rec, colind, &rgb) != MG_TRUE)
return MG_FALSE;
*r = (rgb & 0xff) * colint / 127;
*g = ((rgb>>8) & 0xff) * colint / 127;
*b = ((rgb>>16) & 0xff) * colint / 127;
return MG_TRUE;
}
int mgGetIcoord (mgrec *rec, FltTypes type, double *x, double *y, double *z)
{
if (type != fltIcoord) {
OutputDebugString("Not fltIcoord\n");
return MG_FALSE;
}
if (rec -> type == OPCODE_VERTEX_LIST) {
int *vtx = (int *)rec->data;
mgrec *vr = GetVertex (rec, *vtx);
if (vr == NULL) {
char buf[1024];
sprintf (buf, "No vertex reference found for %d\n", *vtx);
OutputDebugString (buf);
return MG_FALSE;
}
struct flt_VertexCoordinate *vc = (struct flt_VertexCoordinate *)vr->data;
*x = swap_double (vc -> x);
*y = swap_double (vc -> y);
*z = swap_double (vc -> z);
return MG_TRUE;
}
return MG_FALSE;
}
static int mgVtxFetch (mgrec *rec, FltTypes type, void *ptr)
{
if (rec -> type != OPCODE_VERTEX_LIST) return MG_FALSE;
int *vtx = (int *)rec->data;
mgrec *vr = GetVertex (rec, *vtx);
if (vr == NULL) {
char buf[1024];
sprintf (buf, "No vertex reference found for %d\n", *vtx);
OutputDebugString (buf);
return MG_FALSE;
}
switch (type) {
case fltVU:
{
if (vr -> type == OPCODE_VERTEX_WITH_NORMAL_AND_UV) {
struct flt_VertexCoordinateTextureNormal *vt = (struct flt_VertexCoordinateTextureNormal *) vr -> data;
*(float *)ptr = swap_float(vt -> u);
break;
}
else if (vr -> type = OPCODE_VERTEX_WITH_UV) {
struct flt_VertexCoordinateTexture *vt = (struct flt_VertexCoordinateTexture *) vr -> data;
*(float *)ptr = swap_float(vt -> u);
break;
}
else return MG_FALSE;
}
break;
case fltVV:
{
if (vr -> type == OPCODE_VERTEX_WITH_NORMAL_AND_UV) {
struct flt_VertexCoordinateTextureNormal *vt = (struct flt_VertexCoordinateTextureNormal *) vr -> data;
*(float *)ptr = swap_float(vt -> v);
break;
}
else if (vr -> type = OPCODE_VERTEX_WITH_UV) {
struct flt_VertexCoordinateTexture *vt = (struct flt_VertexCoordinateTexture *) vr -> data;
*(float *)ptr = swap_float(vt -> v);
break;
}
else return MG_FALSE;
}
break;
default:
return MG_FALSE;
}
return MG_TRUE;
}
static int mgBspFetch (mgrec *rec, FltTypes type, void *ptr)
{
if (rec -> type != OPCODE_BINARY_SEPARATING_PLANE)
return 0;
struct aflt_BinarySeparatingPlane *bsp =
(struct aflt_BinarySeparatingPlane *)rec -> data;
switch (type) {
case fltDPlaneA:
*(double *)ptr = swap_double(bsp->a);
break;
case fltDPlaneB:
*(double *)ptr = swap_double(bsp->b);
break;
case fltDPlaneC:
*(double *)ptr = swap_double(bsp->c);
break;
case fltDPlaneD:
*(double *)ptr = swap_double(bsp->d);
break;
default:
OutputDebugString ("Unknown BSP\n");
break;
}
return 1;
}
static int
mgPolyFetch (mgrec *rec, FltTypes type, void *ptr)
{
if (rec -> type != OPCODE_POLYGON)
return 0;
if (rec -> vrsn > 1500) {
struct aflt_PolygonRecord *pr =
(struct aflt_PolygonRecord *)rec->data;
switch (type) {
case fltPolyMaterial:
{
*(short *)ptr = swap_short(pr->materialCode);
break;
}
case fltPolyTransparency:
{
*(short*)ptr = swap_short (pr->transparency);
break;
}
case fltPolyMgTemplate:
{
*(char *)ptr = pr->templateTransparency;
break;
}
case fltGcLightMode:
{
*(char *)ptr = pr->lightMode;
break;
}
case fltPolyTexture:
{
*(short*)ptr = swap_short (pr->textureNo);
break;
}
case fltPolyLineStyle:
{
*(char *)ptr = pr->linestyle;
break;
}
case fltPolyDrawType:
{
*(char *)ptr = pr->howToDraw;
break;
}
default:
OutputDebugString ("Unknown poly attr\n");
break;
}
}
else {
struct flt_PolygonRecord *pr =
(struct flt_PolygonRecord *)rec->data;
switch (type) {
case fltPolyMaterial:
{
*(short *)ptr = swap_short(pr->materialCode);
break;
}
case fltPolyTransparency:
{
*(short*)ptr = swap_short (pr->transparency);
break;
}
case fltPolyMgTemplate:
{
*(char *)ptr = pr->templateTransparency;
break;
}
case fltGcLightMode:
{
*(char *)ptr = pr->lightMode;
break;
}
case fltPolyTexture:
{
*(short*)ptr = swap_short (pr->textureNo);
break;
}
case fltPolyLineStyle:
{
*(char *)ptr = pr->linestyle;
break;
}
case fltPolyDrawType:
{
*(char *)ptr = pr->howToDraw;
break;
}
default:
OutputDebugString ("Unknown poly attr\n");
break;
}
}
return 1;
}
static int
mgDofFetch (mgrec *rec, FltTypes type, void *ptr)
{
if (rec -> type != OPCODE_DEGREE_OF_FREEDOM)
return 0;
if (rec -> vrsn > 1500) {
struct aflt_DegreeOfFreedomRecord *dof =
(struct aflt_DegreeOfFreedomRecord *)rec->data;
switch (type) {
case fltDofPutAnchorX:
{
*(double *)ptr = swap_double(dof->originx);
break;
}
case fltDofPutAnchorY:
{
*(double *)ptr = swap_double(dof->originy);
break;
}
case fltDofPutAnchorZ:
{
*(double *)ptr = swap_double(dof->originz);
break;
}
case fltDofPutAlignX:
{
*(double *)ptr = swap_double(dof->pointxaxis_x);
break;
}
case fltDofPutAlignY:
{
*(double *)ptr = swap_double(dof->pointxaxis_y);
break;
}
case fltDofPutAlignZ:
{
*(double *)ptr = swap_double(dof->pointxaxis_z);
break;
}
case fltDofPutTrackX:
{
*(double *)ptr = swap_double(dof->pointxyplane_x);
break;
}
case fltDofPutTrackY:
{
*(double *)ptr = swap_double(dof->pointxyplane_y);
break;
}
case fltDofPutTrackZ:
{
*(double *)ptr = swap_double(dof->pointxyplane_z);
break;
}
case fltDofMaxX:
{
*(double *)ptr = swap_double(dof->maxx);
break;
}
case fltDofMinX:
{
*(double *)ptr = swap_double(dof->minx);
break;
}
default:
OutputDebugString ("Unknown DOF attr\n");
break;
}
}
else {
struct flt_DegreeOfFreedomRecord *dof =
(struct flt_DegreeOfFreedomRecord *)rec->data;
switch (type) {
case fltDofPutAnchorX:
{
*(double *)ptr = swap_double(dof->originx);
break;
}
case fltDofPutAnchorY:
{
*(double *)ptr = swap_double(dof->originy);
break;
}
case fltDofPutAnchorZ:
{
*(double *)ptr = swap_double(dof->originz);
break;
}
case fltDofPutAlignX:
{
*(double *)ptr = swap_double(dof->pointxaxis_x);
break;
}
case fltDofPutAlignY:
{
*(double *)ptr = swap_double(dof->pointxaxis_y);
break;
}
case fltDofPutAlignZ:
{
*(double *)ptr = swap_double(dof->pointxaxis_z);
break;
}
case fltDofPutTrackX:
{
*(double *)ptr = swap_double(dof->pointxyplane_x);
break;
}
case fltDofPutTrackY:
{
*(double *)ptr = swap_double(dof->pointxyplane_y);
break;
}
case fltDofPutTrackZ:
{
*(double *)ptr = swap_double(dof->pointxyplane_z);
break;
}
case fltDofMaxX:
{
*(double *)ptr = swap_double(dof->maxx);
break;
}
case fltDofMinX:
{
*(double *)ptr = swap_double(dof->minx);
break;
}
default:
OutputDebugString ("Unknown DOF attr\n");
break;
}
}
return 1;
}
static int mgMatFetch (mgrec *rec, FltTypes type, void *ptr)
{
if (rec->vrsn > 1500) {
OutputDebugString ("mgMatFetch doesn't support 1500\n");
return MG_FALSE;
}
if (rec -> type != OPCODE_MATERIAL_TABLE)
return MG_FALSE;
struct flt_MaterialTable *mt = (struct flt_MaterialTable *)rec -> data;
switch (type) {
case fltMatAlpha:
*(float *)ptr = swap_float (mt -> alpha);
break;
default:
return MG_FALSE;
}
return MG_TRUE;
}
int mgGetAttList (mgrec *rec, ...)
{
va_list ap;
FltTypes type;
int count = 0;
va_start(ap, rec);
while ((type = va_arg(ap, FltTypes)) != 0) {
switch (type) {
case fltVU:
case fltVV:
{
float *fp = va_arg (ap, float *);
if (mgVtxFetch (rec, type, fp))
count ++;
}
break;
case fltDPlaneA:
case fltDPlaneB:
case fltDPlaneC:
case fltDPlaneD:
{
double *dp = va_arg(ap, double *);
if (mgBspFetch (rec, type, dp))
count ++;
}
break;
case fltPolyMaterial:
{
short *mind = va_arg(ap, short *);
if (mgPolyFetch(rec, type, mind))
count ++;
}
break;
case fltPolyTransparency:
{
short *tp = va_arg(ap, short *);
if (mgPolyFetch(rec, type, tp))
count ++;
}
break;
case fltPolyMgTemplate:
{
char *cp = va_arg(ap, char *);
if (mgPolyFetch (rec, type, cp))
count ++;
}
break;
case fltGcLightMode:
{
char *cp = va_arg(ap, char *);
if (mgPolyFetch (rec, type, cp))
count ++;
}
break;
case fltPolyTexture:
{
short *cp = va_arg(ap, short *);
if (mgPolyFetch (rec, type, cp))
count ++;
}
break;
case fltPolyLineStyle:
{
char *cp = va_arg(ap, char *);
if (mgPolyFetch (rec, type, cp))
count ++;
}
break;
case fltPolyDrawType:
{
char *cp = va_arg(ap, char *);
if (mgPolyFetch (rec, type, cp))
count ++;
}
break;
case fltMatAlpha:
{
float *fp = va_arg (ap, float *);
if (mgMatFetch (rec, type, fp))
count ++;
}
break;
case fltDofPutAnchorX:
case fltDofPutAnchorY:
case fltDofPutAnchorZ:
case fltDofPutAlignX:
case fltDofPutAlignY:
case fltDofPutAlignZ:
case fltDofPutTrackX:
case fltDofPutTrackY:
case fltDofPutTrackZ:
case fltDofMaxX:
case fltDofMinX:
{
double *dp = va_arg(ap, double *);
if (mgDofFetch (rec, type, dp))
count ++;
}
break;
default:
{
char buf[1024];
sprintf (buf, "Unsupported attr type %d %s\n", type, FindFltName(type));
OutputDebugString(buf);
va_arg (ap, char *); // best guess
}
break;
}
}
va_end (ap);
return count;
}
static short getshort (FILE *fp)
{
int c1 = getc(fp);
int c2 = getc(fp);
return (c1 << 8) | c2;
}
static mgrec *mgReadSequence (FILE *fp, mgrec *prnt, int vrsn);
static mgrec *mgReadRecord (FILE *fp, mgrec *prnt, int vrsn)
{
mgrec *rec = NULL;
while (rec == NULL) {
short type = getshort(fp);
if (feof(fp)) return 0;
rec = (mgrec *)calloc (1, sizeof *rec);
rec->type = (OpCode)type;
rec->len = getshort(fp);
rec->data = (char *) calloc (1, rec -> len);
rec->vrsn = vrsn;
rec->parent = prnt;
memcpy (rec->data, &rec->type, 2);
memcpy (rec->data+2, &rec->len, 2);
fread (rec -> data + 4, rec -> len - 4, 1, fp);
if (mgIgnoreRec (rec->type)) {
free (rec->data);
free (rec);
rec = NULL;
}
else if (rec->type == OPCODE_PUSH_LEVEL) {
rec -> child = mgReadSequence(fp, prnt, vrsn);
}
else if (rec -> type == OPCODE_VERTEX_LIST) { // recode this as a sequence
mgrec *last = rec;
char *data = rec -> data;
struct flt_VertexList *vl = (struct flt_VertexList *)data;
rec -> data = (char *)malloc(sizeof (int));
*(int*)rec -> data = swap_int(vl->offset[0]);
for (int i = 1; i < (rec->len - 4) / 4; i++) {
last->next = (mgrec *)calloc (1, sizeof *rec);
last = last->next;
last -> type = rec -> type;
last -> len = rec -> len;
last -> parent = prnt;
last -> vrsn = vrsn;
last -> data = (char *)malloc(sizeof(int));
*(int*)last -> data = swap_int(vl->offset[i]);
}
free (data);
}
}
return rec;
}
static mgrec *mgReadSequence (FILE *fp, mgrec *prnt, int vrsn)
{
mgrec *base = 0;
mgrec *cur = base;
mgrec *np;
int pcount = 0;
while (np = mgReadRecord (fp, base, vrsn)) {
if (np -> type == OPCODE_PUSH_LEVEL) {
pcount ++;
if (cur == NULL) {
cur = np -> child;
if (base == NULL) base = cur;
}
else {
cur-> child = np -> child;
}
np -> child = NULL;
freenode (np);
if (cur) {
for (np = cur -> child; np; np = np -> next) {
np -> parent = base;
}
}
}
else if (np -> type == OPCODE_POP_LEVEL) {
freenode (np);
pcount --;
if (pcount <= 0)
break;
}
else {
if (base == 0) {
cur = base = np;
}
else cur->next = np;
np ->parent = prnt;
while (cur -> next) {
cur->parent = prnt;
cur = cur->next;
}
}
}
return base;
}
mgrec *mgOpenDb (char *filename)
{
FILE *fp = fopen(filename, "rb");
if (fp == NULL) return NULL;
mgrec *base = mgReadRecord (fp, 0, 0);
if (base->type != OPCODE_HEADER) {
return NULL;
}
struct flt_HeaderRecord *fh = (struct flt_HeaderRecord *)base->data;
printf ("Version %d, db version %d\n", swap_int(fh->formatRev), swap_int(fh->DBRev));
base -> next = mgReadSequence (fp, 0, swap_int(fh->formatRev));
fclose (fp);
if (base->type != OPCODE_HEADER) {
return NULL;
}
return base;
}
void mgCloseDb (mgrec *db)
{
// freenode (db);
}
mgrec *mgGetMaterial (mgrec *db, int matind)
{
if (db -> vrsn > 1500) {
OutputDebugString ("mgGetMaterial doesn't support 1500\n");
return MG_FALSE;
}
mgrec *pbase = db;
while (pbase -> parent) {
pbase = pbase -> parent;
}
while (pbase && pbase -> type != OPCODE_MATERIAL_TABLE) {
pbase = pbase -> next;
}
if (pbase == NULL) return 0;
if (pbase -> child) {
for (mgrec *cp = pbase -> child; cp; cp = cp -> next) {
if (cp -> xdata == matind)
return cp;
}
}
flt_MaterialRecord *fmr = (flt_MaterialRecord *)pbase->data;
if (matind < 0 || matind > 64)
return 0;
mgrec *mr = (mgrec *) calloc (1, sizeof *mr);
mr -> type = OPCODE_MATERIAL_TABLE;
mr -> parent = pbase;
mr -> xdata = matind;
mr -> next = pbase -> child;
pbase->child = mr;
mr -> data = (char *)calloc (1, sizeof (flt_MaterialTable));
memcpy (mr -> data, &fmr -> mat[matind], sizeof (flt_MaterialTable));
return mr;
}
static int mgFind15Material (mgrec *db, int matind, short *r, short *g, short *b)
{
mgrec *pbase = db;
while (pbase -> parent) {
pbase = pbase -> parent;
}
while (pbase && pbase -> type != OPCODE_MATERIAL_PALETTE) {
pbase = pbase -> next;
}
if (pbase == NULL) return 0;
while (pbase->type == OPCODE_MATERIAL_PALETTE) {
aflt_MaterialRecord *matrec = (aflt_MaterialRecord *)pbase->data;
if (swap_int(matrec->materialIndex) == matind) {
*r = (short)(255.0f * swap_float(matrec->diffuseRed));
*g = (short)(255.0f * swap_float(matrec->diffuseGreen));
*b = (short)(255.0f * swap_float(matrec->diffuseBlue));
return MG_TRUE;
}
pbase = pbase->next;
}
return MG_FALSE;
}
static int mgFind14Material (mgrec *db, int matind, short *r, short *g, short *b)
{
mgrec *pbase = mgGetMaterial(db, matind);
if (pbase == NULL) return MG_FALSE;
flt_MaterialTable *matrec = (flt_MaterialTable *)pbase->data;
*r = (short)(255.0f * swap_float(matrec->diffuseRed));
*g = (short)(255.0f * swap_float(matrec->diffuseGreen));
*b = (short)(255.0f * swap_float(matrec->diffuseBlue));
return MG_TRUE;
}
int mgGetPolyColorRGB (mgrec *rec, short *r, short *g, short *b)
{
if (rec -> type != OPCODE_POLYGON)
return MG_FALSE;
int colindex;
int colintens;
if (strncmp (rec->data + 4, "f45", 3) == 0 ||
strncmp (rec->data + 4, "f42", 3) == 0) {
*r =0; *g = 255; *b = 0;
return MG_TRUE;
}
if (rec->vrsn > 1500) {
struct aflt_PolygonRecord *pr;
pr = (struct aflt_PolygonRecord *)rec->data;
int mc = swap_short(pr->materialCode);
if (mc != -1) {
return mgFind15Material (rec, mc, r, g, b);
}
else {
int pc = swap_short (pr->primaryColor);
colindex = pc >> 7;
colintens = pc & 0x7f;
}
}
else {
struct flt_PolygonRecord *pr;
pr = (struct flt_PolygonRecord *)rec->data;
int mc = swap_short(pr->materialCode);
if (mc != -1) {
return mgFind14Material (rec, mc, r, g, b);
}
unsigned short pc = swap_short (pr->primaryColor);
colindex = pc >> 7;
colintens = pc & 0x7f;
}
int rgb;
if (mgGetColorInd (rec, colindex, &rgb) != MG_TRUE)
return MG_FALSE;
*r = (rgb & 0xff) * colintens / 127;
*g = ((rgb>>8) & 0xff) * colintens / 127;
*b = ((rgb>>16) & 0xff) * colintens / 127;
return MG_TRUE;
}
static int mgGetFaceFromVertexNormal (mgrec *vert, double *i, double *j, double *k)
{
double i1, j1, k1;
double nx = 0.0, ny = 0.0, nz = 0.0;
int count = 0;
while (vert) {
if (mgGetVertexNormal(vert, &i1, &j1, &k1) != MG_TRUE)
return MG_FALSE;
nx += i1;
ny += j1;
nz += k1;
count ++;
vert = mgGetNext (vert);
}
nx /= count;
ny /= count;
nz /= count;
Normalize (&nx, &ny, &nz);
*i = nx;
*j = ny;
*k = nz;
return MG_TRUE;
}
int mgGetPolyNormal(mgrec *rec, double *i, double *j, double *k)
{
mgrec *child = mgGetChild (rec);
if (child == 0 || child -> type != OPCODE_VERTEX_LIST) {
OutputDebugString ("No child with vertex\n");
return MG_FALSE;
}
if (mgGetFaceFromVertexNormal (child, i, j, k) == MG_TRUE)
return MG_TRUE;
// otherwise compute it ourself.
OutputDebugString ("Got to calculate our own normal\n");
double x1, y1, z1;
if (mgGetIcoord (child, fltIcoord, &x1, &y1, &z1) == MG_FALSE) {
OutputDebugString ("No vertex 1\n");
return MG_FALSE;
}
double x2, y2, z2;
child = child -> next;
if (mgGetIcoord (child, fltIcoord, &x2, &y2, &z2) == MG_FALSE) {
OutputDebugString ("No vertex 2\n");
return MG_FALSE;
}
double x3, y3, z3;
child = child -> next;
if (mgGetIcoord (child, fltIcoord, &x3, &y3, &z3) == MG_FALSE) {
OutputDebugString ("No vertex 3\n");
return MG_FALSE;
}
// 2 - 1 = u
x1 = x2 - x1;
y1 = y2 - y1;
z1 = z2 - z1;
// 3 - 2 = v
x2 = x3 - x2;
y2 = y3 - y2;
z2 = z3 - z2;
// u cross v
x3 = y1 * z2 + z1 * y2;
y3 = z1 * x2 + x1 * z2;
z3 = x1 * y2 + y1 * x2;
Normalize (&x3, &y3, &z3);
*i = x3;
*j = y3;
*k = z3;
return MG_TRUE;
}
int mgGetMatrix (mgrec *rec, FltTypes type, mgmatrix *mat)
{
OutputDebugString("mgGetmatrix not implemented\n");
return MG_FALSE;
}
int mgGetNormColor (mgrec *rec, FltTypes type, float *r, float *g, float *b)
{
if (rec->vrsn > 1500) {
OutputDebugString ("mgGetNormColor not supported in 1500\n");
return MG_FALSE;
}
if (rec -> type != OPCODE_MATERIAL_TABLE)
return MG_FALSE;
struct flt_MaterialTable *mt = (struct flt_MaterialTable *)rec -> data;
switch (type) {
case fltDiffuse:
*r = swap_float(mt->diffuseRed);
*g = swap_float(mt->diffuseGreen);
*b = swap_float(mt->diffuseBlue);
break;
default:
OutputDebugString ("Unknown type for GetNormColor\n");
return MG_FALSE;
}
return MG_TRUE;
}
int mgIndex2RGB (mgrec *rec, int colind, float intensity, short *r, short *g, short *b)
{
OutputDebugString("mgIndex2RGB not implemented\n");
return MG_FALSE;
}
void mgSetMessagesEnabled (int, int)
{
}
| 22.887865 | 105 | 0.61255 | IsraelyFlightSimulator |
b9198bf3a63ba8bacd1b900e3415c97b43e10b6c | 667 | hpp | C++ | library/cgp/containers/buffer_stack/buffer_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | library/cgp/containers/buffer_stack/buffer_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | 2 | 2022-03-03T16:34:03.000Z | 2022-03-20T13:08:56.000Z | library/cgp/containers/buffer_stack/buffer_stack.hpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | #pragma once
namespace cgp
{
/** Base class for small fixed-size vectors (vec3, mat3, etc.).
* buffer_stack structure is a generic fixed-size vector, essentially equivalent to a std::array.
* In addition to std::array syntax, buffer_stack provides extra convenient functions (similar to buffer) for numerical vectors +, -, *, / as well as strict bounds checking.
*/
// template <typename T, int N> struct buffer_stack;
}
#include "implementation/buffer_stack.hpp"
#include "implementation/buffer_stack2.hpp"
#include "implementation/buffer_stack3.hpp"
#include "implementation/buffer_stack4.hpp"
#include "special_types/special_types.hpp" | 33.35 | 177 | 0.746627 | drohmer |
b91a0929fd33b9d9782b9e9cf0f184828ac08702 | 4,342 | cpp | C++ | solved-topcoder/Solved/CatsOnTheLineDiv2.cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | solved-topcoder/Solved/CatsOnTheLineDiv2.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | solved-topcoder/Solved/CatsOnTheLineDiv2.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | /**
* @author : Maruf Tuhin
* @School : CUET CSE 11
* @Topcoder : the_redback
* @CodeForces : the_redback
* @UVA : the_redback
* @link : http://www.fb.com/maruf.2hin
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
#define ft first
#define sd second
#define mp make_pair
#define pb(x) push_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define mem(a,b) memset(a,b,sizeof(a))
#define meminf(a) memset(a,126,sizeof(a))
#define inf 1e7
#define eps 1e-9
#define mod 1000000007
#define NN 10100
#define z 4000
//cout << setfill('0') << setw(3) << a << endl;
//cout << fixed << setprecision(20) << a << endl;
struct D
{
int pos,cnt;
}a[60];
bool flag[NN];
bool comp(D aa,D bb)
{
return aa.pos<bb.pos;
}
struct CatsOnTheLineDiv2
{
string getAnswer(vector <int> position, vector <int> count, int time)
{
string ret;
int n=count.size();
int i,j,k,l;
for(i=0;i<count.size();i++)
{
a[i].pos=position[i];
a[i].cnt=count[i];
}
sort(a,a+n,comp);
mem(flag,0);
int low=-inf;
int high=inf;
for(i=0;i<n;i++)
{
low=a[i].pos-time+z;
high=a[i].pos+time+z;
int cnt=0;
while(low<=high && cnt<a[i].cnt)
{
if(flag[low]==0)
{
cnt++;
flag[low]=1;
}
low++;
}
if(cnt<a[i].cnt)
return "Impossible";
}
return "Possible";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {7}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "Possible"; verify_case(0, Arg3, getAnswer(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {8}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; string Arg3 = "Impossible"; verify_case(1, Arg3, getAnswer(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arr0[] = {0, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; string Arg3 = "Impossible"; verify_case(2, Arg3, getAnswer(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arr0[] = {5, 0, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2, 3, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; string Arg3 = "Impossible"; verify_case(3, Arg3, getAnswer(Arg0, Arg1, Arg2)); }
void test_case_4() { int Arr0[] = {5, 1, -10, 7, 12, 2, 10, 20}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 4, 2, 7, 1, 4, 3, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; string Arg3 = "Possible"; verify_case(4, Arg3, getAnswer(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
CatsOnTheLineDiv2 ___test;
___test.run_test(-1);
int gbase;
cin>>gbase; // erase this line if you are not using dev-cpp! :)
return 0;
}
// END CUT HERE
| 38.767857 | 329 | 0.544219 | Maruf-Tuhin |
b91cd44ed44c1025090cacadecbf00e4dc36bf25 | 924 | cpp | C++ | src/reconstruct.cpp | ckpwinters/StereoTracking | f7e2c52c0c4481303560a1d03603a9d4971e8103 | [
"BSD-2-Clause"
] | null | null | null | src/reconstruct.cpp | ckpwinters/StereoTracking | f7e2c52c0c4481303560a1d03603a9d4971e8103 | [
"BSD-2-Clause"
] | null | null | null | src/reconstruct.cpp | ckpwinters/StereoTracking | f7e2c52c0c4481303560a1d03603a9d4971e8103 | [
"BSD-2-Clause"
] | null | null | null | //
// Created by lab on 16-12-27.
//
#include "reconstruct.h"
namespace tracker{
void Triangulate::Reconstruct3d(vector<Point2f> &matched_L, vector<Point2f> &matched_R, vector<Point3f> &coord_3d) {
size_t num_points=matched_L.size();
//double pixel_size=4.65e-3;
//Z=b*f/d
float d,Z,Y,X;
//cout<<"debug info.."<<endl;
for(size_t i=0;i<num_points;i++)
{
//* Transform them into the same world coordinate.
d=matched_L[i].x-matched_R[i].x;
Z=baseline*f/(d*pixel_size);
Y=pixel_size*Z*(matched_L[i].y-this->camera_matrix.at<float>(1,2))/f;
X=pixel_size*Z*(matched_L[i].x-this->camera_matrix.at<float>(0,2))/f;
//cout<<"X["<<i<<"]:"<<X<<endl;
//* Cartesian coordinate system.(0,0,0) is right at perspective point
coord_3d.push_back(Point3d(X,-Y,-Z));
}
}
} | 31.862069 | 120 | 0.568182 | ckpwinters |
b91ed1f420de1fbaef1d34e93f766b5a45b22d93 | 2,411 | cc | C++ | tests/json-test.cc | kikairoya/black_circle | f3d8b90c9ddc76561d6ddc5e29e5e8fc8d3318c6 | [
"BSL-1.0"
] | 1 | 2016-06-20T21:16:36.000Z | 2016-06-20T21:16:36.000Z | tests/json-test.cc | kikairoya/black_circle | f3d8b90c9ddc76561d6ddc5e29e5e8fc8d3318c6 | [
"BSL-1.0"
] | null | null | null | tests/json-test.cc | kikairoya/black_circle | f3d8b90c9ddc76561d6ddc5e29e5e8fc8d3318c6 | [
"BSL-1.0"
] | null | null | null | #include <common.hpp>
#include "json_parser.hpp"
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
using namespace circle;
template <typename T>
inline T clone(const T &v) { return v; }
template <typename T>
struct object_type { typedef T type; };
template <> struct object_type<int> { typedef circle::int64_t type; };
template <> struct object_type<unsigned> { typedef circle::int64_t type; };
template <> struct object_type<char *> { typedef string type; };
template <> struct object_type<const char *> { typedef string type; };
template <size_t N> struct object_type<char [N]> { typedef string type; };
template <size_t N> struct object_type<const char [N]> { typedef string type; };
struct insert_object_t {
insert_object_t(json::json_object_map &obj, string &jstr): obj(obj), jstr(jstr), n() { }
template <typename T>
void operator()(const T &val, const string &vstr) {
const string key = "val" + boost::lexical_cast<string>(++n);
obj[key] = static_cast<typename object_type<T>::type>(val);
jstr.insert(jstr.length()-1, ",\""+key+"\":"+vstr);
}
json::json_object_map &obj;
string &jstr;
unsigned n;
};
BOOST_AUTO_TEST_CASE(json_parse_test) {
BOOST_CHECK(json::parse_json("[]") == json::json_object_value(json::json_array_type()));
json::json_object_value obj((json::json_object_map()));
json::json_object_map &om = boost::get<json::json_object_map>(obj);
BOOST_CHECK(json::parse_json("{}") == obj);
string jstr = "{\"null\":null}";
insert_object_t ins(om, jstr);
om["null"] = json::null_t();
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(10, "10");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(10., "10.");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins("str", "\"str\"");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins("", "\"\"");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(true, "true");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(false, "false");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(0, "0");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(clone(obj), clone(jstr));
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(-5, "-5");
ins(-3., "-3.");
ins("3.3", "\"3.3\"");
ins("null", "\"null\"");
BOOST_CHECK(json::parse_json(jstr) == obj);
ins(clone(obj), clone(jstr));
BOOST_CHECK(json::parse_json(jstr) == obj);
}
| 34.942029 | 90 | 0.657818 | kikairoya |
b9243933db9eeb3db42009eb0243dccc3fc203f0 | 10,105 | cpp | C++ | Source/Samples/41_DatabaseDemo/DatabaseDemo.cpp | ArnisLielturks/GameOff2017-WildDimension | 16d5cd0a0a7c8c520bee974f008ba719e37c996f | [
"MIT"
] | 3 | 2017-09-18T02:18:49.000Z | 2021-04-10T00:17:15.000Z | Source/Samples/41_DatabaseDemo/DatabaseDemo.cpp | ArnisLielturks/GameOff2017-WildDimension | 16d5cd0a0a7c8c520bee974f008ba719e37c996f | [
"MIT"
] | 1 | 2017-09-18T06:05:25.000Z | 2017-09-18T06:05:25.000Z | Source/Samples/41_DatabaseDemo/DatabaseDemo.cpp | pengfei666/Urho3D | 80658b06596e17e89278dde8e9a6cbe9375c7cee | [
"MIT"
] | null | null | null | //
// Copyright (c) 2008-2017 the Urho3D project.
//
// 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 <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Database/Database.h>
#include <Urho3D/Database/DatabaseEvents.h>
#include <Urho3D/Engine/Console.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Engine/EngineEvents.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/UI/Button.h>
#include "DatabaseDemo.h"
// Expands to this example's entry-point
URHO3D_DEFINE_APPLICATION_MAIN(DatabaseDemo)
DatabaseDemo::DatabaseDemo(Context* context) :
Sample(context),
connection_(nullptr),
row_(0),
maxRows_(50)
{
}
DatabaseDemo::~DatabaseDemo()
{
// Although the managed database connection will be disconnected by Database subsystem automatically in its destructor,
// it is a good practice for a class to balance the number of connect() and disconnect() calls.
GetSubsystem<Database>()->Disconnect(connection_);
connection_ = nullptr;
}
void DatabaseDemo::Start()
{
// Execute base class startup
Sample::Start();
// Subscribe to console commands and the frame update
SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(DatabaseDemo, HandleConsoleCommand));
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(DatabaseDemo, HandleUpdate));
// Subscribe key down event
SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(DatabaseDemo, HandleEscKeyDown));
// Hide logo to make room for the console
SetLogoVisible(false);
// Show the console by default, make it large. Console will show the text edit field when there is at least one
// subscriber for the console command event
Console* console = GetSubsystem<Console>();
console->SetNumRows((unsigned)(GetSubsystem<Graphics>()->GetHeight() / 16));
console->SetNumBufferedRows(2 * console->GetNumRows());
console->SetCommandInterpreter(GetTypeName());
console->SetVisible(true);
console->GetCloseButton()->SetVisible(false);
// Show OS mouse cursor
GetSubsystem<Input>()->SetMouseVisible(true);
// Set the mouse mode to use in the sample
Sample::InitMouseMode(MM_FREE);
// Open the operating system console window (for stdin / stdout) if not open yet
OpenConsoleWindow();
// In general, the connection string is really the only thing that need to be changed when switching underlying database API
// and that when using ODBC API then the connection string must refer to an already installed ODBC driver
// Although it has not been tested yet but the ODBC API should be able to interface with any vendor provided ODBC drivers
// In this particular demo, however, when using ODBC API then the SQLite-ODBC driver need to be installed
// The SQLite-ODBC driver can be built from source downloaded from http://www.ch-werner.de/sqliteodbc/
// You can try to install other ODBC driver and modify the connection string below to match your ODBC driver
// Both DSN and DSN-less connection string should work
// The ODBC API, i.e. URHO3D_DATABASE_ODBC build option, is only available for native (including RPI) platforms
// and it is designed for development of game server connecting to ODBC-compliant databases in mind
// This demo will always work when using SQLite API as the SQLite database engine is embedded inside Urho3D game engine
// and this is also the case when targeting Web platform
// We could have used #ifdef to init the connection string during compile time, but below shows how it is done during runtime
// The "URHO3D_DATABASE_ODBC" compiler define is set when URHO3D_DATABASE_ODBC build option is enabled
// Connect to a temporary in-memory SQLite database
connection_ =
GetSubsystem<Database>()->Connect(Database::GetAPI() == DBAPI_ODBC ? "Driver=SQLite3;Database=:memory:" : "file://");
// Subscribe to database cursor event to loop through query resultset
SubscribeToEvent(E_DBCURSOR, URHO3D_HANDLER(DatabaseDemo, HandleDbCursor));
// Show instruction
Print("This demo connects to temporary in-memory database.\n"
"All the tables and their data will be lost after exiting the demo.\n"
"Enter a valid SQL statement in the console input and press Enter to execute.\n"
"Enter 'get/set maxrows [number]' to get/set the maximum rows to be printed out.\n"
"Enter 'get/set connstr [string]' to get/set the database connection string and establish a new connection to it.\n"
"Enter 'quit' or 'exit' to exit the demo.\n"
"For example:\n ");
HandleInput("create table tbl1(col1 varchar(10), col2 smallint)");
HandleInput("insert into tbl1 values('Hello', 10)");
HandleInput("insert into tbl1 values('World', 20)");
HandleInput("select * from tbl1");
}
void DatabaseDemo::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
{
using namespace ConsoleCommand;
if (eventData[P_ID].GetString() == GetTypeName())
HandleInput(eventData[P_COMMAND].GetString());
}
void DatabaseDemo::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
// Check if there is input from stdin
String input = GetConsoleInput();
if (input.Length())
HandleInput(input);
}
void DatabaseDemo::HandleEscKeyDown(StringHash eventType, VariantMap& eventData)
{
// Unlike the other samples, exiting the engine when ESC is pressed instead of just closing the console
if (eventData[KeyDown::P_KEY].GetInt() == KEY_ESCAPE)
engine_->Exit();
}
void DatabaseDemo::HandleDbCursor(StringHash eventType, VariantMap& eventData)
{
using namespace DbCursor;
// In a real application the P_SQL can be used to do the logic branching in a shared event handler
// However, this is not required in this sample demo
unsigned numCols = eventData[P_NUMCOLS].GetUInt();
const VariantVector& colValues = eventData[P_COLVALUES].GetVariantVector();
const Vector<String>& colHeaders = eventData[P_COLHEADERS].GetStringVector();
// In this sample demo we just use db cursor to dump each row immediately so we can filter out the row to conserve memory
// In a real application this can be used to perform the client-side filtering logic
eventData[P_FILTER] = true;
// In this sample demo we abort the further cursor movement when maximum rows being dumped has been reached
eventData[P_ABORT] = ++row_ >= maxRows_;
for (unsigned i = 0; i < numCols; ++i)
Print(ToString("Row #%d: %s = %s", row_, colHeaders[i].CString(), colValues[i].ToString().CString()));
}
void DatabaseDemo::HandleInput(const String& input)
{
// Echo input string to stdout
Print(input);
row_ = 0;
if (input == "quit" || input == "exit")
engine_->Exit();
else if (input.StartsWith("set") || input.StartsWith("get"))
{
// We expect a key/value pair for 'set' command
Vector<String> tokens = input.Substring(3).Split(' ');
String setting = tokens.Size() ? tokens[0] : "";
if (input.StartsWith("set") && tokens.Size() > 1)
{
if (setting == "maxrows")
maxRows_ = Max(ToUInt(tokens[1]), 1U);
else if (setting == "connstr")
{
String newConnectionString(input.Substring(input.Find(" ", input.Find("connstr")) + 1));
Database* database = GetSubsystem<Database>();
DbConnection* newConnection = database->Connect(newConnectionString);
if (newConnection)
{
database->Disconnect(connection_);
connection_ = newConnection;
}
}
}
if (tokens.Size())
{
if (setting == "maxrows")
Print(ToString("maximum rows is set to %d", maxRows_));
else if (setting == "connstr")
Print(ToString("connection string is set to %s", connection_->GetConnectionString().CString()));
else
Print(ToString("Unrecognized setting: %s", setting.CString()));
}
else
Print("Missing setting paramater. Recognized settings are: maxrows, connstr");
}
else
{
// In this sample demo we use the dbCursor event to loop through each row as it is being fetched
// Regardless of this event is being used or not, all the fetched rows will be made available in the DbResult object,
// unless the dbCursor event handler has instructed to filter out the fetched row from the final result
DbResult result = connection_->Execute(input, true);
// Number of affected rows is only meaningful for DML statements like insert/update/delete
if (result.GetNumAffectedRows() != -1)
Print(ToString("Number of affected rows: %d", result.GetNumAffectedRows()));
}
Print(" ");
}
void DatabaseDemo::Print(const String& output)
{
// Logging appears both in the engine console and stdout
URHO3D_LOGRAW(output + "\n");
}
| 44.911111 | 129 | 0.696388 | ArnisLielturks |
b92a97394e9a2d6911e2afd3285f946db277388b | 3,101 | cpp | C++ | src/ADBSCEditDLL/test/misc-regex/CppRegex.cpp | ClnViewer/ADB-Android-Viewer | c619fe626ab390b656893974700a0b6379159c03 | [
"MIT"
] | 9 | 2019-05-20T12:06:36.000Z | 2022-03-24T19:11:06.000Z | src/ADBSCEditDLL/test/misc-regex/CppRegex.cpp | ClnViewer/ADB-Android-Viewer | c619fe626ab390b656893974700a0b6379159c03 | [
"MIT"
] | null | null | null | src/ADBSCEditDLL/test/misc-regex/CppRegex.cpp | ClnViewer/ADB-Android-Viewer | c619fe626ab390b656893974700a0b6379159c03 | [
"MIT"
] | 3 | 2020-07-06T04:51:33.000Z | 2021-07-26T20:08:02.000Z | /*
MIT License
Android remote Viewer, GUI ADB tools
Android Viewer developed to view and control your android device from a PC.
ADB exchange Android Viewer, support scale view, input tap from mouse,
input swipe from keyboard, save/copy screenshot, etc..
Copyright (c) 2016-2019 PS
GitHub: https://github.com/ClnViewer/ADB-Android-Viewer
GitHub: https://github.com/ClnViewer/ADB-Android-Viewer/ADBSCEditDLL/ADBSCEdit
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, sub license, 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 <string>
#include <iostream>
#include <regex>
#include <filesystem>
#include "../../../ADBViewer/src/version.h"
namespace fs = std::filesystem;
const char *str[] =
{
"class.function()",
"class:function()",
"function()",
" -- 373 | 14 | LOAD \"The table the script received has:\n\"",
" -- 6 | 16 | GET [LuaObject]",
" -- 67 | 18 | GET",
" HYPERLINK \"THELP_APP\"Hot keys help\r" // "^\s+(HYPERLINK)\s+\"(\w+)\"(.*)\r$"
};
int main(int32_t argc, char *argv[])
{
if (argc < 3)
{
fs::path l_exec{ argv[0] };
std::cout << " * version: " << AVIEW_FULLVERSION_STRING << " - " << __DATE__ << std::endl;
std::cout << " * using : " << l_exec.filename().generic_string().c_str() << " <0-6> <ECMAScript regex>" << std::endl;
std::cout << std::endl << " ! Bad arguments.." << std::endl;
return 0;
}
try
{
int32_t idx = std::stoi(argv[1]);
idx = ((idx > 6) ? 6 : idx);
std::string s(str[idx]);
std::string r(argv[2]);
const std::regex re(
r.c_str(),
std::regex::ECMAScript
);
std::smatch m;
bool b = regex_search(s, m, re);
std::cout << "\n\tSearch: " << s.c_str() << std::endl;
uint32_t cnt = 1U;
for (auto & x : m)
std::cout << "\t" << cnt++ << ": " << x <<"\n";
std::cout << "\n\tFound: " << b << " - " << m.size() << std::endl;
}
catch (std::exception const & ex)
{
std::cout << "\n\tException: " << ex.what() << std::endl;
}
return 0;
}
| 34.076923 | 126 | 0.618188 | ClnViewer |
b92e03fdb156047b17616f50b4781434b52ec305 | 1,120 | cpp | C++ | Week-1/Day-07-wordPattern.cpp | utkarshavardhana/september-leetcoding-challenge | 4e188ea914eea331ab3b032571640c82048e136d | [
"MIT"
] | null | null | null | Week-1/Day-07-wordPattern.cpp | utkarshavardhana/september-leetcoding-challenge | 4e188ea914eea331ab3b032571640c82048e136d | [
"MIT"
] | null | null | null | Week-1/Day-07-wordPattern.cpp | utkarshavardhana/september-leetcoding-challenge | 4e188ea914eea331ab3b032571640c82048e136d | [
"MIT"
] | null | null | null | class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> words = split(str, ' ');
map<char, string> table;
if (pattern.size() != words.size()) {
return false;
}
for (auto i = 0; i < pattern.size(); ++ i) {
auto c = pattern[i];
auto iter = table.find(c);
if (iter == table.end()) {
for (auto item : table) {
if (item.second == words[i]) {
return false;
}
}
table.insert(make_pair(c, words[i]));
} else {
if (iter->second != words[i]) {
return false;
}
}
}
return true;
}
vector<string> split(const std::string& str, char delim) {
vector<string> words;
stringstream ss;
ss.str(str);
string item;
while (getline(ss, item, delim)) {
words.push_back(item);
}
return std::move(words);
}
};
| 28.717949 | 60 | 0.415179 | utkarshavardhana |
b930423655c18483adef98ba4c8b335c5e77704f | 580 | hpp | C++ | obsoleted/old/lib-obsolete/int/libled/row-help.hpp | cppcoder123/led-server | 8ebac31e1241bb203d2cedfd644fe52619007cd6 | [
"MIT"
] | 1 | 2021-12-23T13:50:53.000Z | 2021-12-23T13:50:53.000Z | obsoleted/old/lib-obsolete/int/libled/row-help.hpp | cppcoder123/led-server | 8ebac31e1241bb203d2cedfd644fe52619007cd6 | [
"MIT"
] | null | null | null | obsoleted/old/lib-obsolete/int/libled/row-help.hpp | cppcoder123/led-server | 8ebac31e1241bb203d2cedfd644fe52619007cd6 | [
"MIT"
] | null | null | null | //
//
//
#ifndef LIBLED_ROW_HELP_HPP
#define LIBLED_ROW_HELP_HPP
namespace libled
{
namespace row
{
template <typename info_t>
struct help_t
{
static std::size_t size (const info_t &info) {return info.size ();}
//
static bool test (const info_t &info, std::size_t index)
{return info.test (index);}
};
// template <>
// struct help_t<bool>
// {
// static std::size_t size () {return 1;}
// static bool test (bool info, std::size_t) {return info;}
// };
} // namespace row
} // namespace libled
#endif
| 18.125 | 73 | 0.593103 | cppcoder123 |
b939490ef770fd0da9b17425b32989fc2cb77e00 | 3,893 | cpp | C++ | Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.gen.cpp | Maskside/DriftGame | a518574f3ba4256da0cc948b9f147b4d3aaa3b5c | [
"MIT"
] | null | null | null | Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.gen.cpp | Maskside/DriftGame | a518574f3ba4256da0cc948b9f147b4d3aaa3b5c | [
"MIT"
] | null | null | null | Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.gen.cpp | Maskside/DriftGame | a518574f3ba4256da0cc948b9f147b4d3aaa3b5c | [
"MIT"
] | null | null | null | // This file is automatically generated at compile-time to include some subset of the user-created cpp files.
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedExternalUILibrary.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedFriendsGameInstance.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedFriendsInterface.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedFriendsLibrary.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedIdentityLibrary.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedSessions.init.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedSessionsLibrary.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\AdvancedVoiceLibrary.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\BlueprintDataDefinitions.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\CancelFindSessionsCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\CreateSessionCallbackProxyAdvanced.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\EndSessionCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\FindFriendSessionCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\FindSessionsCallbackProxyAdvanced.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\GetFriendsCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\GetRecentPlayersCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\GetUserPrivilegeCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\LoginUserCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\LogoutUserCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\SendFriendInviteCallbackProxy.gen.cpp"
#include "E:\Unreal Projects\github\DriftGame\Plugins\AdvancedSessions\AdvancedSessions\Intermediate\Build\Win64\UE4Editor\Inc\AdvancedSessions\UpdateSessionCallbackProxyAdvanced.gen.cpp"
| 169.26087 | 187 | 0.875417 | Maskside |
b93d6971337ab178a943d239ab8ff80d31c47884 | 1,807 | cpp | C++ | lib/indicator/DbgCliCmdIndSet.cpp | dniklaus/arduino-serial-test | a5efa33111321d8663d5291461e4244af491a6b5 | [
"MIT"
] | 1 | 2021-01-07T12:59:18.000Z | 2021-01-07T12:59:18.000Z | lib/indicator/DbgCliCmdIndSet.cpp | dniklaus/arduino-serial-test | a5efa33111321d8663d5291461e4244af491a6b5 | [
"MIT"
] | 1 | 2018-04-19T12:29:36.000Z | 2018-04-19T12:29:36.000Z | lib/indicator/DbgCliCmdIndSet.cpp | dniklaus/arduino-serial-test | a5efa33111321d8663d5291461e4244af491a6b5 | [
"MIT"
] | 1 | 2017-08-18T18:30:14.000Z | 2017-08-18T18:30:14.000Z | /*
* DbgCliCmdLedSet.cpp
*
* Created on: 01.11.2019
* Author: nid
*/
#include "DbgCliCmdIndSet.h"
#include <string.h>
#include <DbgCliNode.h>
#include <DbgCliTopic.h>
#include <DbgCliCommand.h>
#include <DbgTracePort.h>
#include <DbgTraceContext.h>
#include <DbgTraceOut.h>
#include <DbgPrintConsole.h>
#include <DbgTraceLevel.h>
#include "Indicator.h"
DbgCliCmd_IndSet::DbgCliCmd_IndSet(Indicator& indicator)
: DbgCli_Command(indicator.dbgCliTopic(), "set", "Set indicator state")
, m_trPort(new DbgTrace_Port(this->getParentNode()->getNodeName(), DbgTrace_Level::notice))
, m_indicator(indicator)
{ }
DbgCliCmd_IndSet::~DbgCliCmd_IndSet()
{
delete m_trPort;
m_trPort = 0;
}
void DbgCliCmd_IndSet::printUsage()
{
TR_PRINTF(m_trPort, DbgTrace_Level::alert, "%s", getHelpText());
TR_PRINTF(m_trPort, DbgTrace_Level::alert, "Usage: %s %s %s [blink|on|off].",
DbgCli_Node::RootNode()->getNodeName(), this->getParentNode()->getNodeName(),this->getNodeName());
}
void DbgCliCmd_IndSet::printReport()
{
TR_PRINTF(m_trPort, DbgTrace_Level::alert, "%s : %s", getHelpText(), Indicator::getLedStateText(m_indicator.getLedState()));
}
void DbgCliCmd_IndSet::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)
{
if (argc - idxToFirstArgToHandle == 0)
{
printReport();
}
else
{
if (strncmp(args[idxToFirstArgToHandle], "on", strlen("on")) == 0)
{
m_indicator.set();
printReport();
}
else if (strncmp(args[idxToFirstArgToHandle], "off", strlen("off")) == 0)
{
m_indicator.clear();
printReport();
}
else if (strncmp(args[idxToFirstArgToHandle], "blink", strlen("blink")) == 0)
{
m_indicator.blink();
printReport();
}
else
{
printUsage();
}
}
}
| 24.418919 | 126 | 0.674045 | dniklaus |
b93dd4bab3baaf82c57d23bcaed261571a3ba52f | 4,531 | cpp | C++ | sdk/QtComponents/vuMeter.cpp | InfiniteInteractive/LimitlessSDK | cb71dde14d8c59cbf8a1ece765989c5787fffefa | [
"MIT"
] | 3 | 2017-05-13T20:36:03.000Z | 2021-07-16T17:23:01.000Z | sdk/QtComponents/vuMeter.cpp | InfiniteInteractive/LimitlessSDK | cb71dde14d8c59cbf8a1ece765989c5787fffefa | [
"MIT"
] | null | null | null | sdk/QtComponents/vuMeter.cpp | InfiniteInteractive/LimitlessSDK | cb71dde14d8c59cbf8a1ece765989c5787fffefa | [
"MIT"
] | 2 | 2016-08-04T00:16:50.000Z | 2017-09-07T14:50:03.000Z | #include "VuMeter.h"
#include <QtGui/QPainter>
namespace Limitless
{
VuMeter::VuMeter(QWidget *parent): QWidget(parent)
{
m_backgroundColor=QColor(0, 0, 0);
m_cellColor=QColor(80, 80, 80);
m_highColor=Qt::red;
m_color=Qt::yellow;
m_lowColor=Qt::green;
m_maxiumValue=1.0f;
m_minimumValue=0.0f;
m_value=0.0f;
m_cells=40;
m_vertical=true;
}
QSize VuMeter::minimumSizeHint() const
{
QSize size;
if(m_vertical)
{
size.setHeight(m_cells*4+1);
size.setWidth(6);
}
else
{
size.setWidth(m_cells*4+1);
size.setHeight(6);
}
return size;
}
QSize VuMeter::sizeHint() const
{
QSize size;
if(m_vertical)
{
size.setHeight(m_cells*4+3);
size.setWidth(8);
}
else
{
size.setWidth(m_cells*4+3);
size.setHeight(8);
}
return size;
}
void VuMeter::setVertical(bool value)
{
m_vertical=value;
if(value)
{
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
}
else
{
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
}
setMinimumSize(minimumSizeHint());
}
void VuMeter::setValue(float value)
{
m_value=value;
update();
}
void VuMeter::paintEvent(QPaintEvent *event)
{
if(m_vertical)
paintVertical();
else
paintHorizontal();
}
void VuMeter::paintVertical()
{
QPainter painter(this);
QRect rect=painter.window();
painter.setRenderHint(QPainter::Antialiasing);
int cellSpacers=m_cells+1;
int height=rect.height()-cellSpacers; //need minum 1 pixel space between blocks
int cellHeight=height/m_cells;
int extra=(rect.height()-(cellHeight*m_cells)-cellSpacers)/2;
painter.setBrush(m_backgroundColor);
painter.drawRect(rect);
int cellIndex=ceil(m_value*m_cells);
int colorIndex=ceil(0.70*m_cells);
int highColorIndex=ceil(0.90*m_cells);
if(cellIndex < 0)
cellIndex=0;
else if(cellIndex > m_cells)
cellIndex=m_cells;
QRect cellRect(rect.x()+1, rect.height()-cellHeight-extra-1, rect.width()-2, cellHeight);
QColor currentColor=m_lowColor;
int changeIndex=colorIndex;
painter.setBrush(m_lowColor);
for(size_t i=0; i<cellIndex; ++i)
{
if(i>=changeIndex)
{
if(changeIndex==colorIndex)
{
painter.setBrush(m_color);
changeIndex=highColorIndex;
}
else if(changeIndex==highColorIndex)
{
painter.setBrush(m_highColor);
changeIndex=m_cells;
}
}
painter.drawRect(cellRect);
cellRect.setBottom(cellRect.y()-1);
cellRect.setTop(cellRect.y()-cellHeight-1);
}
painter.setBrush(m_cellColor);
for(size_t i=cellIndex; i<m_cells; ++i)
{
painter.drawRect(cellRect);
cellRect.setBottom(cellRect.y()-1);
cellRect.setTop(cellRect.y()-cellHeight-1);
}
}
void VuMeter::paintHorizontal()
{
QPainter painter(this);
QRect rect=painter.window();
painter.setRenderHint(QPainter::Antialiasing);
int cellSpacers=m_cells+1;
int width=rect.width()-cellSpacers; //need minum 1 pixel space between blocks
int cellWidth=width/m_cells;
int extra=(rect.width()-(cellWidth*m_cells)-cellSpacers)/2;
painter.setBrush(m_backgroundColor);
painter.drawRect(rect);
int cellIndex=ceil(m_value*m_cells);
int colorIndex=ceil(0.5*m_cells);
int highColorIndex=ceil(0.75*m_cells);
if(cellIndex < 0)
cellIndex=0;
else if(cellIndex > m_cells)
cellIndex=m_cells;
QRect cellRect(rect.left(), rect.y()+1, cellWidth, rect.height()-2);
QColor currentColor=m_lowColor;
int changeIndex=colorIndex;
painter.setBrush(m_lowColor);
for(size_t i=0; i<cellIndex; ++i)
{
if(i>=changeIndex)
{
if(changeIndex==colorIndex)
{
painter.setBrush(m_color);
changeIndex=highColorIndex;
}
else if(changeIndex==highColorIndex)
{
painter.setBrush(m_highColor);
changeIndex=m_cells;
}
}
painter.drawRect(cellRect);
cellRect.translate(cellWidth+1, 0);
}
painter.setBrush(m_cellColor);
for(size_t i=cellIndex; i<m_cells; ++i)
{
painter.drawRect(cellRect);
cellRect.translate(cellWidth+1, 0);
}
}
}//namespace Limitless | 21.783654 | 93 | 0.621055 | InfiniteInteractive |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.