blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
547fa1f431a1471afb3b8242d75d4914fece5297
|
db9cc680a60997412eae035b257cc77efbcdcb06
|
/py3/leetcodeCN/hot_100/215. 数组中的第K个最大元素.cpp
|
54036a0b027816894a3c8fb50184ba8c5b06e058
|
[] |
no_license
|
Azson/machineLearning
|
9630b62c73b2388a57c630644dae3ffa8e4db236
|
35662ddf39d322009f074ce8981e5f5d27786819
|
refs/heads/master
| 2022-05-06T07:03:23.543355
| 2021-08-20T14:57:25
| 2021-08-20T14:57:25
| 179,935,258
| 3
| 3
| null | 2019-11-04T14:26:51
| 2019-04-07T08:07:08
|
Python
|
UTF-8
|
C++
| false
| false
| 598
|
cpp
|
215. 数组中的第K个最大元素.cpp
|
# include <cstdio>
# include <stack>
# include <vector>
# include <algorithm>
# include <queue>
# include <cstring>
# include <map>
using namespace std;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int> > pqe;
for (auto & x : nums) {
if (pqe.size() < k) {
pqe.push(x);
}
else if (pqe.top() < x) {
pqe.pop();
pqe.push(x);
}
}
return pqe.top();
}
};
int main() {
return 0;
}
|
5c560d1e4cced9ee139bfea0c2083f28b0c9225e
|
6a55721e06c13b6ae3c0aad722ac84341cecd346
|
/mouse.h
|
e0b72eb5b685d394283702b0cb640152ae677c69
|
[] |
no_license
|
abirbh1/mouseandcat
|
bea6ca4bfbf459bd79ab72d9c94beff5a83aec1b
|
f67c2e3a809105124cd8e568e9027906d902a0cd
|
refs/heads/main
| 2023-05-01T05:28:29.207383
| 2021-05-22T10:20:57
| 2021-05-22T10:20:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 530
|
h
|
mouse.h
|
#ifndef MOUSE_H
#define MOUSE_H
#include "map.h"
class Mouse : public Map
{
public:
Mouse();
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void setPos(int x,int y);
void move();
void setDirection(int a);
private:
int mouState=0;
int direction,nextDirection;//1 right, 2 down, 3 left, 4 up
QPixmap mou;
//up1,up2,up3,right0,right1,right2,right3,down0,down1,down2,down3,left0,left1,left2,left3;
};
#endif // MOUSE_H
|
5ad86af0aef55801df2634058646ee425efaab36
|
ae92a9930a03e7283039c9ce0f7cd809a205f859
|
/Musume/Floor.cpp
|
786601408a103333d34a5c6e1dd77e5568e07d9f
|
[] |
no_license
|
Warhammer4000/OpenGLMusume
|
07f4d4659d60367e78fe0927a45969b7e1b5beeb
|
5c9550187a47e2707c019a9272d72ac6b99a4d35
|
refs/heads/master
| 2020-12-31T04:55:38.901585
| 2016-12-28T01:09:21
| 2016-12-28T01:09:21
| 76,187,669
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,940
|
cpp
|
Floor.cpp
|
#include "Floor.h"
#include <GL\glut.h>
#include "Texture.h"
#include "TexturedCube.h"
#include "Globals.h"
#include "SolarSystem.h"
#include "BomberMan.h"
#include "Fan.h"
#include "SimplePortrait.h"
#include "BatmanLogoFrame.h"
#include "FlashPortrait.h"
#include "HumanModel.h"
#include "Tank.h"
#include "CristmasTree.h"
#include "AIUBCampus.h"
#include "BeizerCurvePortrait.h"
Floor::Floor()
{
}
Floor::~Floor()
{
}
float rotationAngle = 0;
void updateRotation() {
rotationAngle += 2.0f;
if (rotationAngle > 360) {
rotationAngle -= 360;
}
}
void drawFloor(){
glPushMatrix();//main
double width = 250;
double height = 0.1;
double lentgh = 250;
updateRotation();
glPushMatrix();//floor
glScalef(lentgh,height,width);
glColor3f(0.8,0.8,0.8);
glTranslatef(-0.5,0,0.5);
TexturedCube* floor = new TexturedCube(floorTexture,50,50);
glPopMatrix();
glPushMatrix();//roof
glColor3f(0.5, 0.5, 0.5);
glTranslatef(0, 30, 0);
glScalef(lentgh, height, width);
glTranslatef(-0.5,0,0.5);
TexturedCube* roof = new TexturedCube(roofTexture, 25,25);
glPopMatrix();
glPushMatrix();//floorwallE
glTranslatef(0, 10,width/2);
glScalef(lentgh, height+32, width/20);
glTranslatef(-0.5,-0.4,0.5);
TexturedCube* floorwallE = new TexturedCube(wallTexture, 15, 25);
glPopMatrix();
glPushMatrix();//floorwallW
glTranslatef(0, 10, -width/2);
glScalef(lentgh, height + 32, width / 20);
glRotatef(180,0,1,0);
glTranslatef(-0.5,-0.4,0.5);
TexturedCube* floorwallW = new TexturedCube(wallTexture, 15, 25);
glPopMatrix();
glPushMatrix();//floorwallN
glTranslatef(lentgh/2, 10,0);
glScalef(lentgh/20, height + 32, width);
glTranslatef(-0.5,-0.4,0.5);
TexturedCube* floorwallN = new TexturedCube(wallTexture, 15, 25);
glPopMatrix();
glPushMatrix();//floorwallS
glTranslatef(-lentgh / 2, 10, 0);
glScalef(lentgh / 20, height + 32, width);
glRotatef(180,0,1,0);
glTranslatef(-0.5,-0.4,0.5);
TexturedCube* floorwallS = new TexturedCube(wallTexture, 15, 25);
glPopMatrix();
glPushMatrix();//WallBottomL
glColor3f(1, 0.5, 0.1);
glTranslatef(-lentgh/4+lentgh/10, 10, -width/4);
glScalef((lentgh/4)- lentgh / 20, height + 22, 1);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallBottomL = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallBottomR
glColor3f(1, 0.5, 0.1);
glTranslatef(lentgh / 10, 10, -width / 4);
glScalef((lentgh / 4) - lentgh / 20, height + 22, 1);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallBottomR = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallTopL
glColor3f(1, 0.5, 0.1);
glTranslatef(-lentgh / 4 + lentgh / 10, 10, width / 4-width/20);
glScalef((lentgh / 4) - lentgh / 20, height + 22, 1);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallTopL = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallTopR
glColor3f(1, 0.5, 0.1);
glTranslatef(lentgh / 10, 10, width / 4-width/20);
glScalef((lentgh / 4) - lentgh / 20, height + 22, 1);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallTopR = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallRightL
glColor3f(1, 0.5, 0.1);
glTranslatef(-lentgh / 4, 10, -width / 4+width/10);
glScalef(1, height + 22, width/4-width/20);
glRotatef(180,0,0,1);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallRightL = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallRightR
glColor3f(1, 0.5, 0.1);
glTranslatef(-lentgh / 4, 10, width/10);
glScalef(1, height + 22, width / 4 - width / 20);
glRotatef(180,1,0,1);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallRightR = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallLeftL
glColor3f(1, 0.5, 0.1);
glTranslatef(lentgh / 4-lentgh/20, 10, -width / 4 + width / 10);
glScalef(1, height + 22, width / 4 - width / 20);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallLeftL = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
glPushMatrix();//WallLeftR
glColor3f(1, 0.5, 0.1);
glTranslatef(lentgh / 4-lentgh/20, 10, width / 10);
glScalef(1, height + 22, width / 4 - width / 20);
glTranslatef(-0.5,-0.5,0.5);
TexturedCube* WallLeftR = new TexturedCube(innerWallTexture, 5, 5);
glPopMatrix();
//Objects
//fans
glPushMatrix();
glPushMatrix();
//fan1
int fanHeight=23;
glTranslatef(0, fanHeight, 0);
glRotatef(-90, 1, 0, 0);
DrawFan();
glPopMatrix();
glPushMatrix();
//fan2
glTranslatef(lentgh/10, fanHeight, 0);
glRotatef(-90, 1, 0, 0);
DrawFan();
glPopMatrix();
glPushMatrix();
//fan3
glTranslatef(-lentgh / 10, fanHeight, 0);
glRotatef(-90, 1, 0, 0);
DrawFan();
glPopMatrix();
glPushMatrix();
//fan4
glTranslatef(0, fanHeight, width/10);
glRotatef(-90, 1, 0, 0);
DrawFan();
glPopMatrix();
glPushMatrix();
//fan5
glTranslatef(0, fanHeight, -width/10);
glRotatef(-90, 1, 0, 0);
DrawFan();
glPopMatrix();
glPopMatrix();
//BomberMan
glPushMatrix();
glScalef(4,4,4);
SetLightPosition(-1, 10, 1);
glTranslatef(lentgh / 25, 1, lentgh/25);
drawBomberMan();
glPopMatrix();
//solarSystem
glPushMatrix();
glScalef(1, 1, 1);
glTranslatef(-lentgh / 5-5, 1, -lentgh / 5-5);
drawSolarSystem();
glPopMatrix();
//humanoid
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 18, 1, -lentgh / 14);
HumanModel* HM = new HumanModel();
glPopMatrix();
//Tank
glPushMatrix();
glTranslatef(-lentgh / 5 - 5,4, lentgh / 5 - 5);
glScalef(4,4,4);
Tank* tank = new Tank();
glPopMatrix();
//Tree
glPushMatrix();
glTranslatef(-5,3,-5);
glScalef(12,12,12);
CristmasTree* t1 = new CristmasTree();
glPopMatrix();
DisableLight();
//AIUBCampus
glPushMatrix();
glTranslatef(-lentgh / 2 + 12, 2, -10);
glRotatef(-90,0,1,0);
glScalef(2,2,2);
AIUBCampus* AIUB = new AIUBCampus();
glPopMatrix();
EnableLight();
//Basic Models
//SolidCube
//SetLightPosition(1, 1,1);
glPushMatrix();
glScalef(3,3,3);
glTranslatef(lentgh/14, 1, 1);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(1, 1, 1);
glRotatef(45, 1, 1, 1);
SetDiffuse(1,1,0);
glutSolidCube(1);
DisableLight();
glPopMatrix();
////WireCube
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 3);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(1, 1, 1);
glRotatef(45, 1, 1, 1);
SetDiffuse(1, 1, 0);
glutWireCube(1);
DisableLight();
glPopMatrix();
////SolidSphere
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 5);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(1, 1, 1);
glRotatef(45, 1, 1, 1);
SetDiffuse(1, 0, 1);
glutSolidSphere(0.6, 20, 20);
DisableLight();
glPopMatrix();
////WireSphere
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 7);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(1, 1, 1);
glRotatef(45, 1, 1, 1);
SetDiffuse(1, 0, 1);
glutWireSphere(0.6, 20, 20);
DisableLight();
glPopMatrix();
////solidTorus
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 9);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(1, 1, 1);
glRotatef(45, 1, 1, 1);
SetDiffuse(0, 1, 1);
glutSolidTorus(0.3,0.6, 20, 20);
DisableLight();
glPopMatrix();
////wireTorus
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 11);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(1, 1, 1);
glRotatef(45, 1, 1, 1);
SetDiffuse(0, 1, 1);
glutWireTorus(0.3, 0.6, 20, 20);
DisableLight();
glPopMatrix();
////solidCone
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 13);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glTranslatef(0, -0.5, 0);
glScalef(1, 1, 1);
glRotatef(-120, 0, 1, 1);
SetDiffuse(0.5, 1, 0.5);
glutSolidCone(0.5, 1, 20, 20);
DisableLight();
glPopMatrix();
////wireCone
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, 15);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glTranslatef(0, -0.5, 0);
glScalef(1, 1, 1);
glRotatef(-120, 0, 1, 1);
SetDiffuse(0.5, 1, 1);
glutWireCone(0.5, 1, 20, 20);
DisableLight();
glPopMatrix();
//SolidDodecahedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -5);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(0.5, 0.5, 0.5);
glRotatef(45, 1, 1, 1);
SetDiffuse(1, 0.2, 0);
glutSolidDodecahedron();
DisableLight();
glPopMatrix();
//WireDodecahedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -7);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glScalef(0.5, 0.5, 0.5);
glRotatef(45, 1, 1, 1);
SetDiffuse(1, 0.2, 0);
glutWireDodecahedron();
DisableLight();
glPopMatrix();
//Solidcosahedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -9);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glRotatef(45, 1, 1, 1);
SetDiffuse(0.2, 1, 0);
glutSolidIcosahedron();
DisableLight();
glPopMatrix();
//Wirecosahedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -11);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glRotatef(45, 1, 1, 1);
SetDiffuse(0.2, 1, 0);
glutWireIcosahedron();
DisableLight();
glPopMatrix();
//solidOctahedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -13);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glRotatef(45, 1, 1, 1);
SetDiffuse(0.2, 0, 1);
glutSolidOctahedron();
DisableLight();
glPopMatrix();
//WireOctahedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -15);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glRotatef(45, 1, 1, 1);
SetDiffuse(0.2, 0, 1);
glutWireOctahedron();
DisableLight();
glPopMatrix();
//SolidTetraHedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -17);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glRotatef(45, 1, 1, 1);
glScalef(0.8, 0.8, 0.8);
SetDiffuse(0.5, 0.3, 0.3);
glutSolidTetrahedron();
DisableLight();
glPopMatrix();
//WireTetraHedron
glPushMatrix();
glScalef(3, 3, 3);
glTranslatef(lentgh / 14, 1, -19);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 0.2, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
glRotatef(45, 1, 1, 1);
glScalef(0.8,0.8,0.8);
SetDiffuse(0.2, 0.3, 0.3);
glutWireTetrahedron();
DisableLight();
glPopMatrix();
SetLightPosition(-1, 10, 1);
//SolidTeapot
glPushMatrix();
glTranslatef(lentgh / 2 - 10, 1,8);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 8, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
DisableLight();
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
EnableLight();
glTranslatef(0, 4, 0);
SetDiffuse(0.9, 0.9, 0.9);
glutSolidTeapot(1);
DisableLight();
glPopMatrix();
//WireTeapot
glPushMatrix();
glTranslatef(lentgh / 2 - 10, 1, -15);
glPushMatrix();
//Base
glTranslatef(0, -1, 0);
glScalef(1, 8, 1);
EnableLight();
SetDiffuse(0.8, 0.8, 0.8);
glutSolidCube(1);
DisableLight();
glPopMatrix();
glRotatef(rotationAngle, 0, 1, 0);
EnableLight();
glTranslatef(0, 4, 0);
SetDiffuse(0.9, 0.9, 0.9);
glutWireTeapot(1);
DisableLight();
glPopMatrix();
//portrait
glPushMatrix();
glTranslatef(-9,5,width/2-7);
SimplePortrait* sp = new SimplePortrait();
glPopMatrix();
//batman
glPushMatrix();
glTranslatef(-25, 5, width / 2 - 7);
BatmanLogoFrame* bf = new BatmanLogoFrame();
glPopMatrix();
//flash
glPushMatrix();
glTranslatef(8, 3, width / 2 - 7);
FlashPortrait* FP = new FlashPortrait();
glPopMatrix();
glPushMatrix();
glTranslatef(-9, 5, -width / 2 +7);
glRotatef(180, 0, 1, 0);
BeizerCurvePortrait* BCP = new BeizerCurvePortrait();
glPopMatrix();
glPopMatrix();//main end
}
|
be92b1f235be122876c056c72839d0a36448bad9
|
fa38d45e335bfdeb0e64d4f008001f9ef8151786
|
/c++/20131231/c++day02/c++day02/const.cpp
|
1594c60f7344a2efab46c49379c99ea744328d44
|
[] |
no_license
|
ipad4/MyDevelopment
|
e4ddfcb7baa17fe70897e5d73b62151620421795
|
5c4d9cb3afbb87717d08ac3230ada186f45e1fd3
|
refs/heads/master
| 2021-01-24T03:19:38.441710
| 2016-06-27T09:49:25
| 2016-06-27T09:49:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 496
|
cpp
|
const.cpp
|
//const 修饰
#include <iostream>
using namespace std;
int main(){
const int i=99;
//i=100; //常变量的值不能改变
int g=99;
int gg=88;
const int *pg=&g;
//*pg = gg; //不能通过pg 操作对应的内存
pg=≫ //但是可以改变pg的指向
/* 引用和数组的 基本实现 */
int f=123;
int ff=456;
int* const rf=&f;
//rf=&ff; //不能改变rf的指向
*rf=ff; //但是可以通过rf改变值
}
|
0cfb61e2411628eaaa2ea8f9146741ace1ec3760
|
d9d78c2fe5e397cd6fb5310a3d85881952b952a3
|
/GameEngine2D/Entity.cpp
|
460d2496a5bdb57500601bb4cea31b087961110a
|
[] |
no_license
|
GabrielPlante/GameEngine2D
|
194617be1822aa6e7c1cc8768e626ca492a31faa
|
ffd7f1bd2726f52e306be51fdbcfdabb686837d0
|
refs/heads/master
| 2023-02-07T07:02:50.709866
| 2020-12-24T23:01:09
| 2020-12-24T23:01:09
| 204,181,953
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 463
|
cpp
|
Entity.cpp
|
#include "Entity.h"
namespace ge {
IDGenerator<uint32_t> Entity::idGenerator = IDGenerator<uint32_t>{};
Entity Entity::Create(TransformComponent&& transform) {
//Create the entity
Entity entity;
//Add the component handler
ComponentHandler componentHandler{ entity };
Storage<ComponentHandler>::addComponent(std::move(componentHandler), entity);
//Add it's transform component
entity.addComponent(std::move(transform));
return entity;
}
}
|
93fbec2c460310fb38c39e0de3b559280a91ad09
|
fd4b42eb8a59fad84d899dbbafd86396d63c61c5
|
/sources/Frontend/lexer/identifiers_table.hpp
|
88557ede64026c91159f17f4bae44ab7bf5847e1
|
[
"Apache-2.0"
] |
permissive
|
MIPT-ILab-Compilers/mipt-scheme-compiler
|
7440d83bdcf7b404e5e7e06c1036f240a45079bd
|
c14fd5fb79324a42cfc0450c196f3ebdfaba4edd
|
refs/heads/master
| 2021-05-29T16:59:54.245732
| 2015-10-30T10:01:05
| 2015-10-30T10:01:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 445
|
hpp
|
identifiers_table.hpp
|
/**
* @file:identifiersTable.hpp
*/
/**
* Copyright 2012 MIPT-COMPILER team
*/
#pragma once
#include <map>
#include <string>
namespace parser
{
class IdentifiersTable
{
private :
std::map<int, std::string> map_table_priv;
int top_priv;
public:
IdentifiersTable()
: map_table_priv()
, top_priv( 1)
{}
int insert( const std::string& identifier);
std::string getIdentifier( int name) const;
};
}
|
eef4766fd9afbaac7edf1ce7cd2a12349971579f
|
55d13d3e41d8651facf7c26d60de5e8b8ace4be5
|
/ffNtuple/plugins/ffNtupleElectron.cc
|
c21b013ff571e617c5a11530351383726fbca5ad
|
[] |
no_license
|
phylsix/Firefighter
|
e8ab5fdbde2dab341a67740aa62c5710683e9bab
|
8f1d8d6e59b443a8216c70ebdd334b48945aeed0
|
refs/heads/master
| 2020-12-19T18:31:14.312639
| 2020-08-04T00:35:45
| 2020-08-04T00:35:45
| 235,812,142
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,536
|
cc
|
ffNtupleElectron.cc
|
#include <numeric>
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"
#include "DataFormats/Math/interface/LorentzVectorFwd.h"
#include "DataFormats/PatCandidates/interface/VIDCutFlowResult.h"
#include "Firefighter/ffNtuple/interface/ffNtupleBase.h"
class ffNtupleElectron : public ffNtupleBaseNoHLT {
public:
ffNtupleElectron( const edm::ParameterSet& );
void initialize( TTree&,
const edm::ParameterSet&,
edm::ConsumesCollector&& ) final;
void fill( const edm::Event&, const edm::EventSetup& ) final;
private:
void clear() final;
edm::EDGetToken fElectronToken;
edm::EDGetToken fElectronIdCutflowToken;
std::vector<edm::EDGetToken> fIdResultTokens;
const std::string fIdVersion;
const std::string fIdLabel;
const std::vector<std::string> fCutFlowNames;
const std::vector<std::string> kIdLabels{"veto", "loose", "medium", "tight"};
unsigned int fNElectron;
math::XYZTLorentzVectorFCollection fElectronP4;
std::vector<int> fElectronCharge;
std::vector<float> fElectronSCEta;
std::vector<float> fElectronSCPhi;
std::map<std::string, std::vector<float>> fCutFlowValMap;
std::vector<unsigned int> fIdBit;
std::vector<unsigned int> fIdResults;
};
DEFINE_EDM_PLUGIN( ffNtupleFactory, ffNtupleElectron, "ffNtupleElectron" );
ffNtupleElectron::ffNtupleElectron( const edm::ParameterSet& ps )
: ffNtupleBaseNoHLT( ps ),
fIdVersion( ps.getParameter<std::string>( "idVersion" ) ),
fIdLabel( ps.getParameter<std::string>( "idLabel" ) ),
fCutFlowNames( ps.getParameter<std::vector<std::string>>( "cutNames" ) ) {
assert( std::find( kIdLabels.begin(), kIdLabels.end(), fIdLabel ) != kIdLabels.end() );
}
void
ffNtupleElectron::initialize( TTree& tree,
const edm::ParameterSet& ps,
edm::ConsumesCollector&& cc ) {
fElectronToken = cc.consumes<reco::GsfElectronCollection>( ps.getParameter<edm::InputTag>( "src" ) );
fElectronIdCutflowToken = cc.consumes<edm::ValueMap<vid::CutFlowResult>>( edm::InputTag( "egmGsfElectronIDs", fIdVersion + "-" + fIdLabel ) );
for ( const auto& idLabel : kIdLabels )
fIdResultTokens.push_back( cc.consumes<edm::ValueMap<bool>>( edm::InputTag( "egmGsfElectronIDs", fIdVersion + "-" + idLabel ) ) );
tree.Branch( "electron_n", &fNElectron );
tree.Branch( "electron_p4", &fElectronP4 );
tree.Branch( "electron_charge", &fElectronCharge );
tree.Branch( "electron_scEta", &fElectronSCEta )->SetTitle( "superCluster eta" );
tree.Branch( "electron_scPhi", &fElectronSCPhi )->SetTitle( "superCluster phi" );
for ( const auto& name : fCutFlowNames ) {
fCutFlowValMap[ name ] = {};
tree.Branch( ( "electron_" + name ).c_str(), &fCutFlowValMap[ name ] )->SetTitle( ( "ID variable `" + name + "`'s value" ).c_str() );
}
tree.Branch( "electron_idbit", &fIdBit )->SetTitle( "sub-ID result for defined idLabel" );
tree.Branch( "electron_idResults", &fIdResults )->SetTitle( "ID result, encoded as bitmap" );
}
void
ffNtupleElectron::fill( const edm::Event& e, const edm::EventSetup& es ) {
using namespace std;
using namespace edm;
Handle<reco::GsfElectronCollection> electronHdl;
e.getByToken( fElectronToken, electronHdl );
assert( electronHdl.isValid() );
Handle<ValueMap<vid::CutFlowResult>> cutflowHdl;
e.getByToken( fElectronIdCutflowToken, cutflowHdl );
assert( cutflowHdl.isValid() );
vector<Handle<ValueMap<bool>>> idResultHdls( kIdLabels.size() );
for ( size_t i( 0 ); i != kIdLabels.size(); ++i ) {
e.getByToken( fIdResultTokens[ i ], idResultHdls[ i ] );
assert( idResultHdls[ i ].isValid() );
}
clear();
fNElectron = electronHdl->size();
for ( size_t iele( 0 ); iele != electronHdl->size(); iele++ ) {
Ptr<reco::GsfElectron> electronptr( electronHdl, iele );
const auto& electron = *electronptr;
fElectronP4.emplace_back( electron.px(), electron.py(), electron.pz(), electron.energy() );
fElectronCharge.emplace_back( electron.charge() );
const auto& supercluster = electron.superCluster();
fElectronSCEta.emplace_back( supercluster.isNonnull() ? supercluster->eta() : NAN );
fElectronSCPhi.emplace_back( supercluster.isNonnull() ? supercluster->phi() : NAN );
const auto& cutflow = ( *cutflowHdl )[ electronptr ];
// cout<<cutflow.cutFlowName()<<" ** "<<cutflow.cutFlowPassed()<<endl;
unsigned int idbit = 0;
for ( size_t i( 0 ); i != cutflow.cutFlowSize(); i++ ) {
const string& name = cutflow.getNameAtIndex( i );
if ( cutflow.getCutResultByIndex( i ) )
idbit |= 1 << i;
fCutFlowValMap[ name ].emplace_back( cutflow.getValueCutUpon( i ) );
}
fIdBit.emplace_back( idbit );
unsigned int idresult = 0;
for ( size_t i( 0 ); i != kIdLabels.size(); ++i ) {
if ( ( *( idResultHdls[ i ] ) )[ electronptr ] )
idresult |= 1 << i;
}
fIdResults.emplace_back( idresult );
}
}
void
ffNtupleElectron::clear() {
fNElectron = 0;
fElectronP4.clear();
fElectronCharge.clear();
fElectronSCEta.clear();
fElectronSCPhi.clear();
for ( const auto& name : fCutFlowNames )
fCutFlowValMap[ name ].clear();
fIdBit.clear();
fIdResults.clear();
}
|
f22b8f825e6813600bdfe24da27e947c7817c1ce
|
c33f78d605f5bc763d953c97d3c899fc1f9b2a52
|
/Proyecto/Area.cpp
|
dcbf0328d2c87e640803ecba190f220ca2a6c19f
|
[] |
no_license
|
kVLU10/Gestor-de-Empresa
|
247cd5b59489c4f715c25d0b8818b112e904e465
|
cc3d2e7c65d63259fc2cc2b0b4004ee28fd32ffc
|
refs/heads/master
| 2023-06-16T09:03:37.691137
| 2021-07-09T00:55:19
| 2021-07-09T00:55:19
| 367,974,499
| 0
| 2
| null | 2021-06-17T17:35:40
| 2021-05-16T20:03:29
|
C++
|
UTF-8
|
C++
| false
| false
| 101
|
cpp
|
Area.cpp
|
/**
* Project SalesSolution
*/
#include "pch.h"
#include "Area.h"
/**
* Area implementation
*/
|
db2834e8e1cb46fb89369c72117ae3bfd74cfd35
|
8f6f816f91dac0ea4bb94c8f6a07aae67da9d2bb
|
/BEA_EA_BO/limbo/model/gp.hpp
|
facfddf298cc08d741981ee3abcc0c726adae1a7
|
[] |
no_license
|
langongjin/BEA
|
069f8f763302b553cd5bcb500a670284d7132655
|
b2e2cf2d3ab0addec1dcd65db6109f2d8b147f40
|
refs/heads/master
| 2023-01-19T23:27:33.277060
| 2020-11-30T11:29:38
| 2020-11-30T11:29:38
| 297,337,817
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26,630
|
hpp
|
gp.hpp
|
//| Copyright Inria May 2015
//| This project has received funding from the European Research Council (ERC) under
//| the European Union's Horizon 2020 research and innovation programme (grant
//| agreement No 637972) - see http://www.resibots.eu
//|
//| Contributor(s):
//| - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)
//| - Antoine Cully (antoinecully@gmail.com)
//| - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)
//| - Federico Allocati (fede.allocati@gmail.com)
//| - Vaios Papaspyros (b.papaspyros@gmail.com)
//| - Roberto Rama (bertoski@gmail.com)
//|
//| This software is a computer library whose purpose is to optimize continuous,
//| black-box functions. It mainly implements Gaussian processes and Bayesian
//| optimization.
//| Main repository: http://github.com/resibots/limbo
//| Documentation: http://www.resibots.eu/limbo
//|
//| This software is governed by the CeCILL-C license under French law and
//| abiding by the rules of distribution of free software. You can use,
//| modify and/ or redistribute the software under the terms of the CeCILL-C
//| license as circulated by CEA, CNRS and INRIA at the following URL
//| "http://www.cecill.info".
//|
//| As a counterpart to the access to the source code and rights to copy,
//| modify and redistribute granted by the license, users are provided only
//| with a limited warranty and the software's author, the holder of the
//| economic rights, and the successive licensors have only limited
//| liability.
//|
//| In this respect, the user's attention is drawn to the risks associated
//| with loading, using, modifying and/or developing or reproducing the
//| software by the user in light of its specific status of free software,
//| that may mean that it is complicated to manipulate, and that also
//| therefore means that it is reserved for developers and experienced
//| professionals having in-depth computer knowledge. Users are therefore
//| encouraged to load and test the software's suitability as regards their
//| requirements in conditions enabling the security of their systems and/or
//| data to be ensured and, more generally, to use and operate it in the
//| same conditions as regards security.
//|
//| The fact that you are presently reading this means that you have had
//| knowledge of the CeCILL-C license and that you accept its terms.
//|
#ifndef LIMBO_MODEL_GP_HPP
#define LIMBO_MODEL_GP_HPP
#include <cassert>
#include <iostream>
#include <limits>
#include <vector>
#include <Eigen/Cholesky>
#include <Eigen/Core>
#include <Eigen/LU>
// Quick hack for definition of 'I' in <complex.h>
#undef I
//#include "kernel/matern_three_halves.hpp>
#include "kernel/matern_five_halves.hpp"
#include "kernel/squared_exp_ard.hpp"
#include "mean/constant.hpp"
#include "mean/data.hpp"
#include "model/gp/kernel_lf_opt.hpp"
#include "model/gp/no_lf_opt.hpp"
#include "tools.hpp"
namespace limbo {
namespace model {
/// @ingroup model
/// A classic Gaussian process.
/// It is parametrized by:
/// - a kernel function
/// - a mean function
/// - [optional] an optimizer for the hyper-parameters
template <typename Params, typename KernelFunction = kernel::MaternFiveHalves<Params>, typename MeanFunction = mean::Data<Params>, typename HyperParamsOptimizer = gp::NoLFOpt<Params>>
class GP {
public:
/// useful because the model might be created before knowing anything about the process
GP() : _dim_in(-1), _dim_out(-1), _inv_kernel_updated(false) {}
/// useful because the model might be created before having samples
GP(int dim_in, int dim_out)
: _dim_in(dim_in), _dim_out(dim_out), _kernel_function(dim_in), _mean_function(dim_out), _inv_kernel_updated(false) {}
/// Compute the GP from samples and observations. This call needs to be explicit!
void compute(const std::vector<Eigen::VectorXd>& samples,
const std::vector<Eigen::VectorXd>& observations, bool compute_kernel = true)
{
assert(samples.size() != 0);
assert(observations.size() != 0);
assert(samples.size() == observations.size());
if (_dim_in != samples[0].size()) {
_dim_in = samples[0].size();
_kernel_function = KernelFunction(_dim_in); // the cost of building a functor should be relatively low
}
if (_dim_out != observations[0].size()) {
_dim_out = observations[0].size();
_mean_function = MeanFunction(_dim_out); // the cost of building a functor should be relatively low
}
_samples = samples;
_observations.resize(observations.size(), _dim_out);
for (int i = 0; i < _observations.rows(); ++i)
_observations.row(i) = observations[i];
_mean_observation = _observations.colwise().mean();
this->_compute_obs_mean();
if (compute_kernel)
this->_compute_full_kernel();
}
/// Do not forget to call this if you use hyper-prameters optimization!!
void optimize_hyperparams()
{
_hp_optimize(*this);
}
/// add sample and update the GP. This code uses an incremental implementation of the Cholesky
/// decomposition. It is therefore much faster than a call to compute()
void add_sample(const Eigen::VectorXd& sample, const Eigen::VectorXd& observation)
{
if (_samples.empty()) {
if (_dim_in != sample.size()) {
_dim_in = sample.size();
_kernel_function = KernelFunction(_dim_in); // the cost of building a functor should be relatively low
}
if (_dim_out != observation.size()) {
_dim_out = observation.size();
_mean_function = MeanFunction(_dim_out); // the cost of building a functor should be relatively low
}
}
else {
assert(sample.size() == _dim_in);
assert(observation.size() == _dim_out);
}
_samples.push_back(sample);
_observations.conservativeResize(_observations.rows() + 1, _dim_out);
_observations.bottomRows<1>() = observation.transpose();
_mean_observation = _observations.colwise().mean();
this->_compute_obs_mean();
this->_compute_incremental_kernel();
}
/**
\\rst
return :math:`\mu`, :math:`\sigma^2` (unormalized). If there is no sample, return the value according to the mean function. Using this method instead of separate calls to mu() and sigma() is more efficient because some computations are shared between mu() and sigma().
\\endrst
*/
std::tuple<Eigen::VectorXd, double> query(const Eigen::VectorXd& v) const
{
if (_samples.size() == 0)
return std::make_tuple(_mean_function(v, *this),
_kernel_function(v, v));
Eigen::VectorXd k = _compute_k(v);
return std::make_tuple(_mu(v, k), _sigma(v, k));
}
/**
\\rst
return :math:`\mu` (unormalized). If there is no sample, return the value according to the mean function.
\\endrst
*/
Eigen::VectorXd mu(const Eigen::VectorXd& v) const
{
if (_samples.size() == 0)
return _mean_function(v, *this);
return _mu(v, _compute_k(v));
}
/**
\\rst
return :math:`\sigma^2` (unormalized). If there is no sample, return the max :math:`\sigma^2`.
\\endrst
*/
double sigma(const Eigen::VectorXd& v) const
{
if (_samples.size() == 0)
return _kernel_function(v, v);
return _sigma(v, _compute_k(v));
}
/// return the number of dimensions of the input
int dim_in() const
{
assert(_dim_in != -1); // need to compute first !
return _dim_in;
}
/// return the number of dimensions of the output
int dim_out() const
{
assert(_dim_out != -1); // need to compute first !
return _dim_out;
}
const KernelFunction& kernel_function() const { return _kernel_function; }
KernelFunction& kernel_function() { return _kernel_function; }
const MeanFunction& mean_function() const { return _mean_function; }
MeanFunction& mean_function() { return _mean_function; }
/// return the maximum observation (only call this if the output of the GP is of dimension 1)
Eigen::VectorXd max_observation() const
{
if (_observations.cols() > 1)
std::cout << "WARNING max_observation with multi dimensional "
"observations doesn't make sense"
<< std::endl;
return tools::make_vector(_observations.maxCoeff());
}
/// return the mean observation (only call this if the output of the GP is of dimension 1)
Eigen::VectorXd mean_observation() const
{
// TODO: Check if _dim_out is correct?!
return _samples.size() > 0 ? _mean_observation
: Eigen::VectorXd::Zero(_dim_out);
}
const Eigen::MatrixXd& mean_vector() const { return _mean_vector; }
const Eigen::MatrixXd& obs_mean() const { return _obs_mean; }
/// return the number of samples used to compute the GP
int nb_samples() const { return _samples.size(); }
/// recomputes the GP
void recompute(bool update_obs_mean = true, bool update_full_kernel = true)
{
assert(!_samples.empty());
if (update_obs_mean)
this->_compute_obs_mean();
if (update_full_kernel)
this->_compute_full_kernel();
else
this->_compute_alpha();
}
void compute_inv_kernel()
{
size_t n = _obs_mean.rows();
// K^{-1} using Cholesky decomposition
_inv_kernel = Eigen::MatrixXd::Identity(n, n);
_matrixL.template triangularView<Eigen::Lower>().solveInPlace(_inv_kernel);
_matrixL.template triangularView<Eigen::Lower>().transpose().solveInPlace(_inv_kernel);
_inv_kernel_updated = true;
}
/// compute and return the log likelihood
double compute_log_lik()
{
size_t n = _obs_mean.rows();
// --- cholesky ---
// see:
// http://xcorr.net/2008/06/11/log-determinant-of-positive-definite-matrices-in-matlab/
long double det = 2 * _matrixL.diagonal().array().log().sum();
double a = (_obs_mean.transpose() * _alpha)
.trace(); // generalization for multi dimensional observation
_log_lik = -0.5 * a - 0.5 * det - 0.5 * n * std::log(2 * M_PI);
return _log_lik;
}
/// compute and return the gradient of the log likelihood wrt to the kernel parameters
Eigen::VectorXd compute_kernel_grad_log_lik()
{
size_t n = _obs_mean.rows();
// compute K^{-1} only if needed
if (!_inv_kernel_updated) {
compute_inv_kernel();
}
Eigen::MatrixXd w = _inv_kernel;
// alpha * alpha.transpose() - K^{-1}
w = _alpha * _alpha.transpose() - w;
// only compute half of the matrix (symmetrical matrix)
Eigen::VectorXd grad = Eigen::VectorXd::Zero(_kernel_function.h_params_size());
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j <= i; ++j) {
Eigen::VectorXd g = _kernel_function.grad(_samples[i], _samples[j], i, j);
if (i == j)
grad += w(i, j) * g * 0.5;
else
grad += w(i, j) * g;
}
}
return grad;
}
/// compute and return the gradient of the log likelihood wrt to the mean parameters
Eigen::VectorXd compute_mean_grad_log_lik()
{
size_t n = _obs_mean.rows();
// compute K^{-1} only if needed
if (!_inv_kernel_updated) {
compute_inv_kernel();
}
Eigen::VectorXd grad = Eigen::VectorXd::Zero(_mean_function.h_params_size());
for (int i_obs = 0; i_obs < _dim_out; ++i_obs)
for (size_t n_obs = 0; n_obs < n; n_obs++) {
grad += _obs_mean.col(i_obs).transpose() * _inv_kernel.col(n_obs) * _mean_function.grad(_samples[n_obs], *this).row(i_obs);
}
return grad;
}
/// return the likelihood (do not compute it -- return last computed)
double get_log_lik() const { return _log_lik; }
/// set the log likelihood (e.g. computed from outside)
void set_log_lik(double log_lik) { _log_lik = log_lik; }
/// compute and return the log probability of LOO CV
double compute_log_loo_cv()
{
// compute K^{-1} only if needed
if (!_inv_kernel_updated) {
compute_inv_kernel();
}
Eigen::VectorXd inv_diag = _inv_kernel.diagonal().array().inverse();
_log_loo_cv = (((-0.5 * (_alpha.array().square().array().colwise() * inv_diag.array())).array().colwise() - 0.5 * inv_diag.array().log().array()) - 0.5 * std::log(2 * M_PI)).colwise().sum().sum();
return _log_loo_cv;
}
/// compute and return the gradient of the log probability of LOO CV wrt to the kernel parameters
Eigen::VectorXd compute_kernel_grad_log_loo_cv()
{
size_t n = _obs_mean.rows();
size_t n_params = _kernel_function.h_params_size();
// compute K^{-1} only if needed
if (!_inv_kernel_updated) {
compute_inv_kernel();
}
Eigen::VectorXd grad = Eigen::VectorXd::Zero(n_params);
Eigen::MatrixXd grads = Eigen::MatrixXd::Zero(n_params, _dim_out);
// only compute half of the matrix (symmetrical matrix)
// TO-DO: Make it better
std::vector<std::vector<Eigen::VectorXd>> full_dk;
for (size_t i = 0; i < n; i++) {
full_dk.push_back(std::vector<Eigen::VectorXd>());
for (size_t j = 0; j <= i; j++)
full_dk[i].push_back(_kernel_function.grad(_samples[i], _samples[j], i, j));
for (size_t j = i + 1; j < n; j++)
full_dk[i].push_back(Eigen::VectorXd::Zero(n_params));
}
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < i; ++j)
full_dk[j][i] = full_dk[i][j];
Eigen::VectorXd inv_diag = _inv_kernel.diagonal().array().inverse();
for (int j = 0; j < grad.size(); j++) {
Eigen::MatrixXd dKdTheta_j = Eigen::MatrixXd::Zero(n, n);
for (size_t i = 0; i < n; i++) {
for (size_t k = 0; k < n; k++)
dKdTheta_j(i, k) = full_dk[i][k](j);
}
Eigen::MatrixXd Zeta_j = _inv_kernel * dKdTheta_j;
Eigen::MatrixXd Zeta_j_alpha = Zeta_j * _alpha;
Eigen::MatrixXd Zeta_j_K = Zeta_j * _inv_kernel;
grads.row(j) = ((_alpha.array() * Zeta_j_alpha.array() - 0.5 * ((1. + _alpha.array().square().array().colwise() * inv_diag.array()).array().colwise() * Zeta_j_K.diagonal().array())).array().colwise() * inv_diag.array()).colwise().sum();
// for (size_t i = 0; i < n; i++)
// grads.row(j).array() += (_alpha.row(i).array() * Zeta_j_alpha.row(i).array() - 0.5 * (1. + _alpha.row(i).array().square() / _inv_kernel.diagonal()(i)) * Zeta_j_K.diagonal()(i)) / _inv_kernel.diagonal()(i);
}
grad = grads.rowwise().sum();
return grad;
}
/// return the LOO-CV log probability (do not compute it -- return last computed)
double get_log_loo_cv() const { return _log_loo_cv; }
/// set the LOO-CV log probability (e.g. computed from outside)
void set_log_loo_cv(double log_loo_cv) { _log_loo_cv = log_loo_cv; }
/// LLT matrix (from Cholesky decomposition)
//const Eigen::LLT<Eigen::MatrixXd>& llt() const { return _llt; }
const Eigen::MatrixXd& matrixL() const { return _matrixL; }
const Eigen::MatrixXd& alpha() const { return _alpha; }
/// return the list of samples that have been tested so far
const std::vector<Eigen::VectorXd>& samples() const { return _samples; }
bool inv_kernel_computed() { return _inv_kernel_updated; }
/// save the parameters and the data for the GP to the archive (text or binary)
template <typename A>
void save(const std::string& directory)
{
A archive(directory);
save(archive);
}
/// save the parameters and the data for the GP to the archive (text or binary)
template <typename A>
void save(const A& archive)
{
if (_kernel_function.h_params_size() > 0) {
archive.save(_kernel_function.h_params(), "kernel_params");
}
if (_mean_function.h_params_size() > 0) {
archive.save(_mean_function.h_params(), "mean_params");
}
archive.save(_samples, "samples");
archive.save(_observations, "observations");
archive.save(_matrixL, "matrixL");
archive.save(_alpha, "alpha");
}
/// load the parameters and the data for the GP from the archive (text or binary)
/// if recompute is true, we do not read the kernel matrix
/// but we recompute it given the data and the hyperparameters
template <typename A>
void load(const std::string& directory, bool recompute = true)
{
A archive(directory);
load(archive, recompute);
}
/// load the parameters and the data for the GP from the archive (text or binary)
/// if recompute is true, we do not read the kernel matrix
/// but we recompute it given the data and the hyperparameters
template <typename A>
void load(const A& archive, bool recompute = true)
{
_samples.clear();
archive.load(_samples, "samples");
archive.load(_observations, "observations");
_dim_in = _samples[0].size();
_kernel_function = KernelFunction(_dim_in);
if (_kernel_function.h_params_size() > 0) {
Eigen::VectorXd h_params;
archive.load(h_params, "kernel_params");
assert(h_params.size() == (int)_kernel_function.h_params_size());
_kernel_function.set_h_params(h_params);
}
_dim_out = _observations.cols();
_mean_function = MeanFunction(_dim_out);
if (_mean_function.h_params_size() > 0) {
Eigen::VectorXd h_params;
archive.load(h_params, "mean_params");
assert(h_params.size() == (int)_mean_function.h_params_size());
_mean_function.set_h_params(h_params);
}
_mean_observation = _observations.colwise().mean();
if (recompute)
this->recompute(true, true);
else {
archive.load(_matrixL, "matrixL");
archive.load(_alpha, "alpha");
}
}
protected:
int _dim_in;
int _dim_out;
KernelFunction _kernel_function;
MeanFunction _mean_function;
std::vector<Eigen::VectorXd> _samples;
Eigen::MatrixXd _observations;
Eigen::MatrixXd _mean_vector;
Eigen::MatrixXd _obs_mean;
Eigen::MatrixXd _alpha;
Eigen::VectorXd _mean_observation;
Eigen::MatrixXd _kernel, _inv_kernel;
Eigen::MatrixXd _matrixL;
double _log_lik, _log_loo_cv;
bool _inv_kernel_updated;
HyperParamsOptimizer _hp_optimize;
void _compute_obs_mean()
{
assert(!_samples.empty());
_mean_vector.resize(_samples.size(), _dim_out);
for (int i = 0; i < _mean_vector.rows(); i++) {
assert(_samples[i].cols() == 1);
assert(_samples[i].rows() != 0);
assert(_samples[i].rows() == _dim_in);
_mean_vector.row(i) = _mean_function(_samples[i], *this);
}
_obs_mean = _observations - _mean_vector;
}
void _compute_full_kernel()
{
size_t n = _samples.size();
_kernel.resize(n, n);
// O(n^2) [should be negligible]
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j <= i; ++j)
_kernel(i, j) = _kernel_function(_samples[i], _samples[j], i, j);
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < i; ++j)
_kernel(j, i) = _kernel(i, j);
// O(n^3)
_matrixL = Eigen::LLT<Eigen::MatrixXd>(_kernel).matrixL();
this->_compute_alpha();
// notify change of kernel
_inv_kernel_updated = false;
}
void _compute_incremental_kernel()
{
// Incremental LLT
// This part of the code is inpired from the Bayesopt Library (cholesky_add_row function).
// However, the mathematical fundations can be easily retrieved by detailling the equations of the
// extended L matrix that produces the desired kernel.
size_t n = _samples.size();
_kernel.conservativeResize(n, n);
for (size_t i = 0; i < n; ++i) {
_kernel(i, n - 1) = _kernel_function(_samples[i], _samples[n - 1], i, n - 1);
_kernel(n - 1, i) = _kernel(i, n - 1);
}
_matrixL.conservativeResizeLike(Eigen::MatrixXd::Zero(n, n));
double L_j;
for (size_t j = 0; j < n - 1; ++j) {
L_j = _kernel(n - 1, j) - (_matrixL.block(j, 0, 1, j) * _matrixL.block(n - 1, 0, 1, j).transpose())(0, 0);
_matrixL(n - 1, j) = (L_j) / _matrixL(j, j);
}
L_j = _kernel(n - 1, n - 1) - (_matrixL.block(n - 1, 0, 1, n - 1) * _matrixL.block(n - 1, 0, 1, n - 1).transpose())(0, 0);
_matrixL(n - 1, n - 1) = sqrt(L_j);
this->_compute_alpha();
// notify change of kernel
_inv_kernel_updated = false;
}
void _compute_alpha()
{
// alpha = K^{-1} * this->_obs_mean;
Eigen::TriangularView<Eigen::MatrixXd, Eigen::Lower> triang = _matrixL.template triangularView<Eigen::Lower>();
_alpha = triang.solve(_obs_mean);
triang.adjoint().solveInPlace(_alpha);
}
Eigen::VectorXd _mu(const Eigen::VectorXd& v, const Eigen::VectorXd& k) const
{
return (k.transpose() * _alpha) + _mean_function(v, *this).transpose();
}
double _sigma(const Eigen::VectorXd& v, const Eigen::VectorXd& k) const
{
Eigen::VectorXd z = _matrixL.triangularView<Eigen::Lower>().solve(k);
double res = _kernel_function(v, v) - z.dot(z);
return (res <= std::numeric_limits<double>::epsilon()) ? 0 : res;
}
Eigen::VectorXd _compute_k(const Eigen::VectorXd& v) const
{
Eigen::VectorXd k(_samples.size());
for (int i = 0; i < k.size(); i++)
k[i] = _kernel_function(_samples[i], v);
return k;
}
};
/// GPBasic is a GP with a "mean data" mean function, Exponential kernel,
/// and NO hyper-parameter optimization
template <typename Params>
using GPBasic = GP<Params, kernel::MaternFiveHalves<Params>, mean::Data<Params>, gp::NoLFOpt<Params>>;
/// GPOpt is a GP with a "mean data" mean function, Exponential kernel with Automatic Relevance
/// Determination (ARD), and hyper-parameter optimization based on Rprop
template <typename Params>
using GPOpt = GP<Params, kernel::SquaredExpARD<Params>, mean::Data<Params>, gp::KernelLFOpt<Params>>;
} // namespace model
} // namespace limbo
#endif
|
4c5b60b2187010d9ea41b69a9d2b73bf9c439b48
|
b62eadc0e91874165acd809b799192fb00f232e4
|
/Pokemon/Datas.cpp
|
406512e9a5ef353d070d0be32029c20d33ef2d43
|
[] |
no_license
|
molinadejan/Pokemon-Gold
|
a02de2d3561f6fae77741144dfadbf523f0c4afa
|
1ef0f6051d47c46c731303867f006b8b032d1abc
|
refs/heads/main
| 2023-07-13T12:44:28.111619
| 2021-08-21T08:37:21
| 2021-08-21T08:37:21
| 389,046,906
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,178
|
cpp
|
Datas.cpp
|
#include "Datas.h"
#include "PokemonCalculator.h"
#include "DataLoadManager.h"
#include "MyUtils.h"
Tile::Tile()
: pos{ 0, 0 }, tilePos{ -1, -1 }, moveable(0), interactID(-1), isPokemon(0) { }
Map::Map()
: ID(""), music(""), worldPos{ 0, 0 }, mapSize{ -1, -1 } { }
Map::Map(string _ID, int x, int y) : ID(_ID), music(""), worldPos{ 0, 0 }, mapSize{ x, y }
{
tiles = vector<vector<Tile>>(y, vector<Tile>(x, Tile()));
neighbors = vector<string>();
movePoints = vector<MovePoint>();
for (int i = 0; i < y; ++i)
for (int j = 0; j < x; ++j)
tiles[i][j].pos = { j, i };
}
Tile* Map::GetTile(const Point& localPos)
{
if(localPos.X < 0 || localPos.Y < 0 || localPos.X >= mapSize.X || localPos.Y >= mapSize.Y)
return NULL;
return &(tiles[localPos.Y][localPos.X]);
}
MovePoint* Map::GetMovePoint(const Point& localPos)
{
for (int i = 0; i < (int)movePoints.size(); ++i)
if (movePoints[i].pos.X == localPos.X && movePoints[i].pos.Y == localPos.Y)
return &(movePoints[i]);
return NULL;
}
Point MovePoint::GetDir()
{
if (moveType % 4 == 0) return Point( 0, -1);
if (moveType % 4 == 1) return Point(-1, 0);
if (moveType % 4 == 2) return Point( 0, 1);
if (moveType % 4 == 3) return Point( 1, 0);
return Point(0, 0);
}
bool MovePoint::isDoor()
{
return moveType >= 4;
}
bool MovePoint::isCarpet()
{
return moveType < 4;
}
// 포켓몬 개체 데이터 생성
PokemonIndiv::PokemonIndiv(int _id, int _level)
{
id = _id;
PokemonData* data = DM::GetPokemonData(_id);
level = _level + rand() % 3 - 1;
exp = 0;
nextExp = CalNextExp(id, level + 1);
gender = rand() % 2;
maxHP = hp = CalHP(data->HP, level);
ATK_stat = CalStat(data->ATK, level);
DEF_stat = CalStat(data->DEF, level);
SPA_stat = CalStat(data->SPA, level);
SPD_stat = CalStat(data->SPD, level);
SPE_stat = CalStat(data->SPE, level);
statusEffect = 0;
skills[0] = skills[1] = skills[2] = skills[3] = -1;
pps[0] = pps[1] = pps[2] = pps[3] = 0;
int skillCnt = 0;
for (const auto& e : data->learn_skill)
{
if (e.first <= level)
skills[skillCnt++] = e.second;
if (skillCnt == 3)
break;
}
for (int i = 0; i < 4; ++i)
{
if (skills[i] != -1)
{
SkillData* data = DM::GetSkillData(skills[i]);
pps[i] = data->pp;
}
}
}
PokemonBattleData::PokemonBattleData()
: ATK_rank(0), DEF_rank(0), SPA_rank(0), SPD_rank(0), SPE_rank(0), hit_rank(0), vital_rank(0)
{ }
void PokemonBattleData::Reset()
{
ATK_rank = 0;
DEF_rank = 0;
SPA_rank = 0;
SPD_rank = 0;
SPE_rank = 0;
hit_rank = 0;
vital_rank = 0;
}
PlayerData::PlayerData() {}
Tile* GetTile(Map* m, Point pos)
{
if (IsIn(pos, m->mapSize))
return &(m->tiles[pos.Y][pos.X]);
Point worldPos = pos + m->worldPos;
for (const string& n : m->neighbors)
{
Map* nMap = DataLoadManager::GetMapData(n);
Point nLocal = worldPos - nMap->worldPos;
if (IsIn(nLocal, nMap->mapSize))
return &(nMap->tiles[nLocal.Y][nLocal.X]);
}
return NULL;
}
Map* GetNMap(Map* m, Point pos)
{
Point worldPos = pos + m->worldPos;
for (const string& nID : m->neighbors)
{
Map* n = DataLoadManager::GetMapData(nID);
if (IsIn(worldPos, n->worldPos, n->mapSize))
return n;
}
return NULL;
}
|
ce584f66d7beb6fb257e499da8ffbca625687131
|
06da4550b187a16044d24ed9c5a676cb9de2496c
|
/vpn/openvpn/openvpnauth.cpp
|
99c4a5e4db80a5700fda1e4205ffbb73d990e06f
|
[] |
no_license
|
KDE/plasma-nm
|
26a2653de3879622ffd3577547342c5fb0d9e93e
|
6095e17c34cc140911a84e98fe5a817a3b883bde
|
refs/heads/master
| 2023-08-17T10:34:15.701670
| 2023-08-17T02:15:48
| 2023-08-17T02:15:48
| 42,725,602
| 44
| 43
| null | 2023-03-29T01:16:38
| 2015-09-18T14:00:29
|
C++
|
UTF-8
|
C++
| false
| false
| 6,052
|
cpp
|
openvpnauth.cpp
|
/*
SPDX-FileCopyrightText: 2011 Ilia Kats <ilia-kats@gmx.net>
SPDX-FileCopyrightText: 2013 Lukáš Tinkl <ltinkl@redhat.com>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "openvpnauth.h"
#include "passwordfield.h"
#include <QCheckBox>
#include <QFormLayout>
#include <QLabel>
#include <QString>
#include <KLocalizedString>
#include "nm-openvpn-service.h"
#include "plasma_nm_openvpn.h"
class OpenVpnAuthWidgetPrivate
{
public:
NetworkManager::VpnSetting::Ptr setting;
QFormLayout *layout;
};
OpenVpnAuthWidget::OpenVpnAuthWidget(const NetworkManager::VpnSetting::Ptr &setting, const QStringList &hints, QWidget *parent)
: SettingWidget(setting, hints, parent)
, d_ptr(new OpenVpnAuthWidgetPrivate)
{
Q_D(OpenVpnAuthWidget);
d->setting = setting;
d->layout = new QFormLayout(this);
setLayout(d->layout);
readSecrets();
KAcceleratorManager::manage(this);
}
OpenVpnAuthWidget::~OpenVpnAuthWidget()
{
delete d_ptr;
}
void OpenVpnAuthWidget::readSecrets()
{
Q_D(OpenVpnAuthWidget);
const NMStringMap dataMap = d->setting->data();
const NMStringMap secrets = d->setting->secrets();
const QString cType = dataMap[NM_OPENVPN_KEY_CONNECTION_TYPE];
NetworkManager::Setting::SecretFlags certType = (NetworkManager::Setting::SecretFlags)dataMap.value(NM_OPENVPN_KEY_CERTPASS "-flags").toInt();
NetworkManager::Setting::SecretFlags passType = (NetworkManager::Setting::SecretFlags)dataMap.value(NM_OPENVPN_KEY_PASSWORD "-flags").toInt();
NetworkManager::Setting::SecretFlags proxyType = (NetworkManager::Setting::SecretFlags)dataMap.value(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD "-flags").toInt();
// If hints are given, then always ask for what the hints require
if (!m_hints.isEmpty()) {
QString passwordType;
QString prompt;
for (const QString &hint : std::as_const(m_hints)) {
const QString vpnMessage = QStringLiteral("x-vpn-message:");
if (hint.startsWith(vpnMessage)) {
prompt = hint.right(hint.length() - vpnMessage.length());
} else {
passwordType = hint;
}
}
if (prompt.isEmpty()) {
if (passwordType == QLatin1String(NM_OPENVPN_KEY_CERTPASS)) {
prompt = i18n("Key Password:");
} else if (passwordType == QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD)) {
prompt = i18n("Proxy Password:");
} else {
prompt = i18n("Password:");
}
} else if (prompt.endsWith(QLatin1Char('.'))) {
prompt = prompt.replace(prompt.length() - 1, 1, QLatin1Char(':'));
} else if (!prompt.endsWith(QLatin1Char(':'))) {
prompt += QLatin1Char(':');
}
bool isOTP = false;
QStringList possibleTokens = {i18n("OTP"), i18n("authenticator"), i18n("code"), i18n("token"), i18n("one-time password")};
for (const QString &possibleToken : possibleTokens) {
if (prompt.toLower().contains(possibleToken.toLower())) {
isOTP = true;
break;
}
}
addPasswordField(prompt, QString(), passwordType, !isOTP);
} else {
if (cType == QLatin1String(NM_OPENVPN_CONTYPE_TLS) || cType == QLatin1String(NM_OPENVPN_CONTYPE_PASSWORD_TLS)) {
// Normal user password
if (cType == QLatin1String(NM_OPENVPN_CONTYPE_PASSWORD_TLS) && !passType.testFlag(NetworkManager::Setting::NotRequired)) {
addPasswordField(i18n("Password:"), secrets.value(QStringLiteral(NM_OPENVPN_KEY_PASSWORD)), QLatin1String(NM_OPENVPN_KEY_PASSWORD));
}
// Encrypted private key password
if (dataMap.contains(QLatin1String(NM_OPENVPN_KEY_KEY)) && !certType.testFlag(NetworkManager::Setting::NotRequired)) {
addPasswordField(i18n("Key Password:"), secrets.value(QStringLiteral(NM_OPENVPN_KEY_CERTPASS)), QLatin1String(NM_OPENVPN_KEY_CERTPASS));
}
} else if (cType == QLatin1String(NM_OPENVPN_CONTYPE_PASSWORD)) {
addPasswordField(i18n("Password:"), secrets.value(QStringLiteral(NM_OPENVPN_KEY_PASSWORD)), QLatin1String(NM_OPENVPN_KEY_PASSWORD));
}
if (dataMap.contains(NM_OPENVPN_KEY_PROXY_SERVER) && !proxyType.testFlag(NetworkManager::Setting::NotRequired)) {
addPasswordField(i18n("Proxy Password:"),
secrets.value(QStringLiteral(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD)),
QLatin1String(NM_OPENVPN_KEY_HTTP_PROXY_PASSWORD));
}
}
for (int i = 0; i < d->layout->rowCount(); i++) {
auto le = qobject_cast<PasswordField *>(d->layout->itemAt(i, QFormLayout::FieldRole)->widget());
if (le && le->text().isEmpty()) {
le->setFocus(Qt::OtherFocusReason);
break;
}
}
}
QVariantMap OpenVpnAuthWidget::setting() const
{
Q_D(const OpenVpnAuthWidget);
NMStringMap secrets;
QVariantMap secretData;
for (int i = 0; i < d->layout->rowCount(); i++) {
auto le = qobject_cast<PasswordField *>(d->layout->itemAt(i, QFormLayout::FieldRole)->widget());
if (le && !le->text().isEmpty()) {
const QString key = le->property("nm_secrets_key").toString();
secrets.insert(key, le->text());
}
}
secretData.insert("secrets", QVariant::fromValue<NMStringMap>(secrets));
return secretData;
}
void OpenVpnAuthWidget::addPasswordField(const QString &labelText, const QString &password, const QString &secretKey, bool passwordMode)
{
Q_D(const OpenVpnAuthWidget);
auto label = new QLabel(this);
label->setText(labelText);
auto lineEdit = new PasswordField(this);
lineEdit->setPasswordModeEnabled(passwordMode);
lineEdit->setProperty("nm_secrets_key", secretKey);
lineEdit->setText(password);
d->layout->addRow(label, lineEdit);
}
#include "moc_openvpnauth.cpp"
|
d25aabe0cd002fe74db78dc3bc182fad81bc087c
|
ac7c2e64fa66ec7aecc9cf810cb2bf013fd412c0
|
/Baruch_C++/Level_4/Section_2_5/Ex_2_5_3/Source.cpp
|
bb56322c2c1efdc92bd30c07ff2c0bd3e5e2a152
|
[] |
no_license
|
mistletoe999/cpp-samples
|
e7219fcf7dbfe5ddc81cb527f08cd9d55149774a
|
7b5cb634c70d3de476c0d43e15f7a045458dc925
|
refs/heads/master
| 2020-12-25T15:40:30.402680
| 2015-06-23T04:32:50
| 2015-06-23T04:32:50
| 40,014,976
| 0
| 1
| null | 2015-07-31T16:43:13
| 2015-07-31T16:43:10
|
C++
|
UTF-8
|
C++
| false
| false
| 1,982
|
cpp
|
Source.cpp
|
// Ex_2.5.3: Demonstrates the use of dynamic memory alocation
// for classes
// Implements an Array container class
#include "Point.hpp"
#include "Array.hpp"
int main() {
// Testing the default constructor
cout << "Testing the default constructor" << endl;
cout << "==================================================" << endl;
Array * arr = new Array();
delete arr;
arr = 0;
cout << endl;
// Testing the constructor with size parameter
unsigned int arraySize = 3;
cout << "Testing the constructor with size parameter = " << arraySize << endl;
cout << "==================================================" << endl;
arr = new Array(arraySize);
delete arr;
arr = 0;
cout << "Testing the getter, setter, [], and assignment operator" << endl;
cout << "==================================================" << endl;
arr = new Array(arraySize);
Array * arr1 = new Array();
for (int i = 0; i < arraySize; i++)
{
arr->SetElement(i, Point(i, i + 1));
cout << "Element " << (i + 1) << " of arr: " << arr->GetElement(i) << endl;
(*arr1)[i] = Point(2*i, 2*i + 1);
cout << "Element " << (i + 1) << "of arr1: " << (*arr1)[i] << endl;
}
*arr1 = *arr; // Checking the assignment operator
cout << "*arr1 = *arr yields:" << endl;
for (int i = 0; i < arraySize; i++)
{
cout << "Element " << (i + 1) << " of arr1: " << (*arr1)[i] << endl;
}
cout << "Testing the copy constructor" << endl;
cout << "==================================================" << endl;
Array arr2 = Array(*arr); // Defining arr2 on the stack
cout << "Initiated arr2 on stack using copy constructor. Size = " << arr2.Size() << endl;
for (int i = 0; i < arraySize; i++)
{
cout << "Element " << (i + 1) << " of arr2: " << arr2[i] << endl;
}
cout << "Now, arr = arr1 = arr2; " << arraySize << " destructor calls = " << 3*arraySize << " Point objects deleted" << endl;
delete arr;
delete arr1;
return 0;
}
|
6c25c94a729a9b40225bfa0406cd8ea47c3f7cf7
|
5e8be2ac3fefbdb980b2b107c3f74b32aea300e2
|
/src/vt/objgroup/dispatch/dispatch_base.h
|
8019d4e7b2a1143b2dfcc4f3648d2e443437315a
|
[
"BSD-3-Clause"
] |
permissive
|
YouCannotBurnMyShadow/vt
|
23b73b531f0b9bdfcea41eb5b73c903805bd5170
|
8bbcce879f6dd5e125cf8908b41baded077dfcbe
|
refs/heads/master
| 2023-03-18T22:16:32.288410
| 2021-01-11T20:37:31
| 2021-01-11T20:37:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,137
|
h
|
dispatch_base.h
|
/*
//@HEADER
// *****************************************************************************
//
// dispatch_base.h
// DARMA Toolkit v. 1.0.0
// DARMA/vt => Virtual Transport
//
// Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// 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 copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
// Questions? Contact darma@sandia.gov
//
// *****************************************************************************
//@HEADER
*/
#if !defined INCLUDED_VT_OBJGROUP_DISPATCH_DISPATCH_BASE_H
#define INCLUDED_VT_OBJGROUP_DISPATCH_DISPATCH_BASE_H
#include "vt/config.h"
#include "vt/objgroup/common.h"
#include "vt/messaging/message/smart_ptr.h"
namespace vt { namespace objgroup { namespace dispatch {
/*
* DispatchBase implements type erasure to dispatch to a obj group without
* encoding the message directly in the message (as an alternative to using a
* std::function)
*/
struct DispatchBase {
explicit DispatchBase(ObjGroupProxyType in_proxy)
: proxy_(in_proxy)
{ }
virtual ~DispatchBase() = default;
/*
* Dispatch to the handler; the base is closed around the proper object
* pointer that is type-erased here
*/
virtual void run(HandlerType han, BaseMessage* msg) = 0;
virtual void* objPtr() const = 0;
ObjGroupProxyType proxy() const { return proxy_; }
private:
ObjGroupProxyType proxy_ = no_obj_group;
};
}}} /* end namespace vt::objgroup::dispatch */
#endif /*INCLUDED_VT_OBJGROUP_DISPATCH_DISPATCH_BASE_H*/
|
699c79dfcf508c8bfa9b75c225d8ef3c2b9accca
|
dbf21cea1f44b9678f775898241cc80b09aaac85
|
/Source/FacebookArena/ArenaActorInterface.h
|
c2b023720e4a8ccfc16a490802b57753586b5df8
|
[] |
no_license
|
Batname/UE4_FacebookArena
|
8c7433c7e9178a7bc389608965a08906bb778d6e
|
dffcda39fa80888c47870abbaad8d158f0e2d8c5
|
refs/heads/master
| 2021-01-01T16:52:16.178294
| 2017-07-24T14:54:10
| 2017-07-24T14:54:10
| 97,934,435
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 574
|
h
|
ArenaActorInterface.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "ArenaActorInterface.generated.h"
/**
*
*/
//UCLASS()
//class FACEBOOKARENA_API UArenaActorInterface : public UObject
//{
// GENERATED_BODY()
//
//
//
//
//};
UINTERFACE(Blueprintable)
class UArenaActorInterface : public UInterface
{
GENERATED_BODY()
};
class IArenaActorInterface
{
GENERATED_BODY()
public:
UFUNCTION(Category = "ArenaActorInterface")
virtual void AffectHealth(float Delta);
};
|
afcc9139724fb036c3e5a2fca381201b1a8f4619
|
5933fd7859384ff5ae9cf6a1bf26a4139f1243b4
|
/ONP.cpp
|
df86b918b67a201f527bcddb9f14d8f4f0947401
|
[] |
no_license
|
ayanbasak13/C-Basic-Codes
|
b48f1910c9cb142b84217fc2b3b84dd46b5b1c84
|
fc5f6e99cd28b153c60230206fb20e0843acdc1c
|
refs/heads/master
| 2020-04-14T07:56:50.768969
| 2019-01-01T09:08:25
| 2019-01-01T09:08:25
| 163,725,523
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 788
|
cpp
|
ONP.cpp
|
// ((a-b)*(z+x))
// ab-zx+*
#include <iostream>
#include <bits/stdc++.h>
#include <string>
using namespace std;
int main()
{
int t;
string str;
cin>>t;
for(int c=0;c<t;c++)
{
cin>>str;
queue <char> q;
stack <char> op;
for(int i=0;i<str.length();i++)
{
if(((str[i]>='a') && (str[i]<='z')) ||((str[i]>='A') && (str[i]<='Z')))
q.push(str[i]);
else if((str[i]=='+')||(str[i]=='-')||(str[i]=='*')||(str[i]=='/')||(str[i]=='^'))
op.push(str[i]);
else if(str[i]==')')
{
if(!q.empty())
{
while(!q.empty())
{
cout<<q.front();
fflush(stdout);
q.pop();
}
}
if(!op.empty())
{
cout<<op.top();
fflush(stdout);
op.pop();
}
}
}
}
return 0;
}
|
007e327d10e06520f57b8f2c9d2244e714298626
|
a92a96fe76a90f335227676f4ac963c71f5211aa
|
/Hanoi.cpp
|
a778374d297e984885b754b68013727783e32dde
|
[] |
no_license
|
ClayMStamper/AI-4346---Final-Project
|
acbaf1f0ed3fd26810097c770abf4d5eb8f7065f
|
9451b10275712271698bb3d9c49454ac367e77b2
|
refs/heads/master
| 2020-09-15T13:36:57.474711
| 2019-11-25T15:52:21
| 2019-11-25T15:52:21
| 223,462,001
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,987
|
cpp
|
Hanoi.cpp
|
//
// Created by clays on 11/23/2019.
//
#include "Hanoi.h"
#include "AStar.h"
#include "fstream"
Hanoi::Hanoi(int pegCount) {
currentNode = Node();
goalNode = Node();
ofstream file;
file.open("Results.csv");
file << "Algorithm,n,Heuristic,#Nodes Generated,#Nodes Expanded,Execution Time\n";
for (int diskCount = 3; diskCount < 6; ++diskCount) {
InitializeStart(pegCount, diskCount);
InitializeGoal(pegCount, diskCount);
//Ai brain = Ai(diskCount, currentNode, goalNode);
RBFS brain1 = RBFS(diskCount, currentNode, goalNode);
AStar brain2 = AStar(diskCount, currentNode, goalNode);
file << brain1.resultString << "\n" << brain2.resultString << "\n";
}
file.close();
// RBFS brain1 = RBFS(diskCount, currentNode);
// AStar brain2 = AStar(diskCount, currentNode);
}
void Hanoi::InitializeStart(int pegCount, int diskCount) {
currentNode = Node();
currentNode.pegs.emplace_back(diskCount, diskCount); //first peg with disks
for (int i = 1; i < pegCount; ++i) {
currentNode.pegs.emplace_back(0, pegCount); // all other empty startNode->pegs
}
}
void Hanoi::InitializeGoal(int pegCount, int diskCount) {
goalNode = Node();
for (int i = 0; i < pegCount - 1; ++i) {
goalNode.pegs.emplace_back(0, pegCount); // all other empty startNode->pegs
}
goalNode.pegs.emplace_back(diskCount, diskCount); //first peg with disks
}
string Hanoi::ToString() {
string msg;
for (int i = 0; i < currentNode.pegs.size() ; ++i) {
msg += "\n--------------\nPeg: " + to_string(i) + "\n";
msg += "\n" + currentNode.pegs[i].ToString() + "\n";
}
return msg;
}
bool Hanoi::CanMove(Peg a, Peg b) {
if (a.disks.empty())
return false;
if (b.disks.empty())
return true;
return (a.disks.back().width < b.disks.back().width);
}
|
b63f3bceaf9ab930311f77d4de622c89325e2ee3
|
7c18ac19da207835cfde965b2121571453f9a54e
|
/socket_lookahead.cpp
|
2062237e135ef058ceb3cce82c5be9c6912f4471
|
[] |
no_license
|
mrev11/mitm
|
4e254bb38054a7535edb0af82f0d5ca6ae55555d
|
2c1bdd682728c99a21599599fb81dbbe553c8184
|
refs/heads/master
| 2022-04-27T03:09:07.055833
| 2022-04-02T15:01:47
| 2022-04-02T15:01:47
| 140,145,702
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 436
|
cpp
|
socket_lookahead.cpp
|
#include <sys/socket.h>
#include <cccapi.h>
void _clp_socket_lookahead(int argno)
{
CCC_PROLOG("socket_lookahead",1);
int socketfd=_parni(1);
unsigned char c=0;
recv(socketfd,&c,1,MSG_PEEK);
_retni((int)c);
CCC_EPILOG();
}
//vajon a windowson van-e ilyen?
//visszaadja a socket-bol olvashato kovetkezo bajtot
//a bajtot nem veszi ki az olvasasi sorbol
//tehat azt a kovetkezo recv ujbol beolvassa
|
eadbddaaf40388744e8a4aba6d1105de87e6330b
|
9222f818abb402120fb24f61ac8ac24c483de393
|
/question/populating next right pointers in each node.cpp
|
367ea458f5b398a7782c58a8e6e89c501c9983c0
|
[] |
no_license
|
bobzhw/question
|
56fd04d17f7607376446582ed37fc330f011594d
|
4d4bcb673e414e16ce72bd4609bedc9a7ad31e14
|
refs/heads/master
| 2020-05-23T20:59:22.185165
| 2019-06-04T13:31:49
| 2019-06-04T13:31:49
| 186,942,633
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 744
|
cpp
|
populating next right pointers in each node.cpp
|
#include<iostream>
#include<queue>
using namespace std;
// Definition for binary tree with next pointer.
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
queue<TreeLinkNode*> dq;
if (root == nullptr)
return;
dq.push(root);
while (!dq.empty())
{
int size = dq.size();
TreeLinkNode* pre;
for (int i = 0; i < size; i++)
{
TreeLinkNode* tmp = dq.front();
dq.pop();
if (i != 0)
{
pre->next = tmp;
}
pre = tmp;
if (tmp->left != nullptr)
dq.push(tmp->left);
if (tmp->right != nullptr)
dq.push(tmp->right);
}
}
}
};
|
ab069ca28c2340d265a80d7280977c9eb67154ba
|
d5d12943ff123a4bab18ef3cb495de2ffa3354a5
|
/seABaca/stdafx.h
|
d263a148558e746c2b74ed99312639479fb42bfd
|
[] |
no_license
|
ranvli/seABaca
|
db7188cf42394d383dd61519c02ea06d1b88b12e
|
8e3aa904fb3b48855463c783a3aa53cd148b28a6
|
refs/heads/master
| 2021-01-13T04:09:02.232037
| 2017-01-02T21:06:33
| 2017-01-02T21:06:33
| 77,861,771
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 5,130
|
h
|
stdafx.h
|
// stdafx.h: archivo de inclusión de los archivos de inclusión estándar del sistema
// o archivos de inclusión específicos de un proyecto utilizados frecuentemente,
// pero rara vez modificados
#pragma once
#include <iostream>
using namespace std;
// TODO: mencionar aquí los encabezados adicionales que el programa necesita
class nodo {
public:
nodo(nodo *val, nodo *der, bool dibr)
{
dibujado = dibr;
ndato = val;
derecha = der;
}
nodo(nodo *val, nodo *izq, nodo *der, bool dibr)
{
dibujado = dibr;
ndato = val;
derecha = der;
izquierda = izq;
}
nodo(int val, nodo *izq, nodo *der, int posXr, int posYr)
{
dato = val;
derecha = der;
izquierda = izq;
posX = posXr;
posY = posYr;
FB = 0;
acomodado = false;
}
int dato;
private:
int posX;
int posY;
int FB;
bool dibujado;
bool acomodado;
nodo *ndato;
nodo *izquierda;
nodo *derecha;
nodo *raiz;
friend class nodo;
friend class AB;
friend class util;
friend class listaDoble;
};
class listaDoble{
public:
listaDoble() { primerNodo = NULL; };
void borra();
bool ListaVacia() { return primerNodo == NULL; }
void borraAlInicio();
void borraAlFinal();
void borraPos(int pos);
void invertirApartirDe(int pos, listaDoble &destino);
int cantidadDeNodos();
int getDatoEnPos(int pos);
void insertaAlFinal(nodo * val);
void muestraLista();
void borraPosImpares();
void actualizaValor(int vBus, int vNueX, int vNueY);
private:
nodo * primerNodo;
friend class util;
friend class AB;
friend class nodo;
};
//class lista{
//
//public:
// lista() { primerNodo = NULL; }
//
// void muestraLista();
// bool ListaVacia() { return primerNodo == NULL; }
// void insertaAlFinal(nodo * val);
// //void actualizaValor(int vBus, int vNueX, int vNueY);
// int cantidadDeNodos();
//
//private:
// nodo * primerNodo;
//
// friend class nodo;
// friend class AB;
// friend class util;
// friend class lista;
//
//};
public class util{
public:
//void reAcomoda(nodo * nodo, lista &cacheNodos, System::Windows::Forms::Panel^ p1);
void reAcomodaRaiz(nodo * actual, listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1, bool der);
void dibujaNodo(int valor, int posX, int posY, System::Windows::Forms::Panel^ p1, System::Drawing::Pen^ pcolor);
void dibujaArista(int x1, int y1, int x2, int y2, bool ladoDerecho, System::Windows::Forms::Panel^ p1);
void borraNodo(int valor, int posX, int posY, System::Windows::Forms::Panel^ p1);
void mueveNodo(int valor, int posXini, int posYini, int posXfin, int posYfin, System::Windows::Forms::Panel^ p1, listaDoble &cacheNodos);
void dibujaCache(listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1);
void setNoDibujado(int val, listaDoble &cacheNodos);
void setDibujado(int val, listaDoble &cacheNodos);
void dibujaFB(nodo * actual, System::Windows::Forms::Panel^ p1);
//void verificaPosiciones(nodo * nuevo, lista &cacheNodos, System::Windows::Forms::Panel^ p1, bool der);
//void reOrdena(nodo * actref, lista &cacheNodos, System::Windows::Forms::Panel^ p1);
void reOrdena(bool lado, int vS, nodo * actref, nodo * arriba, listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1);
void reOrdena2(int dX, int dY, int inX, bool der, int inY, nodo * raiz, listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1);
void reOrdenaBorrado(int dX, int dY, int inX, bool der, int inY, nodo * raiz, listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1);
void chequeaInterPos(listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1);
int CalculAlturArbol(AB &ArbolB, System::Windows::Forms::Panel ^p1);
int infoNodo(AB &ArbolB, System::String^ tipo);
nodo * util::buscaNodoMenor(nodo * nodoAc, nodo * menor);
void refrescaPD(listaDoble &cacheNodos, System::Windows::Forms::Panel^ p1, int delay);
friend class nodo;
friend class AB;
friend class util;
friend class listaDoble;
};
class AB{
public:
listaDoble nueva;
AB() : cacheNodos(nueva) { raiz = NULL; };
bool estaVacio(){ return raiz == NULL; };
void insertar(int val, System::Windows::Forms::Panel^ p1);
void InOrden(nodo * nodo, System::Windows::Forms::Panel^ p1, System::Drawing::Pen^ pcolor, listaDoble &cacheNodos, int retraso);
void RecorreInOrden(System::Windows::Forms::Panel^ p1, int retraso);
void PreOrden(nodo * nodo, System::Windows::Forms::Panel^ p1, System::Drawing::Pen^ pcolor, listaDoble &cacheNodos, int retraso);
void RecorrePreOrden(System::Windows::Forms::Panel^ p1, int retraso);
void PostOrden(nodo * nodo, System::Windows::Forms::Panel^ p1, System::Drawing::Pen^ pcolor, listaDoble &cacheNodos, int retraso);
void RecorrePostOrden(System::Windows::Forms::Panel^ p1, int retraso);
void setDibujado(int val);
int calculAltura(nodo * nodo);
void borraOrdenado(int val, System::Windows::Forms::Panel^ p1);
void checkAVL(nodo * nodo);
void aplicaRotacionSimple(int val, System::Windows::Forms::Panel^ p1, int delay);
void aplicaRotacionDoble(int val, System::Windows::Forms::Panel^ p1, int delay);
nodo * raiz;
private:
listaDoble &cacheNodos;
friend class nodo;
friend class AB;
friend class util;
friend class listaDoble;
};
|
c5acca89a5edb3e0090c155514a84135fda5416c
|
30d51127475050448ad914d7d7f43ffa3f60106b
|
/Library Management System/main_window.h
|
b09b45433d99afaeb8154d8bbdd4445c9f7c12cc
|
[] |
no_license
|
cmeza432/Library-Management-System
|
f4d70254ccaf6372881215a6744b9c02ea61b1f6
|
56cdf309d9693d2a37346e4b943037f9d9eac085
|
refs/heads/master
| 2020-04-05T09:26:53.091831
| 2018-11-08T19:20:59
| 2018-11-08T19:20:59
| 156,757,033
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 499
|
h
|
main_window.h
|
#ifndef MAIN_WINDOW_H
#define MAIN_WINDOW_H
#include <gtkmm.h>
#include "library.h"
#include "controller.h"
#include "view.h"
class Main_window : public Gtk::Window
{
public:
Main_window();
virtual ~Main_window();
protected:
void on_list_all_click();
void on_add_publication_click();
void on_check_out_click();
void on_check_in_click();
void on_list_patron_click();
void on_add_patron_click();
void on_help_click();
void on_exit_click();
private:
Library library;
};
#endif
|
8a66b3e98028085571d3462311e24cb5e3ca96fd
|
44b99504cd91e9d88f7fa637140e830b4a42f769
|
/ace/ace/INET_Addr.cpp
|
7f07bd9635d7cb4a75d171033999c96d5e1fb220
|
[
"BSD-3-Clause"
] |
permissive
|
dariuskylin/utilityLib
|
ea847988e0c06f63657238f8405775c4ae419348
|
4afc4b016c130982e26c452028114a1d78619a57
|
refs/heads/master
| 2021-01-19T07:46:06.817498
| 2014-11-01T07:32:20
| 2014-11-01T07:32:20
| 4,357,328
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,530
|
cpp
|
INET_Addr.cpp
|
// INET_Addr.cpp,v 4.62 2001/08/24 14:11:03 shuston Exp
// Defines the Internet domain address family address format.
#include "ace/INET_Addr.h"
#include "ace/Log_Msg.h"
#if !defined (__ACE_INLINE__)
#include "ace/INET_Addr.i"
#endif /* __ACE_INLINE__ */
ACE_RCSID(ace, INET_Addr, "INET_Addr.cpp,v 4.62 2001/08/24 14:11:03 shuston Exp")
ACE_ALLOC_HOOK_DEFINE(ACE_INET_Addr)
// Transform the current address into string format.
int
ACE_INET_Addr::addr_to_string (ACE_TCHAR s[],
size_t size,
int ipaddr_format) const
{
ACE_TRACE ("ACE_INET_Addr::addr_to_string");
size_t total_len = (ipaddr_format == 0 ?
ACE_OS::strlen (this->get_host_name ()) :
ACE_OS::strlen (this->get_host_addr ()))
+ ACE_OS::strlen ("65536") // Assume the max port number.
+ sizeof (':')
+ sizeof ('\0'); // For trailing '\0'.
if (size < total_len)
return -1;
else
{
ACE_OS::sprintf (s,
ACE_LIB_TEXT ("%s:%d"),
ACE_TEXT_CHAR_TO_TCHAR (ipaddr_format == 0
? this->get_host_name ()
: this->get_host_addr ()),
this->get_port_number ());
return 0;
}
}
void
ACE_INET_Addr::dump (void) const
{
ACE_TRACE ("ACE_INET_Addr::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACE_TCHAR s[ACE_MAX_FULLY_QUALIFIED_NAME_LEN + 16];
ACE_OS::sprintf (s, ACE_LIB_TEXT ("%s:%d"),
this->get_host_addr (),
this->get_port_number ());
ACE_DEBUG ((LM_DEBUG, ACE_LIB_TEXT ("%s"), s));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
}
// Compare two addresses for inequality.
int
ACE_INET_Addr::operator != (const ACE_INET_Addr &sap) const
{
ACE_TRACE ("ACE_INET_Addr::operator !=");
return !((*this) == sap);
}
// Compare two addresses for equality.
int
ACE_INET_Addr::operator == (const ACE_INET_Addr &sap) const
{
ACE_TRACE ("ACE_INET_Addr::operator ==");
return this->inet_addr_.sin_port == sap.inet_addr_.sin_port
&& ACE_OS::memcmp ((void *) &this->inet_addr_.sin_addr,
(void *) &sap.inet_addr_.sin_addr,
sizeof (this->inet_addr_.sin_addr)) == 0;
}
ACE_INET_Addr::ACE_INET_Addr (void)
: ACE_Addr (AF_INET, sizeof this->inet_addr_)
{
// ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
(void) ACE_OS::memset ((void *) &this->inet_addr_,
0,
sizeof this->inet_addr_);
this->inet_addr_.sin_family = AF_INET;
}
int
ACE_INET_Addr::set (const ACE_INET_Addr &sa)
{
ACE_TRACE ("ACE_INET_Addr::set");
this->ACE_Addr::base_set (sa.get_type (),
sa.get_size ());
if (sa.get_type () == AF_ANY)
// Ugh, this is really a base class, so don't copy it.
(void) ACE_OS::memset ((void *) &this->inet_addr_,
0,
sizeof this->inet_addr_);
else
// It's ok to make the copy.
(void) ACE_OS::memcpy ((void *) &this->inet_addr_,
(void *) &sa.inet_addr_,
sizeof this->inet_addr_);
return 0;
}
// Transform the string into the current addressing format.
int
ACE_INET_Addr::string_to_addr (const char s[])
{
ACE_TRACE ("ACE_INET_Addr::string_to_addr");
int result;
char *t;
// Need to make a duplicate since we'll be overwriting the string.
ACE_ALLOCATOR_RETURN (t,
ACE_OS::strdup (s),
-1);
char *ip_addr = ACE_OS::strchr (t, ':');
if (ip_addr == 0) // Assume it's a port number.
{
if (ACE_OS::strspn (t, "1234567890")
== ACE_OS::strlen (t))
{ // port number
u_short port = (u_short) ACE_OS::atoi (t);
result = this->set (port,
ACE_UINT32 (INADDR_ANY));
}
else // port name
result = this->set (t,
ACE_UINT32 (INADDR_ANY));
}
else
{
*ip_addr = '\0'; ++ip_addr; // skip over ':'
if (ACE_OS::strspn (ip_addr, "1234567890") ==
ACE_OS::strlen (ip_addr))
{
u_short port =
(u_short) ACE_OS::atoi (ip_addr);
result = this->set (port, t);
}
else
result = this->set (ip_addr, t);
}
ACE_OS::free (ACE_MALLOC_T (t));
return result;
}
int
ACE_INET_Addr::set (const char address[])
{
ACE_TRACE ("ACE_INET_Addr::set");
return this->string_to_addr (address);
}
ACE_INET_Addr::ACE_INET_Addr (const char address[])
: ACE_Addr (AF_INET, sizeof this->inet_addr_)
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
this->set (address);
}
#if defined (ACE_HAS_WCHAR)
ACE_INET_Addr::ACE_INET_Addr (const wchar_t address[])
: ACE_Addr (AF_INET, sizeof this->inet_addr_)
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
this->set (address);
}
#endif /* ACE_HAS_WCHAR */
// Copy constructor.
ACE_INET_Addr::ACE_INET_Addr (const ACE_INET_Addr &sa)
: ACE_Addr (AF_INET, sizeof this->inet_addr_)
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
this->set (sa);
}
// Initializes a ACE_INET_Addr from a PORT_NUMBER and an Internet
// address.
int
ACE_INET_Addr::set (u_short port_number,
ACE_UINT32 inet_address,
int encode)
{
ACE_TRACE ("ACE_INET_Addr::set");
this->ACE_Addr::base_set (AF_INET, sizeof this->inet_addr_);
(void) ACE_OS::memset ((void *) &this->inet_addr_,
0, sizeof this->inet_addr_);
this->inet_addr_.sin_family = AF_INET;
#if defined (ACE_HAS_SIN_LEN)
this->inet_addr_.sin_len = sizeof this->inet_addr_;
#endif /* ACE_HAS_SIN_LEN */
if (encode)
{
inet_address = htonl (inet_address);
this->inet_addr_.sin_port = htons (port_number);
}
else
this->inet_addr_.sin_port = port_number;
(void) ACE_OS::memcpy ((void *) &this->inet_addr_.sin_addr,
(void *) &inet_address,
sizeof this->inet_addr_.sin_addr);
return 0;
}
// Initializes a ACE_INET_Addr from a PORT_NUMBER and the remote
// HOST_NAME.
int
ACE_INET_Addr::set (u_short port_number,
const char host_name[],
int encode)
{
ACE_TRACE ("ACE_INET_Addr::set");
ACE_UINT32 addr;
this->ACE_Addr::base_set (AF_INET, sizeof this->inet_addr_);
(void) ACE_OS::memset ((void *) &this->inet_addr_, 0, sizeof
this->inet_addr_);
this->inet_addr_.sin_family = AF_INET;
// Yow, someone gave us a NULL host_name!
if (host_name == 0)
{
errno = EINVAL;
return -1;
}
else if (ACE_OS::inet_aton (host_name,
(struct in_addr *) &addr) == 1)
return this->set (port_number,
encode ? ntohl (addr) : addr,
encode);
else
{
#if defined (VXWORKS) || defined (CHORUS)
hostent *hp = ACE_OS::gethostbyname (host_name);
#else
hostent hentry;
ACE_HOSTENT_DATA buf;
int error;
hostent *hp = ACE_OS::gethostbyname_r (host_name, &hentry,
buf, &error);
#endif /* VXWORKS */
if (hp == 0)
{
errno = EINVAL;
return -1;
}
else
{
(void) ACE_OS::memcpy ((void *) &addr,
hp->h_addr,
hp->h_length);
return this->set (port_number,
encode ? ntohl (addr) : addr,
encode);
}
}
}
// Initializes a ACE_INET_Addr from a <port_name> and the remote
// <host_name>.
int
ACE_INET_Addr::set (const char port_name[],
const char host_name[],
const char protocol[])
{
ACE_TRACE ("ACE_INET_Addr::set");
#if defined (VXWORKS) || defined (CHORUS) || defined (ACE_LACKS_GETSERVBYNAME)
ACE_UNUSED_ARG (port_name);
ACE_UNUSED_ARG (host_name);
ACE_UNUSED_ARG (protocol);
ACE_NOTSUP_RETURN (-1);
#else
servent sentry;
ACE_SERVENT_DATA buf;
servent *sp = ACE_OS::getservbyname_r (port_name,
protocol,
&sentry,
buf);
if (sp == 0)
return -1;
else
return this->set (sp->s_port, host_name, 0);
#endif /* VXWORKS */
}
// Initializes a ACE_INET_Addr from a <port_name> and an Internet
// address.
int
ACE_INET_Addr::set (const char port_name[],
ACE_UINT32 inet_address,
const char protocol[])
{
ACE_TRACE ("ACE_INET_Addr::set");
#if defined (VXWORKS) || defined (CHORUS) || defined (ACE_LACKS_GETSERVBYNAME)
ACE_UNUSED_ARG (port_name);
ACE_UNUSED_ARG (inet_address);
ACE_UNUSED_ARG (protocol);
ACE_NOTSUP_RETURN (-1);
#else
servent sentry;
ACE_SERVENT_DATA buf;
servent *sp = ACE_OS::getservbyname_r (port_name,
protocol,
&sentry,
buf);
if (sp == 0)
return -1;
else
return this->set (sp->s_port, inet_address, 0);
#endif /* VXWORKS */
}
// Creates a ACE_INET_Addr from a PORT_NUMBER and the remote
// HOST_NAME.
ACE_INET_Addr::ACE_INET_Addr (u_short port_number,
const char host_name[])
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_number,
host_name) == -1)
#if defined (ACE_HAS_BROKEN_CONDITIONAL_STRING_CASTS)
ACE_ERROR ((LM_ERROR,
(char *)"ACE_INET_Addr::ACE_INET_Addr: %p\n",
(((char *) host_name == 0) ?
((char *) "<unknown>") :
((char *) (host_name)))));
#else /* ! defined (ACE_HAS_BROKEN_CONDITIONAL_STRING_CASTS) */
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr: %p\n"),
ACE_TEXT_CHAR_TO_TCHAR ((host_name == 0) ?
"<unknown>" : host_name)));
#endif /* ! defined (ACE_HAS_BROKEN_CONDITIONAL_STRING_CASTS) */
}
#if defined (ACE_HAS_WCHAR)
ACE_INET_Addr::ACE_INET_Addr (u_short port_number,
const wchar_t host_name[])
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_number,
host_name) == -1)
#if defined (ACE_HAS_BROKEN_CONDITIONAL_STRING_CASTS)
ACE_ERROR ((LM_ERROR,
(char *)"ACE_INET_Addr::ACE_INET_Addr: %p\n",
(((char *) host_name == 0) ?
((char *) "<unknown>") :
((char *) (host_name)))));
#else /* ! defined (ACE_HAS_BROKEN_CONDITIONAL_STRING_CASTS) */
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr: %p\n"),
ACE_TEXT_WCHAR_TO_TCHAR ((host_name == 0) ?
ACE_TEXT_WIDE ("<unknown>") :
host_name)));
#endif /* ! defined (ACE_HAS_BROKEN_CONDITIONAL_STRING_CASTS) */
}
#endif /* ACE_HAS_WCHAR */
// Creates a ACE_INET_Addr from a sockaddr_in structure.
int
ACE_INET_Addr::set (const sockaddr_in *addr, int len)
{
ACE_TRACE ("ACE_INET_Addr::set");
this->ACE_Addr::base_set (AF_INET, len);
ACE_OS::memcpy ((void *) &this->inet_addr_,
(void *) addr, len);
this->inet_addr_.sin_family = AF_INET;
return 0;
}
// Set a pointer to the address.
void
ACE_INET_Addr::set_addr (void *addr, int len)
{
ACE_TRACE ("ACE_INET_Addr::set_addr");
this->ACE_Addr::base_set (AF_INET, len);
ACE_OS::memcpy ((void *) &this->inet_addr_,
(void *) addr, len);
this->inet_addr_.sin_family = AF_INET;
}
// Creates a ACE_INET_Addr from a sockaddr_in structure.
ACE_INET_Addr::ACE_INET_Addr (const sockaddr_in *addr, int len)
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
this->set (addr, len);
}
// Creates a ACE_INET_Addr from a PORT_NUMBER and an Internet address.
ACE_INET_Addr::ACE_INET_Addr (u_short port_number,
ACE_UINT32 inet_address)
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_number, inet_address) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("%p\n"),
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr")));
}
// Creates a ACE_INET_Addr from a PORT_NAME and the remote
// HOST_NAME.
ACE_INET_Addr::ACE_INET_Addr (const char port_name[],
const char host_name[],
const char protocol[])
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_name,
host_name,
protocol) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr")));
}
#if defined (ACE_HAS_WCHAR)
ACE_INET_Addr::ACE_INET_Addr (const wchar_t port_name[],
const wchar_t host_name[],
const wchar_t protocol[])
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_name,
host_name,
protocol) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr")));
}
#endif /* ACE_HAS_WCHAR */
// Creates a ACE_INET_Addr from a PORT_NAME and an Internet address.
ACE_INET_Addr::ACE_INET_Addr (const char port_name[],
ACE_UINT32 inet_address,
const char protocol[])
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_name,
inet_address,
protocol) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr")));
}
#if defined (ACE_HAS_WCHAR)
ACE_INET_Addr::ACE_INET_Addr (const wchar_t port_name[],
ACE_UINT32 inet_address,
const wchar_t protocol[])
{
ACE_TRACE ("ACE_INET_Addr::ACE_INET_Addr");
if (this->set (port_name,
inet_address,
protocol) == -1)
ACE_ERROR ((LM_ERROR,
ACE_LIB_TEXT ("ACE_INET_Addr::ACE_INET_Addr")));
}
#endif /* ACE_HAS_WCHAR */
int
ACE_INET_Addr::get_host_name (char hostname[],
size_t len) const
{
ACE_TRACE ("ACE_INET_Addr::get_host_name");
int result;
if (len > 1)
{
result = get_host_name_i(hostname,len);
if (result < 0)
{
if (result == -2)
{
result = -1;
// We know that hostname is nul-terminated
}
else
{
//result == -1;
// This could be worse than hostname[len -1] = '\0'?
hostname[0] = '\0';
}
}
}
else
{
if (len == 1)
{
hostname[0] = '\0';
}
result = -1;
}
return result;
}
#if defined (ACE_HAS_WCHAR)
int
ACE_INET_Addr::get_host_name (wchar_t hostname[],
size_t len) const
{
ACE_TRACE ("ACE_INET_Addr::get_host_name");
char char_hostname [MAXHOSTNAMELEN + 1];
// We have a build in limitation of MAXHOSTNAMELEN
if (len > MAXHOSTNAMELEN + 1)
len = MAXHOSTNAMELEN + 1;
// Call the char version
int result = this->get_host_name (char_hostname, len);
// And copy it over, if successful
if (result == 0)
ACE_OS_String::strcpy (hostname,
ACE_Ascii_To_Wide (char_hostname).wchar_rep ());
return result;
}
#endif /* ACE_HAS_WCHAR */
// Return the character representation of the hostname.
const char *
ACE_INET_Addr::get_host_name (void) const
{
ACE_TRACE ("ACE_INET_Addr::get_host_name");
static char name[MAXHOSTNAMELEN + 1];
if (this->get_host_name (name, MAXHOSTNAMELEN + 1) == -1)
ACE_OS::strcpy (name, "<unknown>");
return name;
}
void
ACE_INET_Addr::set_port_number (u_short port_number,
int encode)
{
ACE_TRACE ("ACE_INET_Addr::set_port_number");
if (encode)
port_number = htons (port_number);
this->inet_addr_.sin_port = port_number;
}
// returns -2 when the hostname is truncated
int
ACE_INET_Addr::get_host_name_i (char hostname[], size_t len) const
{
ACE_TRACE ("ACE_INET_Addr::get_host_name_i");
if (this->inet_addr_.sin_addr.s_addr == INADDR_ANY)
{
if (ACE_OS::hostname (hostname, len) == -1)
return -1;
else
return 0;
}
else
{
#if defined (VXWORKS)
ACE_UNUSED_ARG (len);
int error =
::hostGetByAddr ((int) this->inet_addr_.sin_addr.s_addr,
hostname);
if (error == OK)
return 0;
else
{
errno = error;
return -1;
}
#else
# if !defined(_UNICOS)
int a_len = sizeof this->inet_addr_.sin_addr.s_addr;
# else /* _UNICOS */
int a_len = sizeof this->inet_addr_.sin_addr;
# endif /* ! _UNICOS */
int error = 0;
#if defined (CHORUS) || (defined (DIGITAL_UNIX) && defined (__GNUC__))
hostent *hp = ACE_OS::gethostbyaddr ((char *)
&this->inet_addr_.sin_addr,
a_len,
this->addr_type_);
if (hp == 0)
error = errno; // So that the errno gets propagated back; it is
// loaded from error below.
#else
hostent hentry;
ACE_HOSTENT_DATA buf;
hostent *hp =
ACE_OS::gethostbyaddr_r ((char *)&this->inet_addr_.sin_addr,
a_len,
this->addr_type_,
&hentry,
buf,
&error);
#endif /* CHORUS */
if (hp == 0)
{
errno = error;
return -1;
}
if (hp->h_name == 0)
return -1;
if (ACE_OS::strlen (hp->h_name) >= len)
{
// We know the length, so use memcpy
if (len > 0)
{
ACE_OS::memcpy(hostname,hp->h_name,len - 1);
hostname[len-1]= '\0';
}
errno = ENOSPC;
return -2; // -2 Means that we have a good string
// Using errno looks ok, but ENOSPC could be set on
// other places.
}
ACE_OS::strcpy (hostname, hp->h_name);
return 0;
#endif /* VXWORKS */
}
}
|
e2b9e221007b0df0c8c3b0095c44403156dcb9eb
|
b99c97887220c75c90465444b783455f873b22d6
|
/PWS2018Sol/PWS2018/food.cpp
|
99964ad8d17bc5c476859ef32b48088148c47998
|
[] |
no_license
|
Tiagotje/PWS2018
|
531cd261ecd65de15a161e25670a761e59629060
|
d942abe6804b84afa3c4ab4a02348dfc204cf45e
|
refs/heads/master
| 2020-03-27T10:52:39.641643
| 2018-12-02T11:26:33
| 2018-12-02T11:26:33
| 146,451,085
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 899
|
cpp
|
food.cpp
|
#include "food.hpp"
#include <Box2D/Box2D.h>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "physics.hpp"
#include "main.hpp"
#include "creature.hpp"
Food::Food(b2Vec2 pos)
{
p = pos;
shape = sf::CircleShape(10 * r);
shape.setOrigin({ 10 * r, 10 * r });
shape.setFillColor(sf::Color(200, 30, 30));
b2BodyDef bd;
bd.type = b2_staticBody;
bd.position.Set(p.x, p.y);
body = Phys::world.CreateBody(&bd);
b2CircleShape cs;
cs.m_p.Set(0, 0);
cs.m_radius = r;
b2FixtureDef fd;
fd.shape = &cs;
body->CreateFixture(&fd);
}
void Food::draw()
{
if (!body->IsActive())
return;
p = body->GetPosition();
shape.setPosition(sf::Vector2f(10 * p.x, -10 * p.y));
window.draw(shape);
}
bool Food::check()
{
for (b2ContactEdge* ce = body->GetContactList(); ce; ce = ce->next)
{
if (ce->contact->IsTouching()) {
body->SetActive(false);
return true;
}
}
return false;
}
|
1811a3cdd6cf7c020be54e4619bccb3c3d0b65e9
|
20049d88e2e8f0e1904efc561103c1d84d21507a
|
/baboshina.elizaveta/A1/rectangle.cpp
|
d0c592611aa8b4dba17558f582cdb64342d7243b
|
[] |
no_license
|
gogun/Labs-for-SPbSPU-C-course-during-2019
|
5442a69152add3e66f02a7541e8dc8dd817f38a1
|
16ade47b859517a48d0fdb2e9704464bce4cc355
|
refs/heads/master
| 2022-01-09T16:02:54.728830
| 2019-06-06T11:06:33
| 2019-06-06T11:06:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 819
|
cpp
|
rectangle.cpp
|
#include "rectangle.hpp"
#include <iostream>
#include <cassert>
Rectangle::Rectangle(const double width, const double height, const point_t pos):
width_(width),
height_(height),
center_(pos)
{
assert((width > 0) && (height > 0));
}
double Rectangle::getArea() const
{
return height_ * width_;
}
rectangle_t Rectangle::getFrameRect() const
{
return { width_, height_, center_ };
}
void Rectangle::move(const point_t point)
{
center_ = point;
}
void Rectangle::move(const double x, const double y)
{
center_.x += x;
center_.y += y;
}
void Rectangle::getInfo() const
{
std::cout << "\nWidth of rectangle is: " << width_ << std::endl;
std::cout << "Height of rectangle is: " << height_ << std::endl;
std::cout << "Center of rectangle is: x=" << center_.x << " y=" << center_.y << std::endl;
}
|
b8abcbd586c36cd55a523e9179c261258ba574bf
|
4346566fbb14c5dc15759299ace6dd7dfe3c239d
|
/src/punkt.hpp
|
3ee908d5c84458c325100718555313c8eacb77f7
|
[] |
no_license
|
pawelstrzelczyk/TSP_ACO
|
f46dc2badac11f8f598e3e81ffe2e834fe253aac
|
ece6376abb816320f26aa3b7357ff160fe2e8086
|
refs/heads/master
| 2023-02-26T03:15:50.132769
| 2020-12-18T00:51:35
| 2020-12-18T00:51:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 583
|
hpp
|
punkt.hpp
|
#pragma once
#include <queue>
class punkt
{
public:
class pkt
{
private:
int x;
int y;
int id;
public:
bool flag = false;
void setX(int X)
{
this->x = X;
}
void setY(int Y)
{
this->y = Y;
}
void setId(int id)
{
this->id = id;
}
int getX()
{
return this->x;
}
int getY()
{
return this->y;
}
int getId()
{
return this->id;
}
};
int square(int a)
{
return a * a;
}
double odleglosc(pkt a, pkt b)
{
return sqrt(square(double(a.getY()) - double(b.getY())) + square(double(a.getX()) - double(b.getX())));
}
};
|
0466dfad4fe88bdd507b8ac3f3c2b5da1bd3a2dd
|
2dc321b61f45da0353d22fc3908a93fc00456e90
|
/baekjoon/1780_divide_conquer.cpp
|
a65024986f15cc6fd78e8352153822a9787bb1c9
|
[] |
no_license
|
goo-gy/Algorithm
|
6d7e9c65e6791ebe3d78bba8b366552d4b04e59a
|
e22373dead2dfe218effea9b0e61b65c8e167019
|
refs/heads/master
| 2022-09-29T10:21:30.744970
| 2022-09-16T15:04:05
| 2022-09-16T15:04:05
| 365,225,284
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,355
|
cpp
|
1780_divide_conquer.cpp
|
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int N;
vector<vector<int>> total_paper;
int counts[3];
#define NOT_SET -3
#define MIXED -2
int divide_and_conquer(int row, int col, int size) {
if(size == 1)
return total_paper[row][col];
int unit = size/3;
bool is_set = true;
int set_number = NOT_SET;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
int the_number = divide_and_conquer(row + i*unit, col + j*unit, unit);
counts[the_number + 1]++;
if( (set_number != the_number && set_number != NOT_SET) || the_number == MIXED)
is_set = false;
set_number = the_number;
}
}
if(is_set)
{
if(size == N)
counts[set_number + 1] -= 8;
else
counts[set_number + 1] -= 9;
return set_number;
}
else
return MIXED;
}
int solution() {
cin >> N;
memset(counts, 0, sizeof(counts));
total_paper.resize(N);
for(int i = 0; i < N; i++)
{
total_paper[i].resize(N);
for(int j = 0; j < N; j++)
{
cin >> total_paper[i][j];
}
}
if(N == 1)
counts[total_paper[0][0] + 1]++;
else
divide_and_conquer(0, 0, N);
cout << counts[0] << "\n" << counts[1] << "\n" << counts[2] << "\n";
return 0;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solution();
return 0;
}
|
be45ebbf5bc57bd486124a8124df3a018893ab81
|
09b65166716593347044ad346d5f4b9d5847f88f
|
/Lab 4/Lab 4 - Paradigms/lib/SubsetSumSolverDecPis.cpp
|
fc10dd44704def748edfd4a6d60e2cf378ed83e5
|
[] |
no_license
|
BrunoCAF/CES12
|
d0b25e47affb7c48abb3b3065a825f5bf0fdece0
|
0f89a1fd76a599b10844c5ef0895a6716655db24
|
refs/heads/main
| 2023-08-02T11:08:47.348819
| 2021-09-25T22:14:45
| 2021-09-25T22:14:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 773
|
cpp
|
SubsetSumSolverDecPis.cpp
|
#include <SubsetSumSolverDecPis.h>
bool SSPSolverDecPis::solve(const std::vector< long> &input,
long value, std::vector< char> &output) {
output.resize(input.size(),0);
std::vector<int> int_output;
int_output.resize(input.size(),0);
std::vector<long> input_copy;
input_copy.resize(input.size(),0);
for (int i = 0 ; i < input.size() ; i++)
input_copy[i] = input[i];
long z = decompL(input.size(), input_copy.data(), int_output.data(), value);
for (int i = 0 ; i < input.size() ; i++) {
output[i] = int_output[i];
}//for
//std::cerr << "\n******** val " << value << " z " << z << " =? " << (z == value);
return (z == value);
}
|
c05c436dd6b1e3c5ea0bff9fb6c365f3684b325b
|
2e3b0f51c42e9548b6ff3176c6c0b82cdecbc6cd
|
/Aviation_management_c--main/Flight.h
|
8f80df1207f9dba61b979be5e578d5c8096af23a
|
[] |
no_license
|
99002478/Genisis_Mini_Project_2478
|
cc0e8796afb3f4bc8672edc188a3a6320e0eba65
|
999eb2e91f4c3672e4fd4aefabe08d8feb3b8f46
|
refs/heads/master
| 2023-01-11T03:50:43.150110
| 2020-11-11T10:06:48
| 2020-11-11T10:06:48
| 297,558,576
| 0
| 1
| null | 2020-10-10T05:05:31
| 2020-09-22T06:39:15
|
C++
|
UTF-8
|
C++
| false
| false
| 695
|
h
|
Flight.h
|
#ifndef __FLIGHT_H
#define __FLIGHT_H
#include<string>
const double mile_rateINR = 10.0;
const double SpeedInHr = 500;
class Flight{
protected :
std::string fl_name;
std::string fl_id;
std::string src_city;
std::string dest_city;
double distance;
public:
// Constructors
Flight();
Flight(std::string,std::string,std::string,std::string,double);
//Operations
virtual double computeFare() ;
virtual double computeTravelTime() ;
// Getters
virtual std::string getflight_name();
virtual std::string getflight_id();
virtual std:: string getOrigin();
virtual std:: string getDestination();
virtual double getDistance();
}; // Class ending
#endif
|
44d0c2a5ee7dde8e70286cfdb2c4cb9661495856
|
1982fc83c70b448f861e16e8a464935915e89842
|
/Solutions/5.bufory/main.cpp
|
c53076c7ed0ba57e9fe051e4a7f63d96e0652145
|
[] |
no_license
|
fiiniefi/CPP
|
eb0fdb0c8e6623ac6fd956c4f22a87b84369f61f
|
bf9dc3230ba80a27f336d1acf96d5761dd3b67c1
|
refs/heads/master
| 2021-08-30T00:43:30.801389
| 2017-12-15T12:04:08
| 2017-12-15T12:04:08
| 114,362,638
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,988
|
cpp
|
main.cpp
|
#include "stdafx.h"
#include <iostream>
#include <string>
#include "struktury_danych.h"
void testy_listy();
void testy_kolejki();
void testy_stosu();
int main()
{
testy_kolejki();
testy_stosu();
testy_listy();
}
void testy_kolejki()
{
std::cout << "\n\nTESTY KOLEJKI:\n\n";
kolejka k;
std::cout << "rozmiar kolejki: " << k.ile() << std::endl;
k.wstaw(4.5);
k+=(3.4);
std::cout << "element pierwszy do zdjecia: " << k.gotowy() << std::endl;
std::cout << "zdejmuje: " << --k << std::endl;
k += 2.1;
std::cout << "element pierwszy do zdjecia: " << *k << std::endl;
std::cout << "rozmiar kolejki: " << k.ile() << std::endl;
}
void testy_stosu()
{
std::cout << "\n\nTESTY STOSU:\n\n";
stos s;
std::cout << "rozmiar stosu: " << s.ile() << std::endl;
s.wstaw(4.44);
s += 3.33;
s += 1.23;
std::cout << "element pierwszy do zdjecia: " << s.gotowy() << std::endl;
std::cout << "zdejmuje: " << --s << std::endl;
s += 23.33;
s += 2.21;
s.wstaw(3142.2124);
std::cout << "element pierwszy do zdjecia: " << *s << std::endl;
std::cout << "rozmiar stosu: " << s.ile() << std::endl;
}
void testy_listy()
{
std::cout << "\n\nTESTY LISTY:\n\n";
lista l;
l.wstaw(1, 3.5);
l.wstaw(0, 10.2);
l.wstaw(2, 8.1);
std::cout << l.usun(1);
std::cout << " " << l.usun(1);
std::cout << " " << l.usun(0) << "\n";
l.wstaw(0, 1.44);
l.wstaw(0, 44.1);
std::cout << "Lista l w chwili obecnej: ";
std::cout << l << "\n";
lista l2 = l;
std::cout << "Lista l2 zainicjalizowana lista l: " << l2 << "\n";
lista l3 = std::move(l2);
std::cout << "Lista l2 przeniesiona do l3: " << l3 << "\n";
std::cout << "Dodaje do l 3.12 i 4.13. Nastepnie przypisuje ja liscie l3: ";
l.wstaw(5, 3.12);
l.wstaw(1, 4.13);
l3 = l;
std::cout << l3 << std::endl;
std::cout << "Rozmiar l3: " << l3.getSize() << std::endl;
std::cout << "Trzeci element l3: " << l3[2] << std::endl;
std::cout << "Wczytuje przeladowanym operatorem >> do l3: ";
std::cin >> l3;
std::cout << l3 << std::endl;
}
|
5cb9896cc1410da614f8f8786c508b075ee99831
|
8126d163872d9c2e56c6628f41e259d88168fc9f
|
/src/game.h
|
a8a8f5e0efdd1d6e791c9a5cdb31f1493d62ae49
|
[
"BSD-2-Clause-Views",
"BSD-2-Clause"
] |
permissive
|
XProger/OpenLara
|
8c16a7cafdcd44c74356e0c6b7a1d0ab38c20191
|
d2e363db886b0aa2b666aa5d44a1beef321665d7
|
refs/heads/master
| 2023-08-31T14:13:08.805461
| 2023-06-28T22:54:59
| 2023-06-28T22:54:59
| 65,638,810
| 4,515
| 466
|
BSD-2-Clause
| 2023-09-10T18:01:09
| 2016-08-13T22:06:58
|
C
|
UTF-8
|
C++
| false
| false
| 9,832
|
h
|
game.h
|
#ifndef H_GAME
#define H_GAME
#include "core.h"
#include "format.h"
#include "cache.h"
#include "inventory.h"
#include "level.h"
#include "ui.h"
#include "savegame.h"
#define MAX_CHEAT_SEQUENCE 8
namespace Game {
Level *level;
Stream *nextLevel;
ControlKey cheatSeq[MAX_PLAYERS][MAX_CHEAT_SEQUENCE];
void cheatControl(int32 playerIndex) {
ControlKey key = Input::lastState[playerIndex];
if (key == cMAX || !level || level->level.isTitle() || level->level.isCutsceneLevel()) return;
const ControlKey CHEAT_ALL_WEAPONS_1[] = { cLook, cWeapon, cDash, cDuck, cDuck, cDash, cRoll, cLook };
const ControlKey CHEAT_ALL_WEAPONS_2[] = { cWeapon, cLook, cWeapon, cLook, cWeapon, cLook, cWeapon, cLook };
const ControlKey CHEAT_SKIP_LEVEL_1[] = { cDuck, cDash, cLook, cRoll, cWeapon, cLook, cDash, cDuck };
const ControlKey CHEAT_SKIP_LEVEL_2[] = { cJump, cLook, cJump, cLook, cJump, cLook, cJump, cLook };
const ControlKey CHEAT_DOZY_MODE[] = { cWalk, cLook, cWalk, cLook, cWalk, cLook, cWalk, cLook };
for (int i = 0; i < MAX_CHEAT_SEQUENCE - 1; i++)
cheatSeq[playerIndex][i] = cheatSeq[playerIndex][i + 1];
cheatSeq[playerIndex][MAX_CHEAT_SEQUENCE - 1] = key;
#define CHECK_CHEAT(seq) (!memcmp(&cheatSeq[playerIndex][MAX_CHEAT_SEQUENCE - COUNT(seq)], seq, sizeof(seq)))
// add all weapons
if (CHECK_CHEAT(CHEAT_ALL_WEAPONS_1) || CHECK_CHEAT(CHEAT_ALL_WEAPONS_2))
{
inventory->addWeapons();
level->playSound(TR::SND_SCREAM);
}
// skip level
if (CHECK_CHEAT(CHEAT_SKIP_LEVEL_1) || CHECK_CHEAT(CHEAT_SKIP_LEVEL_2))
{
level->loadNextLevel();
}
// dozy mode
if (CHECK_CHEAT(CHEAT_DOZY_MODE))
{
Lara *lara = (Lara*)level->getLara(playerIndex);
if (lara) {
lara->setDozy(true);
}
}
}
void startLevel(Stream *lvl) {
TR::LevelID id = TR::LVL_MAX;
if (level)
id = level->level.id;
Input::stopJoyVibration();
bool playVideo = true;
if (loadSlot != -1)
playVideo = !saveSlots[loadSlot].isCheckpoint();
delete level;
level = new Level(*lvl);
bool playLogo = level->level.isTitle() && id == TR::LVL_MAX;
playVideo = playVideo && (id != level->level.id);
if (level->level.isTitle() && id != TR::LVL_MAX && !TR::isGameEnded)
playVideo = false;
level->init(playLogo, playVideo);
UI::game = level;
#if !defined(INV_GAMEPAD_ONLY)
UI::helpTipTime = 5.0f;
#endif
delete lvl;
}
}
void loadLevelAsync(Stream *stream, void *userData) {
if (!stream) {
if (Game::level) Game::level->isEnded = false;
return;
}
Game::nextLevel = stream;
}
void loadSettings(Stream *stream, void *userData) {
if (stream) {
uint8 version;
stream->read(version);
if (version == SETTINGS_VERSION && stream->size == sizeof(Core::Settings))
stream->raw((char*)&Core::settings + 1, stream->size - 1); // read settings data right after version number
delete stream;
}
if (Core::settings.detail.stereo == Core::Settings::STEREO_VR) {
osToggleVR(true);
}
Core::settings.version = SETTINGS_VERSION;
Core::setVSync(Core::settings.detail.vsync != 0);
#if defined(_GAPI_SW) || defined(_GAPI_GU)
Core::settings.detail.filter = Core::Settings::LOW;
Core::settings.detail.lighting = Core::Settings::LOW;
Core::settings.detail.shadows = Core::Settings::LOW;
Core::settings.detail.water = Core::Settings::LOW;
#endif
shaderCache = new ShaderCache();
Game::startLevel((Stream*)userData);
}
static void readSlotAsync(Stream *stream, void *userData) {
if (!stream) {
saveResult = SAVE_RESULT_ERROR;
return;
}
readSaveSlots(stream);
delete stream;
saveResult = SAVE_RESULT_SUCCESS;
}
void readSlots() {
ASSERT(saveResult != SAVE_RESULT_WAIT);
if (saveResult == SAVE_RESULT_WAIT)
return;
LOG("Read Slots...\n");
saveResult = SAVE_RESULT_WAIT;
osReadSlot(new Stream(SAVE_FILENAME, NULL, 0, readSlotAsync, NULL));
}
namespace Game {
void stopChannel(Sound::Sample *channel) {
if (level) level->stopChannel(channel);
}
void init(Stream *lvl) {
loadSlot = -1;
nextLevel = NULL;
shaderCache = NULL;
level = NULL;
memset(cheatSeq, 0, sizeof(cheatSeq));
Core::init();
Sound::callback = stopChannel;
if (lvl->size == -1) {
delete lvl;
Core::quit();
return;
}
Core::settings.version = SETTINGS_READING;
Stream::cacheRead("settings", loadSettings, lvl);
readSlots();
}
void init(const char *lvlName = NULL) {
#ifdef DEBUG_RENDER
Debug::init();
#endif
char fileName[255];
TR::isGameEnded = false;
TR::Version version = TR::getGameVersion();
if (!lvlName)
TR::getGameLevelFile(fileName, version, TR::getTitleId(version));
else
strcpy(fileName, lvlName);
inventory = new Inventory();
init(new Stream(fileName));
}
void deinit() {
freeSaveSlots();
#ifdef DEBUG_RENDER
Debug::deinit();
#endif
delete inventory;
delete level;
UI::deinit();
delete shaderCache;
Core::deinit();
}
void updateTick() {
Input::update();
Network::update();
for (int32 i = 0; i < MAX_PLAYERS; i++)
{
if (level->players[i]) {
cheatControl(i);
}
}
// Only check for cStart if the inventory is not active.
// Otherwise if cStart was binded to item selection key in inventory it would reset the player.
if (!level->level.isTitle() && !inventory->isActive()) {
if (Input::lastState[0] == cStart) level->addPlayer(0);
if (Input::lastState[1] == cStart) level->addPlayer(1);
}
float dt = Core::deltaTime;
if (Input::down[ikR]) // slow motion (for animation debugging)
Core::deltaTime /= 10.0f;
if (Input::down[ikT]) // fast motion
for (int i = 0; i < 9; i++)
level->update();
level->update();
Core::deltaTime = dt;
}
void quickSave() {
if (!level || TR::isTitleLevel(level->level.id) || TR::isCutsceneLevel(level->level.id)) {
return;
}
level->saveGame(level->level.id, true, false);
}
void quickLoad(bool forced = false) {
if (!level) return;
int slot = getSaveSlot(level->level.id, true);
if (slot == -1) {
slot = getSaveSlot(level->level.id, false);
}
if (slot > -1) {
level->loadGame(slot);
if (forced) {
level->loadGame(slot);
level->loadLevel(saveSlots[slot].getLevelID());
level->loadNextLevelData();
if (nextLevel) {
startLevel(nextLevel);
nextLevel = NULL;
inventory->titleTimer = 0.0f;
}
}
}
}
bool update() {
// async load for settings
if (Core::settings.version == SETTINGS_READING)
return true;
PROFILE_MARKER("UPDATE");
if (!Core::update())
return false;
float delta = Core::deltaTime;
if (nextLevel) {
startLevel(nextLevel);
nextLevel = NULL;
}
if (level->isEnded)
return true;
#ifdef _DEBUG
if (Input::down[ikF]) {
level->flipMap();
Input::down[ikF] = false;
}
#endif
#ifdef _DEBUG_SHADERS
if (Input::down[ikCtrl] && Input::down[ik1]) {
delete shaderCache;
shaderCache = new ShaderCache();
Input::down[ik1] = false;
}
#endif
if (Input::down[ik5] && !inventory->isActive()) {
if (level->players[0]->canSaveGame())
quickSave();
Input::down[ik5] = false;
}
if (Input::down[ik9] && !inventory->isActive()) {
quickLoad();
Input::down[ik9] = false;
}
if (!level->level.isCutsceneLevel())
delta = min(0.2f, delta);
while (delta > EPS) {
Core::deltaTime = min(delta, 1.0f / 30.0f);
Game::updateTick();
delta -= Core::deltaTime;
if (Core::resetState) // resetTime was called
break;
}
return true;
}
bool frameBegin() {
if (Core::settings.version == SETTINGS_READING) return false;
Core::reset();
if (Core::beginFrame()) {
level->renderPrepare();
return true;
}
return false;
}
void frameRender() {
if (Core::settings.version == SETTINGS_READING) return;
PROFILE_MARKER("RENDER");
PROFILE_TIMING(Core::stats.tFrame);
level->render();
#ifdef DEBUG_RENDER
level->renderDebug();
#endif
}
void frameEnd() {
if (Core::settings.version == SETTINGS_READING) return;
UI::renderTouch();
Core::endFrame();
}
bool render() {
if (frameBegin()) {
frameRender();
frameEnd();
return true;
}
return false;
}
}
#endif
|
13b144471343f064abff76bc92b0c8272e16e5fc
|
bcd6309fd23189bd17522575f2ed4e1fb8dbc0e5
|
/Win32/应用程序/进程/semaphore/semaphore_creater/create.cpp
|
9c73fa5e7b207a6f2c1f65da897c92d2eba097be
|
[] |
no_license
|
qqzxingchen/CodeDB
|
f6ed63ee165fe9f67b8b98a77e1e949881456449
|
7bab59fa69a1c132d79e45d4950dc8b575769a5b
|
refs/heads/master
| 2021-01-10T04:47:59.199551
| 2015-12-10T01:57:34
| 2015-12-10T01:57:34
| 47,730,470
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 989
|
cpp
|
create.cpp
|
#include <Windows.h>
#include <stdio.h>
#define MAX_PRODUCTOR 10
TCHAR SEMAPHORENAME[]=TEXT("XINGCHEN_SEMAPHORE");
DWORD WINAPI productor(LPVOID lp){
HANDLE handle;
handle=OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,SEMAPHORENAME);
WaitForSingleObject(handle,INFINITE);
Sleep(1000);
printf("now end\n");
ReleaseSemaphore(handle,2,NULL);
return 0;
}
int main(){
HANDLE handle;
HANDLE pHandle[MAX_PRODUCTOR];
int i;
handle=CreateSemaphore(NULL,0,4,SEMAPHORENAME);
if(handle==NULL){
MessageBox(NULL,TEXT("Create Semaphore Error!"),TEXT("Create"),NULL);
return 0;
}
for(i=0;i<MAX_PRODUCTOR;i++){
pHandle[i]=CreateThread(NULL,0,productor,NULL,0,NULL);
if(pHandle[i]==INVALID_HANDLE_VALUE){
for(i=i-1;i>=0;i--){
CloseHandle(pHandle[i]);
}
CloseHandle(handle);
return 0;
}
}
printf("now start\n");
ReleaseSemaphore(handle,1,NULL);
WaitForMultipleObjects(MAX_PRODUCTOR,pHandle,TRUE,INFINITE);
CloseHandle(handle);
system("pause");
return 0;
}
|
5baae53854fc5883f93dd8bcff6c6d5c347b82e5
|
f2a3f5d48522c8aa0646415bc4a47ef3c383cab9
|
/Code/SVM Classifier/WORDLIST.H
|
a60e960cfc9255915bc6a97f440d8f50d00011f1
|
[] |
no_license
|
ranjiGT/Research-of-Topic-Shifts-in-Comment-Based-Social-Network
|
a6035ef9cb5fd1b1bc3afa5ac2bb18b01b425c34
|
fabd0f6766863411b6ff56965236bc9bf5f214c7
|
refs/heads/master
| 2023-03-15T20:38:56.833220
| 2020-06-05T03:17:17
| 2020-06-05T03:17:17
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,608
|
h
|
WORDLIST.H
|
// WordList.h: interface for the CWordList class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_WORDLIST_H__D7A246C0_9CD0_11D3_BAA2_0000250394FE__INCLUDED_)
#define AFX_WORDLIST_H__D7A246C0_9CD0_11D3_BAA2_0000250394FE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <afxtempl.h>
#define CataMax 200
class CWordNode;
void AFXAPI SerializeElements(CArchive& ar,CWordNode* pElements,int nCount);
class CWordNode
{
public:
CWordNode();
~CWordNode();
CWordNode& operator = (const CWordNode& x);
void AllocBuffer(int nLen);
void DeallocBuffer();
void Serialize(CArchive& ar);
public:
void Copy(CWordNode& wordNode);
void InitBuffer(int nLen);
long GetWordNum();
long GetDocNum();
long GetCataWordNum(int cataID);
long GetCataDocNum(int cataID);
int MaxWeightIndex();
void ComputeWeight(long sum, bool bMult=false);
//在特征选择的时候用来保存特征的类别区分度
//在特征选择完成之后,它用来保存每个特征的"log(训练文档总数/特征的文档频率)"值
double m_dWeight;
short m_nAllocLen;
int m_nWordID; //特征的ID
double *m_pCataWeight; //特征对于每个类别的区分度
double *m_pCataWeightPro; //特征属于每个类别的概率
//特征在整个文档集中的文档频率,实际就是函数GetDocNum()返回的值
//如果特征不是从训练文档集中选择得到的,就无法使用GetDocNum()得到特征的文档频率
//所以,此处使用m_lDocFreq来记录特征的文档频率
long m_lDocFreq; //特征在整个文档集中的文档频率
//特征在整个文档集中的词频,实际就是函数GetWordNum()返回的值
//如果特征不是从训练文档集中选择得到的,就无法使用GetWordNum()得到特征的词频
//所以,此处使用m_lWordFreq来记录特征的词频
long m_lWordFreq; //特征在整个文档集中的词频
long *m_pCataDocFreq; //特征在每一个类别中的文档频率
long *m_pCataWordFreq; //特征在每一个类别中的词频
long m_lDocID; //得到特征的文档频率的时候用到
};
AFX_INLINE UINT AFXAPI HashKey(CString key);
typedef CTypedPtrList<CPtrList,CWordNode*> CPWordList;
class CWordList
{
public:
CWordNode& Add(const CString str, long docID);
bool GetListFromFile(CString strFileName);
CString GetWordByID(long wordID);
CWordList();
CWordList& operator =(CWordList &x);
virtual ~CWordList();
void Serialize(CArchive& ar);
void DumpToFile(CString strFileName);
void DumpWordList(CString strFileName);
void DumpWordProList(CString strFileName,int CataNum);
bool GetFromFile(CString strFileName);
void InitWordList();
//如果词表中不存在这个词,则加入词表
CWordNode& Add(const CString);
//如果词表中不存在这个词,则加入词表,并且根据docID决定文档频率是否加1
CWordNode& Add(const CString, short, long, int);
void SetAt(const CString,CWordNode&);
//获得词表中词的总数
int GetCount();
long GetWordNum();
BOOL Lookup(CString str, CWordNode &wordNode);
CWordNode& GetNext(POSITION &, CString &);
POSITION GetFirstPosition(void);
void IndexWord();
//计算每个词的反比文档频率
void ComputeWeight(long sum, bool bMult=false);
public :
bool GetProFromFile(CString strFileName);
CWordNode& GetWordProByID(POSITION& pos,int j);
double GetWordProByID(POSITION &pos,long wordID,int classnum);
CMap<CString,CString,CWordNode,CWordNode&> m_lstWordList;
};
#endif // !defined(AFX_WORDLIST_H__D7A246C0_9CD0_11D3_BAA2_0000250394FE__INCLUDED_)
|
dcc317225d7818ab869ae106281f5fc8af59b92a
|
a5abae2a2fb2ee5e9ee2477fabd4d5b1878869d8
|
/cpp-modules/module-01/ex03/HumanA.hpp
|
be20f698fa1247d21650e7c7efd2a409c111e696
|
[] |
no_license
|
RafaPC/academia42
|
928e512e93f518c4b461dc98b37c763d3ba766e2
|
3df0ca545c21544cd8325c862b812fae34af1ec7
|
refs/heads/master
| 2022-06-28T18:43:28.036163
| 2022-06-17T10:33:14
| 2022-06-17T10:33:14
| 219,798,721
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 219
|
hpp
|
HumanA.hpp
|
#ifndef HUMANA_HPP
# define HUMANA_HPP
# include <string>
# include "Weapon.hpp"
class HumanA
{
public:
std::string name;
Weapon& weapon;
HumanA( std::string name_, Weapon& weapon_ );
void attack(void);
};
#endif
|
925168fe396fb4fb05fca0850854129e3a640ac6
|
6840356bb8428865c1c64fa8ca9b42c0aca348a7
|
/Core/SoarKernel/src/semantic_memory/smem_structs.h
|
0df14efdeee7301c48419cb331776b67a5e0d192
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
SoarGroup/Soar
|
a5c7281e0673665a4b7eddd39ae4e5eb2a507aef
|
ef42bb24f7b58f9d244c83f5a2f2153c3ee17b77
|
refs/heads/development
| 2023-09-01T08:47:44.349033
| 2023-08-31T22:54:57
| 2023-08-31T22:54:57
| 21,206,914
| 289
| 86
|
NOASSERTION
| 2023-09-14T05:14:06
| 2014-06-25T14:50:12
|
C++
|
UTF-8
|
C++
| false
| false
| 3,143
|
h
|
smem_structs.h
|
/*
* smem_typedefs.h
*
* Created on: Aug 21, 2016
* Author: mazzin
*/
#ifndef CORE_SOARKERNEL_SRC_SEMANTIC_MEMORY_SMEM_STRUCTS_H_
#define CORE_SOARKERNEL_SRC_SEMANTIC_MEMORY_SMEM_STRUCTS_H_
#include "kernel.h"
#include "stl_typedefs.h"
#include <queue>
typedef struct smem_data_struct
{ uint64_t last_cmd_time[2]; // last update to smem.command
uint64_t last_cmd_count[2]; // last update to smem.command
preference_list* smem_wmes; // wmes in last smem
wme* smem_link_wme;
wme* cmd_wme;
wme* result_wme;
} smem_data;
typedef struct ltm_object_struct
{
uint64_t lti_id;
ltm_slot_map* slots;
} ltm_object;
struct ltm_value_const
{ smem_cue_element_type val_type;
Symbol* val_value;
};
struct ltm_value_lti
{ smem_cue_element_type val_type;
ltm_object* val_value;
double edge_weight;
};
typedef struct smem_vis_lti_struct
{ uint64_t lti_id;
std::string lti_name;
unsigned int level;
} smem_vis_lti;
typedef struct smem_weighted_cue_element_struct
{ uint64_t weight;
struct wme_struct* cue_element;
smem_hash_id attr_hash;
smem_hash_id value_hash;
uint64_t value_lti;
smem_cue_element_type element_type;
bool pos_element;
MathQuery* mathElement;
} smem_weighted_cue_element;
struct smem_compare_weighted_cue_elements
{
bool operator()(const smem_weighted_cue_element* a, const smem_weighted_cue_element* b) const { return (a->weight > b->weight); }
};
struct smem_compare_activated_lti
{
bool operator()(const smem_activated_lti a, const smem_activated_lti b) const { return (b.first > a.first); }
};
typedef std::priority_queue<smem_weighted_cue_element*, std::vector<smem_weighted_cue_element*>, smem_compare_weighted_cue_elements> smem_prioritized_weighted_cue;
typedef std::priority_queue< smem_activated_lti, std::vector<smem_activated_lti>, smem_compare_activated_lti> smem_prioritized_activated_lti_queue;
typedef std::pair<double, std::list<std::pair<uint64_t,double>>*> smem_activated_lti_list;
struct smem_compare_activated_lti_list
{
bool operator()(const smem_activated_lti_list a, const smem_activated_lti_list b) const
{
return (b.first > a.first);
}
};
typedef std::priority_queue<smem_activated_lti_list, std::vector<smem_activated_lti_list>, smem_compare_activated_lti_list> smem_prioritized_lti_traversal_queue;
typedef struct smem_edge_update_struct
{
uint64_t lti_edge_id;
double num_touches;
uint64_t update_time;
} smem_edge_update;
typedef std::unordered_map<uint64_t, std::list<smem_edge_update*>> smem_update_map;
typedef union ltm_value_union
{
struct ltm_value_const val_const;
struct ltm_value_lti val_lti;
} ltm_value;
#endif /* CORE_SOARKERNEL_SRC_SEMANTIC_MEMORY_SMEM_STRUCTS_H_ */
|
81e01064b4c73d8bc37d2fb5cd26a500c58f7808
|
b3b8a20021ab8ccc4d730f47685f32332a8979af
|
/server/db_server/dbWrapper/databasemysql.cc
|
3569ca1f6a540bb596ead34589f624f8eadd255e
|
[
"BSD-3-Clause"
] |
permissive
|
yuqingtong1990/ggtalk_server
|
44038c3ebd2fd959100e5b4042dacbbe395dc6fb
|
e28f8542ccc259772fc492b6c703d3b3d495d36a
|
refs/heads/master
| 2020-04-11T15:48:18.665688
| 2018-12-30T13:01:47
| 2018-12-30T13:01:47
| 161,903,527
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,287
|
cc
|
databasemysql.cc
|
#include <fstream>
#include <stdarg.h>
#include "databasemysql.h"
#include "evpp/logging.h"
Field::Field() :
mType(DB_TYPE_UNKNOWN)
{
m_bNULL = false;
}
Field::Field(Field &f)
{
m_strValue = f.m_strValue;
m_strFieldName = f.m_strFieldName;
mType = f.GetType();
}
Field::Field(const char *value, enum Field::DataTypes type) :
mType(type)
{
m_strValue = value;
}
Field::~Field()
{
}
void Field::SetValue(const char *value, size_t uLen)
{
//m_strValue = value;
m_strValue.assign(value, uLen);
}
QueryResult::QueryResult(MYSQL_RES *result, uint64_t rowCount, uint32_t fieldCount, uint32_t uError)
: mFieldCount(fieldCount), mRowCount(rowCount), mError(uError)
{
mResult = result;
mCurrentRow = new Field[mFieldCount];
assert(mCurrentRow);
if (mResult == nullptr)
return;
MYSQL_FIELD *fields = mysql_fetch_fields(mResult);
for (uint32_t i = 0; i < mFieldCount; i++)
{
mFieldNames[i] = fields[i].name;
m_vtFieldNames.push_back(fields[i].name);
mCurrentRow[i].SetType(ConvertNativeType(fields[i].type));
}
}
QueryResult::~QueryResult(void)
{
EndQuery();
}
bool QueryResult::NextRow()
{
MYSQL_ROW row;
if (!mResult)
return false;
row = mysql_fetch_row(mResult);
if (!row)
{
EndQuery();
return false;
}
unsigned long int *ulFieldLength;
ulFieldLength = mysql_fetch_lengths(mResult);
for (uint32_t i = 0; i < mFieldCount; i++)
{
if(row[i] == NULL)
{
mCurrentRow[i].m_bNULL = true;
mCurrentRow[i].SetValue("", 0);
}
else
{
mCurrentRow[i].m_bNULL = false;
mCurrentRow[i].SetValue(row[i], ulFieldLength[i]);
}
mCurrentRow[i].SetName(mFieldNames[i]);
}
return true;
}
void QueryResult::EndQuery()
{
if (mCurrentRow)
{
delete [] mCurrentRow;
mCurrentRow = 0;
}
if (mResult)
{
//LOG_INFO << "QueryResult::EndQuery, mysql_free_result";
mysql_free_result(mResult);
mResult = 0;
}
}
enum Field::DataTypes QueryResult::ConvertNativeType(enum_field_types mysqlType) const
{
switch (mysqlType)
{
case FIELD_TYPE_TIMESTAMP:
case FIELD_TYPE_DATE:
case FIELD_TYPE_TIME:
case FIELD_TYPE_DATETIME:
case FIELD_TYPE_YEAR:
case FIELD_TYPE_STRING:
case FIELD_TYPE_VAR_STRING:
case FIELD_TYPE_BLOB:
case FIELD_TYPE_SET:
case FIELD_TYPE_NULL:
return Field::DB_TYPE_STRING;
case FIELD_TYPE_TINY:
case FIELD_TYPE_SHORT:
case FIELD_TYPE_LONG:
case FIELD_TYPE_INT24:
case FIELD_TYPE_LONGLONG:
case FIELD_TYPE_ENUM:
return Field::DB_TYPE_INTEGER;
case FIELD_TYPE_DECIMAL:
case FIELD_TYPE_FLOAT:
case FIELD_TYPE_DOUBLE:
return Field::DB_TYPE_FLOAT;
default:
return Field::DB_TYPE_UNKNOWN;
}
}
CDatabaseMysql::CDatabaseMysql(void)
{
//m_Mysql = new MYSQL;
m_Mysql = NULL;
m_bInit = false;
}
CDatabaseMysql::~CDatabaseMysql(void)
{
if (m_Mysql != NULL)
{
if (m_bInit)
{
mysql_close(m_Mysql);
}
//delete m_Mysql;
}
}
bool CDatabaseMysql::Initialize(const string& host, const string& user, const string& pwd, const string& dbname)
{
//LOG_INFO << "CDatabaseMysql::Initialize, begin...";
//ClearStoredResults();
if(m_bInit)
{
mysql_close(m_Mysql);
}
m_Mysql = mysql_init(m_Mysql);
m_Mysql = mysql_real_connect(m_Mysql, host.c_str(), user.c_str(),
pwd.c_str(), dbname.c_str(), 0, NULL, 0);
//ClearStoredResults();
LOG_INFO << host.c_str() ;
LOG_INFO << user.c_str() ;
LOG_INFO << pwd.c_str() ;
LOG_INFO << dbname.c_str() ;
m_DBInfo.strDBName = dbname;
m_DBInfo.strHost = host;
m_DBInfo.strUser = user;
m_DBInfo.strPwd = pwd;
if (m_Mysql)
{
LOG_INFO << "m_Mysql address " << (long)m_Mysql;
LOG_INFO << "CDatabaseMysql::Initialize, set names utf8";
mysql_query(m_Mysql, "set names utf8");
//mysql_query(m_Mysql, "set names latin1");
m_bInit = true;
return true;
}
else
{
LOG_ERROR << "Could not connect to MySQL database at " << host.c_str()
<< ", " << mysql_error(m_Mysql);
mysql_close(m_Mysql);
return false;
}
LOG_INFO << "CDatabaseMysql::Initialize, init failed!";
return false;
}
QueryResult* CDatabaseMysql::Query(const char *sql)
{
if (!m_Mysql)
{
LOG_INFO << "CDatabaseMysql::Query, mysql is disconnected!";
if(false == Initialize(m_DBInfo.strHost, m_DBInfo.strUser,
m_DBInfo.strPwd, m_DBInfo.strDBName))
{
return NULL;
}
}
if (!m_Mysql)
return 0;
MYSQL_RES *result = 0;
uint64_t rowCount = 0;
uint32_t fieldCount = 0;
uint32_t uErrno = 0;
{
LOG_INFO << sql;
int iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql));
if(iTempRet)
{
unsigned int uErrno = mysql_errno(m_Mysql);
LOG_INFO << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno;
if(CR_SERVER_GONE_ERROR == uErrno)
{
LOG_INFO << "CDatabaseMysql::Query, mysql is disconnected!";
if(false == Initialize(m_DBInfo.strHost, m_DBInfo.strUser,
m_DBInfo.strPwd, m_DBInfo.strDBName))
{
return NULL;
}
LOG_INFO << sql;
iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql));
if(iTempRet)
{
LOG_ERROR << "SQL: " << sql ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
}
else
{
LOG_ERROR << "SQL: " << sql ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
return NULL;
}
}
LOG_INFO << "call mysql_store_result";
uErrno = mysql_errno(m_Mysql);
result = mysql_store_result(m_Mysql);
rowCount = mysql_affected_rows(m_Mysql);
fieldCount = mysql_field_count(m_Mysql);
// end guarded block
}
QueryResult *queryResult = new QueryResult(result, rowCount, fieldCount, uErrno);
queryResult->NextRow();
return queryResult;
}
QueryResult* CDatabaseMysql::PQuery(const char *format,...)
{
if(!format) return NULL;
va_list ap;
char szQuery [MAX_QUERY_LEN];
va_start(ap, format);
int res = vsnprintf( szQuery, MAX_QUERY_LEN, format, ap );
va_end(ap);
if(res==-1)
{
LOG_ERROR << "SQL Query truncated (and not execute) for format: " << format;
return NULL;
}
return Query(szQuery);
}
bool CDatabaseMysql::Execute(const char* sql)
{
if (!m_Mysql)
return false;
{
int iTempRet = mysql_query(m_Mysql, sql);
if(iTempRet)
{
unsigned int uErrno = mysql_errno(m_Mysql);
LOG_INFO << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno;
if(CR_SERVER_GONE_ERROR == uErrno)
{
LOG_INFO << "CDatabaseMysql::Query, mysql is disconnected!";
if(false == Initialize(m_DBInfo.strHost, m_DBInfo.strUser,
m_DBInfo.strPwd, m_DBInfo.strDBName))
{
return false;
}
LOG_INFO << sql;
iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql));
if(iTempRet)
{
LOG_ERROR << "SQL: " << sql ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
}
else
{
LOG_ERROR << "SQL: " << sql ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
return false;
}
}
return true;
}
bool CDatabaseMysql::Execute(const char* sql, uint32_t& uAffectedCount, int& nErrno)
{
if (!m_Mysql)
return false;
{
int iTempRet = mysql_query(m_Mysql, sql);
if(iTempRet)
{
unsigned int uErrno = mysql_errno(m_Mysql);
LOG_ERROR << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno;
if(CR_SERVER_GONE_ERROR == uErrno)
{
LOG_ERROR << "CDatabaseMysql::Query, mysql is disconnected!";
if(false == Initialize(m_DBInfo.strHost, m_DBInfo.strUser,
m_DBInfo.strPwd, m_DBInfo.strDBName))
{
return false;
}
LOG_INFO << sql;
iTempRet = mysql_query(m_Mysql, sql);
nErrno = iTempRet;
if(iTempRet)
{
LOG_ERROR << "SQL: " << sql ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
}
else
{
LOG_ERROR << "SQL: " << sql ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
return false;
}
uAffectedCount = static_cast<uint32_t>(mysql_affected_rows(m_Mysql));
}
return true;
}
bool CDatabaseMysql::PExecute(const char * format,...)
{
if (!format)
return false;
va_list ap;
char szQuery [MAX_QUERY_LEN];
va_start(ap, format);
int res = vsnprintf( szQuery, MAX_QUERY_LEN, format, ap );
va_end(ap);
if(res==-1)
{
LOG_ERROR << "SQL Query truncated (and not execute) for format: " << format;
return false;
}
if (!m_Mysql)
return false;
{
int iTempRet = mysql_query(m_Mysql, szQuery);
if(iTempRet)
{
unsigned int uErrno = mysql_errno(m_Mysql);
LOG_ERROR << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno;
if(CR_SERVER_GONE_ERROR == uErrno)
{
LOG_ERROR << "CDatabaseMysql::Query, mysql is disconnected!";
if(false == Initialize(m_DBInfo.strHost, m_DBInfo.strUser,
m_DBInfo.strPwd, m_DBInfo.strDBName))
{
return false;
}
LOG_INFO << szQuery;
iTempRet = mysql_query(m_Mysql, szQuery);
if(iTempRet)
{
LOG_ERROR << "SQL: " << szQuery ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
}
else
{
LOG_ERROR << "SQL: " << szQuery ;
LOG_ERROR << "query ERROR: " << mysql_error(m_Mysql);
}
return false;
}
}
return true;
}
void CDatabaseMysql::ClearStoredResults()
{
if(!m_Mysql)
{
return;
}
MYSQL_RES* result = NULL;
while(!mysql_next_result(m_Mysql))
{
if((result = mysql_store_result(m_Mysql)) != NULL)
{
mysql_free_result(result);
}
}
}
uint32_t CDatabaseMysql::GetInsertID()
{
return (uint32_t)mysql_insert_id(m_Mysql);
}
int32_t CDatabaseMysql::EscapeString(char* szDst, const char* szSrc, uint32_t uSize)
{
if (m_Mysql == NULL)
{
return 0;
}
if (szDst == NULL || szSrc == NULL)
{
return 0;
}
return mysql_real_escape_string(m_Mysql, szDst, szSrc, uSize);
}
|
2cbd04fee9754075f1a74bf1bee43124601d1da1
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/base/ntsetup/opktools/depend/list.h
|
037bc0cf985a01f26110756b9a9ff691c98a52e2
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 608
|
h
|
list.h
|
// List.h: interface for the List class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_LIST_H__8579C184_3703_4719_8FCB_5A91A9CA7E4E__INCLUDED_)
#define AFX_LIST_H__8579C184_3703_4719_8FCB_5A91A9CA7E4E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Object.h"
class List
{
public:
Object* head,*tail;
int length;
List();
virtual ~List();
void Add(Object* o);
void Remove(TCHAR* s);
Object* Find(Object* o);
Object* Find(TCHAR* s);
};
#endif // !defined(AFX_LIST_H__8579C184_3703_4719_8FCB_5A91A9CA7E4E__INCLUDED_)
|
105a15846355d35f32b31a43f638283c5c688561
|
3571bee08ecbc24aa20a121e06877818c6dc640c
|
/BillSender.cpp
|
7637e92404eb31a141c6ec3bb45d4fe1fa384482
|
[] |
no_license
|
VorTechS/BillSender
|
a43671c17ad462a9ee11cc39664e190c60a6bf34
|
ce8b7857305d4068a9bd5887008748da15b72b23
|
refs/heads/master
| 2021-12-02T02:46:30.918464
| 2014-03-04T15:29:00
| 2014-03-04T15:29:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,724
|
cpp
|
BillSender.cpp
|
// BillSender.cpp : main project file.
#include "stdafx.h"
#include "Form1.h"
#include <shlobj.h>
#include <vcclr.h>
#include <Windows.h>
#include <Wia.h>
#include <Objbase.h>
#include <comdef.h>
#include <string>
using namespace BillSender;
TCHAR DIRECTORY[MAX_PATH];
_bstr_t DevID;
[STAThreadAttribute]
#pragma comment(lib, "shell32.lib")
HRESULT CreateWiaDeviceManager(IWiaDevMgr2** ppWiaDevMgr)
{
// Validate arguments
if (NULL == ppWiaDevMgr)
{
return E_INVALIDARG;
}
// Initialize out variables
*ppWiaDevMgr = NULL;
// Create an instance of the device manager
HRESULT hr = CoCreateInstance(CLSID_WiaDevMgr2, NULL, CLSCTX_LOCAL_SERVER, IID_IWiaDevMgr2, (void**)ppWiaDevMgr);
// Return the result of creating the device manager
return hr;
}
HRESULT CreateWiaDevice( IWiaDevMgr2 *pWiaDevMgr, BSTR bstrDeviceID, IWiaItem2 **ppWiaDevice )
{
// Validate arguments
if (NULL == pWiaDevMgr || NULL == bstrDeviceID || NULL == ppWiaDevice)
{
return E_INVALIDARG;
}
// Initialize out variables
*ppWiaDevice = NULL;
// Create the WIA Device
HRESULT hr = pWiaDevMgr->CreateDevice(0, bstrDeviceID, ppWiaDevice );
// Return the result of creating the device
return hr;
}
HRESULT ReadSomeWiaProperties( IWiaPropertyStorage *pWiaPropertyStorage )
{
// Validate arguments
if (NULL == pWiaPropertyStorage)
{
return E_INVALIDARG;
}
// Declare PROPSPECs and PROPVARIANTs, and initialize them to zero.
PROPSPEC PropSpec[3] = {0};
PROPVARIANT PropVar[3] = {0};
//
// How many properties are you querying for?
//
const ULONG c_nPropertyCount = sizeof(PropSpec)/sizeof(PropSpec[0]);
// Define which properties you want to read:
// Device ID. This is what you would use to create
// the device.
PropSpec[0].ulKind = PRSPEC_PROPID;
PropSpec[0].propid = WIA_DIP_DEV_ID;
// Device Name
PropSpec[1].ulKind = PRSPEC_PROPID;
PropSpec[1].propid = WIA_DIP_DEV_NAME;
// Device description
PropSpec[2].ulKind = PRSPEC_PROPID;
PropSpec[2].propid = WIA_DIP_DEV_DESC;
// Ask for the property values
HRESULT hr = pWiaPropertyStorage->ReadMultiple( c_nPropertyCount, PropSpec, PropVar );
if (SUCCEEDED(hr))
{
// IWiaPropertyStorage::ReadMultiple will return S_FALSE if some
// properties could not be read, so you have to check the return
// types for each requested item.
// Check the return type for the device ID
if (VT_BSTR == PropVar[0].vt)
{
DevID = PropVar[0].bstrVal;
}
// Check the return type for the device name
if (VT_BSTR == PropVar[1].vt)
{
// Do something with the device name
//_tprintf( TEXT("WIA_DIP_DEV_NAME: %ws\n"), PropVar[1].bstrVal );
}
// Check the return type for the device description
if (VT_BSTR == PropVar[2].vt)
{
// Do something with the device description
//_tprintf( TEXT("WIA_DIP_DEV_DESC: %ws\n"), PropVar[2].bstrVal );
}
// Free the returned PROPVARIANTs
FreePropVariantArray( c_nPropertyCount, PropVar );
}
// Return the result of reading the properties
return hr;
}
HRESULT GetWiaDevices( IWiaDevMgr2 *pWiaDevMgr ) //Vista or later
{
// Validate arguments
if (NULL == pWiaDevMgr)
{
return E_INVALIDARG;
}
// Get a device enumerator interface
IEnumWIA_DEV_INFO *pWiaEnumDevInfo = NULL;
HRESULT hr = pWiaDevMgr->EnumDeviceInfo( WIA_DEVINFO_ENUM_LOCAL, &pWiaEnumDevInfo );
if (SUCCEEDED(hr))
{
// Loop until you get an error or pWiaEnumDevInfo->Next returns
// S_FALSE to signal the end of the list.
while (S_OK == hr)
{
// Get the next device's property storage interface pointer
IWiaPropertyStorage *pWiaPropertyStorage = NULL;
hr = pWiaEnumDevInfo->Next( 1, &pWiaPropertyStorage, NULL );
// pWiaEnumDevInfo->Next will return S_FALSE when the list is
// exhausted, so check for S_OK before using the returned
// value.
if (hr == S_OK)
{
// Do something with the device's IWiaPropertyStorage*
ReadSomeWiaProperties(pWiaPropertyStorage);
// Release the device's IWiaPropertyStorage*
pWiaPropertyStorage->Release();
pWiaPropertyStorage = NULL;
}
}
// If the result of the enumeration is S_FALSE (which
// is normal), change it to S_OK.
if (S_FALSE == hr)
{
hr = S_OK;
}
// Release the enumerator
pWiaEnumDevInfo->Release();
pWiaEnumDevInfo = NULL;
}
// Return the result of the enumeration
return hr;
}
//Get the file count so we can number the files
int GetFileCount()
{
String^ line;
int value = 0;
try
{
HANDLE HR = CreateFile(L"count.ini", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(HR);
StreamReader^ in = gcnew StreamReader("count.ini");
line = in->ReadLine();
in->Close();
value = Convert::ToInt32(line);
value++;
StreamWriter^ out = gcnew StreamWriter("count.ini");
out->Write(Convert::ToString(value));
out->Close();
}
catch (...){}
return value;
}
//Return user name from emailSettings.ini
String^ UserName()
{
String^ username;
StreamReader^ in = gcnew StreamReader("emailSettings.ini");
username = in->ReadLine();
in->Close();
return username;
}
//Return password from emailSettings.ini
String^ Password()
{
String^ password;
StreamReader^ in = gcnew StreamReader("emailSettings.ini");
password = in->ReadLine();
in->Close();
return password;
}
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Form1());
return 0;
}
/*Handles attaching the files to the email then sends it*/
void Form1::SendBill_Click(System::Object^ sender, System::EventArgs^ e) {
//gmail server info
int port = 587;
String^ server = "smtp.gmail.com";
//To field empty
if (String::IsNullOrEmpty(EmailTo->Text))
{
MessageBox::Show("Please input an email address.", "NO EMAIL ADDRESS", MessageBoxButtons::OK, MessageBoxIcon::Warning);
return;
}
//Subject field empty
if (String::IsNullOrEmpty(EmailSubject->Text))
{
MessageBox::Show("Please input a subject.", "NO SUBJECT", MessageBoxButtons::OK, MessageBoxIcon::Warning);
return;
}
//Check to see if there are images.
if (AttachmentList.Count == 0)
{
MessageBox::Show("There are no scanned images! \n Please scan some images.", "No Images!", MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
//Set the from, to, subject, and body of the email
String^ From = UserName();
MailMessage^ msg = gcnew MailMessage(From, EmailTo->Text);
msg->Subject = EmailSubject->Text;
msg->Body = L"Please see attached files.";
//creat the smtp client that will send the message
SmtpClient^ client = gcnew SmtpClient();
client->Host = server;
client->Port = port;
//set up the credentials for the gmail account
client->UseDefaultCredentials = false;
client->DeliveryMethod = SmtpDeliveryMethod::Network;
client->Credentials = gcnew System::Net::NetworkCredential(UserName(), Password());
//gmail requires ssl
client->EnableSsl = true;
//Attach the image(s)
for (int i = 0; i < AttachmentList.Count; i++)
{
Attachment^ data = gcnew Attachment(AttachmentList[i] + ".jpg");
msg->Attachments->Add(data);
}
//send the message
try
{
client->Send(msg);
}
catch (SmtpFailedRecipientException^ e)
{
MessageBox::Show("Failed to send email to recipient. \n Please make sure email address is correct.", "ERROR", MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
catch (...)
{
MessageBox::Show("Error sending Email. \n Please try again.", "ERROR", MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
client->~SmtpClient();
//Write the email to the recent email list for easy access next time to emails.
StreamWriter^ out = gcnew StreamWriter("recentEmails.txt", true);
out->WriteLine(EmailTo->Text);
out->Close();
ScannedImage->Hide();
EmailTo->Text = "";
EmailSubject->Text = "";
MessageBox::Show("Message sent!", "Success!", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
}
/*Gets the device information, scans in the image, and saves it to disk*/
void Form1::ScanImage_Click(System::Object ^sender, System::EventArgs ^e) {
IWiaDevMgr2* devMgr;
IWiaItem2* item;
HRESULT hr;
LONG x = 0L;
int fileCount = 0;
BSTR *files = new BSTR[0];
bool moreImages = true;
//Setup WIA devices
hr = CreateWiaDeviceManager(&devMgr);
if (hr == S_OK)
hr = GetWiaDevices(devMgr);
if (hr == S_OK)
hr = CreateWiaDevice(devMgr, DevID, &item);
//set folder name
_bstr_t FolderName(DIRECTORY);
while (moreImages)
{
//Generate new filenames for the image.
FileValue = gcnew String("TMS");
fileCount = GetFileCount();
FileValue = FileValue + fileCount;
pin_ptr<const wchar_t> wch = PtrToStringChars(FileValue);
printf_s("%S\n", wch);
_bstr_t FileName(wch);
try
{
//Displays a dialog that allows the user to select properties, then scan.
hr = item->DeviceDlg(0, GetActiveWindow(), FolderName, FileName, &x, &files, &item);
}
catch (...)
{
MessageBox::Show("Failed to scan the image. \n Please make sure the scanner is on.", "ERROR", MessageBoxButtons::OK, MessageBoxIcon::Error);
return;
}
//add filename to attachment list
AttachmentList.Add(FileValue);
//Display the image to the screen
ScannedImage->SizeMode = PictureBoxSizeMode::StretchImage;
ScannedImage->Load(FileValue + ".jpg");
ScannedImage->Show();
//See if the user has more images to scan
System::Windows::Forms::DialogResult dr;
dr = MessageBox::Show("Would you like to scan another image?", "More Images?", MessageBoxButtons::YesNo, MessageBoxIcon::Question);
if (dr == ::DialogResult::Yes)
{
moreImages = true;
}
else if (dr == ::DialogResult::No)
{
moreImages = false;
}
}
}
/*Load recent recipients box and display the welcome image
Also retrieves the 'My Documents' folder for the user*/
void Form1::Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
//Get the my documents directory for the logged in user
HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, DIRECTORY);
//add "\\BillSender\\" to the end of the string to create our directory
std::wstring tmp = L"\\BillSender\\";
int i = 0;
bool flag = true;
while (flag)
{
if (DIRECTORY[i] == NULL)
{
for (int x = 0; x < tmp.size(); x++)
{
if (DIRECTORY[i + x] == NULL)
{
DIRECTORY[i + x] = tmp[x];
}
}
flag = false;
}
i++;
}
//create the BillSender directory if it doesn't exist, then set the current directory
CreateDirectory(DIRECTORY, NULL);
SetCurrentDirectory(DIRECTORY);
//Show Welcome image
try
{
ScannedImage->SizeMode = PictureBoxSizeMode::StretchImage;
ScannedImage->Load("WelcomePage.jpg");
ScannedImage->Show();
}
catch (...){}
//read in recent recipients
try
{
//create recentEmails.txt file
HANDLE HR = CreateFile(L"recentEmails.txt", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(HR);
StreamReader^ in = gcnew StreamReader("recentEmails.txt");
String^ Recipient;
while ((Recipient = in->ReadLine()) != nullptr)
RecentRecipList->Items->Add(Recipient);
in->Close();
}
catch (...){}
}
/*Double click an email to place it into the email field*/
void Form1::RecentRecipList_DoubleClick(System::Object^ sender, System::EventArgs^ e)
{
//Clear text box
EmailTo->Text = "";
String^ Recipient = RecentRecipList->FocusedItem->Text;
EmailTo->Text = Recipient;
}
//Open the email settings form
void Form1::emailSettingsToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)
{
EmailSettings^ form = gcnew EmailSettings;
form->Show();
}
|
304104bcaaedad35741ec194278ead726a0e28d3
|
188331e28d33965794e7ea99365a10946768912b
|
/2580_sudoku.cpp
|
1827099ad0043e8596a1f64fa7c26cca15300cc7
|
[] |
no_license
|
fernok/baekjoon
|
17e69ceae3fe33463912d36b5218d5085d1b99f4
|
837d64de25076d0f730019252ddb21b66f6fb746
|
refs/heads/master
| 2021-01-25T23:49:59.085425
| 2020-05-16T03:45:05
| 2020-05-16T03:45:05
| 243,229,971
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,128
|
cpp
|
2580_sudoku.cpp
|
#include <iostream>
using namespace std;
int sudoku[9][9] ={0,};
int row = 0;
bool isValid(int cnt, int row, int value){
int i, j;
for(i=0; i<9; i++){
if(sudoku[row][i] == value){
return false;
}
}
for(i=0; i<9; i++){
if(sudoku[i][cnt]==value){
return false;
}
}
for(i=0; i<3; i++){
for(j=0; j<3; j++){
if(sudoku[row/3 + i][cnt/3 + j] == value){
return false;
}
}
}
return true;
}
void Print(){
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
cout<<sudoku[i][j]<<" ";
}
cout<<"\n";
}
return;
}
void Solve(int cnt){
if(cnt > 8){
cnt = 0;
row++;
}
for(int i=1; i<10; i++){
while(sudoku[row][cnt] != 0 && cnt<9){
cnt++;
cout<<cnt<<" ";
}
if(isValid(cnt, row, i) && sudoku[row][cnt] == 0){
sudoku[row][cnt] = i;
Solve(cnt+1);
}
}
cout<<cnt<<" "<<row<<"\n";
if(row ==8 && cnt == 8){
cout<<"hello\n";
Print();
}
}
int main(void){
int i, j;
for(i=0; i<9; i++){
for(j=0; j<9; j++){
cin>>sudoku[i][j];
}
}
Solve(0);
return 0;
}
|
7423e945e208017dc55b786b7bfecbb48433913c
|
58908b853019a16797de19eebca453988e200273
|
/JobDu1084.cpp
|
7083c72eedf8a7a85c812574c34a4f49cd945e4a
|
[] |
no_license
|
BasicCoder/JobDu1
|
7b165c9caa490e35024899515047750448bddb06
|
00ec5a5d86df3857c6bbe23adce7b8e44ce6e481
|
refs/heads/master
| 2021-01-20T16:18:19.851151
| 2017-03-28T11:59:32
| 2017-03-28T11:59:32
| 82,774,776
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 285
|
cpp
|
JobDu1084.cpp
|
#include <iostream>
using namespace std;
int divi[1000001];
int main(){
int n;
divi[1] = 1;
for(int i = 2; i <= 1000001; ++i){
if(i &1) divi[i] = divi[i -1];
else divi[i] = (divi[i -1] + divi[i /2]) % 1000000000;
}
while(cin >> n){
cout << divi[n] << endl;
}
return 0;
}
|
9b127153f8600db6f01a1b1e237e5b4bb3caa95c
|
9085a121ffad934f550979115fc8a19373ab2a46
|
/laba 5.2/Food.h
|
ec8bbb451dd0eaa99b5b78c387839a1fd4a8b003
|
[] |
no_license
|
a-grebenkin/lab6
|
cc37b3627b4d973565fb6109570add28501adb59
|
939ca9bc01b5a0e25a794ec6dfd57dff50e0e561
|
refs/heads/master
| 2022-07-10T19:44:08.556469
| 2020-05-15T10:33:03
| 2020-05-15T10:33:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,028
|
h
|
Food.h
|
#pragma once
#include <iostream>
using namespace std;
enum CONDITION
{
NORMAL, // нормальное состояние
FROZEN, // перегрет
OVERHEATED // переморожен
};
class Food
{
public:
Food(const string &name, double weight, double temperature, double max_temperature, double min_temperature, double heat_capacity);
string GetName() const;
double GetWeight() const;
double GetTemperature() const;
double GetHeatCapacity() const;
double GetMaxTemperature() const;
double GetMinTemperature() const;
CONDITION GetCondition() const;
void SetTemperature(double temperature);
void TransferThermalEnergy(double Q);
double GetPossibleTemperature(double Q) const;
string GetStatus() const;
private:
string name;
double weight; //kg
double temperature; //°С
double max_temperature; //°С
double min_temperature; //°С
CONDITION condition;
double heat_capacity; //J·kg^−1·K^−1
};
|
786ed4ebe5c114f8611fad91afa8f383ab364acd
|
a126aacc23b7fb734b3408ef6194b21685d61913
|
/KnapsackProblem.h
|
d3ed5a7ed71d2b2f217841443b97d12991d0dc1d
|
[] |
no_license
|
dotlineer/evolutionary-computation
|
b490111ba18cfbc4ef9be77d432e1fe676432c02
|
d4d38c1bd1ef33b8a16cfb7d822bbeaf83ac8e10
|
refs/heads/main
| 2020-04-29T19:48:01.344375
| 2019-03-18T20:51:53
| 2019-03-18T20:51:53
| 176,362,599
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 768
|
h
|
KnapsackProblem.h
|
#ifndef EVO_KNAPSACKPROBLEM_H
#define EVO_KNAPSACKPROBLEM_H
#include "Problem.h"
#include "vector"
using namespace std;
class KnapsackProblem : public Problem {
public:
KnapsackProblem(int iNoOfItems, int iWeightLimit, vector<int> &viWeights, vector<int> &viValues);
~KnapsackProblem();
int getIWeightLimit();
void setIWeightLimit(int iWeightLimit);
int getINoOfItems();
void setINoOfItems(int iNoOfItems);
vector<int> &getViSizes();
void setViSizes(vector<int> &viSizes);
vector<int> &getViValues();
void setViValues(vector<int> &viValues);
Genotype* constructNewGenotype();
private:
vector<int> viValues;
vector<int> viWeights;
int iNoOfItems;
int iWeightLimit;
};
#endif //EVO_KNAPSACKPROBLEM_H
|
d92e5c60a23aa66c54ce847906a38659747c5a62
|
0a5645154953b0a09d3f78753a1711aaa76928ff
|
/common/c/thirdparty/kml/dom/visitor.cc
|
e90eeaafda9eff4a2617c1e671c5e368f184b5ca
|
[] |
no_license
|
GENIVI/navigation-next
|
3a6f26063350ac8862b4d0e2e9d3522f6f249328
|
cb8f7ec5ec4c78ef57aa573315b75960b2a5dd36
|
refs/heads/master
| 2023-08-04T17:44:45.239062
| 2023-07-25T19:22:19
| 2023-07-25T19:22:19
| 116,230,587
| 17
| 11
| null | 2018-05-18T20:00:38
| 2018-01-04T07:43:22
|
C++
|
UTF-8
|
C++
| false
| false
| 10,590
|
cc
|
visitor.cc
|
// Copyright 2009, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
// WARNING: THE VISITOR API IMPLEMENTED IN THIS CLASS IS EXPERIMENTAL AND
// SUBJECT TO CHANGE WITHOUT WARNING.
#include "kml/dom/visitor.h"
#include "kml/dom/kmldom.h"
#include "kml/dom/kml_cast.h"
namespace kmldom {
Visitor::Visitor() { }
Visitor::~Visitor() { }
void Visitor::VisitElement(const ElementPtr& element) {
/* Top of element class hierarchy: Do nothing. */
}
void Visitor::VisitAbstractLatLonBox(
const AbstractLatLonBoxPtr& element) {
VisitObject(element);
}
void Visitor::VisitAbstractLink(
const AbstractLinkPtr& element) {
VisitBasicLink(element);
}
void Visitor::VisitAbstractView(
const AbstractViewPtr& element) {
VisitObject(element);
}
void Visitor::VisitAlias(
const AliasPtr& element) {
VisitObject(element);
}
void Visitor::VisitBalloonStyle(
const BalloonStylePtr& element) {
VisitSubStyle(element);
}
void Visitor::VisitBasicLink(
const BasicLinkPtr& element) {
VisitObject(element);
}
void Visitor::VisitCamera(
const CameraPtr& element) {
VisitAbstractView(element);
}
void Visitor::VisitChange(
const ChangePtr& element) {
VisitUpdateOperation(element);
}
void Visitor::VisitColorStyle(
const ColorStylePtr& element) {
VisitSubStyle(element);
}
void Visitor::VisitContainer(
const ContainerPtr& element) {
VisitFeature(element);
}
void Visitor::VisitCoordinates(
const CoordinatesPtr& element) {
VisitElement(element);
}
void Visitor::VisitCreate(
const CreatePtr& element) {
VisitUpdateOperation(element);
}
void Visitor::VisitData(
const DataPtr& element) {
VisitObject(element);
}
void Visitor::VisitDelete(
const DeletePtr& element) {
VisitUpdateOperation(element);
}
void Visitor::VisitDocument(
const DocumentPtr& element) {
VisitContainer(element);
}
void Visitor::VisitExtendedData(
const ExtendedDataPtr& element) {
VisitElement(element);
}
void Visitor::VisitFeature(
const FeaturePtr& element) {
VisitObject(element);
}
void Visitor::VisitField(
const FieldPtr& element) {
VisitElement(element);
}
void Visitor::VisitFolder(
const FolderPtr& element) {
VisitContainer(element);
}
void Visitor::VisitGeometry(
const GeometryPtr& element) {
VisitObject(element);
}
void Visitor::VisitGroundOverlay(
const GroundOverlayPtr& element) {
VisitOverlay(element);
}
void Visitor::VisitGxAnimatedUpdate(
const GxAnimatedUpdatePtr& element) {
VisitGxTourPrimitive(element);
}
void Visitor::VisitGxFlyTo(
const GxFlyToPtr& element) {
VisitGxTourPrimitive(element);
}
void Visitor::VisitGxLatLonQuad(
const GxLatLonQuadPtr& element) {
VisitObject(element);
}
void Visitor::VisitGxPlaylist(
const GxPlaylistPtr& element) {
VisitObject(element);
}
void Visitor::VisitGxSoundCue(
const GxSoundCuePtr& element) {
VisitGxTourPrimitive(element);
}
void Visitor::VisitGxTimeSpan(
const GxTimeSpanPtr& element) {
VisitTimeSpan(element);
}
void Visitor::VisitGxTimeStamp(
const GxTimeStampPtr& element) {
VisitTimeStamp(element);
}
void Visitor::VisitGxTour(
const GxTourPtr& element) {
VisitFeature(element);
}
void Visitor::VisitGxTourControl(
const GxTourControlPtr& element) {
VisitGxTourPrimitive(element);
}
void Visitor::VisitGxTourPrimitive(
const GxTourPrimitivePtr& element) {
VisitObject(element);
}
void Visitor::VisitGxWait(
const GxWaitPtr& element) {
VisitGxTourPrimitive(element);
}
void Visitor::VisitHotSpot(
const HotSpotPtr& element) {
VisitVec2(element);
}
void Visitor::VisitIcon(
const IconPtr& element) {
VisitAbstractLink(element);
}
void Visitor::VisitIconStyle(
const IconStylePtr& element) {
VisitColorStyle(element);
}
void Visitor::VisitIconStyleIcon(
const IconStyleIconPtr& element) {
VisitBasicLink(element);
}
void Visitor::VisitImagePyramid(
const ImagePyramidPtr& element) {
VisitObject(element);
}
void Visitor::VisitInnerBoundaryIs(
const InnerBoundaryIsPtr& element) {
VisitElement(element);
}
void Visitor::VisitItemIcon(
const ItemIconPtr& element) {
VisitObject(element);
}
void Visitor::VisitKml(
const KmlPtr& element) {
VisitElement(element);
}
void Visitor::VisitLabelStyle(
const LabelStylePtr& element) {
VisitColorStyle(element);
}
void Visitor::VisitLatLonAltBox(
const LatLonAltBoxPtr& element) {
VisitAbstractLatLonBox(element);
}
void Visitor::VisitLatLonBox(
const LatLonBoxPtr& element) {
VisitAbstractLatLonBox(element);
}
void Visitor::VisitLineString(
const LineStringPtr& element) {
VisitGeometry(element);
}
void Visitor::VisitLineStyle(
const LineStylePtr& element) {
VisitColorStyle(element);
}
void Visitor::VisitLinearRing(
const LinearRingPtr& element) {
VisitGeometry(element);
}
void Visitor::VisitLink(
const LinkPtr& element) {
VisitAbstractLink(element);
}
void Visitor::VisitLinkSnippet(
const LinkSnippetPtr& element) {
VisitElement(element);
}
void Visitor::VisitListStyle(
const ListStylePtr& element) {
VisitSubStyle(element);
}
void Visitor::VisitLocation(
const LocationPtr& element) {
VisitObject(element);
}
void Visitor::VisitLod(
const LodPtr& element) {
VisitObject(element);
}
void Visitor::VisitLookAt(
const LookAtPtr& element) {
VisitAbstractView(element);
}
void Visitor::VisitMetadata(
const MetadataPtr& element) {
VisitElement(element);
}
void Visitor::VisitModel(
const ModelPtr& element) {
VisitGeometry(element);
}
void Visitor::VisitMultiGeometry(
const MultiGeometryPtr& element) {
VisitGeometry(element);
}
void Visitor::VisitNetworkLink(
const NetworkLinkPtr& element) {
VisitFeature(element);
}
void Visitor::VisitNetworkLinkControl(
const NetworkLinkControlPtr& element) {
VisitElement(element);
}
void Visitor::VisitObject(
const ObjectPtr& element) {
VisitElement(element);
}
void Visitor::VisitOrientation(
const OrientationPtr& element) {
VisitObject(element);
}
void Visitor::VisitOuterBoundaryIs(
const OuterBoundaryIsPtr& element) {
VisitElement(element);
}
void Visitor::VisitOverlay(
const OverlayPtr& element) {
VisitFeature(element);
}
void Visitor::VisitOverlayXY(
const OverlayXYPtr& element) {
VisitVec2(element);
}
void Visitor::VisitPair(
const PairPtr& element) {
VisitObject(element);
}
void Visitor::VisitPhotoOverlay(
const PhotoOverlayPtr& element) {
VisitOverlay(element);
}
void Visitor::VisitPlacemark(
const PlacemarkPtr& element) {
VisitFeature(element);
}
void Visitor::VisitPoint(
const PointPtr& element) {
VisitGeometry(element);
}
void Visitor::VisitPolyStyle(
const PolyStylePtr& element) {
VisitColorStyle(element);
}
void Visitor::VisitPolygon(
const PolygonPtr& element) {
VisitGeometry(element);
}
void Visitor::VisitRegion(
const RegionPtr& element) {
VisitObject(element);
}
void Visitor::VisitResourceMap(
const ResourceMapPtr& element) {
VisitObject(element);
}
void Visitor::VisitRotationXY(
const RotationXYPtr& element) {
VisitVec2(element);
}
void Visitor::VisitScale(
const ScalePtr& element) {
VisitObject(element);
}
void Visitor::VisitSchema(
const SchemaPtr& element) {
VisitObject(element);
}
void Visitor::VisitSchemaData(
const SchemaDataPtr& element) {
VisitObject(element);
}
void Visitor::VisitScreenOverlay(
const ScreenOverlayPtr& element) {
VisitOverlay(element);
}
void Visitor::VisitScreenXY(
const ScreenXYPtr& element) {
VisitVec2(element);
}
void Visitor::VisitSimpleData(
const SimpleDataPtr& element) {
VisitElement(element);
}
void Visitor::VisitSimpleField(
const SimpleFieldPtr& element) {
VisitElement(element);
}
void Visitor::VisitSize(
const SizePtr& element) {
VisitVec2(element);
}
void Visitor::VisitSnippet(
const SnippetPtr& element) {
VisitElement(element);
}
void Visitor::VisitStyle(
const StylePtr& element) {
VisitStyleSelector(element);
}
void Visitor::VisitStyleMap(
const StyleMapPtr& element) {
VisitStyleSelector(element);
}
void Visitor::VisitStyleSelector(
const StyleSelectorPtr& element) {
VisitObject(element);
}
void Visitor::VisitSubStyle(
const SubStylePtr& element) {
VisitObject(element);
}
void Visitor::VisitTimePrimitive(
const TimePrimitivePtr& element) {
VisitObject(element);
}
void Visitor::VisitTimeSpan(
const TimeSpanPtr& element) {
VisitTimePrimitive(element);
}
void Visitor::VisitTimeStamp(
const TimeStampPtr& element) {
VisitTimePrimitive(element);
}
void Visitor::VisitUpdate(
const UpdatePtr& element) {
VisitElement(element);
}
void Visitor::VisitUpdateOperation(
const UpdateOperationPtr& element) {
VisitElement(element);
}
void Visitor::VisitUrl(
const UrlPtr& element) {
VisitAbstractLink(element);
}
void Visitor::VisitVec2(
const Vec2Ptr& element) {
VisitElement(element);
}
void Visitor::VisitViewVolume(
const ViewVolumePtr& element) {
VisitObject(element);
}
} // end namespace kmldom
|
74aea5a019aa308c1849c7d77487df551517efad
|
47618b768b38f99aec9d91e84839eccf8ad15873
|
/node_odbc/node_odbc_64/src/odbc_connection.cpp
|
3ebfd92da47e3b1f9f0c80b1ed120baadb3fe1cc
|
[
"MIT"
] |
permissive
|
niconico49/NodeJs
|
c3fbcecb06c719c8b2757f532cc0795c2802e212
|
6b23e71b4a342223ec922ed9a5e09cddc91e618b
|
refs/heads/master
| 2021-01-11T15:54:28.410996
| 2017-01-24T20:50:23
| 2017-01-24T20:50:23
| 79,952,893
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 54,807
|
cpp
|
odbc_connection.cpp
|
/*
Copyright (c) 2013, Dan VerWeire <dverweire@gmail.com>
Copyright (c) 2010, Lee Smith<notwink@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <string.h>
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <time.h>
#include <uv.h>
#include "odbc.h"
#include "odbc_connection.h"
#include "odbc_result.h"
#include "odbc_statement.h"
using namespace v8;
using namespace node;
Persistent<FunctionTemplate> ODBCConnection::constructor_template;
Persistent<String> ODBCConnection::OPTION_SQL(v8::Isolate::GetCurrent(), String::NewFromUtf8(v8::Isolate::GetCurrent(), "sql"));
Persistent<String> ODBCConnection::OPTION_PARAMS(v8::Isolate::GetCurrent(), String::NewFromUtf8(v8::Isolate::GetCurrent(), "params"));
Persistent<String> ODBCConnection::OPTION_NORESULTS(v8::Isolate::GetCurrent(), String::NewFromUtf8(v8::Isolate::GetCurrent(), "noResults"));
void ODBCConnection::Init(v8::Handle<Object> target) {
DEBUG_PRINTF("ODBCConnection::Init\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
Local<FunctionTemplate> t = FunctionTemplate::New(isolate, ODBCConnection::New);
// Constructor Template
constructor_template.Reset(isolate, t);
t->SetClassName(String::NewFromUtf8(isolate, "ODBCConnection", String::kInternalizedString));
// Reserve space for one Handle<Value>
Local<ObjectTemplate> instance_template = t->InstanceTemplate();
instance_template->SetInternalFieldCount(1);
// Properties
//instance_template->SetAccessor(String::New("mode"), ModeGetter, ModeSetter);
instance_template->SetAccessor(String::NewFromUtf8(isolate, "connected"), ConnectedGetter);
instance_template->SetAccessor(String::NewFromUtf8(isolate, "connectTimeout"), ConnectTimeoutGetter, (AccessorSetterCallback)ConnectTimeoutSetter);
instance_template->SetAccessor(String::NewFromUtf8(isolate, "loginTimeout"), LoginTimeoutGetter, (AccessorSetterCallback)LoginTimeoutSetter);
// Prototype Methods
NODE_SET_PROTOTYPE_METHOD(t, "open", Open);
NODE_SET_PROTOTYPE_METHOD(t, "openSync", OpenSync);
NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
NODE_SET_PROTOTYPE_METHOD(t, "closeSync", CloseSync);
NODE_SET_PROTOTYPE_METHOD(t, "createStatement", CreateStatement);
NODE_SET_PROTOTYPE_METHOD(t, "createStatementSync", CreateStatementSync);
NODE_SET_PROTOTYPE_METHOD(t, "query", Query);
NODE_SET_PROTOTYPE_METHOD(t, "querySync", QuerySync);
NODE_SET_PROTOTYPE_METHOD(t, "beginTransaction", BeginTransaction);
NODE_SET_PROTOTYPE_METHOD(t, "beginTransactionSync", BeginTransactionSync);
NODE_SET_PROTOTYPE_METHOD(t, "endTransaction", EndTransaction);
NODE_SET_PROTOTYPE_METHOD(t, "endTransactionSync", EndTransactionSync);
NODE_SET_PROTOTYPE_METHOD(t, "columns", Columns);
NODE_SET_PROTOTYPE_METHOD(t, "tables", Tables);
// Attach the Database Constructor to the target object
target->Set(v8::String::NewFromUtf8(isolate, "ODBCConnection", String::kInternalizedString), t->GetFunction());
}
ODBCConnection::~ODBCConnection() {
DEBUG_PRINTF("ODBCConnection::~ODBCConnection\n");
this->Free();
}
void ODBCConnection::Free() {
DEBUG_PRINTF("ODBCConnection::Free\n");
if (m_hDBC) {
uv_mutex_lock(&ODBC::g_odbcMutex);
if (m_hDBC) {
SQLDisconnect(m_hDBC);
SQLFreeHandle(SQL_HANDLE_DBC, m_hDBC);
m_hDBC = NULL;
}
uv_mutex_unlock(&ODBC::g_odbcMutex);
}
}
/*
* New
*/
void ODBCConnection::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::New\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsExternal()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 invalid")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 invalid"));
}
Local<External> js_henv = Local<External>::Cast(args[0]);
if (args.Length() <= (1) || !args[1]->IsExternal()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 invalid")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 invalid"));
}
Local<External> js_hdbc = Local<External>::Cast(args[1]);
HENV hENV = static_cast<HENV>(js_henv->Value());
HDBC hDBC = static_cast<HDBC>(js_hdbc->Value());
ODBCConnection* conn = new ODBCConnection(hENV, hDBC);
conn->Wrap(args.Holder());
//set default connectTimeout to 0 seconds
conn->connectTimeout = 0;
//set default loginTimeout to 5 seconds
conn->loginTimeout = 5;
args.GetReturnValue().Set(args.Holder());
}
void ODBCConnection::ConnectedGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection *obj = ObjectWrap::Unwrap<ODBCConnection>(info.Holder());
info.GetReturnValue().Set(obj->connected ? True(isolate) : False(isolate));
}
void ODBCConnection::ConnectTimeoutGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection *obj = ObjectWrap::Unwrap<ODBCConnection>(info.Holder());
info.GetReturnValue().Set(Number::New(isolate, obj->connectTimeout));
}
void ODBCConnection::ConnectTimeoutSetter(Local<String> property, Local<Value> value, const PropertyCallbackInfo<Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection *obj = ObjectWrap::Unwrap<ODBCConnection>(info.Holder());
if (value->IsNumber()) {
obj->connectTimeout = value->Uint32Value();
}
}
void ODBCConnection::LoginTimeoutGetter(Local<String> property, const PropertyCallbackInfo<Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection *obj = ObjectWrap::Unwrap<ODBCConnection>(info.Holder());
info.GetReturnValue().Set(Number::New(isolate, obj->loginTimeout));
}
void ODBCConnection::LoginTimeoutSetter(Local<String> property, Local<Value> value, const PropertyCallbackInfo<Value>& info) {
v8::Isolate* isolate = info.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection *obj = ObjectWrap::Unwrap<ODBCConnection>(info.Holder());
if (value->IsNumber()) {
obj->loginTimeout = value->Uint32Value();
}
}
/*
* Open
*
*/
void ODBCConnection::Open(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::Open\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string"));
}
Local<String> connection(args[0]->ToString());
if (args.Length() <= (1) || !args[1]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a function")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a function"));
}
Local<Function> cb = Local<Function>::Cast(args[1]);
//get reference to the connection object
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
//create a uv work request
uv_work_t* work_req = (uv_work_t *)(calloc(1, sizeof(uv_work_t)));
//allocate our worker data
open_connection_work_data* data = (open_connection_work_data *)calloc(1, sizeof(open_connection_work_data));
data->connectionLength = connection->Length() + 1;
//copy the connection string to the work data
#ifdef UNICODE
data->connection = (uint16_t *)malloc(sizeof(uint16_t) * data->connectionLength);
connection->Write((uint16_t*)data->connection);
#else
data->connection = (char *)malloc(sizeof(char) * data->connectionLength);
connection->WriteUtf8((char*)data->connection);
#endif
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
data->conn = conn;
work_req->data = data;
//queue the work
uv_queue_work(uv_default_loop(), work_req, UV_Open, (uv_after_work_cb)UV_AfterOpen);
conn->Ref();
args.GetReturnValue().Set(args.Holder());
}
void ODBCConnection::UV_Open(uv_work_t* req) {
DEBUG_PRINTF("ODBCConnection::UV_Open\n");
open_connection_work_data* data = (open_connection_work_data *)(req->data);
ODBCConnection* self = data->conn->self();
DEBUG_PRINTF("ODBCConnection::UV_Open : connectTimeout=%i, loginTimeout = %i\n", *&(self->connectTimeout), *&(self->loginTimeout));
uv_mutex_lock(&ODBC::g_odbcMutex);
if (self->connectTimeout > 0) {
//NOTE: SQLSetConnectAttr requires the thread to be locked
//ConnectionHandle, Attribute, ValuePtr,StringLength
SQLSetConnectAttr(self->m_hDBC, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER) size_t(self->connectTimeout), SQL_IS_UINTEGER);
}
if (self->loginTimeout > 0) {
//NOTE: SQLSetConnectAttr requires the thread to be locked
//ConnectionHandle, Attribute, ValuePtr,StringLength
SQLSetConnectAttr(self->m_hDBC, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER) size_t(self->loginTimeout), SQL_IS_UINTEGER);
}
//Attempt to connect
//NOTE: SQLDriverConnect requires the thread to be locked
//ConnectionHandle, WindowHandle, InConnectionString, StringLength1, OutConnectionString, BufferLength - in characters, StringLength2Ptr, DriverCompletion
int ret = SQLDriverConnect(self->m_hDBC, NULL, (SQLTCHAR*) data->connection, data->connectionLength, NULL, 0, NULL, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCEEDED(ret)) {
HSTMT hStmt;
//allocate a temporary statment
ret = SQLAllocHandle(SQL_HANDLE_STMT, self->m_hDBC, &hStmt);
//try to determine if the driver can handle
//multiple recordsets
ret = SQLGetFunctions(self->m_hDBC, SQL_API_SQLMORERESULTS, &(self->canHaveMoreResults));
if (!SQL_SUCCEEDED(ret)) {
self->canHaveMoreResults = 0;
}
//free the handle
ret = SQLFreeHandle( SQL_HANDLE_STMT, hStmt);
}
uv_mutex_unlock(&ODBC::g_odbcMutex);
data->result = ret;
}
void ODBCConnection::UV_AfterOpen(uv_work_t* req, int status) {
DEBUG_PRINTF("ODBCConnection::UV_AfterOpen\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
open_connection_work_data* data = (open_connection_work_data *)(req->data);
Local<Value> argv[1];
bool err = false;
if (data->result) {
err = true;
Local<Object> objError = ODBC::GetSQLError(SQL_HANDLE_DBC, data->conn->self()->m_hDBC);
argv[0] = objError;
}
if (!err) {
data->conn->self()->connected = true;
//only uv_ref if the connection was successful
#if NODE_VERSION_AT_LEAST(0, 7, 9)
uv_ref((uv_handle_t *)&ODBC::g_async);
#else
uv_ref(uv_default_loop());
#endif
}
TryCatch try_catch;
data->conn->Unref();
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), err ? 1 : 0, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
data->cb.Reset();
free(data->connection);
free(data);
free(req);
}
/*
* OpenSync
*/
void ODBCConnection::OpenSync(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::OpenSync\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string"))); \
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string"));
}
Local<String> connection(args[0]->ToString());
//get reference to the connection object
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
DEBUG_PRINTF("ODBCConnection::OpenSync : connectTimeout=%i, loginTimeout = %i\n", *&(conn->connectTimeout), *&(conn->loginTimeout));
Local<Object> objError;
SQLRETURN ret;
bool err = false;
int connectionLength = connection->Length() + 1;
#ifdef UNICODE
uint16_t* connectionString = (uint16_t *) malloc(connectionLength * sizeof(uint16_t));
connection->Write(connectionString);
#else
char* connectionString = (char *) malloc(connectionLength);
connection->WriteUtf8(connectionString);
#endif
uv_mutex_lock(&ODBC::g_odbcMutex);
if (conn->connectTimeout > 0) {
//NOTE: SQLSetConnectAttr requires the thread to be locked
//ConnectionHandle, Attribute, ValuePtr, StringLength
SQLSetConnectAttr(conn->m_hDBC, SQL_ATTR_CONNECTION_TIMEOUT, (SQLPOINTER) size_t(conn->connectTimeout), SQL_IS_UINTEGER);
}
if (conn->loginTimeout > 0) {
//NOTE: SQLSetConnectAttr requires the thread to be locked
//ConnectionHandle, Attribute, ValuePtr, StringLength
SQLSetConnectAttr(conn->m_hDBC, SQL_ATTR_LOGIN_TIMEOUT, (SQLPOINTER) size_t(conn->loginTimeout), SQL_IS_UINTEGER);
}
//Attempt to connect
//NOTE: SQLDriverConnect requires the thread to be locked
//ConnectionHandle, WindowHandle, InConnectionString, StringLength1, OutConnectionString, BufferLength - in characters, StringLength2Ptr, DriverCompletion
ret = SQLDriverConnect(conn->m_hDBC, NULL, (SQLTCHAR*) connectionString, connectionLength, NULL, 0, NULL, SQL_DRIVER_NOPROMPT);
if (!SQL_SUCCEEDED(ret)) {
err = true;
objError = ODBC::GetSQLError(SQL_HANDLE_DBC, conn->self()->m_hDBC);
}
else {
HSTMT hStmt;
//allocate a temporary statment
ret = SQLAllocHandle(SQL_HANDLE_STMT, conn->m_hDBC, &hStmt);
//try to determine if the driver can handle
//multiple recordsets
ret = SQLGetFunctions(conn->m_hDBC, SQL_API_SQLMORERESULTS, &(conn->canHaveMoreResults));
if (!SQL_SUCCEEDED(ret)) {
conn->canHaveMoreResults = 0;
}
//free the handle
ret = SQLFreeHandle( SQL_HANDLE_STMT, hStmt);
conn->self()->connected = true;
//only uv_ref if the connection was successful
#if NODE_VERSION_AT_LEAST(0, 7, 9)
uv_ref((uv_handle_t *)&ODBC::g_async);
#else
uv_ref(uv_default_loop());
#endif
}
uv_mutex_unlock(&ODBC::g_odbcMutex);
free(connectionString);
if (err) {
isolate->ThrowException(objError);
args.GetReturnValue().Set(False(isolate));
throw objError;
}
else {
args.GetReturnValue().Set(True(isolate));
}
}
/*
* Close
*
*/
void ODBCConnection::Close(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::Close\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a function")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a function"));
}
Local<Function> cb = Local<Function>::Cast(args[0]);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
close_connection_work_data* data = (close_connection_work_data *)(calloc(1, sizeof(close_connection_work_data)));
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_Close, (uv_after_work_cb)UV_AfterClose);
conn->Ref();
args.GetReturnValue().SetUndefined();
}
void ODBCConnection::UV_Close(uv_work_t* req) {
DEBUG_PRINTF("ODBCConnection::UV_Close\n");
close_connection_work_data* data = (close_connection_work_data *)(req->data);
ODBCConnection* conn = data->conn;
//TODO: check to see if there are any open statements
//on this connection
conn->Free();
data->result = 0;
}
void ODBCConnection::UV_AfterClose(uv_work_t* req, int status) {
DEBUG_PRINTF("ODBCConnection::UV_AfterClose\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
close_connection_work_data* data = (close_connection_work_data *)(req->data);
ODBCConnection* conn = data->conn;
Local<Value> argv[1];
bool err = false;
if (data->result) {
err = true;
argv[0] = Exception::Error(String::NewFromUtf8(isolate, "Error closing database"));
}
else {
conn->connected = false;
//only unref if the connection was closed
#if NODE_VERSION_AT_LEAST(0, 7, 9)
uv_unref((uv_handle_t *)&ODBC::g_async);
#else
uv_unref(uv_default_loop());
#endif
}
TryCatch try_catch;
data->conn->Unref();
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), err ? 1 : 0, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
data->cb.Reset();
free(data);
free(req);
}
/*
* CloseSync
*/
void ODBCConnection::CloseSync(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::CloseSync\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
//TODO: check to see if there are any open statements
//on this connection
conn->Free();
conn->connected = false;
#if NODE_VERSION_AT_LEAST(0, 7, 9)
uv_unref((uv_handle_t *)&ODBC::g_async);
#else
uv_unref(uv_default_loop());
#endif
args.GetReturnValue().Set(True(isolate));
}
/*
* CreateStatementSync
*
*/
void ODBCConnection::CreateStatementSync(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::CreateStatementSync\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
HSTMT hSTMT;
uv_mutex_lock(&ODBC::g_odbcMutex);
SQLAllocHandle(SQL_HANDLE_STMT, conn->m_hDBC, &hSTMT);
uv_mutex_unlock(&ODBC::g_odbcMutex);
Local<Value> params[3];
params[0] = External::New(isolate, conn->m_hENV);
params[1] = External::New(isolate, conn->m_hDBC);
params[2] = External::New(isolate, hSTMT);
v8::Local<v8::FunctionTemplate> ft = v8::Local<v8::FunctionTemplate>::New(isolate, ODBCConnection::constructor_template);
Local<Object> js_result = ft->GetFunction()->NewInstance(3, params);
args.GetReturnValue().Set(js_result);
}
/*
* CreateStatement
*
*/
void ODBCConnection::CreateStatement(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::CreateStatement\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a function")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a function"));
}
Local<Function> cb = Local<Function>::Cast(args[0]);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
//initialize work request
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
//initialize our data
create_statement_work_data* data = (create_statement_work_data *) (calloc(1, sizeof(create_statement_work_data)));
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_CreateStatement, (uv_after_work_cb)UV_AfterCreateStatement);
conn->Ref();
args.GetReturnValue().SetUndefined();
}
void ODBCConnection::UV_CreateStatement(uv_work_t* req) {
DEBUG_PRINTF("ODBCConnection::UV_CreateStatement\n");
//get our work data
create_statement_work_data* data = (create_statement_work_data *)(req->data);
DEBUG_PRINTF("ODBCConnection::UV_CreateStatement m_hDBC=%X m_hDBC=%X m_hSTMT=%X\n", data->conn->m_hENV, data->conn->m_hDBC, data->hSTMT);
uv_mutex_lock(&ODBC::g_odbcMutex);
//allocate a new statment handle
SQLAllocHandle( SQL_HANDLE_STMT, data->conn->m_hDBC, &data->hSTMT);
uv_mutex_unlock(&ODBC::g_odbcMutex);
DEBUG_PRINTF("ODBCConnection::UV_CreateStatement m_hDBC=%X m_hDBC=%X m_hSTMT=%X\n", data->conn->m_hENV, data->conn->m_hDBC, data->hSTMT);
}
void ODBCConnection::UV_AfterCreateStatement(uv_work_t* req, int status) {
DEBUG_PRINTF("ODBCConnection::UV_AfterCreateStatement\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
create_statement_work_data* data = (create_statement_work_data *)(req->data);
DEBUG_PRINTF("ODBCConnection::UV_AfterCreateStatement m_hDBC=%X m_hDBC=%X hSTMT=%X\n", data->conn->m_hENV, data->conn->m_hDBC, data->hSTMT);
Local<Value> args[3];
args[0] = External::New(isolate, data->conn->m_hENV);
args[1] = External::New(isolate, data->conn->m_hDBC);
args[2] = External::New(isolate, data->hSTMT);
v8::Local<v8::FunctionTemplate> ft = v8::Local<v8::FunctionTemplate>::New(isolate, ODBCConnection::constructor_template);
Local<Object> js_result = ft->GetFunction()->NewInstance(3, args);
args[0] = Local<Value>::New(isolate, Null(isolate));
args[1] = Local<Object>::New(isolate, js_result);
TryCatch try_catch;
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), 2, args);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
data->conn->Unref();
data->cb.Reset();
free(data);
free(req);
}
/*
* Query
*/
void ODBCConnection::Query(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::Query\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
Local<Function> cb;
Local<String> sql;
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
query_work_data* data = (query_work_data *) calloc(1, sizeof(query_work_data));
//Check arguments for different variations of calling this function
if (args.Length() == 3) {
//handle Query("sql string", [params], function cb () {});
if ( !args[0]->IsString() ) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be an String.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a String"));
}
else if ( !args[1]->IsArray() ) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be an Array.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a an Array"));
}
else if ( !args[2]->IsFunction() ) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a Function.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a Function"));
}
sql = args[0]->ToString();
data->params = ODBC::GetParametersFromArray(
Local<Array>::Cast(args[1]),
&data->paramCount);
cb = Local<Function>::Cast(args[2]);
}
else if (args.Length() == 2 ) {
//handle either Query("sql", cb) or Query({ settings }, cb)
if (!args[1]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Argument 1 must be a Function.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Argument 1 must be a Function."));
}
cb = Local<Function>::Cast(args[1]);
if (args[0]->IsString()) {
//handle Query("sql", function cb () {})
sql = args[0]->ToString();
data->paramCount = 0;
}
else if (args[0]->IsObject()) {
//NOTE: going forward this is the way we should expand options
//rather than adding more arguments to the function signature.
//specify options on an options object.
//handle Query({}, function cb () {});
Local<Object> obj = args[0]->ToObject();
v8::Local<v8::String> optionSql = v8::Local<v8::String>::New(isolate, OPTION_SQL);
v8::Local<v8::String> optionParams = v8::Local<v8::String>::New(isolate, OPTION_PARAMS);
v8::Local<v8::String> optionNoResults = v8::Local<v8::String>::New(isolate, OPTION_NORESULTS);
if (obj->Has(optionSql) && obj->Get(optionSql)->IsString()) {
sql = obj->Get(optionSql)->ToString();
}
else {
sql = String::NewFromUtf8(isolate, "");
}
if (obj->Has(optionParams) && obj->Get(optionParams)->IsArray()) {
data->params = ODBC::GetParametersFromArray(Local<Array>::Cast(obj->Get(optionParams)), &data->paramCount);
}
else {
data->paramCount = 0;
}
if (obj->Has(optionNoResults) && obj->Get(optionNoResults)->IsBoolean()) {
data->noResultObject = obj->Get(optionNoResults)->ToBoolean()->Value();
}
else {
data->noResultObject = false;
}
}
else {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Argument 0 must be a String or an Object.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Argument 0 must be a String or an Object."));
}
}
else {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Requires either 2 or 3 Arguments. ")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Require either 2 or 3 Arguments."));
}
//Done checking arguments
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
data->sqlLen = sql->Length();
#ifdef UNICODE
data->sqlSize = (data->sqlLen * sizeof(uint16_t)) + sizeof(uint16_t);
data->sql = (uint16_t *) malloc(data->sqlSize);
sql->Write((uint16_t *) data->sql);
#else
data->sqlSize = sql->Utf8Length() + 1;
data->sql = (char *) malloc(data->sqlSize);
sql->WriteUtf8((char *) data->sql);
#endif
DEBUG_PRINTF("ODBCConnection::Query : sqlLen=%i, sqlSize=%i, sql=%s\n", data->sqlLen, data->sqlSize, (char*) data->sql);
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_Query, (uv_after_work_cb)UV_AfterQuery);
conn->Ref();
args.GetReturnValue().SetUndefined();
}
void ODBCConnection::UV_Query(uv_work_t* req) {
DEBUG_PRINTF("ODBCConnection::UV_Query\n");
query_work_data* data = (query_work_data *)(req->data);
Parameter prm;
SQLRETURN ret;
uv_mutex_lock(&ODBC::g_odbcMutex);
//allocate a new statment handle
SQLAllocHandle( SQL_HANDLE_STMT, data->conn->m_hDBC, &data->hSTMT);
uv_mutex_unlock(&ODBC::g_odbcMutex);
// SQLExecDirect will use bound parameters, but without the overhead of SQLPrepare
// for a single execution.
if (data->paramCount) {
for (int i = 0; i < data->paramCount; i++) {
prm = data->params[i];
DEBUG_TPRINTF(SQL_T("ODBCConnection::UV_Query - param[%i]: ValueType=%i type=%i BufferLength=%i size=%i length=%i &length=%X\n"), i, prm.ValueType, prm.ParameterType, prm.BufferLength, prm.ColumnSize, prm.StrLen_or_IndPtr, &data->params[i].StrLen_or_IndPtr);
//StatementHandle, ParameterNumber, InputOutputType, ...
ret = SQLBindParameter(data->hSTMT, i + 1, SQL_PARAM_INPUT, prm.ValueType, prm.ParameterType, prm.ColumnSize, prm.DecimalDigits, prm.ParameterValuePtr, prm.BufferLength, &data->params[i].StrLen_or_IndPtr);
if (ret == SQL_ERROR) {
data->result = ret;
return;
}
}
}
// execute the query directly
ret = SQLExecDirect(data->hSTMT, (SQLTCHAR *)data->sql, data->sqlLen);
// this will be checked later in UV_AfterQuery
data->result = ret;
}
void ODBCConnection::UV_AfterQuery(uv_work_t* req, int status) {
DEBUG_PRINTF("ODBCConnection::UV_AfterQuery\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
query_work_data* data = (query_work_data *)(req->data);
TryCatch try_catch;
DEBUG_PRINTF("ODBCConnection::UV_AfterQuery : data->result=%i, data->noResultObject=%i\n", data->result, data->noResultObject);
if (data->result != SQL_ERROR && data->noResultObject) {
//We have been requested to not create a result object
//this means we should release the handle now and call back
//with True()
uv_mutex_lock(&ODBC::g_odbcMutex);
SQLFreeHandle(SQL_HANDLE_STMT, data->hSTMT);
uv_mutex_unlock(&ODBC::g_odbcMutex);
Local<Value> args[2];
args[0] = Local<Value>::New(isolate, Null(isolate));
args[1] = Local<Value>::New(isolate, True(isolate));
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), 2, args);
}
else {
Local<Value> args[4];
bool* canFreeHandle = new bool(true);
args[0] = External::New(isolate, data->conn->m_hENV);
args[1] = External::New(isolate, data->conn->m_hDBC);
args[2] = External::New(isolate, data->hSTMT);
args[3] = External::New(isolate, canFreeHandle);
v8::Local<v8::FunctionTemplate> ft = v8::Local<v8::FunctionTemplate>::New(isolate, ODBCResult::constructor_template);
Local<Object> js_result = ft->GetFunction()->NewInstance(4, args);
// Check now to see if there was an error (as there may be further result sets)
if (data->result == SQL_ERROR) {
args[0] = ODBC::GetSQLError(SQL_HANDLE_STMT, data->hSTMT, (char *) "[node-odbc] SQL_ERROR");
}
else {
args[0] = Local<Value>::New(isolate, Null(isolate));
}
args[1] = Local<Object>::New(isolate, js_result);
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), 2, args);
}
data->conn->Unref();
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
data->cb.Reset();
if (data->paramCount) {
Parameter prm;
// free parameters
for (int i = 0; i < data->paramCount; i++) {
if (prm = data->params[i], prm.ParameterValuePtr != NULL) {
switch (prm.ValueType) {
case SQL_C_WCHAR:
free(prm.ParameterValuePtr);
break;
case SQL_C_CHAR:
free(prm.ParameterValuePtr);
break;
case SQL_C_LONG:
delete (int64_t *)prm.ParameterValuePtr;
break;
case SQL_C_DOUBLE:
delete (double *)prm.ParameterValuePtr;
break;
case SQL_C_BIT:
delete (bool *)prm.ParameterValuePtr;
break;
}
}
}
free(data->params);
}
free(data->sql);
free(data->catalog);
free(data->schema);
free(data->table);
free(data->type);
free(data->column);
free(data);
free(req);
}
/*
* QuerySync
*/
void ODBCConnection::QuerySync(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::QuerySync\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
#ifdef UNICODE
String::Value* sql;
#else
String::Utf8Value* sql;
#endif
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
Parameter* params = new Parameter[0];
Parameter prm;
SQLRETURN ret;
HSTMT hSTMT;
int paramCount = 0;
bool noResultObject = false;
//Check arguments for different variations of calling this function
if (args.Length() == 2) {
//handle QuerySync("sql string", [params]);
if ( !args[0]->IsString() ) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::QuerySync(): Argument 0 must be an String.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Argument 0 must be a String."));
}
else if (!args[1]->IsArray()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::QuerySync(): Argument 1 must be an Array.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::Query(): Argument 1 must be a an Array."));
}
#ifdef UNICODE
sql = new String::Value(args[0]->ToString());
#else
sql = new String::Utf8Value(args[0]->ToString());
#endif
params = ODBC::GetParametersFromArray(Local<Array>::Cast(args[1]), ¶mCount);
}
else if (args.Length() == 1 ) {
//handle either QuerySync("sql") or QuerySync({ settings })
if (args[0]->IsString()) {
//handle Query("sql")
#ifdef UNICODE
sql = new String::Value(args[0]->ToString());
#else
sql = new String::Utf8Value(args[0]->ToString());
#endif
paramCount = 0;
}
else if (args[0]->IsObject()) {
//NOTE: going forward this is the way we should expand options
//rather than adding more arguments to the function signature.
//specify options on an options object.
//handle Query({}, function cb () {});
Local<Object> obj = args[0]->ToObject();
v8::Local<v8::String> optionSql = v8::Local<v8::String>::New(isolate, OPTION_SQL);
v8::Local<v8::String> optionParams = v8::Local<v8::String>::New(isolate, OPTION_PARAMS);
v8::Local<v8::String> optionNoResults = v8::Local<v8::String>::New(isolate, OPTION_NORESULTS);
if (obj->Has(optionSql) && obj->Get(optionSql)->IsString()) {
#ifdef UNICODE
sql = new String::Value(obj->Get(optionSql)->ToString());
#else
sql = new String::Utf8Value(obj->Get(optionSql)->ToString());
#endif
}
else {
#ifdef UNICODE
sql = new String::Value(String::NewFromUtf8(isolate, ""));
#else
sql = new String::Utf8Value(String::NewFromUtf8(isolate, ""));
#endif
}
if (obj->Has(optionParams) && obj->Get(optionParams)->IsArray()) {
params = ODBC::GetParametersFromArray(Local<Array>::Cast(obj->Get(optionParams)), ¶mCount);
}
else {
paramCount = 0;
}
if (obj->Has(optionNoResults) && obj->Get(optionNoResults)->IsBoolean()) {
noResultObject = obj->Get(optionNoResults)->ToBoolean()->Value();
}
}
else {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::QuerySync(): Argument 0 must be a String or an Object.")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::QuerySync(): Argument 0 must be a String or an Object."));
}
}
else {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::QuerySync(): Requires either 1 or 2 Arguments. ")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "ODBCConnection::QuerySync(): Requires either 1 or 2 Arguments."));
}
//Done checking arguments
uv_mutex_lock(&ODBC::g_odbcMutex);
//allocate a new statment handle
ret = SQLAllocHandle( SQL_HANDLE_STMT, conn->m_hDBC, &hSTMT);
uv_mutex_unlock(&ODBC::g_odbcMutex);
DEBUG_PRINTF("ODBCConnection::QuerySync - hSTMT=%p\n", hSTMT);
if (SQL_SUCCEEDED(ret)) {
if (paramCount) {
for (int i = 0; i < paramCount; i++) {
prm = params[i];
DEBUG_PRINTF("ODBCConnection::UV_Query - param[%i]: ValueType=%i type=%i BufferLength=%i size=%i length=%i &length=%X\n", i, prm.ValueType, prm.ParameterType, prm.BufferLength, prm.ColumnSize, prm.StrLen_or_IndPtr, ¶ms[i].StrLen_or_IndPtr);
//StatementHandle, ParameterNumber, InputOutputType
ret = SQLBindParameter(hSTMT, i + 1, SQL_PARAM_INPUT, prm.ValueType, prm.ParameterType, prm.ColumnSize, prm.DecimalDigits, prm.ParameterValuePtr, prm.BufferLength, ¶ms[i].StrLen_or_IndPtr);
if (ret == SQL_ERROR) {
break;
}
}
}
if (SQL_SUCCEEDED(ret)) {
ret = SQLExecDirect(hSTMT, (SQLTCHAR *) **sql, sql->length());
}
// free parameters
for (int i = 0; i < paramCount; i++) {
if (prm = params[i], prm.ParameterValuePtr != NULL) {
switch (prm.ValueType) {
case SQL_C_WCHAR:
free(prm.ParameterValuePtr);
break;
case SQL_C_CHAR:
free(prm.ParameterValuePtr);
break;
case SQL_C_LONG:
delete (int64_t *)prm.ParameterValuePtr;
break;
case SQL_C_DOUBLE:
delete (double *)prm.ParameterValuePtr;
break;
case SQL_C_BIT:
delete (bool *)prm.ParameterValuePtr;
break;
}
}
}
free(params);
}
delete sql;
//check to see if there was an error during execution
if (ret == SQL_ERROR) {
isolate->ThrowException(ODBC::GetSQLError(SQL_HANDLE_STMT, hSTMT, (char *) "[node-odbc] Error in ODBCConnection::QuerySync"));
throw ODBC::GetSQLError(SQL_HANDLE_STMT, hSTMT, (char *) "[node-odbc] Error in ODBCConnection::QuerySync");
args.GetReturnValue().SetUndefined();
}
else if (noResultObject) {
//if there is not result object requested then
//we must destroy the STMT ourselves.
uv_mutex_lock(&ODBC::g_odbcMutex);
SQLFreeHandle(SQL_HANDLE_STMT, hSTMT);
uv_mutex_unlock(&ODBC::g_odbcMutex);
args.GetReturnValue().Set(True(isolate));
}
else {
Local<Value> args1[4];
bool* canFreeHandle = new bool(true);
args1[0] = External::New(isolate, conn->m_hENV);
args1[1] = External::New(isolate, conn->m_hDBC);
args1[2] = External::New(isolate, hSTMT);
args1[3] = External::New(isolate, canFreeHandle);
v8::Local<v8::FunctionTemplate> ft = v8::Local<v8::FunctionTemplate>::New(isolate, ODBCResult::constructor_template);
Local<Object> js_result = ft->GetFunction()->NewInstance(4, args1);
args.GetReturnValue().Set(js_result);
}
}
/*
* Tables
*/
void ODBCConnection::Tables(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || (!args[0]->IsString() && !args[0]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string or null"));
}
Local<String> catalog(args[0]->ToString());
if (args.Length() <= (1) || (!args[1]->IsString() && !args[1]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a string or null"));
}
Local<String> schema(args[1]->ToString());
if (args.Length() <= (2) || (!args[2]->IsString() && !args[2]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a string or null"));
}
Local<String> table(args[2]->ToString());
if (args.Length() <= (3) || (!args[3]->IsString() && !args[3]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 3 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 3 must be a string or null"));
}
Local<String> type(args[3]->ToString());
Local<Function> cb = Local<Function>::Cast(args[4]);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
query_work_data* data = (query_work_data *) calloc(1, sizeof(query_work_data));
if (!data) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Could not allocate enough memory")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Could not allocate enough memory"));
}
data->sql = NULL;
data->catalog = NULL;
data->schema = NULL;
data->table = NULL;
data->type = NULL;
data->column = NULL;
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
if (!catalog->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->catalog = (uint16_t *) malloc((catalog->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
catalog->Write((uint16_t *) data->catalog);
#else
data->catalog = (char *) malloc(catalog->Length() + 1);
catalog->WriteUtf8((char *) data->catalog);
#endif
}
if (!schema->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->schema = (uint16_t *) malloc((schema->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
schema->Write((uint16_t *) data->schema);
#else
data->schema = (char *) malloc(schema->Length() + 1);
schema->WriteUtf8((char *) data->schema);
#endif
}
if (!table->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->table = (uint16_t *) malloc((table->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
table->Write((uint16_t *) data->table);
#else
data->table = (char *) malloc(table->Length() + 1);
table->WriteUtf8((char *) data->table);
#endif
}
if (!type->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->type = (uint16_t *) malloc((type->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
type->Write((uint16_t *) data->type);
#else
data->type = (char *) malloc(type->Length() + 1);
type->WriteUtf8((char *) data->type);
#endif
}
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_Tables, (uv_after_work_cb) UV_AfterQuery);
conn->Ref();
args.GetReturnValue().SetUndefined();
}
void ODBCConnection::UV_Tables(uv_work_t* req) {
query_work_data* data = (query_work_data *)(req->data);
uv_mutex_lock(&ODBC::g_odbcMutex);
SQLAllocHandle(SQL_HANDLE_STMT, data->conn->m_hDBC, &data->hSTMT );
uv_mutex_unlock(&ODBC::g_odbcMutex);
SQLRETURN ret = SQLTables(data->hSTMT, (SQLTCHAR *) data->catalog, SQL_NTS, (SQLTCHAR *) data->schema, SQL_NTS, (SQLTCHAR *) data->table, SQL_NTS, (SQLTCHAR *) data->type, SQL_NTS);
// this will be checked later in UV_AfterQuery
data->result = ret;
}
/*
* Columns
*/
void ODBCConnection::Columns(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || (!args[0]->IsString() && !args[0]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a string or null"));
}
Local<String> catalog(args[0]->ToString());
if (args.Length() <= (1) || (!args[1]->IsString() && !args[1]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a string or null"));
}
Local<String> schema(args[1]->ToString());
if (args.Length() <= (2) || (!args[2]->IsString() && !args[2]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a string or null"));
}
Local<String> table(args[2]->ToString());
if (args.Length() <= (3) || (!args[3]->IsString() && !args[3]->IsNull())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 3 must be a string or null")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 3 must be a string or null"));
}
Local<String> column(args[3]->ToString());
Local<Function> cb = Local<Function>::Cast(args[4]);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
query_work_data* data = (query_work_data *) calloc(1, sizeof(query_work_data));
if (!data) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Could not allocate enough memory")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Could not allocate enough memory"));
}
data->sql = NULL;
data->catalog = NULL;
data->schema = NULL;
data->table = NULL;
data->type = NULL;
data->column = NULL;
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
if (!catalog->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->catalog = (uint16_t *) malloc((catalog->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
catalog->Write((uint16_t *) data->catalog);
#else
data->catalog = (char *) malloc(catalog->Length() + 1);
catalog->WriteUtf8((char *) data->catalog);
#endif
}
if (!schema->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->schema = (uint16_t *) malloc((schema->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
schema->Write((uint16_t *) data->schema);
#else
data->schema = (char *) malloc(schema->Length() + 1);
schema->WriteUtf8((char *) data->schema);
#endif
}
if (!table->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->table = (uint16_t *) malloc((table->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
table->Write((uint16_t *) data->table);
#else
data->table = (char *) malloc(table->Length() + 1);
table->WriteUtf8((char *) data->table);
#endif
}
if (!column->Equals(String::NewFromUtf8(isolate, "null"))) {
#ifdef UNICODE
data->column = (uint16_t *) malloc((column->Length() * sizeof(uint16_t)) + sizeof(uint16_t));
column->Write((uint16_t *) data->column);
#else
data->column = (char *) malloc(column->Length() + 1);
column->WriteUtf8((char *) data->column);
#endif
}
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_Columns, (uv_after_work_cb)UV_AfterQuery);
conn->Ref();
args.GetReturnValue().SetUndefined();
}
void ODBCConnection::UV_Columns(uv_work_t* req) {
query_work_data* data = (query_work_data *)(req->data);
uv_mutex_lock(&ODBC::g_odbcMutex);
SQLAllocHandle(SQL_HANDLE_STMT, data->conn->m_hDBC, &data->hSTMT );
uv_mutex_unlock(&ODBC::g_odbcMutex);
SQLRETURN ret = SQLColumns(data->hSTMT, (SQLTCHAR *) data->catalog, SQL_NTS, (SQLTCHAR *) data->schema, SQL_NTS, (SQLTCHAR *) data->table, SQL_NTS, (SQLTCHAR *) data->column, SQL_NTS);
// this will be checked later in UV_AfterQuery
data->result = ret;
}
/*
* BeginTransactionSync
*
*/
void ODBCConnection::BeginTransactionSync(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::BeginTransactionSync\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
SQLRETURN ret;
//set the connection manual commits
ret = SQLSetConnectAttr(conn->m_hDBC, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_NTS);
if (!SQL_SUCCEEDED(ret)) {
Local<Object> objError = ODBC::GetSQLError(SQL_HANDLE_DBC, conn->m_hDBC);
isolate->ThrowException(objError);
args.GetReturnValue().Set(False(isolate));
throw objError;
}
args.GetReturnValue().Set(True(isolate));
}
/*
* BeginTransaction
*
*/
void ODBCConnection::BeginTransaction(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::BeginTransaction\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a function")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 2 must be a function"));
}
Local<Function> cb = Local<Function>::Cast(args[0]);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
query_work_data* data = (query_work_data *) calloc(1, sizeof(query_work_data));
if (!data) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Could not allocate enough memory")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Could not allocate enough memory"));
}
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_BeginTransaction, (uv_after_work_cb)UV_AfterBeginTransaction);
args.GetReturnValue().SetUndefined();
}
/*
* UV_BeginTransaction
*
*/
void ODBCConnection::UV_BeginTransaction(uv_work_t* req) {
DEBUG_PRINTF("ODBCConnection::UV_BeginTransaction\n");
query_work_data* data = (query_work_data *)(req->data);
//set the connection manual commits
data->result = SQLSetConnectAttr(data->conn->self()->m_hDBC, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_OFF, SQL_NTS);
}
/*
* UV_AfterBeginTransaction
*
*/
void ODBCConnection::UV_AfterBeginTransaction(uv_work_t* req, int status) {
DEBUG_PRINTF("ODBCConnection::UV_AfterBeginTransaction\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
open_connection_work_data* data = (open_connection_work_data *)(req->data);
Local<Value> argv[1];
bool err = false;
if (!SQL_SUCCEEDED(data->result)) {
err = true;
Local<Object> objError = ODBC::GetSQLError(SQL_HANDLE_DBC, data->conn->self()->m_hDBC);
argv[0] = objError;
}
TryCatch try_catch;
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), err ? 1 : 0, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
data->cb.Reset();
free(data);
free(req);
}
/*
* EndTransactionSync
*
*/
void ODBCConnection::EndTransactionSync(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::EndTransactionSync\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
if (args.Length() <= (0) || !args[0]->IsBoolean()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a boolean")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a boolean"));
}
Local<Boolean> rollback = (args[0]->ToBoolean());
Local<Object> objError;
SQLRETURN ret;
bool error = false;
SQLSMALLINT completionType = (rollback->Value()) ? SQL_ROLLBACK : SQL_COMMIT;
//Call SQLEndTran
ret = SQLEndTran(SQL_HANDLE_DBC, conn->m_hDBC, completionType);
//check how the transaction went
if (!SQL_SUCCEEDED(ret)) {
error = true;
objError = ODBC::GetSQLError(SQL_HANDLE_DBC, conn->m_hDBC);
}
//Reset the connection back to autocommit
ret = SQLSetConnectAttr(conn->m_hDBC, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_ON, SQL_NTS);
//check how setting the connection attr went
//but only process the code if an error has not already
//occurred. If an error occurred during SQLEndTran,
//that is the error that we want to throw.
if (!SQL_SUCCEEDED(ret) && !error) {
//TODO: if this also failed, we really should
//be restarting the connection or something to deal with this state
error = true;
objError = ODBC::GetSQLError(SQL_HANDLE_DBC, conn->m_hDBC);
}
if (error) {
isolate->ThrowException(objError);
args.GetReturnValue().Set(False(isolate));
throw objError;
}
else {
args.GetReturnValue().Set(True(isolate));
}
}
/*
* EndTransaction
*
*/
void ODBCConnection::EndTransaction(const v8::FunctionCallbackInfo<v8::Value>& args) {
DEBUG_PRINTF("ODBCConnection::EndTransaction\n");
v8::Isolate* isolate = args.GetIsolate();
v8::EscapableHandleScope scope(isolate);
if (args.Length() <= (0) || !args[0]->IsBoolean()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a boolean")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 0 must be a boolean"));
}
Local<Boolean> rollback = (args[0]->ToBoolean());
if (args.Length() <= (1) || !args[1]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a function")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be a function"));
}
Local<Function> cb = Local<Function>::Cast(args[1]);
ODBCConnection* conn = ObjectWrap::Unwrap<ODBCConnection>(args.Holder());
uv_work_t* work_req = (uv_work_t *) (calloc(1, sizeof(uv_work_t)));
query_work_data* data = (query_work_data *) calloc(1, sizeof(query_work_data));
if (!data) {
isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Could not allocate enough memory")));
throw Exception::TypeError(String::NewFromUtf8(isolate, "Could not allocate enough memory"));
}
data->completionType = (rollback->Value()) ? SQL_ROLLBACK : SQL_COMMIT;
v8::Persistent<v8::Function, CopyablePersistentTraits<v8::Function>> persistent(isolate, cb);
data->cb = persistent;
data->conn = conn;
work_req->data = data;
uv_queue_work(uv_default_loop(), work_req, UV_EndTransaction, (uv_after_work_cb)UV_AfterEndTransaction);
args.GetReturnValue().SetUndefined();
}
/*
* UV_EndTransaction
*
*/
void ODBCConnection::UV_EndTransaction(uv_work_t* req) {
DEBUG_PRINTF("ODBCConnection::UV_EndTransaction\n");
query_work_data* data = (query_work_data *)(req->data);
bool err = false;
//Call SQLEndTran
SQLRETURN ret = SQLEndTran(SQL_HANDLE_DBC, data->conn->m_hDBC, data->completionType);
data->result = ret;
if (!SQL_SUCCEEDED(ret)) {
err = true;
}
//Reset the connection back to autocommit
ret = SQLSetConnectAttr(data->conn->m_hDBC, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) SQL_AUTOCOMMIT_ON, SQL_NTS);
if (!SQL_SUCCEEDED(ret) && !err) {
//there was not an earlier error,
//so we shall pass the return code from
//this last call.
data->result = ret;
}
}
/*
* UV_AfterEndTransaction
*
*/
void ODBCConnection::UV_AfterEndTransaction(uv_work_t* req, int status) {
DEBUG_PRINTF("ODBCConnection::UV_AfterEndTransaction\n");
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope scope(isolate);
open_connection_work_data* data = (open_connection_work_data *)(req->data);
Local<Value> argv[1];
bool err = false;
if (!SQL_SUCCEEDED(data->result)) {
err = true;
Local<Object> objError = ODBC::GetSQLError(SQL_HANDLE_DBC, data->conn->self()->m_hDBC);
argv[0] = objError;
}
TryCatch try_catch;
v8::Local<v8::Function> f = v8::Local<v8::Function>::New(isolate, data->cb);
f->Call(isolate->GetCurrentContext()->Global(), err ? 1 : 0, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
data->cb.Reset();
free(data);
free(req);
}
|
9b497e9fd8def80f295750847b2e1026e33f27ca
|
2640219e4100cdaffbe78be28bd94c3a99d4e63c
|
/libsdlgame/Game.cpp
|
ca5e544dcb498534da661e5950230382a668ac88
|
[] |
no_license
|
akesterson/defunct-libsdlgame
|
e8f23cd7fc05adeccedd79f2ea17f7b81ea13c43
|
51ae9e81d66ea94cde09f0403db2be734363f5c8
|
refs/heads/master
| 2021-01-20T01:41:14.804682
| 2013-01-22T12:50:13
| 2013-01-22T12:50:13
| 89,317,322
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,858
|
cpp
|
Game.cpp
|
#include "Game.h"
#include "SpriteStrip.h"
#include "Actor.h"
#include "Display2D.h"
#include <SDL_mixer.h>
#include <SDL.h>
#include <iostream>
Game::Game()
{
this->musicVolume = 128;
this->soundVolume = 128;
this->lastNumKeys = 0;
this->lastKeyState = NULL;
this->fpslock = 0;
this->realfps = 0;
return;
}
Game::~Game()
{
if ( this->canvas != NULL ) {
SDL_FreeSurface(this->canvas);
}
}
int Game::initSDL(int audio_rate, Uint16 audio_format, int audio_channels, int audio_buffers)
{
if ( SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0 ) {
//std::cerr << "Failed to initialize SDL. Error was: " << SDL_GetError() << "\n";
return 1;
}
if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) {
//std::cerr << "Unable to initialize audio: " << Mix_GetError() << "\n";
exit(1);
}
return 0;
}
int Game::initVideo(int w, int h, int depth, int flags)
{
this->canvas = SDL_SetVideoMode(w, h, depth, flags);
if ( this->canvas == NULL ) {
//std::cerr << "Failed to create new SDL display. Error was: " << SDL_GetError() << "\n";
return 1;
}
////std::cerr << "Created new SDL display at " << this->canvas << "\n";
return 0;
}
void Game::update(int logicOnly)
{
DisplayList::iterator displayIter;
SDL_Surface *curFrame = NULL;
Display *display = NULL;
Uint8 *keyState = NULL;
int numKeys = 0;
int gfxframe = 1;
static unsigned int lastTime = 0;
static unsigned int lastfps = 0;
static unsigned int realFPStimer = 0;
SDL_Rect screen = {0, 0, this->canvas->w, this->canvas->h};
Vector displaypos;
SDL_PumpEvents();
if ( (this->fpslock != 0) && (SDL_GetTicks() - lastTime) >= (1000/this->fpslock) ) {
gfxframe = 1;
lastTime = SDL_GetTicks();
} else if (this->fpslock != 0) {
return;
}
if ( (SDL_GetTicks() - realFPStimer) > 1000 ) {
this->realfps = lastfps;
lastfps = 0;
realFPStimer = SDL_GetTicks();
} else {
lastfps++;
}
if ( logicOnly == 0 ) {
SDL_FillRect(this->canvas, &screen, 0);
}
for ( displayIter = this->windows.begin(); displayIter != this->windows.end() ; displayIter++ ) {
display = (*displayIter);
//std::cerr << "Updating display " << display << "\n";
display->update();
if ( logicOnly == 1 ) {
continue;
}
curFrame = display->nextFrame();
displaypos = display->getPosition();
//std::cerr << "Position of " << display << " " << displaypos.x << "x" << displaypos.y << "\n";
if ( curFrame && curFrame != this->canvas ) {
//std::cerr << "Blitting display " << display << " canvas " << curFrame << " to main canvas " << this->canvas << "(" << displaypos.x << "," << displaypos.y << ")...\n";
SDL_Rect destRect = {(Sint16) displaypos.x, (Sint16) displaypos.y, 0, 0};
SDL_BlitSurface(curFrame, NULL, this->canvas, &destRect);
//this->blitSprite(curFrame, 0, 0);
} else if ( curFrame == this->canvas ) {
//std::cerr << "Not blitting display window " << display << " to our canvas " << this->canvas << " because it is sharing our canvas at " << curFrame << "\n";
} else if ( curFrame == NULL ) {
//std::cerr << "display " << display << " has a NULL canvas\n";
}
}
if ( this->lastKeyState != NULL ) {
delete this->lastKeyState;
}
keyState = SDL_GetKeyState(&numKeys);
this->lastKeyState = new Uint8[numKeys];
if ( this->lastKeyState != NULL ) {
memcpy(this->lastKeyState, keyState, (sizeof(Uint8)*numKeys));
}
//this->handleEvents();
this->cleanSounds();
}
/*int Game::handleControlEvent(SDL_Event *event)
{
switch(event->type) {
case SDL_KEYUP:
if ( event->key.state == SDL_RELEASED ) {
if ( event->key.keysym.sym == SDLK_ESCAPE ) {
exit(0);
}
}
}
return 0;
}
int Game::handleEvents()
{
SDL_Event nextEvent;
while ( SDL_PollEvent(&nextEvent) ) {
switch(nextEvent.type) {
case SDL_KEYUP:
this->handleControlEvent(&nextEvent);
}
}
return 0;
}
*/
int Game::playMusic(std::string filename)
{
Mix_HaltMusic();
if ( this->bgmusic )
Mix_FreeMusic(this->bgmusic);
this->bgmusic = Mix_LoadMUS(filename.c_str());
if ( this->bgmusic == NULL ) {
//std::cerr << "Unable to load " << filename.c_str() << " to play music.\n";
return 1;
}
if ( Mix_PlayMusic(this->bgmusic, -1) == -1 ) {
//std::cerr << "Unable to play background music. " << Mix_GetError() << " \n";
return 1;
}
Mix_VolumeMusic(this->musicVolume);
return 0;
}
void Game::haltMusic()
{
Mix_HaltMusic();
if ( this->bgmusic )
Mix_FreeMusic(this->bgmusic);
this->bgmusic = NULL;
}
int Game::playSound(std::string filename, int loops)
{
PlayingSound *sndstruct = NULL;
Mix_Chunk *sound = NULL;
int channel = 0;
sound = Mix_LoadWAV(filename.c_str());
if ( sound == NULL ) {
return 1;
}
channel = Mix_PlayChannel(-1, sound, loops);
if ( channel > -1 ) {
//std::cerr << "Pushing sound chunk " << sound << " on channel " << channel << "\n";
sndstruct = new PlayingSound();
sndstruct->sound = sound;
sndstruct->channel = channel;
this->playingSounds.push_back(sndstruct);
} else {
Mix_FreeChunk(sound);
return 1;
}
Mix_Volume(sndstruct->channel, this->soundVolume);
return 0;
}
void Game::cleanSounds(int force)
{
PlayingSoundList::iterator iter;
PlayingSoundList::iterator newIter;
PlayingSound *curSound = NULL;
iter = this->playingSounds.begin() ;
while ( iter != this->playingSounds.end()) {
curSound = *iter;
if ( curSound == NULL ) {
iter++;
continue;
}
if ( Mix_Playing(curSound->channel) != 0 && force == 1) {
Mix_HaltChannel(curSound->channel);
} else if ( Mix_Playing(curSound->channel) != 0 ) {
iter++;
continue;
}
newIter = iter;
iter++;
Mix_FreeChunk(curSound->sound);
//std::cerr << "Cleared sound at channel" << curSound->channel << "\n";
iter = this->playingSounds.erase(newIter);
delete curSound;
//iter++;
}
}
void Game::setMusicVolume(int volume)
{
this->musicVolume = volume;
Mix_VolumeMusic(this->musicVolume);
}
void Game::setSoundVolume(int volume)
{
this->soundVolume = volume;
Mix_Volume(-1, this->soundVolume);
}
int Game::keyHeldDown(int keysym)
{
Uint8 *keyState = NULL;
int numKeys = 0;
keyState = SDL_GetKeyState(&numKeys);
if ( this->lastKeyState == NULL ) {
return 0;
}
if ( keysym < this->lastNumKeys && keysym < numKeys ) {
return 0;
}
if ( this->lastKeyState[keysym] + keyState[keysym] == 2 ) {
return 1;
}
return 0;
}
// ------------ class factory and memory management stuff
SpriteStrip *Game::newSpriteStrip(std::string key)
{
SpriteStrip *obj = new SpriteStrip();
if ( obj == NULL )
return NULL;
if ( key != "" ) {
if ( this->addSpriteStrip(obj, key) != 0 ) {
delete obj;
return NULL;
}
}
return obj;
}
int Game::freeSpriteStrip(std::string key, SpriteStrip *obj)
{
if ( obj == NULL && this->spriteMap.count(key) == 0 ) {
return 1;
} else if ( obj == NULL ) {
obj = this->spriteMap[key];
}
this->spriteMap.erase(key);
delete obj;
}
Animation *Game::newAnimation(std::string key)
{
Animation *obj = new Animation();
if ( obj == NULL )
return NULL;
if ( key != "" ) {
if ( this->addAnimation(obj, key) != 0 ) {
delete obj;
return NULL;
}
}
return obj;
}
int Game::freeAnimation(std::string key, Animation *obj)
{
if ( obj == NULL && this->animationMap.count(key) == 0 ) {
return 1;
} else if ( obj == NULL ) {
obj = this->animationMap[key];
}
this->animationMap.erase(key);
delete obj;
}
Actor *Game::newActor(std::string key)
{
Actor *obj = new Actor();
if ( obj == NULL )
return NULL;
if ( key != "" ) {
if ( this->addActor(obj, key) != 0 ) {
delete obj;
return NULL;
}
}
return obj;
}
int Game::freeActor(std::string key, Actor *obj)
{
if ( obj == NULL && this->actorMap.count(key) == 0 ) {
return 1;
} else if ( obj == NULL ) {
obj = this->actorMap[key];
}
this->actorMap.erase(key);
delete obj;
}
Display2D *Game::newDisplay2D(std::string key)
{
Display2D *obj = new Display2D();
if ( obj == NULL )
return NULL;
if ( key != "" ) {
if ( this->addDisplay(obj, key) != 0 ) {
delete obj;
return NULL;
}
}
return obj;
}
int Game::freeDisplay2D(std::string key, Display2D *obj)
{
if ( obj == NULL && this->displayMap.count(key) == 0 ) {
return 1;
} else if ( obj == NULL ) {
obj = (Display2D *)this->displayMap[key];
}
this->displayMap.erase(key);
delete obj;
}
MenuDisplay *Game::newMenuDisplay(std::string key)
{
MenuDisplay *obj = new MenuDisplay();
if ( obj == NULL )
return NULL;
if ( key != "" ) {
if ( this->addDisplay(obj, key) != 0 ) {
delete obj;
return NULL;
}
}
return obj;
}
int Game::freeMenuDisplay(std::string key, MenuDisplay *obj)
{
if ( obj == NULL && this->displayMap.count(key) == 0 ) {
return 1;
} else if ( obj == NULL ) {
obj = (MenuDisplay *)this->displayMap[key];
}
this->displayMap.erase(key);
delete obj;
}
int Game::addSpriteStrip(SpriteStrip *strip, std::string key)
{
if ( strip == NULL || this->spriteMap.count(key) > 0 )
return 1;
this->spriteMap[key] = strip;
return 0;
}
SpriteStrip *Game::getSpriteStrip(std::string key)
{
if ( this->spriteMap.count(key) > 0 ) {
return this->spriteMap[key];
}
return NULL;
}
int Game::removeSpriteStrip(std::string stripName)
{
if ( this->spriteMap.count(stripName) > 0 ) {
this->spriteMap.erase(stripName);
return 0;
}
return 1;
}
int Game::addAnimation(Animation *ptr, std::string key)
{
if ( ptr != NULL || this->animationMap.count(key) == 0 ) {
this->animationMap[key] = ptr;
return 0;
}
return 1;
}
Animation *Game::getAnimation(std::string key)
{
if ( this->animationMap.count(key) > 0 ) {
return this->animationMap[key];
}
return NULL;
}
int Game::removeAnimation(std::string key)
{
if ( this->animationMap.count(key) > 0 ) {
this->animationMap.erase(key);
return 0;
}
return 1;
}
int Game::addActor(Actor *ptr, std::string key)
{
if ( ptr != NULL || this->actorMap.count(key) == 0 ) {
this->actorMap[key] = ptr;
return 0;
}
return 1;
}
Actor *Game::getActor(std::string key)
{
if ( this->actorMap.count(key) > 0 ) {
return this->actorMap[key];
}
return NULL;
}
int Game::removeActor(std::string key)
{
if ( this->actorMap.count(key) > 0 ) {
this->actorMap.erase(key);
return 0;
}
return 1;
}
int Game::addDisplay(Display *ptr, std::string key)
{
if ( ptr != NULL || this->displayMap.count(key) == 0 ) {
this->displayMap[key] = ptr;
return 0;
}
return 1;
}
Display *Game::getDisplay(std::string key)
{
if ( this->displayMap.count(key) > 0 ) {
return this->displayMap[key];
}
return NULL;
}
int Game::removeDisplay(std::string key)
{
if ( this->displayMap.count(key) > 0 ) {
this->displayMap.erase(key);
return 0;
}
return 1;
}
void Game::lockFPS(int fps)
{
this->fpslock = fps;
}
void Game::finishFrame()
{
SDL_Flip(this->canvas);
}
SDL_Surface *Game::getCanvas()
{
return this->canvas;
}
|
a68ce09d396592791e89d287356fcaeb4c56b9f9
|
fa1f3e80c15e226848b024bc4a8407f6fc944ad9
|
/RailwayBridgeJoint/RailWayBridge.cpp
|
3ab2a2d3ec358c0754c839af65d35bede05a6c9e
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
DccShield/RailwayBridgeJoint
|
1b78449b90c80e33a4c54f9d385339d59acc75a6
|
a2e2cfe27ab8abce71de025352c7202ffcf2ec78
|
refs/heads/master
| 2022-06-25T14:12:53.778046
| 2020-05-10T06:31:52
| 2020-05-10T06:31:52
| 262,571,030
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,756
|
cpp
|
RailWayBridge.cpp
|
//--------------------------------------------------------------------------------
// レイアウト用鉄橋ジョイント音ジェネレータ
// [RailwayBridgeJoint.cpp]
// Copyright (c) 2020 Ayanosuke(Maison de DCC)
// https://desktopstation.net/bb/index.php
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//--------------------------------------------------------------------------------
#include "RailwayBridge.h"
#include "jointini.h"
#include "cds.h"
void RailWayBridgeState( JOINT ad ){
static Cds TrainSensor(0,1,2,200,500); // CDSセンサのセットアップ
static int state = ST_INIT;
static int TrainVal = 0;
static int wait = 0;
int re;
switch(state){
case ST_INIT:
Serial.println("Railway:ST_INIT");
TrainVal = ad.RollingStock[0];
digitalWrite(LED_BUILTIN,LOW);
state = ST_TRSENSING;
break;
case ST_TRSENSING: // 車両侵入チェック
re = TrainSensor.statechk(LOW); // 明るさ閾値LOWでチェック
if( re == 0 )
break;
else {
TrainSensor.Reset();
gSound_played = re;
wait = ad.TrainWait;
state = ST_STTRAINWAIT;
}
break;
case ST_STTRAINWAIT:
digitalWrite(LED_BUILTIN,HIGH); // 再生中
wait--;
if(wait<=0)
state = ST_TRAIN;
break;
case ST_TRAIN:
if(TrainVal < 1){
state = ST_INIT;
break;
}
TrainVal--;
state = ST_WHEELBASE1;
break;
case ST_WHEELBASE1: // 最初の台車のガタンガタン
ImaAdpcmPlay(); // ジョイント音発生依頼
wait = ad.ChassisWheelbase[0][gSound_played]; //台車間隔時間を算出
Serial.println(gSound_played);
Serial.println(wait);
state = ST_CHASSILENWAIT;
break;
case ST_CHASSILENWAIT:
wait--;
if(wait<=0)
state = ST_WHEELBASE2;
break;
case ST_WHEELBASE2: // 2番目の台車のガタンガタン
ImaAdpcmPlay(); // ジョイント音発生依頼
if( ad.BogieWheelbaseNum[0] == 3){ // 台車が3台ある?
wait = ad.ChassisWheelbase[0][gSound_played]; //台車間隔時間を算出
Serial.println(wait);
state = ST_CHASSILENWAIT2;
break;
}
wait = ad.VehicleSpace[0][gSound_played]; //車両間隔時間を算出
state = ST_TRAINWAIT;
break;
case ST_CHASSILENWAIT2:
wait--;
if(wait<=0)
state = ST_WHEELBASE3;
break;
case ST_WHEELBASE3: // 3番目の台車のガタンガタン
ImaAdpcmPlay(); // ジョイント音発生依頼
wait = ad.VehicleSpace[0][gSound_played]; //車両感覚時間を算出
state = ST_TRAINWAIT;
break;
case ST_TRAINWAIT:
wait--;
if(wait<=0)
state = ST_TRAIN;
break;
default:
break;
}
}
|
79c370527104d1f6e3fd6ea00baa00d8746ed056
|
8721dde19a9951e8d78e14df902f60daf414b018
|
/WhatToDo/SystemTests/SystemTests_Undo.cpp
|
5f283593f1e1c66708622485bed8f23374c2f908
|
[] |
no_license
|
cs2103aug2014-t14-4c/main
|
2497be361c7d928e675a92569c3740425b85c8d5
|
00f61158469d97eb7e89e99c4c64b704fe051a3c
|
refs/heads/master
| 2016-09-06T11:36:18.548249
| 2014-11-10T15:45:25
| 2014-11-10T15:45:25
| 23,483,659
| 2
| 0
| null | 2014-10-06T08:30:27
| 2014-08-30T03:09:17
|
C++
|
UTF-8
|
C++
| false
| false
| 3,911
|
cpp
|
SystemTests_Undo.cpp
|
//****************************************************************************
//@author A0110648L
//
// All system tests for an Undo user operation are performed here.
#include "stdafx.h"
#include "TestSupportLibrary.h"
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace SystemTests_Undo
{
TEST_CLASS(SystemTests_Undo)
{
public:
// These tests are for the partition "Undo following different
// task types"
TEST_METHOD(SystemTests_Undo_One_01_Add)
{
string testPartition = "SystemTests_Undo_One_01_Add";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_One_02_Delete)
{
string testPartition = "SystemTests_Undo_One_02_Delete";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_One_03_Edit)
{
string testPartition = "SystemTests_Undo_One_03_Edit";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_One_04_Done)
{
string testPartition = "SystemTests_Undo_One_04_Done";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_One_05_Search)
{
string testPartition = "SystemTests_Undo_One_05_Search";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_One_06_Clear)
{
string testPartition = "SystemTests_Undo_One_06_Clear";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_Two_01_Add)
{
string testPartition = "SystemTests_Undo_Two_01_Add";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_Two_02_Delete)
{
string testPartition = "SystemTests_Undo_Two_02_Delete";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_Two_03_Edit)
{
string testPartition = "SystemTests_Undo_Two_03_Edit";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
TEST_METHOD(SystemTests_Undo_Two_04_Done)
{
string testPartition = "SystemTests_Undo_Two_04_Done";
State actualState = TestSupportLibrary::executeCommandsFromInputFile(
testPartition + INPUT_COMMAND_FILE_EXT);
TestSupportLibrary::checkIsStateEqualsExpected(actualState,
testPartition + EXPECTED_STATE_FILE_EXT);
}
};
}
|
b0a3955424ae6babde9ba947078918e5eed6e02a
|
b5c502c7c71743ce510df82055ab6f95ee57fce3
|
/MQTT4RelayOTA.ino
|
72bce80dd94529b8b47f3fbdee7ae86ded6dda6a
|
[] |
no_license
|
cmheong/IsolatedAS3935
|
ea17b476519be3706c18e17fa9898b6319291b82
|
d76bf9fee8c0814a9a6a768f88b79652a8d8e65a
|
refs/heads/master
| 2022-04-19T01:03:06.940465
| 2020-04-19T12:58:26
| 2020-04-19T12:58:26
| 256,994,399
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,155
|
ino
|
MQTT4RelayOTA.ino
|
#include <ESP8266WiFi.h>
#include <SPI.h>
#include <ESP8266mDNS.h> // 2019-10-22
#include <WiFiUdp.h> // Needed for NTP as well as mDNSResolver
#include <ArduinoOTA.h>
#include <TimeLib.h>
#include <mDNSResolver.h> // Also needs WiFiUdp.h
#include <PubSubClient.h>
using namespace mDNSResolver;
WiFiUDP mdns; // 2019-11-04
Resolver resolver(mdns);
#define WLAN_SSID "MySSID"
#define WLAN_PASS "MySecretPassword"
extern "C" {
#include <user_interface.h> // to detect cold starts
}
const char *mqtt_servername = "mqttserver.local";
IPAddress mqtt_serveraddress;
WiFiClient espClient;
PubSubClient mqtt_client(espClient);
#define MQTT_PUBLISH "lightning/messages"
#define MQTT_SUBSCRIBE "lightning/commands"
long lastMsg = 0;
char msg[80];
IPAddress dns(8, 8, 8, 8); //Google dns
IPAddress staticIP(111,222,33,55); // required for dns set
IPAddress gateway(111,222,33,1);
IPAddress subnet(255,255,255,0);
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(8080);
// NTP Servers:
static const char ntpServerName[] = "pool.ntp.org"; // 2019-03-24 from us.pool.ntp.org
const int timeZone = +8; // Malaysia Time Time
WiFiUDP Udp;
unsigned int localPort = 8888; // local port to listen for UDP packets
time_t getNtpTime();
void digitalClockDisplay();
void digitalClockStr();
void printDigits(int digits);
void sendNTPpacket(IPAddress &address);
// 2019-10-21
//Hex command to send to serial for close relay
byte relON[] = {0xA0, 0x01, 0x01, 0xA2};
//Hex command to send to serial for open relay
byte relOFF[] = {0xA0, 0x01, 0x00, 0xA1};
//Hex command to send to serial for close relay
byte rel2ON[] = {0xA0, 0x02, 0x01, 0xA3};
//Hex command to send to serial for open relay
byte rel2OFF[] = {0xA0, 0x02, 0x00, 0xA2};
time_t LastDisconnect = now();
int disconnected = 0;
void publish_mqtt(const char *str) {
snprintf (msg, 80, "%s", str);
mqtt_client.publish(MQTT_PUBLISH, msg);
mqtt_client.loop(); // 2019-11-06
}
// 2019-11-04 PubSubClient
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("MQTT message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the modem on receiving command.
if (strncmp((char *)payload, "modem_on", 8)==0) {
digitalClockStr("Relay module reconnecting the phone lines ...");
Serial.println("Reconnecting the phone lines ...");
Serial.write (relON, sizeof(relON));
delay(100); // give relay cpu some time before the next command
Serial.write (rel2ON, sizeof(rel2ON));
delay(100);
disconnected = 0;
}
else if (strncmp((char*)payload, "modem_off", 9)==0)
{
digitalClockStr("Relay module disconnecting the phone lines ...");
Serial.println("Disconnecting the phone lines ...");
Serial.write (relOFF, sizeof(relOFF));
delay(100);
Serial.write (rel2OFF, sizeof(rel2OFF));
delay(100);
disconnected = 1;
LastDisconnect = now();
}
//else if (length>0)
//{
//digitalClockStr((char *)payload);
//}
}
long lastReconnectAttempt = 0; // 2019-11-05 Non-blocking reconnect
boolean reconnect() {
Serial.print("Attempting MQTT reconnection...");
// Create a random client ID
String clientId = "heong"; // 2019-03-23
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (mqtt_client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
// client.publish("outTopic", "hello esp8266 mqtt world");
digitalClockStr("Lightning detector relay module reconnected");
// publish_mqtt("Lightning detector relay module reconnected\n");
mqtt_client.subscribe(MQTT_SUBSCRIBE);
mqtt_client.loop();
} else {
Serial.print("failed, rc=");
Serial.println(mqtt_client.state());
}
return mqtt_client.connected();
}
void setup()
{ // 2019-11-12 Try not to mqtt_publish() as it may not be set up yet
// Serial.begin(9600);
Serial.begin(115200); // 2019-10-19
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.mode(WIFI_OFF); // 2018-12-11 workaround from 2018-10-09
WiFi.mode(WIFI_STA); // 2018-11-27 remove rogue AP
WiFi.config(staticIP, dns, gateway, subnet);
WiFi.begin(WLAN_SSID, WLAN_PASS); // 2018-12-11 changed to after WIFI_STA
while (WiFi.waitForConnectResult() != WL_CONNECTED) { // 2019-10-17
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
randomSeed(micros()); // 2019-11-04
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Start the server
server.begin();
rst_info *rinfo;
rinfo = ESP.getResetInfoPtr();
Serial.println(String("ResetInfo.reason = ") + (*rinfo).reason);
// if ((*rinfo).reason == 0) // power up
// There is a problem: 'int disconnected' needs to be saved as well. Until this is done do
// not apply cold-start code
// It would be nice to read the relays states from the 2nd cpu
delay(100);
// OTA
// Port defaults to 8266
// ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname("MQTT4RelayOTA");
// No authentication by default
ArduinoOTA.setPassword("MyIoTpassword");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH) {
type = "sketch";
} else { // U_SPIFFS
type = "filesystem";
}
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) {
Serial.println("Auth Failed");
} else if (error == OTA_BEGIN_ERROR) {
Serial.println("Begin Failed");
} else if (error == OTA_CONNECT_ERROR) {
Serial.println("Connect Failed");
} else if (error == OTA_RECEIVE_ERROR) {
Serial.println("Receive Failed");
} else if (error == OTA_END_ERROR) {
Serial.println("End Failed");
}
});
ArduinoOTA.begin();
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(Udp.localPort());
Serial.println("waiting for sync");
setSyncProvider(getNtpTime);
setSyncInterval(300);
Serial.print("Resolving ");
Serial.println(mqtt_servername);
resolver.setLocalIP(WiFi.localIP());
mqtt_serveraddress = resolver.search(mqtt_servername);
if(mqtt_serveraddress != INADDR_NONE) {
Serial.print("Resolved: ");
Serial.println(mqtt_serveraddress);
}
else {
Serial.println("Not resolved");
Serial.println("Connection Failed! Rebooting in 5s ...");
delay(5000);
ESP.restart();
}
mqtt_client.setServer(mqtt_serveraddress, 1883); // Use mdns name
mqtt_client.setCallback(callback);
lastReconnectAttempt = 0; // 2019-11-05
//Serial.write (relON, sizeof(relON)); // Connect phone line
//delay(100); // give relay cpu some time before the next command
//Serial.write (rel2ON, sizeof(rel2ON));
//delay(100);
}
static int dots = 0;
static int val = 0;
static int commas = 0;
void loop()
{
ArduinoOTA.handle(); // 2019-10-22
// 2019-02-24 Check for broken wifi links
if (WiFi.status() != WL_CONNECTED) {
Serial.println("No WiFi! Initiating reset ...");
// Serial.write(relON, sizeof(relON)); // 2019-10-16
delay(5000); // 2019-10-14
ESP.restart();
}
// 2019-11-05 nonblocking reconnects
if (!mqtt_client.connected()) {
long mqtt_now = millis();
if (mqtt_now - lastReconnectAttempt > 5000)
{
lastReconnectAttempt = mqtt_now;
Serial.print("mqtt_client.connected() returns false ...");
Serial.print("Retrying after 5s ...");
if (reconnect())
{
lastReconnectAttempt = 0;
Serial.println(" reconnected!");
}
}
}
else
{
long mqtt_now = millis();
if (mqtt_now - lastMsg > 3600000)
{
lastMsg = mqtt_now;
digitalClockStr("MQTT loop time");
}
}
mqtt_client.loop();
// Check if a client has connected
WiFiClient client = server.available();
if ( ! client ) {
return;
}
//Wait until the client sends some data
while ( ! client.available () )
{
delay (10); // 2019-02-28 reduced from 100
Serial.print(".");
if (commas++ > 5) {
commas = 0;
Serial.println("Terminating client connecting without reading");
delay(20);
client.stop();
return;
}
mqtt_client.loop(); // 2019-12-22
ArduinoOTA.handle(); // 2019-12-22
}
Serial.println("new client connect, waiting for data ");
// Read the first line of the request
String req = client.readStringUntil ('\r');
client.flush ();
// Match the request
String s = "";
// Prepare the response
if (req.indexOf ("/1/on") != -1)
{
Serial.write (relON, sizeof(relON));
val |= 0x01; // if you want feedback see below
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nStatus is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += "</html>\n";
} else if (req.indexOf ("/1/off") != -1) {
Serial.write (relOFF, sizeof(relOFF));
val &= 0xfe; // if you want feedback
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nStatus is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += "</html>\n";
} else if (req.indexOf ("/2/on") != -1) {
Serial.write (rel2ON, sizeof(rel2ON));
val |= 0x02; // if you want feedback see below
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nStatus is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += "</html>\n";
} else if (req.indexOf ("/2/off") != -1) {
Serial.write (rel2OFF, sizeof(rel2OFF));
val &= 0xfd; // if you want feedback
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nStatus is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += "</html>\n";
} else if (req.indexOf ("/modem/on") != -1) {
Serial.write (relON, sizeof(relON));
delay(100);
Serial.write (rel2ON, sizeof(rel2ON));
disconnected = 0;
LastDisconnect = now();
digitalClockDisplay();
Serial.println("Modem remotely connected");
digitalClockStr("Modem remotely connected");
val |= 0x02; // if you want feedback see below
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nModem Status is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += "</html>\n";
} else if (req.indexOf ("/modem/off") != -1) {
Serial.write (relOFF, sizeof(relOFF));
delay(100);
Serial.write (rel2OFF, sizeof(rel2OFF));
delay(100);
disconnected = 1;
LastDisconnect = now();
digitalClockDisplay();
Serial.println("Modem remotely disconnected");
digitalClockStr("Modem remotely disconnected");
val |= 0x02; // if you want feedback see below
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nModem Status is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += "</html>\n";
} else if (req.indexOf("/index.html") != -1) {
/*
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nStatus is ";
//s += (val)?"on":"off";
s += val; // 2018-10-25
s += " Firmware version: "; // 2019-10-14
s += ESP.getSdkVersion();
s += "</HTML>\n";
s += "<HTML><body><h1>It works!</h1></body></HTML>";
*/
s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: text/html\r\n";
s += "Connection: close\r\n";
s += "\r\n<!DOCTYPE HTML><html>";
s += "Firmware version: ";
s += ESP.getSdkVersion();
s += "</html>\r\n";
Serial.println("responded to index.html");
}
else {
Serial.println("invalid request");
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nInvalid request</html>\n";
}
client.flush ();
// Send the response to the client
client.print (s);
delay (10);
client.stop(); // 2019-02-24
Serial.println("Client disonnected");
delay(10);
}
int digitalClockStr(const char *message)
{
char clockstr[80];
// output digital clock time to char buffer
snprintf(clockstr, 80, "%02d:%02d:%02d %02d.%02d.%02d %s\n", hour(), minute(), second(), year(), month(), day(), message);
publish_mqtt(clockstr);
mqtt_client.loop();
}
void digitalClockDisplay()
{
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.print(" ");
Serial.print(day());
Serial.print(".");
Serial.print(month());
Serial.print(".");
Serial.print(year());
// Serial.println();
// debugV("%d:%d:%d", hour(), minute(), second());
Serial.print(" ");
}
void printDigits(int digits)
{
// utility for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
/*-------- NTP code ----------*/
const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
time_t getNtpTime()
{
IPAddress ntpServerIP; // NTP server's ip address
while (Udp.parsePacket() > 0) ; // discard any previously received packets
Serial.println("Transmit NTP Request");
// get a random server from the pool
WiFi.hostByName(ntpServerName, ntpServerIP);
Serial.print(ntpServerName);
Serial.print(": ");
Serial.println(ntpServerIP);
sendNTPpacket(ntpServerIP);
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = Udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
Serial.println("Receive NTP Response");
Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
}
}
Serial.println("No NTP Response :-(");
return 0; // return 0 if unable to get the time
}
// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
}
|
bbc08f39c80d4bfee66c9aad29efb12740462864
|
550e17ad61efc7bea2066db5844663c8b5835e4f
|
/Source/Contrib/UserInterface/src/Text/OSGUIFontBase.cpp
|
adc1cfac78c2712c04423b70f089f97aa258893c
|
[] |
no_license
|
danguilliams/OpenSGToolbox
|
9287424c66c9c4b38856cf749a311f15d8aac4f0
|
102a9fb02ad1ceeaf5784e6611c2862c4ba84d61
|
refs/heads/master
| 2021-01-17T23:02:36.528911
| 2010-11-01T16:56:31
| 2010-11-01T16:56:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 28,234
|
cpp
|
OSGUIFontBase.cpp
|
/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* www.opensg.org *
* *
* contact: David Kabala (djkabala@gmail.com) *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
/*****************************************************************************\
*****************************************************************************
** **
** This file is automatically generated. **
** **
** Any changes made to this file WILL be lost when it is **
** regenerated, which can become necessary at any time. **
** **
** Do not change this file, changes should be done in the derived **
** class UIFont!
** **
*****************************************************************************
\*****************************************************************************/
#include <cstdlib>
#include <cstdio>
#include <boost/assign/list_of.hpp>
#include "OSGConfig.h"
#include "OSGTextFace.h" // Style default header
#include "OSGTextureObjChunk.h" // Texture Class
#include "OSGUIFontBase.h"
#include "OSGUIFont.h"
#include <boost/bind.hpp>
#ifdef WIN32 // turn off 'this' : used in base member initializer list warning
#pragma warning(disable:4355)
#endif
OSG_BEGIN_NAMESPACE
/***************************************************************************\
* Description *
\***************************************************************************/
/*! \class OSG::UIFont
UI Font.
*/
/***************************************************************************\
* Field Documentation *
\***************************************************************************/
/*! \var std::string UIFontBase::_sfFamily
*/
/*! \var UInt32 UIFontBase::_sfGlyphPixelSize
*/
/*! \var UInt32 UIFontBase::_sfSize
*/
/*! \var UInt32 UIFontBase::_sfGap
*/
/*! \var UInt32 UIFontBase::_sfTextureWidth
*/
/*! \var UInt32 UIFontBase::_sfStyle
*/
/*! \var bool UIFontBase::_sfAntiAliasing
*/
/*! \var TextureObjChunk * UIFontBase::_sfTexture
*/
/***************************************************************************\
* FieldType/FieldTrait Instantiation *
\***************************************************************************/
#if !defined(OSG_DO_DOC) || defined(OSG_DOC_DEV)
DataType FieldTraits<UIFont *>::_type("UIFontPtr", "AttachmentContainerPtr");
#endif
OSG_FIELDTRAITS_GETTYPE(UIFont *)
OSG_EXPORT_PTR_SFIELD_FULL(PointerSField,
UIFont *,
0);
OSG_EXPORT_PTR_MFIELD_FULL(PointerMField,
UIFont *,
0);
/***************************************************************************\
* Field Description *
\***************************************************************************/
void UIFontBase::classDescInserter(TypeObject &oType)
{
FieldDescriptionBase *pDesc = NULL;
pDesc = new SFString::Description(
SFString::getClassType(),
"Family",
"",
FamilyFieldId, FamilyFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleFamily),
static_cast<FieldGetMethodSig >(&UIFont::getHandleFamily));
oType.addInitialDesc(pDesc);
pDesc = new SFUInt32::Description(
SFUInt32::getClassType(),
"GlyphPixelSize",
"",
GlyphPixelSizeFieldId, GlyphPixelSizeFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleGlyphPixelSize),
static_cast<FieldGetMethodSig >(&UIFont::getHandleGlyphPixelSize));
oType.addInitialDesc(pDesc);
pDesc = new SFUInt32::Description(
SFUInt32::getClassType(),
"Size",
"",
SizeFieldId, SizeFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleSize),
static_cast<FieldGetMethodSig >(&UIFont::getHandleSize));
oType.addInitialDesc(pDesc);
pDesc = new SFUInt32::Description(
SFUInt32::getClassType(),
"Gap",
"",
GapFieldId, GapFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleGap),
static_cast<FieldGetMethodSig >(&UIFont::getHandleGap));
oType.addInitialDesc(pDesc);
pDesc = new SFUInt32::Description(
SFUInt32::getClassType(),
"TextureWidth",
"",
TextureWidthFieldId, TextureWidthFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleTextureWidth),
static_cast<FieldGetMethodSig >(&UIFont::getHandleTextureWidth));
oType.addInitialDesc(pDesc);
pDesc = new SFUInt32::Description(
SFUInt32::getClassType(),
"Style",
"",
StyleFieldId, StyleFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleStyle),
static_cast<FieldGetMethodSig >(&UIFont::getHandleStyle));
oType.addInitialDesc(pDesc);
pDesc = new SFBool::Description(
SFBool::getClassType(),
"AntiAliasing",
"",
AntiAliasingFieldId, AntiAliasingFieldMask,
false,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleAntiAliasing),
static_cast<FieldGetMethodSig >(&UIFont::getHandleAntiAliasing));
oType.addInitialDesc(pDesc);
pDesc = new SFUnrecTextureObjChunkPtr::Description(
SFUnrecTextureObjChunkPtr::getClassType(),
"Texture",
"",
TextureFieldId, TextureFieldMask,
true,
(Field::SFDefaultFlags | Field::FStdAccess),
static_cast<FieldEditMethodSig>(&UIFont::editHandleTexture),
static_cast<FieldGetMethodSig >(&UIFont::getHandleTexture));
oType.addInitialDesc(pDesc);
}
UIFontBase::TypeObject UIFontBase::_type(
UIFontBase::getClassname(),
Inherited::getClassname(),
"NULL",
0,
reinterpret_cast<PrototypeCreateF>(&UIFontBase::createEmptyLocal),
UIFont::initMethod,
UIFont::exitMethod,
reinterpret_cast<InitalInsertDescFunc>(&UIFont::classDescInserter),
false,
0,
"<?xml version=\"1.0\"?>\n"
"\n"
"<FieldContainer\n"
"\tname=\"UIFont\"\n"
"\tparent=\"AttachmentContainer\"\n"
" library=\"ContribUserInterface\"\n"
" pointerfieldtypes=\"both\"\n"
"\tstructure=\"concrete\"\n"
" systemcomponent=\"true\"\n"
" parentsystemcomponent=\"true\"\n"
" decoratable=\"false\"\n"
" useLocalIncludes=\"false\"\n"
" isNodeCore=\"false\"\n"
" authors=\"David Kabala (djkabala@gmail.com) \"\n"
">\n"
"UI Font.\n"
"\t<Field\n"
"\t\tname=\"Family\"\n"
"\t\ttype=\"std::string\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue='\"SANS\"'\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"GlyphPixelSize\"\n"
"\t\ttype=\"UInt32\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue=\"46\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"Size\"\n"
"\t\ttype=\"UInt32\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue=\"12\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"Gap\"\n"
"\t\ttype=\"UInt32\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue=\"3\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"TextureWidth\"\n"
"\t\ttype=\"UInt32\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue=\"0\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"Style\"\n"
"\t\ttype=\"UInt32\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue=\"TextFace::STYLE_PLAIN\"\n"
"\t\tdefaultHeader=\"OSGTextFace.h\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"AntiAliasing\"\n"
"\t\ttype=\"bool\"\n"
" category=\"data\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"external\"\n"
"\t\tdefaultValue=\"true\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"\t<Field\n"
"\t\tname=\"Texture\"\n"
"\t\ttype=\"TextureObjChunk\"\n"
" category=\"pointer\"\n"
"\t\tcardinality=\"single\"\n"
"\t\tvisibility=\"internal\"\n"
"\t\taccess=\"public\"\n"
"\t>\n"
"\t</Field>\n"
"</FieldContainer>\n",
"UI Font.\n"
);
/*------------------------------ get -----------------------------------*/
FieldContainerType &UIFontBase::getType(void)
{
return _type;
}
const FieldContainerType &UIFontBase::getType(void) const
{
return _type;
}
UInt32 UIFontBase::getContainerSize(void) const
{
return sizeof(UIFont);
}
/*------------------------- decorator get ------------------------------*/
SFString *UIFontBase::editSFFamily(void)
{
editSField(FamilyFieldMask);
return &_sfFamily;
}
const SFString *UIFontBase::getSFFamily(void) const
{
return &_sfFamily;
}
SFUInt32 *UIFontBase::editSFGlyphPixelSize(void)
{
editSField(GlyphPixelSizeFieldMask);
return &_sfGlyphPixelSize;
}
const SFUInt32 *UIFontBase::getSFGlyphPixelSize(void) const
{
return &_sfGlyphPixelSize;
}
SFUInt32 *UIFontBase::editSFSize(void)
{
editSField(SizeFieldMask);
return &_sfSize;
}
const SFUInt32 *UIFontBase::getSFSize(void) const
{
return &_sfSize;
}
SFUInt32 *UIFontBase::editSFGap(void)
{
editSField(GapFieldMask);
return &_sfGap;
}
const SFUInt32 *UIFontBase::getSFGap(void) const
{
return &_sfGap;
}
SFUInt32 *UIFontBase::editSFTextureWidth(void)
{
editSField(TextureWidthFieldMask);
return &_sfTextureWidth;
}
const SFUInt32 *UIFontBase::getSFTextureWidth(void) const
{
return &_sfTextureWidth;
}
SFUInt32 *UIFontBase::editSFStyle(void)
{
editSField(StyleFieldMask);
return &_sfStyle;
}
const SFUInt32 *UIFontBase::getSFStyle(void) const
{
return &_sfStyle;
}
SFBool *UIFontBase::editSFAntiAliasing(void)
{
editSField(AntiAliasingFieldMask);
return &_sfAntiAliasing;
}
const SFBool *UIFontBase::getSFAntiAliasing(void) const
{
return &_sfAntiAliasing;
}
//! Get the UIFont::_sfTexture field.
const SFUnrecTextureObjChunkPtr *UIFontBase::getSFTexture(void) const
{
return &_sfTexture;
}
SFUnrecTextureObjChunkPtr *UIFontBase::editSFTexture (void)
{
editSField(TextureFieldMask);
return &_sfTexture;
}
/*------------------------------ access -----------------------------------*/
UInt32 UIFontBase::getBinSize(ConstFieldMaskArg whichField)
{
UInt32 returnValue = Inherited::getBinSize(whichField);
if(FieldBits::NoField != (FamilyFieldMask & whichField))
{
returnValue += _sfFamily.getBinSize();
}
if(FieldBits::NoField != (GlyphPixelSizeFieldMask & whichField))
{
returnValue += _sfGlyphPixelSize.getBinSize();
}
if(FieldBits::NoField != (SizeFieldMask & whichField))
{
returnValue += _sfSize.getBinSize();
}
if(FieldBits::NoField != (GapFieldMask & whichField))
{
returnValue += _sfGap.getBinSize();
}
if(FieldBits::NoField != (TextureWidthFieldMask & whichField))
{
returnValue += _sfTextureWidth.getBinSize();
}
if(FieldBits::NoField != (StyleFieldMask & whichField))
{
returnValue += _sfStyle.getBinSize();
}
if(FieldBits::NoField != (AntiAliasingFieldMask & whichField))
{
returnValue += _sfAntiAliasing.getBinSize();
}
if(FieldBits::NoField != (TextureFieldMask & whichField))
{
returnValue += _sfTexture.getBinSize();
}
return returnValue;
}
void UIFontBase::copyToBin(BinaryDataHandler &pMem,
ConstFieldMaskArg whichField)
{
Inherited::copyToBin(pMem, whichField);
if(FieldBits::NoField != (FamilyFieldMask & whichField))
{
_sfFamily.copyToBin(pMem);
}
if(FieldBits::NoField != (GlyphPixelSizeFieldMask & whichField))
{
_sfGlyphPixelSize.copyToBin(pMem);
}
if(FieldBits::NoField != (SizeFieldMask & whichField))
{
_sfSize.copyToBin(pMem);
}
if(FieldBits::NoField != (GapFieldMask & whichField))
{
_sfGap.copyToBin(pMem);
}
if(FieldBits::NoField != (TextureWidthFieldMask & whichField))
{
_sfTextureWidth.copyToBin(pMem);
}
if(FieldBits::NoField != (StyleFieldMask & whichField))
{
_sfStyle.copyToBin(pMem);
}
if(FieldBits::NoField != (AntiAliasingFieldMask & whichField))
{
_sfAntiAliasing.copyToBin(pMem);
}
if(FieldBits::NoField != (TextureFieldMask & whichField))
{
_sfTexture.copyToBin(pMem);
}
}
void UIFontBase::copyFromBin(BinaryDataHandler &pMem,
ConstFieldMaskArg whichField)
{
Inherited::copyFromBin(pMem, whichField);
if(FieldBits::NoField != (FamilyFieldMask & whichField))
{
_sfFamily.copyFromBin(pMem);
}
if(FieldBits::NoField != (GlyphPixelSizeFieldMask & whichField))
{
_sfGlyphPixelSize.copyFromBin(pMem);
}
if(FieldBits::NoField != (SizeFieldMask & whichField))
{
_sfSize.copyFromBin(pMem);
}
if(FieldBits::NoField != (GapFieldMask & whichField))
{
_sfGap.copyFromBin(pMem);
}
if(FieldBits::NoField != (TextureWidthFieldMask & whichField))
{
_sfTextureWidth.copyFromBin(pMem);
}
if(FieldBits::NoField != (StyleFieldMask & whichField))
{
_sfStyle.copyFromBin(pMem);
}
if(FieldBits::NoField != (AntiAliasingFieldMask & whichField))
{
_sfAntiAliasing.copyFromBin(pMem);
}
if(FieldBits::NoField != (TextureFieldMask & whichField))
{
_sfTexture.copyFromBin(pMem);
}
}
//! create a new instance of the class
UIFontTransitPtr UIFontBase::createLocal(BitVector bFlags)
{
UIFontTransitPtr fc;
if(getClassType().getPrototype() != NULL)
{
FieldContainerTransitPtr tmpPtr =
getClassType().getPrototype()-> shallowCopyLocal(bFlags);
fc = dynamic_pointer_cast<UIFont>(tmpPtr);
}
return fc;
}
//! create a new instance of the class, copy the container flags
UIFontTransitPtr UIFontBase::createDependent(BitVector bFlags)
{
UIFontTransitPtr fc;
if(getClassType().getPrototype() != NULL)
{
FieldContainerTransitPtr tmpPtr =
getClassType().getPrototype()-> shallowCopyDependent(bFlags);
fc = dynamic_pointer_cast<UIFont>(tmpPtr);
}
return fc;
}
//! create a new instance of the class
UIFontTransitPtr UIFontBase::create(void)
{
UIFontTransitPtr fc;
if(getClassType().getPrototype() != NULL)
{
FieldContainerTransitPtr tmpPtr =
getClassType().getPrototype()-> shallowCopy();
fc = dynamic_pointer_cast<UIFont>(tmpPtr);
}
return fc;
}
UIFont *UIFontBase::createEmptyLocal(BitVector bFlags)
{
UIFont *returnValue;
newPtr<UIFont>(returnValue, bFlags);
returnValue->_pFieldFlags->_bNamespaceMask &= ~bFlags;
return returnValue;
}
//! create an empty new instance of the class, do not copy the prototype
UIFont *UIFontBase::createEmpty(void)
{
UIFont *returnValue;
newPtr<UIFont>(returnValue, Thread::getCurrentLocalFlags());
returnValue->_pFieldFlags->_bNamespaceMask &=
~Thread::getCurrentLocalFlags();
return returnValue;
}
FieldContainerTransitPtr UIFontBase::shallowCopyLocal(
BitVector bFlags) const
{
UIFont *tmpPtr;
newPtr(tmpPtr, dynamic_cast<const UIFont *>(this), bFlags);
FieldContainerTransitPtr returnValue(tmpPtr);
tmpPtr->_pFieldFlags->_bNamespaceMask &= ~bFlags;
return returnValue;
}
FieldContainerTransitPtr UIFontBase::shallowCopyDependent(
BitVector bFlags) const
{
UIFont *tmpPtr;
newPtr(tmpPtr, dynamic_cast<const UIFont *>(this), ~bFlags);
FieldContainerTransitPtr returnValue(tmpPtr);
tmpPtr->_pFieldFlags->_bNamespaceMask = bFlags;
return returnValue;
}
FieldContainerTransitPtr UIFontBase::shallowCopy(void) const
{
UIFont *tmpPtr;
newPtr(tmpPtr,
dynamic_cast<const UIFont *>(this),
Thread::getCurrentLocalFlags());
tmpPtr->_pFieldFlags->_bNamespaceMask &= ~Thread::getCurrentLocalFlags();
FieldContainerTransitPtr returnValue(tmpPtr);
return returnValue;
}
/*------------------------- constructors ----------------------------------*/
UIFontBase::UIFontBase(void) :
Inherited(),
_sfFamily (std::string("SANS")),
_sfGlyphPixelSize (UInt32(46)),
_sfSize (UInt32(12)),
_sfGap (UInt32(3)),
_sfTextureWidth (UInt32(0)),
_sfStyle (UInt32(TextFace::STYLE_PLAIN)),
_sfAntiAliasing (bool(true)),
_sfTexture (NULL)
{
}
UIFontBase::UIFontBase(const UIFontBase &source) :
Inherited(source),
_sfFamily (source._sfFamily ),
_sfGlyphPixelSize (source._sfGlyphPixelSize ),
_sfSize (source._sfSize ),
_sfGap (source._sfGap ),
_sfTextureWidth (source._sfTextureWidth ),
_sfStyle (source._sfStyle ),
_sfAntiAliasing (source._sfAntiAliasing ),
_sfTexture (NULL)
{
}
/*-------------------------- destructors ----------------------------------*/
UIFontBase::~UIFontBase(void)
{
}
void UIFontBase::onCreate(const UIFont *source)
{
Inherited::onCreate(source);
if(source != NULL)
{
UIFont *pThis = static_cast<UIFont *>(this);
pThis->setTexture(source->getTexture());
}
}
GetFieldHandlePtr UIFontBase::getHandleFamily (void) const
{
SFString::GetHandlePtr returnValue(
new SFString::GetHandle(
&_sfFamily,
this->getType().getFieldDesc(FamilyFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleFamily (void)
{
SFString::EditHandlePtr returnValue(
new SFString::EditHandle(
&_sfFamily,
this->getType().getFieldDesc(FamilyFieldId),
this));
editSField(FamilyFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleGlyphPixelSize (void) const
{
SFUInt32::GetHandlePtr returnValue(
new SFUInt32::GetHandle(
&_sfGlyphPixelSize,
this->getType().getFieldDesc(GlyphPixelSizeFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleGlyphPixelSize (void)
{
SFUInt32::EditHandlePtr returnValue(
new SFUInt32::EditHandle(
&_sfGlyphPixelSize,
this->getType().getFieldDesc(GlyphPixelSizeFieldId),
this));
editSField(GlyphPixelSizeFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleSize (void) const
{
SFUInt32::GetHandlePtr returnValue(
new SFUInt32::GetHandle(
&_sfSize,
this->getType().getFieldDesc(SizeFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleSize (void)
{
SFUInt32::EditHandlePtr returnValue(
new SFUInt32::EditHandle(
&_sfSize,
this->getType().getFieldDesc(SizeFieldId),
this));
editSField(SizeFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleGap (void) const
{
SFUInt32::GetHandlePtr returnValue(
new SFUInt32::GetHandle(
&_sfGap,
this->getType().getFieldDesc(GapFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleGap (void)
{
SFUInt32::EditHandlePtr returnValue(
new SFUInt32::EditHandle(
&_sfGap,
this->getType().getFieldDesc(GapFieldId),
this));
editSField(GapFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleTextureWidth (void) const
{
SFUInt32::GetHandlePtr returnValue(
new SFUInt32::GetHandle(
&_sfTextureWidth,
this->getType().getFieldDesc(TextureWidthFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleTextureWidth (void)
{
SFUInt32::EditHandlePtr returnValue(
new SFUInt32::EditHandle(
&_sfTextureWidth,
this->getType().getFieldDesc(TextureWidthFieldId),
this));
editSField(TextureWidthFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleStyle (void) const
{
SFUInt32::GetHandlePtr returnValue(
new SFUInt32::GetHandle(
&_sfStyle,
this->getType().getFieldDesc(StyleFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleStyle (void)
{
SFUInt32::EditHandlePtr returnValue(
new SFUInt32::EditHandle(
&_sfStyle,
this->getType().getFieldDesc(StyleFieldId),
this));
editSField(StyleFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleAntiAliasing (void) const
{
SFBool::GetHandlePtr returnValue(
new SFBool::GetHandle(
&_sfAntiAliasing,
this->getType().getFieldDesc(AntiAliasingFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleAntiAliasing (void)
{
SFBool::EditHandlePtr returnValue(
new SFBool::EditHandle(
&_sfAntiAliasing,
this->getType().getFieldDesc(AntiAliasingFieldId),
this));
editSField(AntiAliasingFieldMask);
return returnValue;
}
GetFieldHandlePtr UIFontBase::getHandleTexture (void) const
{
SFUnrecTextureObjChunkPtr::GetHandlePtr returnValue(
new SFUnrecTextureObjChunkPtr::GetHandle(
&_sfTexture,
this->getType().getFieldDesc(TextureFieldId),
const_cast<UIFontBase *>(this)));
return returnValue;
}
EditFieldHandlePtr UIFontBase::editHandleTexture (void)
{
SFUnrecTextureObjChunkPtr::EditHandlePtr returnValue(
new SFUnrecTextureObjChunkPtr::EditHandle(
&_sfTexture,
this->getType().getFieldDesc(TextureFieldId),
this));
returnValue->setSetMethod(
boost::bind(&UIFont::setTexture,
static_cast<UIFont *>(this), _1));
editSField(TextureFieldMask);
return returnValue;
}
#ifdef OSG_MT_CPTR_ASPECT
void UIFontBase::execSyncV( FieldContainer &oFrom,
ConstFieldMaskArg whichField,
AspectOffsetStore &oOffsets,
ConstFieldMaskArg syncMode,
const UInt32 uiSyncInfo)
{
UIFont *pThis = static_cast<UIFont *>(this);
pThis->execSync(static_cast<UIFont *>(&oFrom),
whichField,
oOffsets,
syncMode,
uiSyncInfo);
}
#endif
#ifdef OSG_MT_CPTR_ASPECT
FieldContainer *UIFontBase::createAspectCopy(
const FieldContainer *pRefAspect) const
{
UIFont *returnValue;
newAspectCopy(returnValue,
dynamic_cast<const UIFont *>(pRefAspect),
dynamic_cast<const UIFont *>(this));
return returnValue;
}
#endif
void UIFontBase::resolveLinks(void)
{
Inherited::resolveLinks();
static_cast<UIFont *>(this)->setTexture(NULL);
}
OSG_END_NAMESPACE
|
742561384bafae5346feb414177f7676b6069990
|
a6590941fea4880593d5b1cd23eedfe696f4e446
|
/ABC100_199/ABC119/c.cpp
|
f21ccdb0b6570f8dbb7e10dd37f37d0366f8b869
|
[] |
no_license
|
cod4i3/MyAtcoder
|
9fb92f2dd06c5b6217e925a82d8db4f91355a70f
|
53bdac3fa7eb4ac48ca6d5c70461639beb6aa81d
|
refs/heads/master
| 2023-02-17T09:15:16.282873
| 2021-01-15T13:34:03
| 2021-01-15T13:34:03
| 232,006,424
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 901
|
cpp
|
c.cpp
|
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
int N, A, B, C;
int ans = 0;
void dfs(vector<int> &l, int i, int mp, int l1, int l2, int l3) {
if (i == N) {
if (l1 == 0 || l2 == 0 || l3 == 0) return;
ans = min(ans, abs(A - l1) + abs(B - l2) + abs(C - l3) + mp);
return;
}
if (l1 != 0)
dfs(l, i + 1, mp + 10, l1 + l[i], l2, l3);
else
dfs(l, i + 1, mp, l1 + l[i], l2, l3);
if (l2 != 0)
dfs(l, i + 1, mp + 10, l1, l2 + l[i], l3);
else
dfs(l, i + 1, mp, l1, l2 + l[i], l3);
if (l3 != 0)
dfs(l, i + 1, mp + 10, l1, l2, l3 + l[i]);
else
dfs(l, i + 1, mp, l1, l2, l3 + l[i]);
dfs(l, i + 1, mp, l1, l2, l3);
return;
}
int main() {
cin >> N >> A >> B >> C;
vector<int> l(N);
for (int i = 0; i < N; i++) cin >> l[i];
ans = 1000000;
dfs(l, 0, 0, 0, 0, 0);
cout << ans << endl;
return 0;
}
|
7bd4560e3c4b521f3c66ef43771ebf6f1bad9779
|
3abac7626bca25c1a2e6c7340e88bc5ed6ab1b98
|
/assign1/prodcons3.cpp
|
db0ce8287f589fa24fce6c9720a87f3ba22fd267
|
[] |
no_license
|
mcspohrer/515-Parallel
|
5f516b7643074e0998d977c6389f3e50f9cf5773
|
500905b9bfbfaae830ac5df3a384393b3a380661
|
refs/heads/main
| 2023-03-24T16:49:18.611246
| 2021-03-25T23:28:52
| 2021-03-25T23:28:52
| 348,458,169
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,168
|
cpp
|
prodcons3.cpp
|
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "queue.h"
using namespace std;
mutex mtx; //mutex for the conditional
condition_variable con_cv; //consumer's cv, con wait on empty Q
condition_variable prod_cv; //producer's cv, prod wait on full Q
int BUFFSIZE = 20;
int NUMITEMS = 100;
int * conRes; //results array for the consumer
int * prodRes; //results array for the producer
int numProds; //number of producers
Queue pcq(BUFFSIZE);
/* Called from main. It waits on the producer's conditional
* variable when the queue is full otherwise adds a number
* to the queue.
*/
void producer(int tid) {
int core = sched_getcpu();
int range = NUMITEMS/numProds;
int start = (range * tid) + 1;
int stop = start + range - 1;
int i, c = 0;
if(tid == numProds - 1)
stop = NUMITEMS;
cout << "Producer[" + to_string(tid) + "] starting on core " + to_string(core)
+ " for segment [" + to_string(start) + ".." + to_string(stop) + "]\n";
for(i = start; i <= stop; i++){
unique_lock<mutex> lck(mtx);
while(pcq.isFull())
{
con_cv.notify_all();
prod_cv.wait(lck);
}
pcq.add(i);
con_cv.notify_one();
lck.unlock();
++c;
cout << "Producer[" + to_string(tid) + "] added " + to_string(i)
+ " (qsz: " + to_string(pcq.size()) + ")\n";
}
prodRes[tid] = c; //records the count it added
cout << "Producer[" + to_string(tid) + "] ending\n";
}
/* Called from main. It waits on the consumer's conditional
* variable when the queue is empty otherwise removes a number
* from the queue.
*/
void consumer(int tid) {
int r, c = 0;
int core = sched_getcpu();
cout << "Consumer[" + to_string(tid) + "] starting on core " + to_string(core) + "\n";
while(r != -1) {
unique_lock<mutex> lck(mtx);
while(pcq.isEmpty())
{
prod_cv.notify_all();
con_cv.wait(lck);
}
r = pcq.remove();
prod_cv.notify_one();
lck.unlock();
if (r != -1) {
++c;
cout << "Consumer[" + to_string(tid) + "] removed " + to_string(r)
+ " (qsz: " + to_string(pcq.size()) + ")\n";
}
}
prod_cv.notify_one();
conRes[tid] = c;
cout << "Consumer[" + to_string(tid) + "] ending\n";
}
int main(int argc, char **argv) {
int numCons, tot = 0;
if(argv[1]) numCons = atoi(argv[1]); //gets the number of
else numCons = 1; //consumers
if(argv[2]) numProds = atoi(argv[2]); //gets the number of
else numProds = 1; //producers
conRes = new int [numCons]; //inits consumer result
prodRes = new int [numProds]; //inits prod results
thread pthd[numProds], cthd[numCons];
cout << "Prodcons3 with "+ to_string(numCons) + " consumers, "+ to_string(numProds) + " producers\n";
for (int k = 0; k < numProds; k++) //start ptoducers
pthd[k] = thread(producer, k);
for (int k = 0; k < numCons; k++) //start consumers
cthd[k] = thread(consumer, k);
for (int k = 0; k < numProds; k++) //join producers
pthd[k].join();
for (int k = 0; k < numCons; ++k){ //add -1 to the queue
unique_lock<mutex> lck(mtx); //stop the consumers
while(pcq.isFull())
{
con_cv.notify_all();
prod_cv.wait(lck);
}
pcq.add(-1);
con_cv.notify_one();
lck.unlock();
}
for (int k = 0; k < numCons; k++) //join consumers
cthd[k].join();
cout << "Main added " + to_string(numCons) + " ENDSIGNs (qsz: " + to_string(pcq.size()) + ")\n";
cout << "Producer stats: [";
for(int i = 0; i < numProds; ++i) {
cout << to_string(prodRes[i]) + ",";
tot += prodRes[i];
}
cout << "] = " + to_string(tot) + "\n";
tot = 0; //resets the total count
cout << "Consumer stats: [";
for(int i = 0; i < numCons; ++i) {
cout << to_string(conRes[i]) + ",";
tot += conRes[i];
}
cout << "] = " + to_string(tot) + "\n";
cout << "Main: all done! Now stop bothering me!\n";
delete(conRes);
delete(prodRes);
}
|
1e0f76f35d67b7cd87dc7747a7fba76bc6214d02
|
47e458101f543cecee59b27d27f67e8944930d3a
|
/Chapter_11/Task_04/Task_04.cpp
|
bc0d448f75c61f2aff104c5b98c63aa6faae61aa
|
[] |
no_license
|
callmeFilip/Thinking-in-CPP-Volume-1-2nd-Edition
|
f1bb1c9e7edef1e9ca4eadb7758f80e08ee68bba
|
95db8120d67423c35728bd8b216393e9e869371d
|
refs/heads/master
| 2023-03-27T00:31:56.940278
| 2021-03-25T17:12:34
| 2021-03-25T17:12:34
| 312,387,460
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 243
|
cpp
|
Task_04.cpp
|
#include <iostream>
int &function(int *ptr)
{
ptr++;
return *ptr;
}
int main()
{
int a = 10;
int &result = function(&a);
std::cout << (long)&a << std::endl;
std::cout << (long)&result << std::endl;
return 0;
}
|
a33abdd134657f9e7d9fd48593ae52907eef0074
|
f50cdfb25df922f9b55f8366751e0f2dcbfd07d3
|
/复试/机试/部分常见代码/北航机试题/beihan_lianxi_invertsub.cpp
|
7317061b734e33d6a113452cc8728cbe55e02b3c
|
[] |
no_license
|
liujiming789/Unified-National-Graduate-Entrance-Examination
|
a3fada93858775d30353e03b002648a31921a411
|
7e1420d0862cf834b1ceae987e9514b17e9ddefd
|
refs/heads/master
| 2022-02-19T05:58:50.551457
| 2019-09-02T11:24:44
| 2019-09-02T11:24:44
| 196,735,885
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 619
|
cpp
|
beihan_lianxi_invertsub.cpp
|
#include <stdio.h>
#include <string.h>
int main()
{
FILE *in,*out;
int f,i,j,len1,len2;
char s1[60],s2[60];
in=fopen("input.txt","r");
out=fopen("output.txt","w");
fgets(s1,sizeof(s1),in);
fgets(s2,sizeof(s2),in);
len1=strlen(s1)-2;
len2=strlen(s2)-2;
s1[len1]='\0';
s2[len2]='\0';
f=0;i=j=0;
while(i<len1&&j<len2)
{
if(s1[i]==s2[j]) { i++; j++; }
else { f++; i=f; j=0; }
}
if(j>len2)
fprintf(out,"%s",s1);
else
{
for(i=0;i<f;i++)
fprintf(out,"%c",s1[i]);
for(i=len2-1;i>=0;i--)
fprintf(out,"%c",s2[i]);
for(i=f+len2;i<len1;i++)
fprintf(out,"%c",s1[i]);
}
fclose(in);
fclose(out);
return 0;
}
|
d5ac02f262dbf21297441cd89c318d8272988d86
|
4bbdad79137d589cf9dd48cfddaa2b6ccf6317f0
|
/hausaufgabe/cpp9/spielertrainer.hpp
|
a8ba2db06fe6869aa554690465692a6d75b2372f
|
[] |
no_license
|
leventeBajczi/prog2-ubungen
|
7a37ed2ecbc0cf6b3b3f72957fe056611a43e6a7
|
5bc3318901860845b0bd81f6eef6dae77c29b1b8
|
refs/heads/master
| 2021-03-30T21:09:09.662792
| 2018-05-02T06:32:46
| 2018-05-02T06:32:46
| 124,792,057
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 440
|
hpp
|
spielertrainer.hpp
|
#ifndef _SPIELERTRAINER_HPP
#define _SPIELERTRAINER_HPP
#include <iostream>
#include "spieler.hpp"
#include "trainer.hpp"
class SpielerTrainer : public Spieler, public Trainer{
public:
SpielerTrainer(std::string str, unsigned int rn, char l) : Person(str), Spieler(str, rn), Trainer(str, l){}
virtual void print(){std::cout<<name<<" (Spieler und Trainer), "<<rnummer<<", "<<licence<<" Licence"<<std::endl;}
};
#endif
|
75deeb0dab28b9aa455d9d972ba8e519bca4231e
|
9b7f8b025d3932939b333ff62f88159f9ff0b490
|
/leetNgeeks/450/graph/rat_maze.cpp
|
3ec8fe5734236a3eb1e84a18d7ccb181335b8740
|
[] |
no_license
|
afAditya/Competitive-Coding
|
b43b64e2ab12a3839a9822e1ec4d9b38620ee251
|
378fe8b8a95cb1419953052857291cc3afbe3fe4
|
refs/heads/master
| 2023-08-21T19:47:31.385873
| 2021-10-19T05:50:54
| 2021-10-19T05:50:54
| 418,787,747
| 0
| 0
| null | 2021-10-19T05:47:47
| 2021-10-19T05:47:46
| null |
UTF-8
|
C++
| false
| false
| 1,404
|
cpp
|
rat_maze.cpp
|
// rate in maze
#include<bits/stdc++.h>
using namespace std;
namespace my {
vector<string> ans;
}
char move_char(int i) {
if(i == 0) {
return 'U';
}
else if(i == 1) {
return 'L';
}
else if(i == 2) {
return 'R';
}
else{
return 'D';
}
}
void dfs(int x,int y,vector<vector<int>>g,string &path,vector<vector<bool>>&vis) {
int m = g.size();
int n = g[0].size();
int C[4] = {-1,0,0,1};
int R[4] = {0,-1,1,0};
vis[x][y] = true;
if(x == m-1 and y == n-1) {
cout<<"path "<<path<<endl;
my::ans.push_back(path);
//return;
}
for(int i = 0; i < 4; i++) {
char move = move_char(i);
int xx = C[i] + x;
int yy = R[i] + y;
if(xx>=0 && xx<m and yy>=0 and yy < n) {
if(vis[xx][yy] == false && g[xx][yy]==1) {
path += move;
dfs(xx,yy,g,path,vis);
}
}
}
vis[x][y] = false;
path.pop_back();
}
void print_path(vector<vector<int>> g) {
// vector<string> ans;
string path = "";
int m = g.size();
int n = g[0].size();
vector<vector<bool> > vis(m);
for(int i = 0; i < m; i++ ){
vis[i].resize(n);
for(int j = 0; j < n; j++) {
vis[i][j] = false;
}
}
dfs(0,0,g,path,vis);
for(auto s:my::ans){
cout<<s<<" ";
}
cout<<endl;
}
int main() {
int m; cin>>m;
int n; cin>>n;
vector<vector<int>> g(m);
for(int i = 0; i < m; i++) {
g[i].resize(n);
for(int j = 0; j < n; j++) {
cin>>g[i][j];
}
}
print_path(g);
}
|
14bf184f197fc6e47c9143cf829053b50c071470
|
a809cd70ef136d7e2fcf70a207880f186d019207
|
/modules/ui/src/types/Camera.cpp
|
25a7ff24c38f6fdb29c5c545b41396227febb250
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"MPL-2.0",
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
adobe/lagrange
|
ea9d4c700ed70003ee9c9ecef55fecd6b9d77ba7
|
2f78a647ecb867619c73489a5e3ea752f26353ef
|
refs/heads/main
| 2023-08-10T05:18:14.852199
| 2023-06-28T18:29:31
| 2023-06-28T18:29:31
| 319,374,542
| 229
| 23
|
Apache-2.0
| 2023-08-30T23:21:30
| 2020-12-07T16:14:06
|
C++
|
UTF-8
|
C++
| false
| false
| 19,896
|
cpp
|
Camera.cpp
|
/*
* Copyright 2019 Adobe. All rights reserved.
* This file is licensed 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
#include <assert.h>
#include <lagrange/Logger.h>
#include <lagrange/ui/types/Camera.h>
#include <lagrange/utils/utils.h>
#include <cmath>
namespace lagrange {
namespace ui {
Camera::Camera(Type type /* = Type::PERSPECTIVE*/)
: m_type(type)
{
m_P = Eigen::Matrix4f::Identity();
m_Pinv = Eigen::Matrix4f::Identity();
}
Camera Camera::default_camera(float width, float height, Type type /* = Type::PERSPECTIVE*/)
{
Camera c(type);
c.set_up(Eigen::Vector3f(0, 1, 0));
c.set_position(Eigen::Vector3f(-4.11f, 0.569f, -0.195f));
c.set_lookat(Eigen::Vector3f::Zero());
c.set_window_dimensions(width, height);
c.set_fov(3.14f / 4.0f);
c.set_planes(0.0125f, 128.0f);
return c;
}
void Camera::set_type(Type type)
{
if (m_type == type) return;
// Convert perspective to orthographic
if (get_type() == Type::PERSPECTIVE && type == Type::ORTHOGRAPHIC) {
float depth = (get_position() - get_lookat()).norm();
float h = depth * 2.0f * std::atan(get_fov());
float w = h * m_aspectRatio;
set_ortho_viewport(Eigen::Vector4f(w / -2.0f, w / 2.0f, h / -2.0f, h / 2.0f));
}
m_type = type;
update_view();
update_perspective();
}
void Camera::set_position(const Eigen::Vector3f& pos)
{
if (!std::isfinite(pos.x()) || !std::isfinite(pos.y()) || !std::isfinite(pos.z())) return;
m_pos = pos.cwiseMin(1e15f).cwiseMax(-1e15f);
update_view();
}
void Camera::set_up(const Eigen::Vector3f& up)
{
m_up = up;
update_view();
}
Eigen::Vector3f Camera::get_position() const
{
return m_pos;
}
Eigen::Vector3f Camera::get_direction() const
{
return (m_lookat - m_pos).normalized();
}
Eigen::Vector3f Camera::get_up() const
{
return m_up;
}
float Camera::get_far_plane() const
{
return m_zfar;
}
float Camera::get_near_plane() const
{
return m_znear;
}
void Camera::set_window_dimensions(float width, float height)
{
m_windowWidth = width;
m_windowHeight = height;
set_aspect_ratio(m_windowWidth, m_windowHeight);
}
void Camera::set_aspect_ratio(float width, float height)
{
m_aspectRatio = float(width) / float(height);
if (get_type() == Type::ORTHOGRAPHIC) {
auto v = get_ortho_viewport();
float w = (v.y() - v.x());
float h = w / m_aspectRatio;
set_ortho_viewport(Eigen::Vector4f(w / -2.0f, w / 2.0f, h / -2.0f, h / 2.0f));
}
update_perspective();
}
void Camera::set_fov(float fov)
{
m_fov = fov;
update_perspective();
}
void Camera::set_planes(float znear, float zfar)
{
m_znear = znear;
m_zfar = zfar;
update_perspective();
}
Eigen::Projective3f Camera::get_perspective() const
{
return m_P;
}
Eigen::Matrix4f Camera::get_view() const
{
return m_V;
}
Eigen::Matrix4f Camera::get_PV() const
{
return m_P * m_V;
}
float Camera::get_window_width() const
{
return m_windowWidth * m_retina_scale;
}
float Camera::get_window_height() const
{
return m_windowHeight * m_retina_scale;
}
Eigen::Vector2f Camera::get_window_size() const
{
return Eigen::Vector2f(get_window_width(), get_window_height());
}
void Camera::update_view()
{
m_V = look_at(m_pos, m_lookat, m_up);
m_Vinv = m_V.inverse();
assert(std::isfinite(m_V(0)));
}
void Camera::update_perspective()
{
if (m_type == Type::PERSPECTIVE) {
m_P = perspective(m_fov, m_aspectRatio, m_znear, m_zfar);
} else if (m_type == Type::ORTHOGRAPHIC) {
m_P = ortho(
m_ortho_viewport.x(),
m_ortho_viewport.y(),
m_ortho_viewport.z(),
m_ortho_viewport.w(),
m_znear,
m_zfar);
}
m_Pinv = m_P.inverse();
assert(std::isfinite(m_P.matrix()(0)));
}
Camera::Ray Camera::cast_ray(const Eigen::Vector2f& coord) const
{
if (m_type == Type::PERSPECTIVE) {
Eigen::Vector4f rayNorm =
Eigen::Vector4f(coord.x() / m_windowWidth, (coord.y() / m_windowHeight), 0.0f, 0.0f) *
2.0f -
Eigen::Vector4f(1.0f, 1.0f, 0.0f, 0.0f);
rayNorm.z() = -1.0f;
rayNorm.w() = 1.0f;
Eigen::Vector4f rayEye = m_Pinv * rayNorm;
rayEye.z() = -1.0f;
rayEye.w() = 0.0f;
Eigen::Vector4f rayWorld = m_Vinv * rayEye;
Eigen::Vector3f ray = rayWorld.head<3>().normalized();
return {get_position(), ray};
} else {
Eigen::Vector3f pos = unproject(coord, 0.0f);
return {pos, get_direction()};
}
}
Eigen::Vector2f Camera::project(const Eigen::Vector3f& pos) const
{
Eigen::Vector4f v = Eigen::Vector4f(pos.x(), pos.y(), pos.z(), 1.0f);
// Project
v = m_P * m_V * v;
//Viewport //Perspective division
Eigen::Vector2f s = Eigen::Vector2f(v.x() / v.w(), v.y() / v.w());
s.x() = (s.x() + 1.0f) / 2.0f;
s.y() = 1.0f - ((s.y() + 1.0f) / 2.0f);
s.x() *= m_windowWidth;
s.y() *= m_windowHeight;
return s;
}
Eigen::Vector3f Camera::project_with_depth(const Eigen::Vector3f& pos) const
{
Eigen::Vector4f v = Eigen::Vector4f(pos.x(), pos.y(), pos.z(), 1.0f);
// Project
v = m_P * m_V * v;
//Viewport //Perspective division
Eigen::Vector3f s = Eigen::Vector3f(v.x() / v.w(), v.y() / v.w(), v.z() / v.w());
s.x() = (s.x() + 1.0f) / 2.0f;
s.y() = 1.0f - ((s.y() + 1.0f) / 2.0f);
s.x() *= m_windowWidth;
s.y() *= m_windowHeight;
return s;
}
Eigen::Vector3f Camera::unproject(const Eigen::Vector2f& screen, float z) const
{
Eigen::Vector4f Vp = Eigen::Vector4f(0, 0, m_windowWidth, m_windowHeight);
return unproject_point(Eigen::Vector3f(screen.x(), screen.y(), z), m_V, m_P.matrix(), Vp);
}
bool Camera::get_ray_to_screen(
const Eigen::Vector3f& rayOrigin,
const Eigen::Vector3f& rayDir,
Eigen::Vector2f* beginOut,
Eigen::Vector2f* endOut) const
{
Eigen::Vector2f begin = project(rayOrigin);
Eigen::Vector2f end = project(rayOrigin + rayDir * m_zfar);
Eigen::Vector2f bounds[2];
bounds[0] = Eigen::Vector2f::Zero();
bounds[1] = Eigen::Vector2f(m_windowWidth, m_windowHeight);
begin = begin.cwiseMax(bounds[0]).cwiseMin(bounds[1]);
end = end.cwiseMax(bounds[0]).cwiseMin(bounds[1]);
// Out of screen
if (begin.x() == end.x() && begin.y() == end.y()) return false;
*beginOut = begin;
*endOut = end;
return true;
}
void Camera::rotate_around_lookat(float angleRad)
{
const Eigen::Vector3f at_to_eye = m_pos - m_lookat;
const Eigen::Vector3f rotated_at_to_eye = Eigen::AngleAxisf(angleRad, m_up) * at_to_eye;
set_position(m_lookat + rotated_at_to_eye);
}
void Camera::rotate_tumble(float yaw_delta, float pitch_delta)
{
if (get_up().y() < 0.0f) {
yaw_delta = -yaw_delta;
}
const float dist = (get_position() - get_lookat()).norm();
const Eigen::Vector3f look = (get_position() - get_lookat()).normalized();
float yaw = std::atan2(look.z(), look.x()); // azimuth
float pitch = std::acos(look.y()); // inclination
// Map pitch to [0,2pi] ([0,pi] when up vector points up, [pi,2pi] when down)
if (get_up().y() < 0.0f) {
pitch = two_pi() - pitch;
}
yaw -= yaw_delta;
pitch -= pitch_delta;
// Remap yaw when camera is inverted (rotate in circle by half circle)
if (get_up().y() < 0.0f) {
yaw = yaw + pi();
// Modulo two pi
if (yaw > two_pi()) {
yaw -= two_pi();
}
}
const Eigen::Vector3f sphere_pos = Eigen::Vector3f(
std::sin(pitch) * std::cos(yaw),
std::cos(pitch),
std::sin(pitch) * std::sin(yaw));
const Eigen::Vector3f new_pos = get_lookat() + dist * sphere_pos;
const Eigen::Vector3f new_side = Eigen::Vector3f(-std::sin(yaw), 0, std::cos(yaw));
const Eigen::Vector3f new_up = (-sphere_pos).cross(new_side);
set_position(new_pos);
set_up(new_up);
}
void Camera::rotate_turntable(float yaw_delta, float pitch_delta, Eigen::Vector3f primary_axis)
{
if (primary_axis.x() != 0 || primary_axis.y() != 0 || primary_axis.z() != 0) {
set_up(primary_axis);
}
const Eigen::Vector3f look = (get_position() - get_lookat()).normalized();
const Eigen::Vector3f side = look.cross(get_up());
const Eigen::AngleAxisf R_yaw = Eigen::AngleAxisf(yaw_delta, get_up());
const Eigen::AngleAxisf R_pitch = Eigen::AngleAxisf(pitch_delta, side);
const Eigen::Vector3f pos = get_position();
const Eigen::Vector3f new_pos = (R_yaw * R_pitch * pos);
set_position(new_pos);
}
void Camera::rotate_arcball(
const Eigen::Vector3f& camera_pos_start,
const Eigen::Vector3f& camera_up_start,
const Eigen::Vector2f& mouse_start,
const Eigen::Vector2f& mouse_current)
{
// No change of camera
if (mouse_start.x() == mouse_current.x() && mouse_start.y() == mouse_current.y()) return;
const auto map_to_sphere = [&](const Eigen::Vector2f& pos) -> Eigen::Vector3f {
Eigen::Vector3f p = Eigen::Vector3f::Zero();
// Map to fullscreen ellipse
p.x() = (2 * pos.x() / get_window_width() - 1.0f);
p.y() = (2 * (pos.y() / get_window_height()) - 1.0f);
float lensq = p.x() * p.x() + p.y() * p.y();
if (lensq <= 1.0f) {
p.z() = std::sqrt(1 - lensq);
} else {
p = p.normalized();
}
return p;
};
const auto decompose =
[](const Eigen::Matrix4f& m, Eigen::Vector3f& T, Eigen::Matrix3f& R, Eigen::Vector3f& S) {
T = m.col(3).head<3>();
S = Eigen::Vector3f((m.col(0).norm()), (m.col(1).norm()), (m.col(2).norm()));
R.col(0) = m.col(0).head<3>() * (1.0f / S(0));
R.col(1) = m.col(1).head<3>() * (1.0f / S(1));
R.col(2) = m.col(2).head<3>() * (1.0f / S(2));
};
//Calculate points on sphere and rotation axis/angle
const Eigen::Vector3f p0 = map_to_sphere(mouse_start);
const Eigen::Vector3f p1 = map_to_sphere(mouse_current);
// Axis is in default coord system
const Eigen::Vector3f axis = p0.cross(p1).normalized();
const float angle = vector_angle(p0, p1);
// Initial rotation
const Eigen::Matrix4f r_0 = look_at(camera_pos_start, m_lookat, camera_up_start);
// Rotate axis to current frame and rotate around it
const Eigen::Vector3f rotated_axis = (r_0.inverse().block<3, 3>(0, 0) * axis);
Eigen::Matrix4f r_arc = Eigen::Matrix4f::Identity();
r_arc.block<3, 3>(0, 0) = Eigen::AngleAxisf(angle, rotated_axis).matrix();
// Get inverse new view matrix
const Eigen::Matrix4f r = (r_0 * r_arc).inverse().matrix();
Eigen::Vector3f new_pos, new_scale;
Eigen::Matrix3f r_decomp;
// Decompose new position and new rotation
decompose(r, new_pos, r_decomp, new_scale);
// Rotate default up axis
const Eigen::Vector3f up = r_decomp * Eigen::Vector3f(0, 1, 0);
// Set new camera properties
set_position(new_pos);
set_up(up);
}
void Camera::zoom(float delta)
{
if (delta == 0.0f) return;
delta = std::min(std::max(delta, -0.25f), 0.25f);
if (get_type() == Camera::Type::PERSPECTIVE) {
const float fov = lagrange::to_degrees(get_fov());
float max_step_deg = 2.0f;
if (fov > 100.0f) max_step_deg *= std::exp(-((fov - 100.0f) / 70.0f) * 8.0f);
float new_fov =
std::max(std::min(fov * (1.0f - 0.5f * delta), fov + max_step_deg), fov - max_step_deg);
new_fov = std::max(1.0e-5f, new_fov);
new_fov = std::min(170.0f, new_fov);
set_fov(lagrange::to_radians(new_fov));
} else {
dolly(delta);
}
}
void Camera::dolly(float delta)
{
if (delta == 0.0f) return;
delta = std::min(std::max(delta, -0.25f), 0.25f);
if (get_type() == Camera::Type::PERSPECTIVE) {
set_position(((1.0f - 1.0f * delta) * (get_position() - get_lookat())) + get_lookat());
} else if (get_type() == Camera::Type::ORTHOGRAPHIC) {
const auto new_v = (get_ortho_viewport() * (1.0f - delta)).eval();
if ((new_v.array().cwiseAbs() > 1e-5f).all()) {
set_ortho_viewport(new_v);
}
}
update_view();
update_perspective();
}
void Camera::move_forward(float delta)
{
Eigen::Vector3f v = get_direction() * delta;
m_lookat = get_lookat() + v;
m_pos = get_position() + v;
update_view();
}
void Camera::move_right(float delta)
{
const Eigen::Vector3f right = get_direction().cross(get_up()).normalized();
Eigen::Vector3f v = right * delta;
m_pos = get_position() + v;
m_lookat = get_lookat() + v;
update_view();
}
void Camera::move_up(float delta)
{
const Eigen::Vector3f v = get_up() * delta;
m_pos = get_position() + v;
m_lookat = get_lookat() + v;
update_view();
}
void Camera::set_ortho_viewport(Eigen::Vector4f viewport)
{
if (std::isnan(viewport.x()) || std::isnan(viewport.y()) || std::isnan(viewport.z()) ||
std::isnan(viewport.w()))
return;
m_ortho_viewport = viewport;
update_perspective();
}
Eigen::Vector4f Camera::get_ortho_viewport() const
{
return m_ortho_viewport;
}
Camera Camera::transformed(const ViewportTransform& vt) const
{
Camera cam = *this;
if (vt.clip) {
Eigen::Vector2f orig = cam.get_window_origin();
cam.set_window_origin(
orig.x() + cam.get_window_width() * vt.translate.x(),
orig.y() + cam.get_window_height() * vt.translate.y());
cam.set_window_dimensions(
cam.get_window_width() * vt.scale.x(),
cam.get_window_height() * vt.scale.y());
} else {
cam.set_aspect_ratio(
cam.get_window_width() * vt.scale.x(),
cam.get_window_height() * vt.scale.y());
const Eigen::Translation3f half = Eigen::Translation3f(Eigen::Vector3f(1.0f, 1.0f, 0));
const Eigen::Vector2f translate_flip =
Eigen::Vector2f(vt.translate.x(), 1.0f - vt.scale.y() - vt.translate.y());
const Eigen::Vector2f offset = translate_flip * 2.0f - Eigen::Vector2f::Ones();
const Eigen::Translation3f V_T =
Eigen::Translation3f(Eigen::Vector3f(offset.x(), offset.y(), 0));
const Eigen::Matrix3f V_S = Eigen::Scaling(vt.scale.x(), vt.scale.y(), 1.0f);
cam.m_P = V_T * V_S * half * cam.m_P;
}
return cam;
}
Eigen::Vector2f Camera::inverse_viewport_transform(
const ViewportTransform& vt,
Eigen::Vector2f& pixel) const
{
const Eigen::Vector2f vt_origin = vt.translate.cwiseProduct(get_window_size());
return (pixel - vt_origin)
.cwiseProduct(Eigen::Vector2f(1.0f / vt.scale.x(), 1.0f / vt.scale.y()));
}
bool Camera::is_pixel_in(const Eigen::Vector2f& p) const
{
return p.x() >= 0.0f && p.y() >= 0.0f && p.x() < float(get_window_width()) &&
p.y() < float(get_window_height());
}
bool Camera::intersects_region(const Eigen::Vector2f& begin, const Eigen::Vector2f& end) const
{
Eigen::Vector2f min = begin.cwiseMin(end);
Eigen::Vector2f max = begin.cwiseMax(end);
if (max.x() < 0.0f || min.x() > get_window_width()) return false;
if (max.y() < 0.0f || min.y() > get_window_height()) return false;
return true;
}
bool Camera::is_orthogonal_direction(Dir dir) const
{
auto config = get_orthogonal_direction(dir);
return (config.first.array() == get_position().array()).all();
}
void Camera::set_orthogonal_direction(Dir dir)
{
auto config = get_orthogonal_direction(dir);
set_position_up(config.first, config.second);
}
std::pair<Eigen::Vector3f, Eigen::Vector3f> Camera::get_orthogonal_direction(Dir dir) const
{
const float d = (get_lookat() - get_position()).norm();
switch (dir) {
case Dir::TOP: return {Eigen::Vector3f(0, 1, 0) * d + get_lookat(), Eigen::Vector3f(1, 0, 0)};
case Dir::BOTTOM:
return {Eigen::Vector3f(0, -1, 0) * d + get_lookat(), Eigen::Vector3f(-1, 0, 0)};
case Dir::LEFT: return {Eigen::Vector3f(0, 0, -1) * d + get_lookat(), Eigen::Vector3f(0, 1, 0)};
case Dir::RIGHT: return {Eigen::Vector3f(0, 0, 1) * d + get_lookat(), Eigen::Vector3f(0, 1, 0)};
case Dir::FRONT:
return {Eigen::Vector3f(-1, 0, 0) * d + get_lookat(), Eigen::Vector3f(0, 1, 0)};
case Dir::BACK: return {Eigen::Vector3f(1, 0, 0) * d + get_lookat(), Eigen::Vector3f(0, 1, 0)};
default: break;
}
return {};
}
void Camera::set_lookat(const Eigen::Vector3f& dir)
{
m_lookat = dir;
update_view();
}
void Camera::set_position_up(const Eigen::Vector3f& pos, const Eigen::Vector3f& up)
{
m_pos = pos;
m_up = up;
update_view();
}
Frustum Camera::get_frustum() const
{
return get_frustum(Eigen::Vector2f(0), Eigen::Vector2f(get_window_size()));
}
Frustum Camera::get_frustum(Eigen::Vector2f min, Eigen::Vector2f max) const
{
auto ray_bottom_left = cast_ray(min);
auto ray_top_left = cast_ray({min.x(), max.y()});
auto ray_top_right = cast_ray(max);
auto ray_bottom_right = cast_ray({max.x(), min.y()});
auto ray_center = cast_ray((min + max) * 0.5f);
const Eigen::Vector3f side = get_direction().cross(get_up());
const Eigen::Vector3f c_near = ray_center.origin + ray_center.dir * get_near();
const Eigen::Vector3f c_far = ray_center.origin + ray_center.dir * get_far();
Frustum f;
f.vertices[FRUSTUM_FAR_LEFT_TOP] = ray_top_left.origin + ray_top_left.dir * get_far();
f.vertices[FRUSTUM_FAR_RIGHT_TOP] = ray_top_right.origin + ray_top_right.dir * get_far();
f.vertices[FRUSTUM_FAR_LEFT_BOTTOM] = ray_bottom_left.origin + ray_bottom_left.dir * get_far();
f.vertices[FRUSTUM_FAR_RIGHT_BOTTOM] =
ray_bottom_right.origin + ray_bottom_right.dir * get_far();
f.vertices[FRUSTUM_NEAR_LEFT_TOP] = ray_top_left.origin + ray_top_left.dir * get_near();
f.vertices[FRUSTUM_NEAR_RIGHT_TOP] = ray_top_right.origin + ray_top_right.dir * get_near();
f.vertices[FRUSTUM_NEAR_LEFT_BOTTOM] =
ray_bottom_left.origin + ray_bottom_left.dir * get_near();
f.vertices[FRUSTUM_NEAR_RIGHT_BOTTOM] =
ray_bottom_right.origin + ray_bottom_right.dir * get_near();
const Eigen::Vector3f n_right =
(f.vertices[FRUSTUM_FAR_RIGHT_BOTTOM] - f.vertices[FRUSTUM_NEAR_RIGHT_BOTTOM])
.cross(get_up());
const Eigen::Vector3f n_left =
get_up().cross(f.vertices[FRUSTUM_FAR_LEFT_BOTTOM] - f.vertices[FRUSTUM_NEAR_LEFT_BOTTOM]);
const Eigen::Vector3f n_top =
side.cross(f.vertices[FRUSTUM_FAR_LEFT_TOP] - f.vertices[FRUSTUM_NEAR_LEFT_TOP]);
const Eigen::Vector3f n_bottom =
(f.vertices[FRUSTUM_FAR_LEFT_BOTTOM] - f.vertices[FRUSTUM_NEAR_LEFT_BOTTOM]).cross(side);
const float sgn = -1.0f; // outward
f.planes[FRUSTUM_NEAR] = Frustum::Plane(-sgn * get_direction(), c_near);
f.planes[FRUSTUM_FAR] = Frustum::Plane(sgn * get_direction(), c_far);
f.planes[FRUSTUM_LEFT] = Frustum::Plane(sgn * n_left, f.vertices[FRUSTUM_NEAR_LEFT_BOTTOM]);
f.planes[FRUSTUM_RIGHT] = Frustum::Plane(sgn * n_right, f.vertices[FRUSTUM_NEAR_RIGHT_BOTTOM]);
f.planes[FRUSTUM_TOP] = Frustum::Plane(sgn * n_top, f.vertices[FRUSTUM_NEAR_LEFT_TOP]);
f.planes[FRUSTUM_BOTTOM] = Frustum::Plane(sgn * n_bottom, f.vertices[FRUSTUM_NEAR_LEFT_BOTTOM]);
return f;
}
} // namespace ui
} // namespace lagrange
|
a2290acb4f765b5b555799c3707cd4f42dd6a38c
|
0db39939d606590f563d638f9da34c4a909b4b6a
|
/Include/Vector3.h
|
d7e06d80261869a632378283aba3eff4fcf12b14
|
[] |
no_license
|
G-Cristian/ComputerGraphics
|
e4df9fa14e466f36870225baa86ccf6e8b946488
|
b8e696bb112e299c034954a55932033a68cd146a
|
refs/heads/master
| 2020-03-30T06:54:59.690597
| 2019-06-08T14:51:33
| 2019-06-08T14:51:33
| 150,899,474
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,953
|
h
|
Vector3.h
|
#ifndef _VECTOR3_H_
#define _VECTOR3_H_
#include <algorithm>
namespace K9 {
class Vector3 {
public:
Vector3():
Vector3(0.0f, 0.0f, 0.0f) {
}
Vector3(float x, float y, float z) {
_vectorImp.x = x;
_vectorImp.y = y;
_vectorImp.z = z;
}
Vector3(const Vector3 &other) {
memcpy((void*)_vectorImp.vec, (void*)other._vectorImp.vec, 3 * sizeof(float));
}
~Vector3() {}
//access operators
float operator[](int i) const { return _vectorImp.vec[i]; }
float& operator[](int i) { return _vectorImp.vec[i]; }
//operators
Vector3& operator=(const Vector3 &other) {
memcpy((void*)_vectorImp.vec, (void*)other._vectorImp.vec, 3 * sizeof(float));
return *this;
}
//aritmetic operators
Vector3 operator+(const Vector3 &other) const;
Vector3 operator-() const;
Vector3 operator-(const Vector3 &other) const;
float operator*(const Vector3 &other) const;
Vector3 operator*(float scalar) const;
Vector3 operator/(float scalar) const;
friend Vector3 operator*(float scalar, const Vector3 &vector);
//other vector operations
float norm() const;
Vector3& normalize();
friend Vector3 cross(const Vector3 &v1, const Vector3 &v2);
friend Vector3 perElementProduct(const Vector3 &v1, const Vector3 &v2);
bool isZero() const { return _vectorImp.x == 0.0f && _vectorImp.y == 0.0f && _vectorImp.z == 0.0f; }
//helpers
friend void swap(Vector3 &v1, Vector3 &v2);
private:
union Vector3Imp {
struct {
float x;
float y;
float z;
};
float vec[3];
};
Vector3Imp _vectorImp;
};
//friend functions
Vector3 operator*(float scalar, const Vector3 &vector);
//other functions
inline Vector3 normalized(const Vector3 &vector);
inline Vector3 cross(const Vector3 &v1, const Vector3 &v2);
inline Vector3 perElementProduct(const Vector3 &v1, const Vector3 &v2);
inline void swap(Vector3 &v1, Vector3 &v2);
}
#include "../Source/Vector3.cpp"
#endif // !_VECTOR3_H_
|
d10a2e9dd5cb4510492b16dbee1679f4922b4373
|
d3a19285f928a91ef7c60b1469c2934080af41c5
|
/FP_PP_1_20141578_정민교/FP_PP_1_20141578_정민교/utils/rwdata.h
|
772c171256209d59dc052997daf2685be3cec30c
|
[] |
no_license
|
jmg7173/FileProcessing
|
b32731b2669c2f8f8b0160a85d1f0e2a3fa1f773
|
7804ce10e1f8df3538778f2e58634322cbdb7ab8
|
refs/heads/master
| 2021-05-01T01:15:46.592096
| 2016-11-14T05:14:28
| 2016-11-14T05:14:28
| 70,041,897
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,971
|
h
|
rwdata.h
|
#ifndef RWDATA_H_
#define RWDATA_H_
#include <fstream>
#include <string>
#include "recfile.h"
#include "../structure/dataset.h"
// Read from .txt Files
template <class Type>
void readTxt(const string filename, vector<Type> &list) {
ifstream ifs(filename);
if (ifs.fail())
{
cout << "File open error!" << endl;
exit(1);
}
int n;
ifs >> n;
ifs.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < n; i++) {
Type p;
ifs >> p;
list.push_back(p);
}
ifs.close();
}
// Write to .dat Files
template <class Type>
bool writeDat(const string filename, const vector<Type> list) {
DelimFieldBuffer buffer('|', MAXBUF);
RecordFile <Type> TypeFile(buffer);
TypeFile.Create(filename.c_str(), ios::out | ios::trunc);
if (list.empty())
return false;
for (Type t : list) {
int recaddr;
if ((recaddr = TypeFile.Write(t)) == -1) {
cout << "Write Error!" << endl;
return false;
}
}
TypeFile.Close();
return true;
}
template <class Type>
bool writeSpecificDat(const string filename, Type t, int recaddr, unsigned char skipSize = 0) {
DelimFieldBuffer buffer('|', MAXBUF);
RecordFile <Type> TypeFile(buffer);
if (!TypeFile.Open(filename.c_str(), ios::out))
return false;
int rectmp;
if ((rectmp = TypeFile.Write(t,recaddr,skipSize)) == -1) {
cout << "Write Error!" << endl;
return false;
}
TypeFile.Close();
return true;
}
template <class Type>
Type readSpecificDat(const string filename, int recaddr) {
DelimFieldBuffer buffer('|', MAXBUF);
RecordFile <Type> TypeFile(buffer);
if (!TypeFile.Open(filename.c_str(), ios::in))
return Type();
int rectmp;
Type t;
unsigned char bufSize, skipSize;
if ((rectmp = TypeFile.Read(t, bufSize, skipSize, recaddr)) == -1)
return Type();
if (!bufSize)
return Type();
TypeFile.Close();
return t;
}
// Read from .dat Files (Member, Stock)
template <class Type>
bool readDat(
const string filename,
vector< pair<int ,int> >& deleted,
map<string, pair<int, int> > &Map
) {
DelimFieldBuffer buffer('|', MAXBUF);
RecordFile <Type> TypeFile(buffer);
int state = 0;
if (!TypeFile.Open(filename.c_str(), ios::in))
return false;
while (true) {
Type t;
unsigned char bufSize = 0;
unsigned char skipSize = 0;
state = TypeFile.Read(t, bufSize, skipSize);
if (state == -1)
break;
if (!bufSize) {
deleted.push_back(make_pair(state, skipSize));
continue;
}
Map[t.getID()] = make_pair(state, bufSize + skipSize);
}
TypeFile.Close();
return true;
}
extern map<string, pair<int, int> > Map_Purchase_PID;
extern map<string, vector<pair<int, int> > > Map_Purchse_MID;
extern map<string, vector<pair<int, int> > > Map_Purchse_SID;
static bool readDatPurchase(
const string filename,
vector< pair<int, int> >& deleted
) {
DelimFieldBuffer buffer('|', MAXBUF);
RecordFile <Purchase> PurchaseFile(buffer);
int state = 0;
int idx = 0;
if (!PurchaseFile.Open(filename.c_str(), ios::in))
return false;
while (true) {
Purchase p;
unsigned char bufSize = 0;
unsigned char skipSize = 0;
state = PurchaseFile.Read(p, bufSize, skipSize);
if (state == -1)
break;
if (!bufSize) {
deleted.push_back(make_pair(state, skipSize));
continue;
}
Map_Purchase_PID[p.getPurchaseID()] = make_pair(state, bufSize+skipSize);
Map_Purchase_MID[p.getMemberID()].push_back(make_pair(state, bufSize + skipSize));
Map_Purchase_SID[p.getStockID()].push_back(make_pair(state, bufSize + skipSize));
}
PurchaseFile.Close();
return true;
}
#include "strings.h"
extern map<string, pair<int, int> > Map_Member;
extern map<string, pair<int, int> > Map_Stock;
extern vector<pair<int, int> > Deleted_Purchase;
extern vector<pair<int, int> > Deleted_Stock;
extern vector<pair<int, int> > Deleted_Member;
static void constructDatas() {
readDat<Member>(
datFileMem,
Deleted_Member,
Map_Member);
readDat<Stock>(
datFileStock,
Deleted_Stock,
Map_Stock);
readDatPurchase(
datFilePur,
Deleted_Purchase);
}
#endif
|
8a21eea928d5015940528b4b878f8fe5e745f5f7
|
99f7e6b14a37d2033c3ece8c1c8d7ff2992d4aa3
|
/misc/Sort/QuickSort.cpp
|
372bce031a819be86e1ace6f2f69b7224f3420e4
|
[] |
no_license
|
gnthibault/EPI
|
76cf18725d610589c31c03b806d5809c858ff2bd
|
af6969170aa9e4e766f248013e92a7156fff8dab
|
refs/heads/master
| 2021-01-09T09:37:01.399477
| 2017-01-19T22:46:09
| 2017-01-19T22:46:09
| 64,335,930
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,080
|
cpp
|
QuickSort.cpp
|
/*
* Compile using g++ --std=c++11 ./QuickSort.cpp -o ./test
*/
#include <vector>
#include <algorithm>
#include <iostream>
#include <cassert>
template<typename T>
void Print(const std::vector<T>& v) {
std::for_each( v.cbegin(), v.cend(), [](T in) {
std::cout << in << ","; } );
std::cout << std::endl;
}
//In place recursive algorithm for O(n log2(n)) sort
template<typename T>
std::vector<T> QuickSort(std::vector<T> in, size_t begin, size_t end) {
std::vector<T> v(in);
assert(begin<=end);
size_t size = end-begin;
if (size>1) {
T pivIdx = begin+size/2;//could use rand(begin,end)
std::swap(v[pivIdx],v[end-1]);
size_t j=begin;
for (size_t i=begin; i<end-1; i++) {
if (v[i]<=v[end-1]) {
std::swap(v[i],v[j]);
j++;
}
}
std::swap(v[j],v[end-1]);
v=QuickSort(v,begin,j);
v=QuickSort(v,j+1,end);
}
return v;
}
int main(int argc, char* argv[])
{
std::vector<int> v = {-1,5,-9,3,-3,4,4,2};
Print(QuickSort(v, 0, v.size()));
std::cout << "--------------" << std::endl;
return EXIT_SUCCESS;
}
|
906165daf72d6cb7eaa064d8b7923b0854c43839
|
757142f3794caadb4df652df53844036a48be11d
|
/sketch_sep20a/sketch_sep20a.ino
|
483c74aa8ea4ad0375503ae7a8713c52f1b25f8f
|
[] |
no_license
|
BarbaraLukowska/arduino
|
2ecc1ec2112b6a7b5ca83b9c7d30f273692cde16
|
6482ce118cc86edd05e47a8f6ff4b016dab8530a
|
refs/heads/master
| 2020-03-29T06:20:16.161322
| 2018-09-20T14:10:24
| 2018-09-20T14:10:24
| 149,620,370
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 584
|
ino
|
sketch_sep20a.ino
|
void setup() {
for (int pin = 2; pin < 10; pin++) {
pinMode(pin, OUTPUT);
}
}
void loop() {
int t = 20;
for(int i = 2; i < 10; i++){
digitalWrite(i, HIGH);
delay(t);
digitalWrite(i+1, HIGH);
delay(t);
digitalWrite(i+2, HIGH);
delay(t);
digitalWrite(i, LOW);
delay(t);
digitalWrite(i+1, LOW);
}
for(int i = 9; i > 1; i--){
digitalWrite(i, HIGH);
delay(t);
digitalWrite(i-1, HIGH);
delay(t);
digitalWrite(i-2, HIGH);
delay(t);
digitalWrite(i, LOW);
delay(t);
digitalWrite(i-1, LOW);
}
}
|
74c871813e58ce2cc34f1480ebf2c595f42f69e7
|
fb900dcc615ebb8cf7647e0e8fb721e68dca4823
|
/mercury 4.0/mercury_4_0_2/PID.ino
|
5a0da1ed378b236081c7b6ba31a62dc11c8df7b7
|
[] |
no_license
|
Piaktipik/Arduino
|
085d6944cb19569beedbfbaf5887c9da9a807e1f
|
6045fc88c18eb5b25272ffde57919cab288db3f9
|
refs/heads/master
| 2021-01-11T12:17:07.705597
| 2016-12-14T23:04:00
| 2016-12-14T23:04:00
| 76,507,626
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,552
|
ino
|
PID.ino
|
// Variables de trabajo.
unsigned long lastTime; // guardo el instante donde se ralizo el ultimo calculo
//double Input, Output, Setpoint; // parametros de entrada, salida y deseados del controlador
double ITerm = 0, lastInput; // Termino integral, termino diferencial
double kp, ki, kd; // constanstes del pid
int SampleTime = 20; // Tiempo de muestreo 20m segundos.
double outMin, outMax; // valor maximo y minimo de la salida
bool inAuto = false;
int controllerDirection = 0;
// zzzzzzzzzzzzzzzzzzzzzzzzzzzzz funciones zzzzzzzzzzzzzzzzzzzzzzzzzzzzz
void Compute(){
if(!inAuto) return; // esto nos permite poner el pid en modo manual
// ------------ si esta en modo automatico ------------
unsigned long now = millis(); // guardamos e tiempo actual
int timeChange = (now - lastTime); // calculamos el tiempo trascurrido desde la ultima ejecucion
if(timeChange>=SampleTime){
// Calculamos todos los errores.
double error = Setpoint - Input;
// ------------ costante integral ------------
ITerm += (ki * error);
// limitamos al rango
if(ITerm > outMax) ITerm = outMax; // se limita al valor maximo
else if(ITerm< outMin) ITerm = outMin; // se limita al se al valor minimo
// ------------ calculamos derivada ------------
double dInput = (Input - lastInput); // se deriva la entrada
// ------------ Calculamos la función de salida del PID ------------
Output = kp*error + ITerm - kd*dInput;
// limitamos al rango
if(Output > outMax) Output = outMax;
else if(Output < outMin) Output = outMin;
// Guardamos el valor de algunas variables para el próximo recálculo.
lastInput = Input; // valor para la derivada
lastTime = now; // tiempo del fin de la ultima ejecucion
}
}
// ---------------- se configaran los parametros del controlador ----------------
void SetTunings(double Kp, double Ki, double Kd){
if (Kp<0 || Ki<0|| Kd<0) return;
double SampleTimeInSec = ((double)SampleTime)/1000;
kp = Kp;
ki = Ki * SampleTimeInSec;
kd = Kd / SampleTimeInSec;
if(controllerDirection == 1){
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
}
// ---------------- se configura el tiempo de muestreo ----------------
void SetSampleTime(int NewSampleTime){
if (NewSampleTime > 0){
double ratio = (double)NewSampleTime / (double)SampleTime;
ki *= ratio;
kd /= ratio;
SampleTime = (unsigned long)NewSampleTime;
}
}
// ---------------- se configuran los valores ultimos ----------------
void SetOutputLimits(double Min, double Max){
if(Min > Max) return;
outMin = Min;
outMax = Max;
if(Output > outMax) Output = outMax;
else if(Output < outMin) Output = outMin;
if(ITerm > outMax) ITerm = outMax;
else if(ITerm < outMin) ITerm = outMin;
}
// ---------------- se configura el modo de muestreo ----------------
void SetMode(int Mode){
bool newAuto = (Mode == 1);
if(newAuto && !inAuto){ // Para cambiar de manual a automático, inicializamos algunos parámetros.
Initialize();
}
inAuto = newAuto;
}
// ---------------- se inicializa el controlador ----------------
void Initialize(){
lastInput = Input;
ITerm = Output;
if(ITerm > outMax) ITerm = outMax;
else if(ITerm < outMin) ITerm = outMin;
}
// ---------------- se donfigura la direccion del controlador ----------------
void SetControllerDirection(int Direction){
controllerDirection = Direction;
}
|
b6190348e1e2de2d77bd16097e6fc4b9fc3e8488
|
6b79670d3881bcd069cf688611ad36e0c114e95a
|
/piranha.h
|
cef28297d9b0a5c8b612e7214617d70eabf1752d
|
[] |
no_license
|
kabeero/piranha_gui
|
0dc0f4b9f6b132b6b3fa721cd10c45b5447afd74
|
089c8a0c9c4216ac78c27970efaf618df2b4fa7a
|
refs/heads/master
| 2021-01-13T00:33:41.581392
| 2017-02-09T01:52:57
| 2017-02-09T01:52:57
| 81,395,223
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 31,240
|
h
|
piranha.h
|
#ifndef EXAMPLEPLI892_H
#define EXAMPLEPLI892_H
#include <QtGui>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
QT_BEGIN_NAMESPACE
class UIpiranha : public QMainWindow
{
Q_OBJECT
public:
UIpiranha();
~UIpiranha();
private:
void readASMhex(std::string*, std::vector<uint>*);
std::string decodeASMhex(int);
QString mu = QChar(0x03bc);
QString iconPlay = QChar(0x23f5);
QString iconPause = QChar(0x23f8);
QString iconStop = QChar(0x23f9);
QString iconRecord = QChar(0x23fa);
QString iconUpload = QChar(0x23f6);
QString iconReset = QChar(0x2b6f);
QString iconSave = QChar(0x1f4be);
QAction *actionRecord, *actionExport, *actionExit, *actionSetup;
QWidget *centralwidget;
QFrame *frameVideo;
QLabel *lcdFPS;
QTabWidget *tabConfig;
QVBoxLayout *layoutConfig;
QStackedLayout *layoutOpts;
QGridLayout *layoutProgram;
QGridLayout *layoutBlank;
QGridLayout *layoutImage;
QGridLayout *layoutTrack;
QGridLayout *layoutFlags;
QButtonGroup *grpImage;
QButtonGroup *grpTrack;
QButtonGroup *grpFlags;
QGridLayout *layoutSettings;
QTabWidget *tabActions;
QGridLayout *layoutActions;
QGridLayout *layoutRecord;
QLabel *lblProgram;
QComboBox *comboProgram;
QLabel *lblImage;
QRadioButton *rdoImage, *rdoImageSlow, *rdoImageFPN;
QRadioButton *rdoTrack, *rdoTrackEmbed, *rdoTrackTrajLinear, *rdoTrackTrajNonlinear, *rdoTrackRPM;
QLabel *lblDataPoints, *lblDataPointsUnits, *lblPredictPoints, *lblPredictPointsUnits, *lblPredictInterval, *lblPredictIntervalUnits;
QSpinBox *spinDataPoints, *spinPredictPoints, *spinPredictInterval;
QCheckBox *chkCDS, *chkParallel, *chkRepeat, *chkDebug, *chkDummy, *chkStretch, *chkFlip, *chkTransform;
QLabel *lblDesc;
QLabel *lblVmax, *lblVmaxUnits;
QDoubleSpinBox *spinVmax;
QLabel *lblVmin, *lblVminUnits;
QDoubleSpinBox *spinVmin;
QLabel *lblVrst, *lblVrstUnits;
QDoubleSpinBox *spinVrst;
QLabel *lblVbias, *lblVbiasUnits;
QDoubleSpinBox *spinVbias;
QLabel *lblTrst, *lblTrstUnits;
QSpinBox *spinTrst;
QLabel *lblTint, *lblTintUnits;
QSpinBox *spinTint;
QLabel *lblTimeout, *lblTimeoutUnits;
QSpinBox *spinTimeout;
QLabel *lblThreshold;
QSpinBox *spinThreshold;
QLabel *lblFrames, *lblFramesUnits;
QSpinBox *spinFrames;
QLabel *lblFPS, *lblFPSUnits;
QSpinBox *spinFPS;
QPushButton *btnApply, *btnReset, *btnStop, *btnStart;
QPushButton *btnExportImage, *btnRecordStart, *btnRecordStop;
QProgressBar *barRecord;
QMenuBar *menubar;
QMenu *menuFile, *menuTools;
QStatusBar *statusbar;
void setupUI(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName("MainWindow");
MainWindow->resize(1080, 725);
MainWindow->setFixedSize(1080, 725);
MainWindow->setDocumentMode(false);
//MainWindow->statusBar()->setSizeGripEnabled(false);
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName("centralwidget");
frameVideo = new QFrame(centralwidget);
frameVideo->setObjectName("frameVideo");
frameVideo->setGeometry(QRect(15, 15, 800, 640));
frameVideo->setFrameShape(QFrame::StyledPanel);
frameVideo->setFrameShadow(QFrame::Raised);
lcdFPS = new QLabel(MainWindow);
lcdFPS->setObjectName("lcdFPS");
lcdFPS->setGeometry(QRect(735, 685, 80, 35));
QPalette lcdPal = lcdFPS->palette();
lcdPal.setColor(lcdPal.WindowText, QColor(255,255,255));
lcdPal.setColor(lcdPal.Background, QColor( 0, 0, 0));
lcdFPS->setPalette(lcdPal);
lcdFPS->setAutoFillBackground(false);
lcdFPS->setAlignment(Qt::AlignRight);
lcdFPS->setStyleSheet("font-family: Terminus; font-size: 12pt; font-weight: bold");
tabConfig = new QTabWidget(centralwidget);
tabConfig->setObjectName("tabConfig");
tabConfig->setGeometry(QRect(830, 15, 235, 490));
tabConfig->addTab(new QWidget(), "Program");
tabConfig->addTab(new QWidget(), "Settings");
grpImage = new QButtonGroup(tabConfig->widget(0));
grpImage->setObjectName("grpImage");
grpImage->setExclusive(true);
grpTrack = new QButtonGroup(tabConfig->widget(0));
grpTrack->setObjectName("grpTrack");
grpTrack->setExclusive(true);
grpFlags = new QButtonGroup(tabConfig->widget(0));
grpFlags->setObjectName("grpFlags");
grpFlags->setExclusive(false);
tabActions = new QTabWidget(centralwidget);
tabActions->setObjectName("tabActions");
tabActions->setGeometry(QRect(830, 525, 235, 130));
tabActions->addTab(new QWidget(), "Stream");
tabActions->addTab(new QWidget(), "Record");
layoutConfig = new QVBoxLayout(tabConfig->widget(0));
layoutConfig->setObjectName("layoutConfig");
layoutOpts = new QStackedLayout();
layoutOpts->setObjectName("layoutOpts");
layoutProgram = new QGridLayout();
layoutProgram->setObjectName("layoutProgram");
layoutBlank = new QGridLayout();
layoutBlank->setObjectName("layoutBlank");
layoutImage = new QGridLayout();
layoutImage->setObjectName("layoutImage");
layoutTrack = new QGridLayout();
layoutTrack->setObjectName("layoutTrack");
layoutFlags = new QGridLayout();
layoutFlags->setObjectName("layoutFlags");
layoutFlags->setVerticalSpacing(15);
QWidget *widBlank = new QWidget();
widBlank->setLayout(layoutBlank);
QWidget *widImage = new QWidget();
widImage->setLayout(layoutImage);
QWidget *widTrack = new QWidget();
widTrack->setLayout(layoutTrack);
layoutOpts->addWidget(widBlank);
layoutOpts->addWidget(widImage);
layoutOpts->addWidget(widTrack);
layoutConfig->addLayout(layoutProgram);
layoutConfig->addLayout(layoutOpts);
layoutConfig->addLayout(layoutFlags);
layoutSettings = new QGridLayout(tabConfig->widget(1));
layoutSettings->setObjectName("layoutSettings");
layoutActions = new QGridLayout(tabActions->widget(0));
layoutActions->setObjectName("layoutActions");
layoutRecord = new QGridLayout(tabActions->widget(1));
layoutRecord->setObjectName("layoutRecord");
lblImage = new QLabel(frameVideo);
lblImage->setObjectName("lblImage");
lblImage->setGeometry(QRect(0, 0, 800, 640));
lblImage->setAlignment(Qt::AlignCenter);
lblProgram = new QLabel(tabConfig->widget(0));
lblProgram->setObjectName("lblProgram");
lblProgram->setText("Operation");
comboProgram = new QComboBox(tabConfig->widget(0));
comboProgram->setObjectName("comboProgram");
lblProgram->setBuddy(comboProgram);
layoutProgram->addWidget(lblProgram, 0, 0, Qt::AlignLeft);
layoutProgram->addWidget(comboProgram, 0, 1, 1, 2);
layoutProgram->setColumnStretch(0, 1);
layoutProgram->setColumnStretch(1, 1);
lblDesc = new QLabel(layoutOpts->widget(0));
lblDesc->setGeometry(QRect(0, 10, 178, 90));
lblDesc->setObjectName("lblDesc");
lblDesc->setAlignment(Qt::AlignTop);
lblDesc->setText("");
lblDesc->setWordWrap(true);
rdoImage = new QRadioButton(layoutOpts->widget(1));
rdoImage->setObjectName("rdoImage");
rdoImage->setText("Output | Integrate");
rdoImageSlow = new QRadioButton(layoutOpts->widget(1));
rdoImageSlow->setObjectName("rdoImageSlow");
rdoImageSlow->setText("Integrate | Output");
rdoImageFPN = new QRadioButton(layoutOpts->widget(1));
rdoImageFPN->setObjectName("rdoImageFPN");
rdoImageFPN->setText("Fixed Pattern Noise");
grpImage->addButton(rdoImage);
grpImage->addButton(rdoImageSlow);
grpImage->addButton(rdoImageFPN);
layoutImage->setVerticalSpacing(4);
layoutImage->addWidget(rdoImage, 0, 0);
layoutImage->addWidget(rdoImageSlow, 1, 0);
layoutImage->addWidget(rdoImageFPN, 2, 0);
//rdoTrack = new QRadioButton(layoutOpts->widget(2));
rdoTrack = new QRadioButton();
rdoTrack->setObjectName("rdoTrack");
rdoTrack->setText("Data + Image Packets");
rdoTrackEmbed = new QRadioButton(layoutOpts->widget(2));
rdoTrackEmbed->setObjectName("rdoTrackEmbed");
rdoTrackEmbed->setText("Embed Data in Image");
rdoTrackTrajLinear = new QRadioButton(layoutOpts->widget(2));
rdoTrackTrajLinear->setObjectName("rdoTrackTrajLinear");
rdoTrackTrajLinear->setText("Linear Trajectory");
rdoTrackTrajNonlinear = new QRadioButton(layoutOpts->widget(2));
rdoTrackTrajNonlinear->setObjectName("rdoTrackTrajNonlinear");
rdoTrackTrajNonlinear->setText("Nonlinear Trajectory");
//rdoTrackRPM = new QRadioButton(layoutOpts->widget(2));
rdoTrackRPM = new QRadioButton();
rdoTrackRPM->setObjectName("rdoTrackRPM");
rdoTrackRPM->setText("RPM (untested)");
lblDataPoints = new QLabel(tabConfig->widget(0));
lblDataPoints->setObjectName("lblDataPoints");
lblDataPoints->setText("Draw");
spinDataPoints = new QSpinBox(tabConfig->widget(0));
spinDataPoints->setObjectName("spinDataPoints");
spinDataPoints->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinDataPoints->setAccelerated(true);
spinDataPoints->setMaximum(1024);
spinDataPoints->setAlignment(Qt::AlignRight);
lblDataPointsUnits = new QLabel(tabConfig->widget(0));
lblDataPointsUnits->setObjectName("lblDataPointsUnits");
lblDataPointsUnits->setText("points");
lblDataPoints->setBuddy(spinDataPoints);
lblPredictPoints = new QLabel(tabConfig->widget(0));
lblPredictPoints->setObjectName("lblPredictPoints");
lblPredictPoints->setText("Predict");
spinPredictPoints = new QSpinBox(tabConfig->widget(0));
spinPredictPoints->setObjectName("spinPredictPoints");
spinPredictPoints->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinPredictPoints->setAccelerated(false);
spinPredictPoints->setMaximum(6);
spinPredictPoints->setAlignment(Qt::AlignRight);
lblPredictPointsUnits = new QLabel(tabConfig->widget(0));
lblPredictPointsUnits->setObjectName("lblPredictPointsUnits");
lblPredictPointsUnits->setText("points");
lblPredictPoints->setBuddy(spinPredictPoints);
lblPredictInterval = new QLabel(tabConfig->widget(0));
lblPredictInterval->setObjectName("lblPredictInterval");
lblPredictInterval->setText("Every");
spinPredictInterval = new QSpinBox(tabConfig->widget(0));
spinPredictInterval->setObjectName("spinPredictInterval");
spinPredictInterval->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinPredictInterval->setAccelerated(true);
spinPredictInterval->setMaximum(1000);
spinPredictInterval->setMinimum(1);
spinPredictInterval->setAlignment(Qt::AlignRight);
lblPredictIntervalUnits = new QLabel(tabConfig->widget(0));
lblPredictIntervalUnits->setObjectName("lblPredictIntervalUnits");
lblPredictIntervalUnits->setText("frames");
lblPredictInterval->setBuddy(spinPredictInterval);
grpTrack->addButton(rdoTrack);
grpTrack->addButton(rdoTrackEmbed);
grpTrack->addButton(rdoTrackTrajLinear);
grpTrack->addButton(rdoTrackTrajNonlinear);
grpTrack->addButton(rdoTrackRPM);
layoutTrack->setVerticalSpacing(4);
//layoutTrack->addWidget(rdoTrack, 0, 0, 1, 3); // i never use these ..
//layoutTrack->addWidget(rdoTrackRPM, 2, 0, 1, 3);
layoutTrack->addWidget(rdoTrackEmbed, 1, 0, 1, 3);
layoutTrack->addWidget(rdoTrackTrajLinear, 2, 0, 1, 3);
layoutTrack->addWidget(rdoTrackTrajNonlinear, 3, 0, 1, 3);
layoutTrack->addWidget(lblDataPoints, 4, 0);
layoutTrack->addWidget(spinDataPoints, 4, 1);
layoutTrack->addWidget(lblDataPointsUnits, 4, 2);
layoutTrack->addWidget(lblPredictPoints, 5, 0);
layoutTrack->addWidget(spinPredictPoints, 5, 1);
layoutTrack->addWidget(lblPredictPointsUnits, 5, 2);
layoutTrack->addWidget(lblPredictInterval, 6, 0);
layoutTrack->addWidget(spinPredictInterval, 6, 1);
layoutTrack->addWidget(lblPredictIntervalUnits, 6, 2);
chkCDS = new QCheckBox("Double Sampling", tabConfig->widget(0));
chkCDS->setObjectName("chkCDS");
chkParallel = new QCheckBox("Parallel Readout", tabConfig->widget(0));
chkParallel->setObjectName("chkParallel");
chkRepeat = new QCheckBox("Repeat Record", tabConfig->widget(0));
chkRepeat->setObjectName("chkRepeat");
chkDebug = new QCheckBox("Console Output", tabConfig->widget(0));
chkDebug->setObjectName("chkDebug");
chkDummy = new QCheckBox("Random Data", tabConfig->widget(0));
chkDummy->setObjectName("chkDummy");
chkStretch = new QCheckBox("Stretch", tabConfig->widget(0));
chkStretch->setObjectName("chkStretch");
chkFlip = new QCheckBox("Vertical Flip", tabConfig->widget(0));
chkFlip->setObjectName("chkFlip");
chkTransform = new QCheckBox("Transform Readout", tabConfig->widget(0));
chkTransform->setObjectName("chkTransform");
grpFlags->addButton(chkCDS);
grpFlags->addButton(chkParallel);
grpFlags->addButton(chkRepeat);
grpFlags->addButton(chkDebug);
grpFlags->addButton(chkDummy);
grpFlags->addButton(chkStretch);
grpFlags->addButton(chkFlip);
grpFlags->addButton(chkTransform);
layoutFlags->addWidget(chkCDS, 0, 0);
layoutFlags->addWidget(chkParallel, 1, 0);
layoutFlags->addWidget(chkRepeat, 2, 0);
layoutFlags->addWidget(chkDebug, 3, 0);
layoutFlags->addWidget(chkDummy, 4, 0);
layoutFlags->addWidget(chkStretch, 5, 0);
layoutFlags->addWidget(chkFlip, 6, 0);
layoutFlags->addWidget(chkTransform, 7, 0);
lblVmax = new QLabel(tabConfig->widget(1));
lblVmax->setObjectName("lblVmax");
lblVmax->setText(QApplication::translate("MainWindow", "Vmax", 0));
lblVmaxUnits = new QLabel(tabConfig->widget(1));
lblVmaxUnits->setObjectName("lblVmaxUnits");
lblVmaxUnits->setText(QApplication::translate("MainWindow", "V", 0));
spinVmax = new QDoubleSpinBox(tabConfig->widget(1));
spinVmax->setObjectName("spinVmax");
spinVmax->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinVmax->setAccelerated(true);
spinVmax->setMaximum(2.5);
spinVmax->setSingleStep(0.05);
spinVmax->setAlignment(Qt::AlignRight);
lblVmax->setBuddy(spinVmax);
lblVmin = new QLabel(tabConfig->widget(1));
lblVmin->setObjectName("lblVmin");
lblVmin->setText(QApplication::translate("MainWindow", "Vmin", 0));
lblVminUnits = new QLabel(tabConfig->widget(1));
lblVminUnits->setObjectName("lblVminUnits");
lblVminUnits->setText(QApplication::translate("MainWindow", "V", 0));
spinVmin = new QDoubleSpinBox(tabConfig->widget(1));
spinVmin->setObjectName("spinVmin");
spinVmin->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinVmin->setAccelerated(true);
spinVmin->setMaximum(2.5);
spinVmin->setSingleStep(0.05);
spinVmin->setAlignment(Qt::AlignRight);
lblVmax->setBuddy(spinVmax);
lblVmin->setBuddy(spinVmin);
lblVrst = new QLabel(tabConfig->widget(1));
lblVrst->setObjectName("lblVrst");
lblVrst->setText(QApplication::translate("MainWindow", "Vrst", 0));
lblVrstUnits = new QLabel(tabConfig->widget(1));
lblVrstUnits->setObjectName("lblVrstUnits");
lblVrstUnits->setText(QApplication::translate("MainWindow", "V", 0));
spinVrst = new QDoubleSpinBox(tabConfig->widget(1));
spinVrst->setObjectName("spinVrst");
spinVrst->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinVrst->setAccelerated(true);
spinVrst->setMaximum(2.5);
spinVrst->setSingleStep(0.05);
spinVrst->setAlignment(Qt::AlignRight);
lblVrst->setBuddy(spinVrst);
lblVbias = new QLabel(tabConfig->widget(1));
lblVbias->setObjectName("lblVbias");
lblVbias->setText(QApplication::translate("MainWindow", "Vbias", 0));
lblVbiasUnits = new QLabel(tabConfig->widget(1));
lblVbiasUnits->setObjectName("lblVbiasUnits");
lblVbiasUnits->setText(QApplication::translate("MainWindow", "V", 0));
spinVbias = new QDoubleSpinBox(tabConfig->widget(1));
spinVbias->setObjectName("spinVbias");
spinVbias->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinVbias->setAccelerated(true);
spinVbias->setMaximum(2.5);
spinVbias->setSingleStep(0.005);
spinVbias->setAlignment(Qt::AlignRight);
lblVbias->setBuddy(spinVbias);
lblTrst = new QLabel(tabConfig->widget(1));
lblTrst->setObjectName("lblTrst");
lblTrst->setText("Trst");
lblTrstUnits = new QLabel(tabConfig->widget(1));
lblTrstUnits->setObjectName("lblTrstUnits");
lblTrstUnits->setText(mu + "s");
spinTrst = new QSpinBox(tabConfig->widget(1));
spinTrst->setObjectName("spinTrst");
spinTrst->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinTrst->setAccelerated(true);
spinTrst->setMaximum(1000000);
spinTrst->setAlignment(Qt::AlignRight);
lblTrst->setBuddy(spinTrst);
lblTint = new QLabel(tabConfig->widget(1));
lblTint->setObjectName("lblTint");
lblTint->setText("Tint");
lblTintUnits = new QLabel(tabConfig->widget(1));
lblTintUnits->setObjectName("lblTintUnits");
lblTintUnits->setText(mu + "s");
spinTint = new QSpinBox(tabConfig->widget(1));
spinTint->setObjectName("spinTint");
spinTint->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinTint->setAccelerated(true);
spinTint->setMaximum(1000000);
spinTint->setAlignment(Qt::AlignRight);
lblTint->setBuddy(spinTint);
lblTimeout = new QLabel(tabConfig->widget(1));
lblTimeout->setObjectName("lblTimeout");
lblTimeout->setText(QApplication::translate("MainWindow", "Timeout", 0));
lblTimeoutUnits = new QLabel(tabConfig->widget(1));
lblTimeoutUnits->setObjectName("lblTimeoutUnits");
lblTimeoutUnits->setText(QApplication::translate("MainWindow", "ms", 0));
spinTimeout = new QSpinBox(tabConfig->widget(1));
spinTimeout->setObjectName("spinTimeout");
spinTimeout->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinTimeout->setAccelerated(true);
spinTimeout->setMaximum(500);
spinTimeout->setAlignment(Qt::AlignRight);
lblTimeout->setBuddy(spinTimeout);
lblThreshold = new QLabel(tabConfig->widget(1));
lblThreshold->setObjectName("lblThreshold");
lblThreshold->setText(QApplication::translate("MainWindow", "Threshold", 0));
spinThreshold = new QSpinBox(tabConfig->widget(1));
spinThreshold->setObjectName("spinThreshold");
spinThreshold->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinThreshold->setAccelerated(true);
spinThreshold->setMaximum(255);
spinThreshold->setAlignment(Qt::AlignRight);
lblFrames = new QLabel(tabActions->widget(1));
lblFrames->setObjectName("lblFrames");
lblFrames->setText(QApplication::translate("MainWindow", "Capture", 0));
lblFramesUnits = new QLabel(tabActions->widget(1));
lblFramesUnits->setObjectName("lblFramesUnits");
lblFramesUnits->setText(QApplication::translate("MainWindow", "frames", 0));
spinFrames = new QSpinBox(tabActions->widget(1));
spinFrames->setObjectName("spinFrames");
spinFrames->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinFrames->setAccelerated(true);
spinFrames->setMaximum(1000000);
spinFrames->setAlignment(Qt::AlignRight);
lblFrames->setBuddy(spinFrames);
lblFPS = new QLabel(tabActions->widget(1));
lblFPS->setObjectName("lblFPS");
lblFPS->setText(QApplication::translate("MainWindow", "Encode", 0));
lblFPSUnits = new QLabel(tabActions->widget(1));
lblFPSUnits->setObjectName("lblFPSUnits");
lblFPSUnits->setText(QApplication::translate("MainWindow", "fps", 0));
spinFPS = new QSpinBox(tabActions->widget(1));
spinFPS->setObjectName("spinFPS");
spinFPS->setButtonSymbols(QAbstractSpinBox::PlusMinus);
spinFPS->setAccelerated(true);
spinFPS->setMaximum(2000);
spinFPS->setValue(30);
spinFPS->setAlignment(Qt::AlignRight);
lblFPS->setBuddy(spinFPS);
layoutSettings->addWidget(lblVmax, 0, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinVmax, 0, 1);
layoutSettings->addWidget(lblVmaxUnits, 0, 2);
layoutSettings->addWidget(lblVmin, 1, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinVmin, 1, 1);
layoutSettings->addWidget(lblVminUnits, 1, 2);
layoutSettings->addWidget(lblVrst, 2, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinVrst, 2, 1);
layoutSettings->addWidget(lblVrstUnits, 2, 2);
layoutSettings->addWidget(lblVbias, 3, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinVbias, 3, 1);
layoutSettings->addWidget(lblVbiasUnits, 3, 2);
layoutSettings->addWidget(lblTrst, 4, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinTrst, 4, 1);
layoutSettings->addWidget(lblTrstUnits, 4, 2);
layoutSettings->addWidget(lblTint, 5, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinTint, 5, 1);
layoutSettings->addWidget(lblTintUnits, 5, 2);
layoutSettings->addWidget(lblTimeout, 6, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinTimeout, 6, 1);
layoutSettings->addWidget(lblTimeoutUnits, 6, 2);
layoutSettings->addWidget(lblThreshold, 7, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinThreshold, 7, 1);
layoutSettings->addWidget(lblFrames, 8, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinFrames, 8, 1);
layoutSettings->addWidget(lblFramesUnits, 8, 2);
layoutSettings->addWidget(lblFPS, 9, 0, Qt::AlignLeft);
layoutSettings->addWidget(spinFPS, 9, 1);
layoutSettings->addWidget(lblFPSUnits, 9, 2);
layoutSettings->setColumnStretch(0, 2);
layoutSettings->setColumnStretch(1, 4);
layoutSettings->setColumnStretch(2, 1);
btnStart = new QPushButton(tabActions->widget(0));
btnStart->setObjectName("btnStart");
btnStart->setText(QApplication::translate("MainWindow", "&Start", 0));
//btnStart->setText(iconPlay);
btnStop = new QPushButton(tabActions->widget(0));
btnStop->setObjectName("btnStop");
btnStop->setText(QApplication::translate("MainWindow", "St&op", 0));
//btnStop->setText(iconStop);
btnApply = new QPushButton(tabActions->widget(0));
btnApply->setObjectName("btnApply");
btnApply->setText(QApplication::translate("MainWindow", "&Apply", 0));
//btnApply->setText(iconUpload);
btnReset = new QPushButton(tabActions->widget(0));
btnReset->setObjectName("btnReset");
btnReset->setText(QApplication::translate("MainWindow", "&Reset", 0));
//btnReset->setText(iconReset);
layoutActions->addWidget(btnApply, 0, 0);
layoutActions->addWidget(btnStart, 0, 1);
layoutActions->addWidget(btnReset, 1, 0);
layoutActions->addWidget(btnStop, 1, 1);
btnRecordStart = new QPushButton(tabActions->widget(1));
btnRecordStart->setObjectName("btnRecordStart");
btnRecordStart->setText(QApplication::translate("MainWindow", "Start", 0));
//btnRecordStart->setText(iconRecord);
btnRecordStop = new QPushButton(tabActions->widget(1));
btnRecordStop->setObjectName("btnRecordStop");
btnRecordStop->setText(QApplication::translate("MainWindow", "Stop", 0));
//btnRecordStop->setText(iconPause);
btnExportImage = new QPushButton(tabActions->widget(1));
btnExportImage->setObjectName("btnExportImage");
btnExportImage->setText(QApplication::translate("MainWindow", "Image", 0));
//btnExportImage->setText(iconSave);
barRecord = new QProgressBar(tabActions->widget(1));
barRecord->setFormat("%v/%m");
barRecord->setMinimum(0);
barRecord->setMaximum(1);
barRecord->setValue(0);
barRecord->reset();
layoutRecord->addWidget(btnRecordStart, 0, 0, 1, 1);
layoutRecord->addWidget(btnRecordStop, 0, 1, 1, 1);
layoutRecord->addWidget(btnExportImage, 0, 2, 1, 1);
layoutRecord->addWidget(barRecord, 1, 0, 1, 3);
MainWindow->setCentralWidget(centralwidget);
// ??
//lcdFPS->raise();
//tabActions->widget(1)->raise();
menubar = new QMenuBar(MainWindow);
menubar->setObjectName("menubar");
menubar->setGeometry(QRect(0, 0, 725, 22));
menuFile = new QMenu(menubar);
menuFile->setObjectName("menuFile");
menuTools = new QMenu(menubar);
menuTools->setObjectName("menuTools");
MainWindow->setMenuBar(menubar);
statusbar = new QStatusBar(MainWindow);
statusbar->setObjectName("statusbar");
MainWindow->setStatusBar(statusbar);
actionRecord = new QAction(MainWindow);
actionRecord->setObjectName("actionRecord");
actionExport = new QAction(MainWindow);
actionExport->setObjectName("actionExport");
actionExit = new QAction(MainWindow);
actionExit->setObjectName("actionExit");
actionSetup = new QAction(MainWindow);
actionSetup->setObjectName("actionSetup");
actionSetup->setShortcut(Qt::CTRL + Qt::Key_M);
menubar->addAction(menuFile->menuAction());
menubar->addAction(menuTools->menuAction());
menuFile->addAction(actionRecord);
menuFile->addSeparator();
menuFile->addAction(actionExport);
menuFile->addSeparator();
menuFile->addAction(actionExit);
menuTools->addAction(actionSetup);
QWidget::setTabOrder(comboProgram, chkCDS);
QWidget::setTabOrder(chkCDS, chkParallel);
QWidget::setTabOrder(chkParallel, chkRepeat);
QWidget::setTabOrder(chkRepeat, chkDebug);
QWidget::setTabOrder(chkDebug, chkDummy);
QWidget::setTabOrder(chkDummy, chkStretch);
QWidget::setTabOrder(chkStretch, chkFlip);
QWidget::setTabOrder(chkFlip, chkTransform);
QWidget::setTabOrder(chkTransform, btnApply);
QWidget::setTabOrder(btnApply, btnStart);
QWidget::setTabOrder(btnStart, btnStop);
QWidget::setTabOrder(btnStop, btnReset);
QWidget::setTabOrder(spinVmax, spinVmin);
QWidget::setTabOrder(spinVmin, spinVrst);
QWidget::setTabOrder(spinVrst, spinVbias);
QWidget::setTabOrder(spinVbias, spinTrst);
QWidget::setTabOrder(spinTrst, spinTint);
QWidget::setTabOrder(spinTint, spinTimeout);
QWidget::setTabOrder(spinTimeout, spinThreshold);
QWidget::setTabOrder(spinThreshold, spinFrames);
QWidget::setTabOrder(spinFrames, spinFPS);
QWidget::setTabOrder(spinFPS, btnRecordStart);
QWidget::setTabOrder(btnRecordStart, btnRecordStop);
QWidget::setTabOrder(btnRecordStop, btnExportImage);
retranslateUI(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUI(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "PIRANHA", 0));
actionExit->setText(QApplication::translate("MainWindow", "Exit", 0));
actionRecord->setText(QApplication::translate("MainWindow", "Record", 0));
actionExport->setText(QApplication::translate("MainWindow", "Export", 0));
actionSetup->setText(QApplication::translate("MainWindow", "Setup", 0));
lblImage->setText(QApplication::translate("MainWindow", "", 0));
comboProgram->clear();
comboProgram->insertItems(0, QStringList()
<< QApplication::translate("MainWindow", "Imaging", 0)
<< QApplication::translate("MainWindow", "RCR Readout", 0)
<< QApplication::translate("MainWindow", "Edge Detect", 0)
<< QApplication::translate("MainWindow", "Median Filter", 0)
<< QApplication::translate("MainWindow", "DCT Filter", 0)
<< QApplication::translate("MainWindow", "Histogram", 0)
<< QApplication::translate("MainWindow", "Tracking", 0)
<< QApplication::translate("MainWindow", "AER", 0)
<< QApplication::translate("MainWindow", "Benchmark", 0)
);
menuFile->setTitle(QApplication::translate("MainWindow", "File", 0));
menuTools->setTitle(QApplication::translate("MainWindow", "Tools", 0));
} // retranslateUi
private slots:
//void open();
//void save();
void export_image();
void record_start();
void record_stop();
void exit();
void setup();
void apply();
void start();
void stop();
void reset();
void initValues();
void imageChanged(int imageIndex);
void trackChanged(int trackIndex);
void flagsChanged(int flagsIndex);
void programChanged(int programIndex);
void printFrame();
int acquireImage(cv::Mat*);
QImage mat2qimage(const cv::Mat&);
void trackDataPlot(cv::Mat*, cv::Mat*);
void trackDataPlotEmbedded(cv::Mat*);
void trackDataPlotTrajectory(cv::Mat*);
signals:
void abortCapture();
};
struct dataCoor
{
int x,y;
dataCoor(int xx, int yy) : x(xx), y(yy) {}
};
QT_END_NAMESPACE
#endif // EXAMPLEPLI892_H
|
47c23c5bd024c4b6f0412fdc3d902b8bdd7b97a2
|
33e53f444a1b256b8d15307f37694abba0921de3
|
/CGoGN/src/Utils/Qt/qtgl.cpp
|
25ab05b9c67fdc32053eb03b0e91c2b60be15584
|
[] |
no_license
|
tewk/CGoGN
|
468665a650ff3a07c53d2a50e21d30d19b7d97f8
|
7039925801ac5241f604ff50a32d8416b1a04282
|
refs/heads/master
| 2022-11-04T22:27:29.477218
| 2022-10-28T22:37:46
| 2022-10-28T22:37:46
| 44,613,432
| 0
| 1
| null | 2020-01-10T16:37:18
| 2015-10-20T14:51:44
|
C++
|
UTF-8
|
C++
| false
| false
| 13,753
|
cpp
|
qtgl.cpp
|
/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps *
* version 0.1 *
* Copyright (C) 2009-2012, IGG Team, LSIIT, University of Strasbourg *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your *
* option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
* *
* Web site: http://cgogn.unistra.fr/ *
* Contact information: cgogn@unistra.fr *
* *
*******************************************************************************/
#include "Utils/GLSLShader.h"
#include <iostream>
#include "Utils/trackball.h"
#include "Utils/Qt/qtgl.h"
#include "Utils/Qt/qtSimple.h"
#include "glm/gtc/type_precision.hpp"
namespace CGoGN
{
namespace Utils
{
namespace QT
{
float GLWidget::FAR_PLANE = 500.0f;
GLWidget::GLWidget(SimpleQT* cbs, QWidget *parent) :
QGLWidget(parent),
m_cbs(cbs),
m_state_modifier(0),
allow_rotation(true)
{
makeCurrent();
glewExperimental = GL_TRUE;
glewInit();
newModel = 1;
m_cbs->trans_x() = 0.;
m_cbs->trans_y() = 0.;
float f = FAR_PLANE;
m_cbs->trans_z() = -f / 5.0f;
foc = 2.0f;
// init trackball
trackball(m_cbs->curquat(), 0.0f, 0.0f, 0.0f, 0.0f);
}
GLWidget::~GLWidget()
{
}
void GLWidget::setParamObject(float width, float* pos)
{
m_obj_sc = ((FAR_PLANE / 5.0f) / foc) / width;
m_obj_pos = glm::vec3(-pos[0], -pos[1], -pos[2]);
m_obj_pos_save = glm::vec3(pos[0], pos[1], pos[2]);
m_obj_width = width;
}
void GLWidget::resetCenterOfRotation(float width, float* pos)
{
m_cbs->trans_x() = 0.;
m_cbs->trans_y() = 0.;
m_cbs->trans_z() = -FAR_PLANE / 5.0f;
m_obj_sc = ((FAR_PLANE / 5.0f) / foc) / width;
m_obj_pos = glm::vec3(-pos[0], -pos[1], -pos[2]);
newModel=1;
}
void GLWidget::setRotation(bool b)
{
allow_rotation = b;
}
void GLWidget::setFocal(float df)
{
if (df > 5.0f)
df = 5.0f;
if (df < 0.2f)
df = 0.2f;
m_obj_sc *= foc / df;
foc = df;
resizeGL(W, H);
}
QSize GLWidget::minimumSizeHint() const
{
return QSize(200, 200);
}
QSize GLWidget::sizeHint() const
{
return QSize(500, 500);
}
void GLWidget::recalcModelView()
{
m_cbs->modelViewMatrix()= glm::mat4(1.0f);
// positionne l'objet / mvt souris
oglTranslate(m_cbs->trans_x(), m_cbs->trans_y(), m_cbs->trans_z());
// tourne l'objet / mvt souris
glm::mat4 m;
build_rotmatrixgl3(m, m_cbs->curquat());
// update matrice
m_cbs->modelViewMatrix() *= m;
// transfo pour que l'objet soit centre et a la bonne taille
oglScale(m_obj_sc, m_obj_sc, m_obj_sc);
oglTranslate(m_obj_pos[0], m_obj_pos[1], m_obj_pos[2]);
// ajout transformation
// m_cbs->modelViewMatrix() *= m_cbs->transfoMatrix();
newModel = 0;
if (m_cbs)
m_cbs->cb_updateMatrix();
}
void GLWidget::changeCenterOfRotation(const glm::vec3& newCenter)
{
glm::mat4 storeMVM(m_cbs->modelViewMatrix());
m_cbs->modelViewMatrix() = glm::mat4(1.0f);
// positionne l'objet / mvt souris
oglTranslate(m_cbs->trans_x(), m_cbs->trans_y(), m_cbs->trans_z());
// tourne l'objet / mvt souris
glm::mat4 m;
build_rotmatrixgl3(m, m_cbs->curquat());
// update matrice
m_cbs->modelViewMatrix() *= m;
// ajout transformation in screen
m_cbs->modelViewMatrix()*= m_cbs->transfoMatrix();
// transfo pour que l'objet soit centre et a la bonne taille
oglScale(m_obj_sc, m_obj_sc, m_obj_sc);
oglTranslate(m_obj_pos[0], m_obj_pos[1], m_obj_pos[2]);
oglTranslate(newCenter[0], newCenter[1], newCenter[2]);
oglScale(1.0f / m_obj_sc, 1.0f / m_obj_sc, 1.0f / m_obj_sc);
m = glm::inverse(m_cbs->transfoMatrix());
m_cbs->modelViewMatrix() *= m;
matrix_to_quat( m_cbs->curquat(), m_cbs->modelViewMatrix());
m_cbs->trans_x() = m_cbs->modelViewMatrix()[3][0];
m_cbs->trans_y() = m_cbs->modelViewMatrix()[3][1];
m_cbs->trans_z() = m_cbs->modelViewMatrix()[3][2];
m_cbs->modelViewMatrix() = storeMVM;
m_obj_pos = glm::vec3(-newCenter[0], -newCenter[1], -newCenter[2]);
}
glm::vec3& GLWidget::getObjPos()
{
return m_obj_pos ;
}
void GLWidget::initializeGL()
{
glEnable(GL_DEPTH_TEST);
if (m_cbs)
m_cbs->cb_initGL();
}
void GLWidget::resizeGL(int w, int h)
{
W = w;
H = h;
glViewport(0, 0, W, H);
float f = FAR_PLANE;
m_cbs->projectionMatrix() = glm::frustum(-1.0f, 1.0f, -1.0f * H / W, 1.0f * H / W, foc, f);
recalcModelView();
}
void GLWidget::paintGL()
{
if (newModel)
recalcModelView();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (m_cbs)
{
Utils::GLSLShader::s_current_matrices = m_cbs->matricesPtr();
m_cbs->cb_redraw();
}
}
void GLWidget::mousePressEvent(QMouseEvent* event)
{
beginx = event->x();
beginy = event->y();
clickPoint = event->pos();
m_current_button = event->button();
if (m_cbs)
m_cbs->cb_mousePress(event->button(), event->x()*pixelRatio(), getHeight() - event->y()*pixelRatio());
setFocus(Qt::MouseFocusReason);
}
void GLWidget::mouseReleaseEvent(QMouseEvent* event)
{
if (m_cbs)
m_cbs->cb_mouseRelease(event->button(), event->x()*pixelRatio(), getHeight() - event->y()*pixelRatio());
if(event->pos() == clickPoint)
mouseClickEvent(event) ;
}
void GLWidget::mouseClickEvent(QMouseEvent* event)
{
if (m_cbs)
m_cbs->cb_mouseClick(event->button(), event->x()*pixelRatio(), getHeight() - event->y()*pixelRatio());
}
void GLWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
if (event->button()==1)
{
GLint x = event->x()*pixelRatio();
GLint y = getHeight() - event->y()*pixelRatio();
GLfloat depth;
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
if (depth < 1.0f)
{
glm::i32vec4 viewport;
glGetIntegerv(GL_VIEWPORT, &(viewport[0]));
glm::vec3 win(x, y, depth);
glm::vec3 P = glm::unProject(win, m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
changeCenterOfRotation(P);
}
else
{
resetCenterOfRotation(m_obj_width, static_cast<float*>(&m_obj_pos_save.x)) ;
updateGL();
}
}
}
void GLWidget::mouseMoveEvent(QMouseEvent* event)
{
// move object only if no special keys pressed
if (!(m_state_modifier & ( Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)))
{
int x = event->x();
int y = event->y();
switch (m_current_button)
{
case Qt::RightButton:
{
float wl;
if (m_cbs->trans_z() > -20.0f)
wl = 20.0f / foc;
else
wl = -2.0f * m_cbs->trans_z() / foc;
m_cbs->trans_x() += wl / W * (x - beginx);
m_cbs->trans_y() += wl / H * (beginy - y);
}
break;
case Qt::MidButton:
{
float wl = -0.5f * FAR_PLANE / foc;
m_cbs->trans_z() -= wl / W * (x - beginx);
m_cbs->trans_z() -= wl / H * (y - beginy);
}
break;
case Qt::LeftButton:
{
if(allow_rotation)
{
trackball(
m_cbs->lastquat(),
(2.0f * beginx - W) / W,
(H - 2.0f * beginy) / H,
(2.0f * x - W) / W,(H - 2.0f * y) / H
);
add_quats(m_cbs->lastquat(), m_cbs->curquat(), m_cbs->curquat());
}
}
break;
}
beginx = x;
beginy = y;
newModel = 1;
updateGL();
}
if (m_cbs)
m_cbs->cb_mouseMove(event->buttons(), event->x(), getHeight() - event->y());
}
void GLWidget::wheelEvent(QWheelEvent* event)
{
if (!(m_state_modifier & ( Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)))
{
float wl = -0.05f * FAR_PLANE / foc;
if (event->delta() > 0)
m_cbs->trans_z() += wl;
else
m_cbs->trans_z() -= wl;
newModel = 1;
updateGL();
}
if (m_cbs)
m_cbs->cb_wheelEvent(event->delta(), event->x(), getHeight() - event->y());
}
void GLWidget::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Escape)
{
close();
m_cbs->close();
return;
}
m_state_modifier = event->modifiers();
int k = event->key();
if ( (k >= 65) && (k <= 91) && !(event->modifiers() & Qt::ShiftModifier) )
k += 32;
if (m_cbs)
m_cbs->cb_keyPress(k);
}
void GLWidget::keyReleaseEvent(QKeyEvent *event)
{
// QWidget::keyReleaseEvent(event);
m_state_modifier = event->modifiers();
int k = event->key();
// align on axis
if ((k == 'Z') && (event->modifiers() & Qt::ShiftModifier))
{
float Z[3] = { 0.0f, 0.0f, 1.0f };
axis_to_quat(Z, 0.0f, m_cbs->curquat());
newModel = 1;
updateGL();
}
if ((k == 'Y') && (event->modifiers() & Qt::ShiftModifier))
{
float X[3] = { 1.0f, 0.0f, 0.0f };
axis_to_quat(X, float(M_PI / 2.0), m_cbs->curquat());
newModel = 1;
updateGL();
}
if ((k == 'X') && (event->modifiers() & Qt::ShiftModifier))
{
float Y[3] = { 0.0f, 1.0f, 0.0f };
axis_to_quat(Y, float(-M_PI / 2.0), m_cbs->curquat());
newModel = 1;
updateGL();
}
if ( (k >= 65) && (k <= 91) && (event->modifiers() != Qt::ShiftModifier) )
k += 32;
if (m_cbs)
m_cbs->cb_keyRelease(k);
}
void GLWidget::glMousePosition(int& x, int& y)
{
QPoint xy = mapFromGlobal(QCursor::pos());
x = xy.x();
y = getHeight() - xy.y();
}
void GLWidget::oglRotate(float angle, float x, float y, float z)
{
m_cbs->modelViewMatrix() = glm::rotate(m_cbs->modelViewMatrix(), glm::radians(angle), glm::vec3(x,y,z));
}
void GLWidget::oglTranslate(float tx, float ty, float tz)
{
m_cbs->modelViewMatrix() = glm::translate(m_cbs->modelViewMatrix(), glm::vec3(tx,ty,tz));
}
void GLWidget::oglScale(float sx, float sy, float sz)
{
m_cbs->modelViewMatrix() = glm::scale(m_cbs->modelViewMatrix(), glm::vec3(sx,sy,sz));
}
GLfloat GLWidget::getOrthoScreenRay(int x, int y, Geom::Vec3f& rayA, Geom::Vec3f& rayB, int radius)
{
// get Z from depth buffer
int yy = y;
GLfloat depth_t[25];
glReadPixels(x-2, yy-2, 5, 5, GL_DEPTH_COMPONENT, GL_FLOAT, depth_t);
GLfloat depth=0.0f;
unsigned int nb=0;
for (unsigned int i=0; i< 25; ++i)
{
if (depth_t[i] != 1.0f)
{
depth += depth_t[i];
nb++;
}
}
if (nb>0)
depth /= float(nb);
else
depth = 0.5f;
glm::i32vec4 viewport;
glGetIntegerv(GL_VIEWPORT, &(viewport[0]));
glm::vec3 win(x, yy, 0.0f);
glm::vec3 P = glm::unProject(win, m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
rayA[0] = P[0];
rayA[1] = P[1];
rayA[2] = P[2];
win[2] = depth;
P = glm::unProject(win, m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
rayB[0] = P[0];
rayB[1] = P[1];
rayB[2] = P[2];
if (depth == 1.0f) // depth vary in [0-1]
win[2] = 0.5f;
win[0] += radius;
P = glm::unProject(win, m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
Geom::Vec3f Q;
Q[0] = P[0];
Q[1] = P[1];
Q[2] = P[2];
// compute & return distance
Q -= rayB;
return float(Q.norm());
}
float GLWidget::getWidthInWorld(unsigned int pixel_width, const Geom::Vec3f& center)
{
glm::i32vec4 viewport;
glGetIntegerv(GL_VIEWPORT, &(viewport[0]));
glm::vec3 win = glm::project(glm::vec3(center[0],center[1],center[2]), m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
win[0]-= pixel_width/2;
glm::vec3 P = glm::unProject(win, m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
win[0] += pixel_width;
glm::vec3 Q = glm::unProject(win, m_cbs->modelViewMatrix(), m_cbs->projectionMatrix(), viewport);
return glm::distance(P,Q);
}
void GLWidget::transfoRotate(float angle, float x, float y, float z)
{
m_cbs->transfoMatrix() = glm::rotate( m_cbs->transfoMatrix(), glm::radians(angle), glm::vec3(x,y,z));
recalcModelView() ;
}
void GLWidget::transfoTranslate(float tx, float ty, float tz)
{
m_cbs->transfoMatrix() = glm::translate( m_cbs->transfoMatrix(), glm::vec3(tx,ty,tz));
}
void GLWidget::transfoScale(float sx, float sy, float sz)
{
m_cbs->transfoMatrix() = glm::scale( m_cbs->transfoMatrix(), glm::vec3(sx,sy,sz));
}
void GLWidget::pushTransfoMatrix()
{
m_stack_trf.push( m_cbs->transfoMatrix());
}
bool GLWidget::popTransfoMatrix()
{
if (m_stack_trf.empty())
return false;
m_cbs->transfoMatrix() = m_stack_trf.top();
m_stack_trf.pop();
return true;
}
/**
* current transfo matrix
*/
const glm::mat4& GLWidget::transfoMatrix() const { return m_cbs->transfoMatrix(); }
glm::mat4& GLWidget::transfoMatrix() { return m_cbs->transfoMatrix(); }
/**
* current modelview matrix
*/
const glm::mat4& GLWidget::modelViewMatrix() const { return m_cbs->modelViewMatrix(); }
glm::mat4& GLWidget::modelViewMatrix() { return m_cbs->modelViewMatrix(); }
/**
* current projection matrix
*/
const glm::mat4& GLWidget::projectionMatrix() const { return m_cbs->projectionMatrix(); }
glm::mat4& GLWidget::projectionMatrix() { return m_cbs->projectionMatrix(); }
} // namespace QT
} // namespace Utils
} // namespace CGoGN
|
4185fc0a19d3b6ea8a315db2136081772ebf1fad
|
0706b83ece4db1fb6310d984fd5a259eb91b5bbf
|
/AVPRG-Projekt/OpenCV_Tools.cpp
|
ba3cf5f828af7951959c9a01a93ba0a1f763d82e
|
[] |
no_license
|
AlexanderPiehl/AVPRG-Projekt
|
78246dce12a1a63465e33a24850654d0a6b099ee
|
9731312b6563e014ca5383a1879ff894a44eaeea
|
refs/heads/master
| 2021-01-20T11:57:38.443740
| 2014-01-12T21:09:43
| 2014-01-12T21:09:43
| 14,141,164
| 0
| 0
| null | 2014-01-09T20:26:54
| 2013-11-05T12:45:13
|
C++
|
UTF-8
|
C++
| false
| false
| 949
|
cpp
|
OpenCV_Tools.cpp
|
#include "OpenCV_Tools.h"
using namespace cv;
using namespace std;
OpenCV_Tools::OpenCV_Tools(void){}
OpenCV_Tools::~OpenCV_Tools(void){}
Mat OpenCV_Tools::loadImage(string path)
{
Mat image = imread(path);
return image;
}
Mat OpenCV_Tools::loadImageAsBW(string path)
{
Mat image = imread(path);
Mat imageGrey;
cvtColor(image,imageGrey,CV_RGB2GRAY);
Mat imageBW = imageGrey > 20;
return imageBW;
}
VideoCapture OpenCV_Tools::loadVideo(string path)
{
VideoCapture video;
video.open(path);
return video;
}
VideoCapture OpenCV_Tools::loadVideoByWebcam()
{
VideoCapture video;
video.open(0);
return video;
}
int OpenCV_Tools::getVideoHeight(VideoCapture video)
{
int height = static_cast<int>(video.get(CV_CAP_PROP_FRAME_HEIGHT));
return height;
}
int OpenCV_Tools::getVideoWidth(VideoCapture video)
{
int width = static_cast<int>(video.get(CV_CAP_PROP_FRAME_WIDTH));
return width;
}
|
78b312e36851d0c7e3767860b8f978176c447b6d
|
24004e1c3b8005af26d5890091d3c207427a799e
|
/Win32/NXOPEN/NXOpen/CAM_WedmMoveControlBuilder.hxx
|
d148a1cd003abad007c79aa61319e063707f4326
|
[] |
no_license
|
15831944/PHStart
|
068ca6f86b736a9cc857d7db391b2f20d2f52ba9
|
f79280bca2ec7e5f344067ead05f98b7d592ae39
|
refs/heads/master
| 2022-02-20T04:07:46.994182
| 2019-09-29T06:15:37
| 2019-09-29T06:15:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,975
|
hxx
|
CAM_WedmMoveControlBuilder.hxx
|
#ifndef NXOpen_CAM_WEDMMOVECONTROLBUILDER_HXX_INCLUDED
#define NXOpen_CAM_WEDMMOVECONTROLBUILDER_HXX_INCLUDED
//--------------------------------------------------------------------------
// Header for C++ interface to JA API
//--------------------------------------------------------------------------
//
// Source File:
// CAM_WedmMoveControlBuilder.ja
//
// Generated by:
// apiwrap
//
// WARNING:
// This file is automatically generated - do not edit by hand
//
#ifdef _MSC_VER
#pragma once
#endif
#include <NXOpen/NXDeprecation.hxx>
#include <vector>
#include <NXOpen/NXString.hxx>
#include <NXOpen/Callback.hxx>
#include <NXOpen/CAM_ParamBuilder.hxx>
#include <NXOpen/libnxopencpp_cam_exports.hxx>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
namespace NXOpen
{
namespace CAM
{
class WedmMoveControlBuilder;
}
namespace CAM
{
class ParamBuilder;
}
namespace CAM
{
class _WedmMoveControlBuilderBuilder;
class WedmMoveControlBuilderImpl;
/** Represents a WedmMoveControl Builder <br> To create a new instance of this class, use @link CAM::NCGroupCollection::CreateWedmMoveControlBuilder CAM::NCGroupCollection::CreateWedmMoveControlBuilder@endlink <br>
<br> Created in NX6.0.0. <br>
*/
class NXOPENCPP_CAMEXPORT WedmMoveControlBuilder : public CAM::ParamBuilder
{
private: WedmMoveControlBuilderImpl * m_wedmmovecontrolbuilder_impl;
private: friend class _WedmMoveControlBuilderBuilder;
protected: WedmMoveControlBuilder();
public: ~WedmMoveControlBuilder();
};
}
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#ifdef __GNUC__
#ifndef NX_NO_GCC_DEPRECATION_WARNINGS
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#endif
#endif
#undef EXPORTLIBRARY
#endif
|
ccb054b3fa7026e78c459a84d233427d96b8aa80
|
3eb1d680026e7a19bc3c0b86c7b34aed49af20d3
|
/uFuncRag.cpp
|
f18a28f5c2d760dfcd5a814492d9c9a0edf39e85
|
[] |
no_license
|
andreyV512/talinka_thick
|
6a37e875f3f3e37e91a682c43b51419f29c0bc63
|
af378118eec958fee73e1f9b88af387cfa6aadc1
|
refs/heads/master
| 2020-03-29T18:29:05.294266
| 2018-11-21T03:24:38
| 2018-11-21T03:24:38
| 150,215,593
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 449
|
cpp
|
uFuncRag.cpp
|
//---------------------------------------------------------------------------
#pragma hdrstop
#include "uFuncRag.h"
#include <Forms.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
void CheckThread(AnsiString _head)
{
WideString w=_head;
AnsiString msg="Thread: ";
msg+=GetCurrentThreadId();
WideString wmsg=msg;
Application->MessageBoxW(wmsg.c_bstr(),w.c_bstr(),MB_ICONWARNING);
}
|
1ebdd4bc643fd529679e1bdc64d812cd426539c9
|
6f86a2533e592fa02428521fc7dfb2ffdc9343d0
|
/src/elements/MITCShell.h
|
8cf6c4df681ef9af106e555b5ce94f3ab0191b0d
|
[
"GPL-3.0-only",
"Apache-2.0"
] |
permissive
|
SourangshuGhosh/tacs
|
d3ff6d7b4a36d98ba35aae2b985fd721f7738775
|
1473eec093f3ac2c18ee9759865dc39a15b2e048
|
refs/heads/master
| 2022-11-19T05:33:02.127603
| 2020-07-22T13:08:44
| 2020-07-22T13:08:44
| 278,541,353
| 4
| 1
|
Apache-2.0
| 2020-07-21T07:08:02
| 2020-07-10T04:52:46
|
C++
|
UTF-8
|
C++
| false
| false
| 121,209
|
h
|
MITCShell.h
|
/*
This file is part of TACS: The Toolkit for the Analysis of Composite
Structures, a parallel finite-element code for structural and
multidisciplinary design optimization.
Copyright (C) 2010 University of Toronto
Copyright (C) 2012 University of Michigan
Copyright (C) 2014 Georgia Tech Research Corporation
Additional copyright (C) 2010 Graeme J. Kennedy and Joaquim
R.R.A. Martins All rights reserved.
TACS is licensed under the Apache License, Version 2.0 (the
"License"); you may not use this software except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef TACS_MITC_SHELL_H
#define TACS_MITC_SHELL_H
/*
MITC (Mixed interpolation of tensorial components)-based shell
element.
*/
#include "TACSElement.h"
#include "FSDTStiffness.h"
#include "FElibrary.h"
#include "TensorToolbox.h"
#include "TACSShell.h"
#include "ShellUtils.h"
#include "LargeRotUtils.h"
// Include all the functions from the namespace shellutils
using namespace shellutils;
using namespace largerot;
/*
A Shell element for general linear and geometrically nonlinear
analysis.
This element employs a mixed interpolation of tensorial (strain)
components (MITC) method to avoid shear locking problems. The flag
MITCShellType signals whether to use the full nonlinear terms in the
strain expressions. However, the element unknowns are in-plane
displacements and small-angle rotations. This limits the element to
relative small rotations. Stability and post-buckling can be explored
as long as the rotations remain moderate.
In the MITC approach, the strain compoennts susceptible to locking
are interpolated with appropriate low-order polynomials. In plance
of interpolating the shear and in-plane components directly, the
tensorial strains are interpolated and transformed back to the local
coordinate strains at the interpolation points (also called tying
points). This means that the evaluation of the residuals, stiffness
matrix and design-type derivatives are more computationally expensive
than an equivalent displacement-based shell. However, avoiding shear
locking is a key advantage and these elements should be used whenever
possible!
*/
template <int order, int tying_order=order>
class MITCShell : public TACSShell {
public:
MITCShell( FSDTStiffness *_stiff,
ElementBehaviorType type=LINEAR,
int _componentNum=0,
int _use_lobatto_quadrature=0 );
~MITCShell();
// How many nodes/variables per element
// ------------------------------------
int numNodes();
int numVariables();
// Compute the kinetic and potential energy within the element
// -----------------------------------------------------------
void computeEnergies( double time,
TacsScalar *_Te, TacsScalar *_Pe,
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[] );
// Compute the residual of the governing equations
// -----------------------------------------------
void addResidual( double time,
TacsScalar res[], const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] );
// Compute the Jacobian of the governing equations
// -----------------------------------------------
void addJacobian( double time, TacsScalar J[],
double alpha, double beta, double gamma,
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] );
// Add the product of the adjoint with the derivative of the design variables
// --------------------------------------------------------------------------
void addAdjResProduct( double time, double scale,
TacsScalar dvSens[], int dvLen,
const TacsScalar psi[],
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] );
// Add the product of the adjoint with the derivative of the design variables
// --------------------------------------------------------------------------
void addAdjResXptProduct( double time, double scale,
TacsScalar XptSens[],
const TacsScalar psi[],
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] );
// Retrieve a specific time-independent matrix from the element
// ------------------------------------------------------------
void getMatType( ElementMatrixType matType,
TacsScalar mat[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// Compute the derivative of the inner product w.r.t. design variables
// -------------------------------------------------------------------
void addMatDVSensInnerProduct( ElementMatrixType matType,
double scale,
TacsScalar dvSens[], int dvLen,
const TacsScalar psi[],
const TacsScalar phi[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// Compute the derivative of the inner product w.r.t. vars[]
// ---------------------------------------------------------
void getMatSVSensInnerProduct( ElementMatrixType matType,
TacsScalar res[],
const TacsScalar psi[],
const TacsScalar phi[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// Member functions for evaluating global functions of interest
// ------------------------------------------------------------
TACSConstitutive * getConstitutive(){ return stiff; }
// Get the number of Gauss quadrature points
// -----------------------------------------
int getNumGaussPts();
// Get the quadrature points and weights
// -------------------------------------
double getGaussWtsPts( const int num, double * pt );
// Get the shape functions from the element
// ----------------------------------------
void getShapeFunctions( const double pt[], double N[] );
// Return the determinant of the Jacobian at this point
// ----------------------------------------------------
TacsScalar getDetJacobian( const double * pt,
const TacsScalar Xpts[] );
// Return the determinant of the Jacobian and its sensitivity at this point
// ------------------------------------------------------------------------
TacsScalar getDetJacobianXptSens( TacsScalar * hXptSens,
const double * pt,
const TacsScalar Xpts[] );
// This function returns the strain evaluated at pt
// ------------------------------------------------
void getStrain( TacsScalar strain[],
const double pt[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// This function returns the sensitivity of the strain w.r.t. Xpts
// ---------------------------------------------------------------
void addStrainXptSens( TacsScalar fXptSens[],
const double pt[],
const TacsScalar scale,
const TacsScalar strainSens[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// This function adds the sensitivity of the strain to the state variables
// -----------------------------------------------------------------------
void addStrainSVSens( TacsScalar strainSVSens[],
const double pt[],
const TacsScalar scale,
const TacsScalar strainSens[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// Function used for localizing the error to nodes with PU-weights
// ---------------------------------------------------------------
void addLocalizedError( double time, TacsScalar err[],
const TacsScalar adjoint[],
const TacsScalar Xpts[],
const TacsScalar vars[] );
// Functions for post-processing
// -----------------------------
void addOutputCount( int *nelems, int *nnodes, int *ncsr );
void getOutputData( unsigned int out_type,
double *data, int ld_data,
const TacsScalar Xpts[],
const TacsScalar vars[] );
void getOutputConnectivity( int *con, int node );
// Set the number of nodes/number of variables per element
// -------------------------------------------------------
static const int NUM_NODES = order*order;
static const int NUM_VARIABLES = 6*order*order;
private:
// Get the partition of unity constraint
void getPartUnityShapeFunctions( const double pt[],
double N[], double Na[], double Nb[] );
static const int NUM_G11 = (tying_order-1)*tying_order;
static const int NUM_G22 = (tying_order-1)*tying_order;
static const int NUM_G12 = (tying_order-1)*(tying_order-1);
static const int NUM_G13 = (tying_order-1)*tying_order;
static const int NUM_G23 = (tying_order-1)*tying_order;
inline static TacsScalar strain_product( const TacsScalar a[],
const TacsScalar b[] ){
return (a[0]*b[0] + a[1]*b[1] +
a[2]*b[2] + a[3]*b[3] +
a[4]*b[4] + a[5]*b[5] +
a[6]*b[6] + a[7]*b[7]);
}
// The type of strain expressions to use
ElementBehaviorType type;
// The quadrature scheme for integrating the residual/stiffness
// matrix -- this is Gauss quadrature
int numGauss;
const double *gaussWts, *gaussPts;
// The knot locations
const double *knots; // "tying_order" Gauss points
const double *pknots; // "tying_order"-1 Gauss points
};
const double MITCShellFirstOrderKnots[2] = {-1.0, 1.0};
template <int order, int tying_order>
MITCShell<order, tying_order>::MITCShell( FSDTStiffness * _stiff,
ElementBehaviorType _type,
int _componentNum,
int use_lobatto_quadrature ):
TACSShell(_stiff, _componentNum){
type = _type;
if (use_lobatto_quadrature){
if (order == 2){
numGauss = 3;
gaussPts = FElibrary::lobattoPts3;
gaussWts = FElibrary::lobattoWts3;
}
else if (order == 3){
numGauss = 4;
gaussPts = FElibrary::lobattoPts4;
gaussWts = FElibrary::lobattoWts4;
}
else if (order == 4){
numGauss = 5;
gaussPts = FElibrary::lobattoPts5;
gaussWts = FElibrary::lobattoWts5;
}
else {
unsigned int gaussOrder = order;
numGauss = FElibrary::getGaussPtsWts(gaussOrder, &gaussPts, &gaussWts);
}
}
else {
unsigned int gaussOrder = order;
numGauss = FElibrary::getGaussPtsWts(gaussOrder, &gaussPts, &gaussWts);
}
// Get the knot points - the order and order-1-th Gauss points
if (tying_order == 2){
knots = MITCShellFirstOrderKnots;
}
else {
FElibrary::getGaussPtsWts(tying_order, &knots, NULL);
}
FElibrary::getGaussPtsWts(tying_order-1, &pknots, NULL);
}
template <int order, int tying_order>
MITCShell<order, tying_order>::~MITCShell(){}
template <int order, int tying_order>
int MITCShell<order, tying_order>::numNodes(){
return NUM_NODES;
}
template <int order, int tying_order>
int MITCShell<order, tying_order>::numVariables(){
return NUM_VARIABLES;
}
/*
Compute the kinetic energy and strain energy (potential energy)
contribution from this element. These are assigned (not added)
to the output values of Pe and Te.
input:
time: the simulation time
Xpts: the nodal locations
vars: the element variables
dvars: the time derivative of the element variables
output:
Te: the kinetic energy within the body
Pe: the potential energy of the body
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::computeEnergies( double time,
TacsScalar *_Te,
TacsScalar *_Pe,
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain at the tying points
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The stress and strain variables
TacsScalar strain[NUM_STRESSES], stress[NUM_STRESSES];
// The derivative of rthe rotation penalty term
TacsScalar drot[NUM_VARIABLES];
// The element kinetic and potential energies
TacsScalar Pe = 0.0, Te = 0.0;
// Compute the values of the tensorial strain at the tying points
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
TacsScalar kpenalty = stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Calculate the shape functions and the Jacobian/Hessian of the
// shell position at the quadrature point
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the transformation from the global coordinates to
// local shell coordinates
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = gaussWts[n]*gaussWts[m]*h;
// Compute the strain and rotation at the qudrature point
TacsScalar rot = 0.0;
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Rotation matrix data
TacsScalar C[9], Ct[27], Ctt[54];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_2nd_rate_matrix(Ctt, c1, s1, c2, s2, c3, s3);
// Evaluate the in-plane rotation term
rot = compute_inplane_penalty(drot, NUM_NODES, Xd, Ud,
C, Ct, N, Na, Nb);
// Calculate the deformation at the current point...
large_rot_bend_strain(strain, U, Ud, C, Ct, t, tx, ztx,
normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
// Compute the stress at the current Gauss point
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
Pe += 0.5*h*(strain_product(stress, strain) + kpenalty*rot*rot);
}
}
*_Te = Te;
*_Pe = Pe;
}
/*
Compute the residuals of the governing equations of motion.
Get the element residuals corresponding to the strain energy
contributions (e.g. not the work terms)
output:
res: the element residual
input:
vars: the element variables
Xpts: the element nodal locations in R^{3}
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addResidual( double time,
TacsScalar res[],
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The strain an rotation matrices
TacsScalar strain[NUM_STRESSES], stress[NUM_STRESSES];
TacsScalar drot[NUM_VARIABLES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
TacsScalar kpenalty = stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Calculate the shape functions and the Jacobian/Hessian of the
// shell position at the quadrature point
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the transformation from the global coordinates to
// local shell coordinates
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = gaussWts[n]*gaussWts[m]*h;
// Compute the strain and rotation at the qudrature point
TacsScalar rot = 0.0;
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
nonlinear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Rotation matrix data
TacsScalar C[9], Ct[27], Ctt[54];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_2nd_rate_matrix(Ctt, c1, s1, c2, s2, c3, s3);
// Evaluate the in-plane rotation term
rot = compute_inplane_penalty(drot, NUM_NODES, Xd, Ud,
C, Ct, N, Na, Nb);
// Calculate the deformation at the current point...
large_rot_bend_strain(strain, U, Ud, C, Ct, t, tx, ztx,
normal, normal_xi, normal_eta);
large_rot_bend_bmat(B, NUM_NODES, N, Na, Nb, U, Ud, C, Ct, Ctt,
t, tx, ztx, normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
// Compute the stress at the current Gauss point
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
// Get the pointwise mass at the quadrature point
TacsScalar mass[2];
stiff->getPointwiseMass(pt, mass);
// Compute the accelerations at the current point due to the
// ddvars input. Store the accelerations in the variable U[].
TacsScalar Uddot[NUM_DISPS];
compute_shell_U(NUM_NODES, Uddot, ddvars, N);
TacsScalar *r = res;
const TacsScalar *b = B;
const TacsScalar *br = drot;
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int ii = 0; ii < NUM_DISPS; ii++ ){
r[ii] += h*(strain_product(b, stress) + kpenalty*rot*br[0]);
b += NUM_STRESSES;
br++;
}
// Add the inertial terms from the accelerations
r[0] += h*N[i]*mass[0]*Uddot[0];
r[1] += h*N[i]*mass[0]*Uddot[1];
r[2] += h*N[i]*mass[0]*Uddot[2];
// Add the inertial terms from the rotations
TacsScalar d = normal[0]*Uddot[3] + normal[1]*Uddot[4] + normal[2]*Uddot[5];
r[3] += h*N[i]*mass[1]*(Uddot[3] - normal[0]*d);
r[4] += h*N[i]*mass[1]*(Uddot[4] - normal[1]*d);
r[5] += h*N[i]*mass[1]*(Uddot[5] - normal[2]*d);
r += NUM_DISPS;
}
}
}
}
/*
Add the element tangent stiffness matrix - the exact Jacobian of the
residual expressions.
output:
mat: the element tangent stiffness matrix
res: the element residual
input:
vars: the element variables
Xpts: the element nodal locations in R^{3}
matOr: the matrix orientation (NORMAL or TRANSPOSE)
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addJacobian( double time,
TacsScalar J[],
double alpha, double beta, double gamma,
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The second derivatives of the tying strain
TacsScalar n13[12*order*order*(order*order+1)*NUM_G13];
TacsScalar n23[12*order*order*(order*order+1)*NUM_G23];
// The stress and strain information
TacsScalar stress[NUM_STRESSES], strain[NUM_STRESSES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
TacsScalar BStress[NUM_STRESSES];
TacsScalar drot[NUM_VARIABLES];
// Evaluate the strain and derivative of the strain at the
// tying points within the element
if (type == LARGE_ROTATION){
compute_lr_tying_nmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13, n23, n13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
TacsScalar kpenalty = stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Compute the shape functions and evaluate the surface derivatives
// at the quadrature point
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the transformation matrix from the global coordinate
// system to the shell-aligned frame
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
// Scale the determinant of the Jacobian transformation by the
// quadrature weight at this point
h = gaussWts[n]*gaussWts[m]*h;
// Store the difference between the rotation variable
// and the in-plane rotation
TacsScalar rot = 0.0;
// Rotation matrix data
TacsScalar C[9], Ct[27], Ctt[54], Cttt[63];
// Compute the strain at the current point
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES, N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
nonlinear_bend_bmat(B, drot, NUM_NODES, N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_2nd_rate_matrix(Ctt, c1, s1, c2, s2, c3, s3);
compute_3rd_rate_matrix(Cttt, c1, s1, c2, s2, c3, s3);
// Evaluate the in-plane rotation term
rot = compute_inplane_penalty(drot, NUM_NODES, Xd, Ud,
C, Ct, N, Na, Nb);
// Calculate the strain/bmat at the current point
large_rot_bend_strain(strain, U, Ud, C, Ct,
t, tx, ztx, normal, normal_xi, normal_eta);
large_rot_bend_bmat(B, NUM_NODES, N, Na, Nb, U, Ud, C, Ct, Ctt,
t, tx, ztx, normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
// Add the interpolated strain and the interpolated b-matrix to the
// point-wise strain and strain-derivative (B)
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
// Get the pointwise mass at the quadrature point
TacsScalar mass[2];
stiff->getPointwiseMass(pt, mass);
// Scale the determinant of the Jacobian matrix by the alpha
// scaling factor
TacsScalar ha = h*alpha;
TacsScalar hg = h*gamma;
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int ii = 0; ii < NUM_DISPS; ii++ ){
int row = ii + NUM_DISPS*i;
// Calculate the stress associated with B
stiff->calculateStress(At, Bt, Dt, Ats,
&B[row*NUM_STRESSES], BStress);
for ( int j = 0; j <= i; j++ ){
int end = ( j == i ? ii : NUM_DISPS-1);
for ( int jj = 0; jj <= end; jj++ ){
int col = jj + NUM_DISPS*j;
// The regular element matrix
J[col + row*NUM_VARIABLES] +=
ha*(strain_product(BStress, &B[col*NUM_STRESSES]) +
kpenalty*drot[row]*drot[col]);
}
}
}
}
if (type == NONLINEAR){
nonlinear_bend_stress_bmat(J, NUM_NODES, ha, stress,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
add_nonlinear_tying_stress_nmat<order, tying_order>(J, ha, stress,
tx, N11, N22, N12,
knots, pknots, Xpts);
}
else if (type == LARGE_ROTATION){
// Add the second-derivative contributions from the bending strain
add_large_rot_bend_stress_bmat(J, NUM_NODES, ha, stress,
N, Na, Nb, U, Ud, C, Ct, Ctt, Cttt,
t, tx, ztx, normal, normal_xi, normal_eta);
// Add the contributions to the second derivative of the tying strain
add_lr_tying_stress_nmat<order, tying_order>(J, ha, stress, n13, n23, tx,
N11, N22, N12, knots, pknots);
// Add the second derivative of the in-plane penalty
add_inplane_penalty(J, NUM_NODES, ha*kpenalty*rot, Xd, Ud,
Ct, Ctt, N, Na, Nb);
}
// Add the kinetic energy terms from the displacement
TacsScalar Am = hg*mass[0];
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int j = 0; j < NUM_NODES; j++ ){
for ( int ii = 0; ii < 3; ii++ ){
int row = ii + NUM_DISPS*i;
int col = ii + NUM_DISPS*j;
J[col + row*NUM_VARIABLES] += Am*N[i]*N[j];
}
}
}
// Add the contribution due to the rotational terms
TacsScalar Dm = hg*mass[1];
TacsScalar D[9];
D[0] = Dm*(1.0 - normal[0]*normal[0]);
D[1] = -Dm*normal[0]*normal[1];
D[2] = -Dm*normal[0]*normal[2];
D[3] = -Dm*normal[1]*normal[0];
D[4] = Dm*(1.0 - normal[1]*normal[1]);
D[5] = -Dm*normal[1]*normal[2];
D[6] = -Dm*normal[2]*normal[0];
D[7] = -Dm*normal[2]*normal[1];
D[8] = Dm*(1.0 - normal[2]*normal[2]);
// Add the values to the matrix
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int j = 0; j < NUM_NODES; j++ ){
for ( int ii = 0; ii < 3; ii++ ){
int row = 3+ii + NUM_DISPS*i;
for ( int jj = 0; jj < 3; jj++ ){
int col = 3+jj + NUM_DISPS*j;
J[col + row*NUM_VARIABLES] += D[ii + 3*jj]*N[i]*N[j];
}
}
}
}
}
}
// Copy over the matrix
// Take the lower triangle and copy to the upper triangle
for ( int row = 0; row < NUM_VARIABLES; row++ ){
for ( int col = row+1; col < NUM_VARIABLES; col++ ){
J[col + row*NUM_VARIABLES] = J[row + col*NUM_VARIABLES];
}
}
}
/*
Evaluate the element matrix of a specified type
output:
mat: the element matrix of the specified type
input:
matType: the matrix type (e.g. MASS_MATRIX)
vars: the element variables
Xpts: the nodal coordinates in R^{3}
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getMatType( ElementMatrixType matType,
TacsScalar *mat,
const TacsScalar Xpts[],
const TacsScalar vars[] ){
memset(mat, 0, NUM_VARIABLES*NUM_VARIABLES*sizeof(TacsScalar));
if (matType == STIFFNESS_MATRIX){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The second derivatives of the tying strain
TacsScalar n13[12*order*order*(order*order+1)*NUM_G13];
TacsScalar n23[12*order*order*(order*order+1)*NUM_G23];
// The stress and strain information
TacsScalar stress[NUM_STRESSES], strain[NUM_STRESSES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
TacsScalar BStress[NUM_STRESSES];
TacsScalar drot[NUM_VARIABLES];
// Evaluate the strain and derivative of the strain at the
// tying points within the element
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
TacsScalar kpenalty = stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Compute the shape functions and evaluate the surface derivatives
// at the quadrature point
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the transformation matrix from the global coordinate
// system to the shell-aligned frame
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
// Scale the determinant of the Jacobian transformation by the
// quadrature weight at this point
h = gaussWts[n]*gaussWts[m]*h;
// Store the difference between the rotation variable
// and the in-plane rotation
TacsScalar rot = 0.0;
// Rotation matrix data
TacsScalar C[9], Ct[27], Ctt[54], Cttt[63];
// Compute the strain at the current point
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES, N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
nonlinear_bend_bmat(B, drot, NUM_NODES, N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_2nd_rate_matrix(Ctt, c1, s1, c2, s2, c3, s3);
compute_3rd_rate_matrix(Cttt, c1, s1, c2, s2, c3, s3);
// Evaluate the in-plane rotation term
rot = compute_inplane_penalty(drot, NUM_NODES, Xd, Ud,
C, Ct, N, Na, Nb);
// Calculate the strain/bmat at the current point
large_rot_bend_strain(strain, U, Ud, C, Ct,
t, tx, ztx, normal, normal_xi, normal_eta);
large_rot_bend_bmat(B, NUM_NODES, N, Na, Nb, U, Ud, C, Ct, Ctt,
t, tx, ztx, normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
// Add the interpolated strain and the interpolated b-matrix to the
// point-wise strain and strain-derivative (B)
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
add_tying_bmat<tying_order>(B, NUM_NODES,
tx, b11, b22, b12, b23, b13,
N11, N22, N12);
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
// Get the pointwise mass at the quadrature point
TacsScalar mass[2];
stiff->getPointwiseMass(pt, mass);
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int ii = 0; ii < NUM_DISPS; ii++ ){
int row = ii + NUM_DISPS*i;
// Calculate the stress associated with B
stiff->calculateStress(At, Bt, Dt, Ats,
&B[row*NUM_STRESSES], BStress);
for ( int j = 0; j <= i; j++ ){
int end = ( j == i ? ii : NUM_DISPS-1);
for ( int jj = 0; jj <= end; jj++ ){
int col = jj + NUM_DISPS*j;
// The regular element matrix
mat[col + row*NUM_VARIABLES] +=
h*(strain_product(BStress, &B[col*NUM_STRESSES]) +
kpenalty*drot[row]*drot[col]);
}
}
}
}
if (type == NONLINEAR){
nonlinear_bend_stress_bmat(mat, NUM_NODES, h, stress,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
add_nonlinear_tying_stress_nmat<order, tying_order>(mat, h, stress,
tx, N11, N22, N12,
knots, pknots, Xpts);
}
else if (type == LARGE_ROTATION){
// Add the second-derivative contributions from the bending strain
add_large_rot_bend_stress_bmat(mat, NUM_NODES, h, stress,
N, Na, Nb, U, Ud, C, Ct, Ctt, Cttt,
t, tx, ztx, normal, normal_xi, normal_eta);
// Add the contributions to the second derivative of the tying strain
add_lr_tying_stress_nmat<order, tying_order>(mat, h, stress, n13, n23, tx,
N11, N22, N12, knots, pknots);
// Add the second derivative of the in-plane penalty
add_inplane_penalty(mat, NUM_NODES, h*kpenalty*rot, Xd, Ud,
Ct, Ctt, N, Na, Nb);
}
// Copy over the matrix
// Take the lower triangle and copy to the upper triangle
for ( int row = 0; row < NUM_VARIABLES; row++ ){
for ( int col = row+1; col < NUM_VARIABLES; col++ ){
mat[col + row*NUM_VARIABLES] = mat[row + col*NUM_VARIABLES];
}
}
}
}
}
else if (matType == MASS_MATRIX){
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point within the element
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the shape functions and the derivative of the
// shell surface location along the u/v directions
TacsScalar X[3], Xd[9], normal[3];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
shell_jacobian(order, X, Xd, N, Na, Nb, pt, Xpts);
// Compute the normal vector and set it in the final row
// of the Xd transformation matrix
Tensor::crossProduct3D(normal, &Xd[0], &Xd[3]);
Tensor::normalize3D(normal);
for ( int i = 0; i < 3; i++ ){
Xd[6+i] = normal[i];
}
// Compute the determinant of the jacobian transformation and
// scale it by the qudrature weight
TacsScalar h = FElibrary::jacobian3d(Xd);
h = gaussWts[n]*gaussWts[m]*h;
// Get the pointwise mass at the quadrature point
TacsScalar mass[2];
stiff->getPointwiseMass(pt, mass);
// Add the kinetic energy terms from the displacement
TacsScalar Am = mass[0]*h;
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int j = 0; j < NUM_NODES; j++ ){
for ( int ii = 0; ii < 3; ii++ ){
int row = ii + NUM_DISPS*i;
int col = ii + NUM_DISPS*j;
mat[col + row*NUM_VARIABLES] += Am*N[i]*N[j];
}
}
}
// Add the contribution due to the rotational terms
TacsScalar Dm = mass[1]*h;
TacsScalar D[9];
D[0] = Dm*(1.0 - normal[0]*normal[0]);
D[1] = -Dm*normal[0]*normal[1];
D[2] = -Dm*normal[0]*normal[2];
D[3] = -Dm*normal[1]*normal[0];
D[4] = Dm*(1.0 - normal[1]*normal[1]);
D[5] = -Dm*normal[1]*normal[2];
D[6] = -Dm*normal[2]*normal[0];
D[7] = -Dm*normal[2]*normal[1];
D[8] = Dm*(1.0 - normal[2]*normal[2]);
// Add the values to the matrix
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int j = 0; j < NUM_NODES; j++ ){
for ( int ii = 0; ii < 3; ii++ ){
int row = 3+ii + NUM_DISPS*i;
for ( int jj = 0; jj < 3; jj++ ){
int col = 3+jj + NUM_DISPS*j;
mat[col + row*NUM_VARIABLES] += D[ii + 3*jj]*N[i]*N[j];
}
}
}
}
}
}
}
else if (matType == GEOMETRIC_STIFFNESS_MATRIX &&
type == LINEAR){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
// Displacements/rotations and shape functions
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The stress/strain values
TacsScalar stress[NUM_STRESSES], strain[NUM_STRESSES];
// Compute the tying strain
const int is_linear = 1;
compute_tying_strain<order, tying_order>(is_linear,
g11, g22, g12, g23, g13,
knots, pknots, vars, Xpts);
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the transformation
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = gaussWts[n]*gaussWts[m]*h;
// Calculate the strain/bmat at the current point...
TacsScalar rot;
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx, g11, g22, g12, g23, g13,
N11, N22, N12);
// Compute the stress at this Gauss point
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
// Add the geometric stiffness terms
nonlinear_bend_stress_bmat(mat, NUM_NODES, h, stress,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
add_nonlinear_tying_stress_nmat<order, tying_order>(mat, h, stress,
tx, N11, N22, N12,
knots, pknots, Xpts);
}
}
// Copy over the matrix
// Take the lower triangle and copy to the upper triangle
for ( int row = 0; row < NUM_VARIABLES; row++ ){
for ( int col = row+1; col < NUM_VARIABLES; col++ ){
mat[col + row*NUM_VARIABLES] = mat[row + col*NUM_VARIABLES];
}
}
}
}
/*
Compute the derivative of the product of the residual with the
adjoint vector psi with respect to the design variables. The result
is added to a design-variable array.
input:
time: the simulation time
scale: the scaling factor applied to the derivative
dvLen: the length of the design variable vector
psi: the left-multiplying vector
phi: the right-multiplying vector
vars: the element state variables
Xpts: the nodal locations for this element
output:
dvSens: the result is added to this vector
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addAdjResProduct( double time,
double scale,
TacsScalar fdvSens[],
int dvLen,
const TacsScalar psi[],
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
TacsScalar strain[NUM_STRESSES];
TacsScalar drot[NUM_VARIABLES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
// Compute the tying terms in the matrix
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point within the element
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Compute the shape functions and the derivatives of the
// position of the shell with respect to the coordinates
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the coordinate transformation
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
// Scale the determinant of the Jacobian transformation by the
// quadrature weight
h = scale*gaussWts[n]*gaussWts[m]*h;
// Calculate the deformation at the current point...
TacsScalar rot = 0.0;
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
nonlinear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Rotation matrix data
TacsScalar C[9], Ct[27], Ctt[54];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_2nd_rate_matrix(Ctt, c1, s1, c2, s2, c3, s3);
// Evaluate the in-plane rotation term
rot = compute_inplane_penalty(drot, NUM_NODES, Xd, Ud,
C, Ct, N, Na, Nb);
// Calculate the deformation at the current point...
large_rot_bend_strain(strain, U, Ud, C, Ct, t, tx, ztx,
normal, normal_xi, normal_eta);
large_rot_bend_bmat(B, NUM_NODES, N, Na, Nb, U, Ud, C, Ct, Ctt,
t, tx, ztx, normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
// Compute the product of psi^{T}*B^{T}
TacsScalar bpsi[NUM_STRESSES], brot = 0.0;
memset(bpsi, 0, NUM_STRESSES*sizeof(TacsScalar));
TacsScalar *b = B, *dr = drot;
const TacsScalar *ps = psi;
for ( int i = 0; i < NUM_VARIABLES; i++ ){
bpsi[0] += ps[0]*b[0];
bpsi[1] += ps[0]*b[1];
bpsi[2] += ps[0]*b[2];
bpsi[3] += ps[0]*b[3];
bpsi[4] += ps[0]*b[4];
bpsi[5] += ps[0]*b[5];
bpsi[6] += ps[0]*b[6];
bpsi[7] += ps[0]*b[7];
brot += ps[0]*dr[0];
b += NUM_STRESSES;
dr++;
ps++;
}
// Scale the strain and rotational terms by scale*h
for ( int i = 0; i < NUM_STRESSES; i++ ){
bpsi[i] *= h;
}
brot *= h;
// Add the term: scale*psi^{T}*B^{T}*dC/dx*strain to the vector
// dvSens - Note that this is much more efficient than computing
// the terms component by component
stiff->addStiffnessDVSens(pt, strain, bpsi, brot*rot,
fdvSens, dvLen);
// Compute the accelerations at the current point due to the
// ddvars input. Store the accelerations in the variable U[].
TacsScalar Uddot[NUM_DISPS];
compute_shell_U(NUM_NODES, Uddot, ddvars, N);
// Set the scalar for the mass matrix
TacsScalar mscale[2] = {0.0, 0.0};
const TacsScalar *p = psi;
for ( int i = 0; i < NUM_NODES; i++ ){
mscale[0] += h*N[i]*(Uddot[0]*p[0] + Uddot[1]*p[1] + Uddot[2]*p[2]);
TacsScalar d = normal[0]*Uddot[3] + normal[1]*Uddot[4] + normal[2]*Uddot[5];
mscale[1] += h*N[i]*((Uddot[3] - normal[0]*d)*p[3] +
(Uddot[4] - normal[1]*d)*p[4] +
(Uddot[5] - normal[2]*d)*p[5]);
p += NUM_DISPS;
}
// Add the sensitivity term from the mass matrix contribution
stiff->addPointwiseMassDVSens(pt, mscale, fdvSens, dvLen);
}
}
}
/*
Evaluate the derivative of the element residuals with respect
to the nodal coordinates e.g res = dR/dXpts
output:
res: the derivative of the residuals w.r.t. the element nodes
input:
vars: the element variables
Xpts: the element nodal locations
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addAdjResXptProduct( double time, double scale,
TacsScalar fXptSens[],
const TacsScalar psi[],
const TacsScalar Xpts[],
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
TacsScalar dnormal[9*NUM_NODES], dnormal_xi[9*NUM_NODES],
dnormal_eta[9*NUM_NODES];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar dt[27*NUM_NODES], dtx[27*NUM_NODES], dztx[27*NUM_NODES];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the tensorial tying strain components
TacsScalar dg11[3*NUM_G11*NUM_NODES], dg22[3*NUM_G22*NUM_NODES],
dg12[3*NUM_G12*NUM_NODES];
TacsScalar dg13[3*NUM_G13*NUM_NODES], dg23[3*NUM_G23*NUM_NODES];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The stress and strain and their sensitivities
TacsScalar strain[NUM_STRESSES], stress[NUM_STRESSES];
TacsScalar dstrain[3*NUM_STRESSES*NUM_NODES], dstress[NUM_STRESSES];
// The rotational contributions
TacsScalar drot[NUM_VARIABLES], srot[NUM_VARIABLES];
// The derivative of the strain w.r.t. the nodal displacements
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
// The sensitivity of the determinant of the Jacobian
TacsScalar dh[3*NUM_NODES];
compute_tying_strain_sens<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
dg11, dg22, dg12, dg23, dg13,
knots, pknots, vars, Xpts);
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
TacsScalar k_penalty = stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Calculate the shape functions and the surface derivatives
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
// Compute the values of U and Ud - the variables and their
// derivatives w.r.t. the local coordinates
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12, knots, pknots);
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform_sens(dh, t, dt, tx, dtx, ztx, dztx,
normal, dnormal,
normal_xi, dnormal_xi,
normal_eta, dnormal_eta,
Xd, Xdd, Na, Nb, Naa, Nab, Nbb, NUM_NODES);
}
else {
const TacsScalar *axis = stiff->getRefAxis();
h = compute_transform_refaxis_sens(dh, t, dt, tx, dtx, ztx, dztx,
normal, dnormal,
normal_xi, dnormal_xi,
normal_eta, dnormal_eta, axis,
Xd, Xdd, Na, Nb, Naa, Nab, Nbb,
NUM_NODES);
}
h = scale*gaussWts[n]*gaussWts[m]*h;
// Evaluate the strain and the derivative of the strain w.r.t.
// the displacements and the nodal coordinates
TacsScalar rot;
if (type == LINEAR){
linear_bend_strain_sens(strain, dstrain, &rot, srot, U, Ud,
t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi,
dnormal_xi, normal_eta, dnormal_eta,
3*NUM_NODES);
linear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain_sens(strain, dstrain, &rot, srot, U, Ud,
t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi,
dnormal_xi, normal_eta, dnormal_eta,
3*NUM_NODES);
nonlinear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
// Add the sensitivities of the tying strain points into the
// strain senstivities
add_tying_strain_sens<tying_order>(strain, dstrain, tx, dtx,
g11, g22, g12, g23, g13,
dg11, dg22, dg12, dg23, dg13,
N11, N22, N12);
// Add the tying strain to the B-matrix
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
// Calculate the stress at the current point
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
for ( int k = 0; k < 3*NUM_NODES; k++ ){
dh[k] = scale*gaussWts[n]*gaussWts[m]*dh[k];
stiff->calculateStress(At, Bt, Dt, Ats,
&dstrain[k*NUM_STRESSES], dstress);
for ( int row = 0; row < NUM_VARIABLES; row++ ){
fXptSens[k] +=
psi[row]*(h*(strain_product(&B[NUM_STRESSES*row], dstress) +
k_penalty*(srot[k]*drot[row])) +
dh[k]*(strain_product(&B[NUM_STRESSES*row], stress) +
k_penalty*rot*drot[row]));
}
}
if (type == LINEAR){
add_linear_bend_bmat_sens(fXptSens, psi, NUM_NODES, h, h*k_penalty*rot,
stress, N, Na, Nb,
t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi, dnormal_xi,
normal_eta, dnormal_eta, 3*NUM_NODES);
}
else if (type == NONLINEAR){
add_nonlinear_bend_bmat_sens(fXptSens, psi, NUM_NODES, h, h*k_penalty*rot,
stress, N, Na, Nb, U, Ud,
t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi, dnormal_xi,
normal_eta, dnormal_eta, 3*NUM_NODES);
}
add_tying_bmat_sens<order, tying_order>((type == LINEAR),
fXptSens, psi, h, stress, tx, dtx,
knots, pknots, vars, Xpts,
N11, N22, N12);
// Get the pointwise mass at the quadrature point
TacsScalar mass[2];
stiff->getPointwiseMass(pt, mass);
// Compute the accelerations at the current point due to the
// ddvars input. Store the accelerations in the variable U[].
TacsScalar Uddot[NUM_DISPS];
compute_shell_U(NUM_NODES, Uddot, ddvars, N);
// Find the derivative of the inner product w.r.t. the
// determinant of the Jacobian transformation and the derivative
// w.r.t. the normal direction
double alpha = scale*gaussWts[n]*gaussWts[m];
TacsScalar hd = 0.0;
TacsScalar nd[3] = {0.0, 0.0, 0.0};
const TacsScalar *p = psi;
for ( int i = 0; i < NUM_NODES; i++ ){
hd += alpha*mass[0]*N[i]*(Uddot[0]*p[0] + Uddot[1]*p[1] + Uddot[2]*p[2]);
TacsScalar d = normal[0]*Uddot[3] + normal[1]*Uddot[4] + normal[2]*Uddot[5];
hd += alpha*mass[1]*N[i]*((Uddot[3] - normal[0]*d)*p[3] +
(Uddot[4] - normal[1]*d)*p[4] +
(Uddot[5] - normal[2]*d)*p[5]);
// Find the derivative of Psi^{T}*(I - n*n^{T})*U w.r.t n:
TacsScalar psid = (p[3]*normal[0] + p[4]*normal[1] + p[5]*normal[2]);
nd[0] -= h*mass[1]*N[i]*(p[3]*d + Uddot[3]*psid);
nd[1] -= h*mass[1]*N[i]*(p[4]*d + Uddot[4]*psid);
nd[2] -= h*mass[1]*N[i]*(p[5]*d + Uddot[5]*psid);
p += NUM_DISPS;
}
// Add the derivative to the fXptSens array
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int k = 0; k < 3; k++ ){
TacsScalar XdSens[9];
XdSens[0] = XdSens[1] = XdSens[2] = 0.0;
XdSens[3] = XdSens[4] = XdSens[5] = 0.0;
XdSens[k] = Na[i];
XdSens[3+k] = Nb[i];
// Compute the derivative of the cross product
Tensor::crossProduct3DSens(&Xd[6], &XdSens[6],
&Xd[0], &Xd[3], &XdSens[0], &XdSens[3]);
// Compute the derivative of the normal vector
TacsScalar snrm;
Tensor::normalize3DSens(&snrm, &Xd[6], &XdSens[6]);
TacsScalar hXptSens;
FElibrary::jacobian3dSens(Xd, XdSens, &hXptSens);
fXptSens[3*i+k] += hXptSens*hd +
(nd[0]*XdSens[6] + nd[1]*XdSens[7] + nd[2]*XdSens[8]);
}
}
}
}
}
/*
Compute the derivative of the inner product of the stiffness or mass
matrices with the given vectors psi and phi with respect to the
design variables. The result is a vector which is the length of the
number of design variables.
input:
matType: the type of matrix
scale: the scaling factor applied to the derivative
dvLen: the length of the design variable vector
psi: the left-multiplying vector
phi: the right-multiplying vector
vars: the element state variables
Xpts: the nodal locations for this element
output:
dvSens: the result is added to this vector
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addMatDVSensInnerProduct( ElementMatrixType matType,
double scale,
TacsScalar fdvSens[], int dvLen,
const TacsScalar psi[],
const TacsScalar phi[],
const TacsScalar Xpts[],
const TacsScalar vars[] ){
if (matType == STIFFNESS_MATRIX){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
TacsScalar strain[NUM_STRESSES];
TacsScalar drot[NUM_VARIABLES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
// Compute the tying terms in the matrix
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature points
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = gaussWts[n]*gaussWts[m]*h;
// Calculate the deformation at the current point...
TacsScalar rot = 0.0; // Difference between inplane/drilling rotation
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
// Compute the product of psi^{T}*B^{T}
TacsScalar bpsi[NUM_STRESSES], bphi[NUM_STRESSES];
memset(bpsi, 0, NUM_STRESSES*sizeof(TacsScalar));
memset(bphi, 0, NUM_STRESSES*sizeof(TacsScalar));
TacsScalar brpsi = 0.0, brphi = 0.0;
TacsScalar *b = B, *dr = drot;
const TacsScalar *ps = psi, *ph = phi;
for ( int i = 0; i < NUM_VARIABLES; i++ ){
bpsi[0] += ps[0]*b[0]; bpsi[1] += ps[0]*b[1];
bpsi[2] += ps[0]*b[2]; bpsi[3] += ps[0]*b[3];
bpsi[4] += ps[0]*b[4]; bpsi[5] += ps[0]*b[5];
bpsi[6] += ps[0]*b[6]; bpsi[7] += ps[0]*b[7];
bphi[0] += ph[0]*b[0]; bphi[1] += ph[0]*b[1];
bphi[2] += ph[0]*b[2]; bphi[3] += ph[0]*b[3];
bphi[4] += ph[0]*b[4]; bphi[5] += ph[0]*b[5];
bphi[6] += ph[0]*b[6]; bphi[7] += ph[0]*b[7];
brpsi += ps[0]*dr[0];
brphi += ph[0]*dr[0];
// Increment the pointers
b += NUM_STRESSES;
dr++; ps++; ph++;
}
for ( int i = 0; i < NUM_STRESSES; i++ ){
bpsi[i] *= scale*h;
}
// Add the term: scale*psi^{T}*B^{T}*dC/dx*strain to the vector
// dvSens - Note that this is much more efficient than computing
// the terms component by component
stiff->addStiffnessDVSens(pt, bpsi, bphi, scale*h*brpsi*brphi,
fdvSens, dvLen);
}
}
}
else if (matType == MASS_MATRIX){
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature points
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the shape functions and the derivatives of the
// position of the shell surface
TacsScalar X[3], Xd[9], normal[3];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
shell_jacobian(order, X, Xd, N, Na, Nb, pt, Xpts);
// Compute the normal to the surface
Tensor::crossProduct3D(normal, &Xd[0], &Xd[3]);
Tensor::normalize3D(normal);
for ( int i = 0; i < 3; i++ ){
Xd[6+i] = normal[i];
}
// Compute the determinant of the shell position
TacsScalar h = FElibrary::jacobian3d(Xd);
h = gaussWts[n]*gaussWts[m]*h;
// Compute the nodal accelerations at the quadrature point
TacsScalar upsi[6], uphi[6];
upsi[0] = upsi[1] = upsi[2] = upsi[3] = upsi[4] = upsi[5] = 0.0;
uphi[0] = uphi[1] = uphi[2] = uphi[3] = uphi[4] = uphi[5] = 0.0;
double *ns = N;
const TacsScalar *ps = psi, *ph = phi;
for ( int i = 0; i < NUM_NODES; i++ ){
upsi[0] += ns[0]*ps[0]; upsi[1] += ns[0]*ps[1];
upsi[2] += ns[0]*ps[2]; upsi[3] += ns[0]*ps[3];
upsi[4] += ns[0]*ps[4]; upsi[5] += ns[0]*ps[5];
uphi[0] += ns[0]*ph[0]; uphi[1] += ns[0]*ph[1];
uphi[2] += ns[0]*ph[2]; uphi[3] += ns[0]*ph[3];
uphi[4] += ns[0]*ph[4]; uphi[5] += ns[0]*ph[5];
ps += 6; ph += 6; ns++;
}
// Compute the weights on each component of the mass moments
TacsScalar rho_scale[2];
rho_scale[0] = scale*h*(upsi[0]*uphi[0] + upsi[1]*uphi[1] +
upsi[2]*uphi[2]);
TacsScalar tphi[3], tpsi[3];
Tensor::crossProduct3D(tphi, &uphi[3], normal);
Tensor::crossProduct3D(tpsi, &upsi[3], normal);
rho_scale[1] = scale*h*(tphi[0]*tpsi[0] + tphi[1]*tpsi[1] +
tphi[2]*tpsi[2]);
// Add the result to the design variable vector
stiff->addPointwiseMassDVSens(pt, rho_scale, fdvSens, dvLen);
}
}
}
else if (matType == GEOMETRIC_STIFFNESS_MATRIX &&
type == LINEAR){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
// Displacements/rotations and shape functions
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The strain values
TacsScalar strain[NUM_STRESSES];
TacsScalar bstrain[NUM_STRESSES];
// Compute the tying strain values
const int is_linear = 1;
compute_tying_strain<order, tying_order>(is_linear,
g11, g22, g12, g23, g13,
knots, pknots, vars, Xpts);
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
double gpt[2];
gpt[0] = gaussPts[n];
gpt[1] = gaussPts[m];
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
gpt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = gaussWts[n]*gaussWts[m]*h;
// Calculate the strain/bmat at the current point...
TacsScalar rot;
linear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(gpt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx, g11, g22, g12, g23, g13,
N11, N22, N12);
// Compute the derivatives of the phi/psi vectors
TacsScalar Upsi[NUM_DISPS], Udpsi[2*NUM_DISPS];
TacsScalar Uphi[NUM_DISPS], Udphi[2*NUM_DISPS];
compute_shell_Ud(NUM_NODES, Upsi, Udpsi, psi, N, Na, Nb);
compute_shell_Ud(NUM_NODES, Uphi, Udphi, phi, N, Na, Nb);
// Compute the inner product of the second derivatives of the
// stiffness matrix with the psi and phi vectors
inner_nonlinear_bend_bmat(bstrain, Upsi, Udpsi, Uphi, Udphi,
t, tx, ztx, normal, normal_xi, normal_eta);
add_nonlinear_tying_inner_nmat<order, tying_order>(bstrain, psi, phi,
tx, N11, N22, N12,
knots, pknots, Xpts);
for ( int i = 0; i < NUM_STRESSES; i++ ){
strain[i] *= scale*h;
}
// Add the term: scale*psi^{T}*B^{T}*dC/dx*strain to the vector
// dvSens - Note that this is much more efficient than computing
// the terms component by component
stiff->addStiffnessDVSens(gpt, strain, bstrain, 0.0,
fdvSens, dvLen);
}
}
}
}
/*
Add the derivative of the inner product of the given matrix type
with the given psi and phi vectors with respect to the state
variables. This only makes sense for nonlinear Jacobian matrices
such as the geometric stiffness matrix.
input:
matType: the type of matrix
scale: the scaling factor applied to the derivative
psi: the left-multiplying vector
phi: the right-multiplying vector
vars: the element state variables
Xpts: the nodal locations for this element
output:
res: the derivative of the inner product w.r.t. vars
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getMatSVSensInnerProduct( ElementMatrixType matType,
TacsScalar res[],
const TacsScalar psi[],
const TacsScalar phi[],
const TacsScalar Xpts[],
const TacsScalar vars[] ){
if (matType == GEOMETRIC_STIFFNESS_MATRIX &&
type == LINEAR){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
// Displacements/rotations and shape functions
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The strain values
TacsScalar strain[NUM_STRESSES];
TacsScalar bstrain[NUM_STRESSES], bstress[NUM_STRESSES];
// The derivative of the strain w.r.t. the displacements
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
TacsScalar drot[NUM_VARIABLES];
// Compute the tying strain values
const int is_linear = 1;
compute_tying_bmat<order, tying_order>(is_linear,
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
for ( int m = 0; m < numGauss; m++ ){
for ( int n = 0; n < numGauss; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
// Evaluate the stiffness properties at the quadrature poitn
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb, pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = gaussWts[n]*gaussWts[m]*h;
// Calculate the strain/bmat at the current point...
TacsScalar rot;
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx, g11, g22, g12, g23, g13,
N11, N22, N12);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
// Compute the derivatives of the phi/psi vectors
TacsScalar Upsi[NUM_DISPS], Udpsi[2*NUM_DISPS];
TacsScalar Uphi[NUM_DISPS], Udphi[2*NUM_DISPS];
compute_shell_Ud(NUM_NODES, Upsi, Udpsi, psi, N, Na, Nb);
compute_shell_Ud(NUM_NODES, Uphi, Udphi, phi, N, Na, Nb);
// Compute the inner product of the second derivatives of the
// stiffness matrix with the psi and phi vectors
inner_nonlinear_bend_bmat(bstrain, Upsi, Udpsi, Uphi, Udphi,
t, tx, ztx, normal, normal_xi, normal_eta);
add_nonlinear_tying_inner_nmat<order, tying_order>(bstrain, psi, phi,
tx, N11, N22, N12,
knots, pknots, Xpts);
// Compute the stress at the current Gauss point
stiff->calculateStress(At, Bt, Dt, Ats, bstrain, bstress);
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int ii = 0; ii < NUM_DISPS; ii++ ){
int row = ii + NUM_DISPS*i;
res[row] +=
h*strain_product(&B[NUM_STRESSES*row], bstress);
}
}
}
}
}
}
/*
Return the number of points in the specified quadrature scheme
*/
template <int order, int tying_order>
int MITCShell<order, tying_order>::getNumGaussPts(){
return numGauss*numGauss;
}
/*
Retrieve the Gauss points and weights for the given Gauss point
number
input:
scheme: the Gauss quadrature scheme
num: the Gauss point index for the quadrature point
returns: the Gauss quadrature weight for the given point
output:
pt: the Gauss point for the given index
*/
template <int order, int tying_order>
double MITCShell<order, tying_order>::getGaussWtsPts( const int num, double *pt ){
int m = (int)(num/numGauss);
int n = num % numGauss;
pt[0] = gaussPts[n];
pt[1] = gaussPts[m];
return gaussWts[n]*gaussWts[m];
}
/*
Evaluate the shape functions for this element at the specified point
output:
N: the shape functions values evaluated at the parametric point pt
input:
pt: the parametric point within the element
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getShapeFunctions( const double pt[], double N[] ){
double na[order], nb[order];
FElibrary::lagrangeSF(na, pt[0], order);
FElibrary::lagrangeSF(nb, pt[1], order);
for ( int j = 0; j < order; j++ ){
for ( int i = 0; i < order; i++ ){
N[0] = na[i]*nb[j];
N++;
}
}
}
/*
Evaluate the determinant of the Jacobian for numerical integration
returns: the determinant of the Jacobian
input:
pt: the parametric point within the element
Xpts: the element nodes
*/
template <int order, int tying_order>
TacsScalar MITCShell<order, tying_order>::getDetJacobian( const double * pt,
const TacsScalar Xpts[] ){
TacsScalar X[3], Xd[9];
TacsScalar normal[3];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
shell_jacobian(order, X, Xd, N, Na, Nb, pt, Xpts);
Tensor::crossProduct3D(normal, &Xd[0], &Xd[3]);
Tensor::normalize3D(normal);
for ( int i = 0; i < 3; i++ ){
Xd[i+6] = normal[i];
}
return FElibrary::jacobian3d(Xd);
}
/*
Evaluate the derivative of the determinant of the Jacobian with respect
to the element nodal locations
output:
hXptSens: the derivative of the determinant w.r.t. the nodal locations
returns: the determinant of the Jacobian
input:
pt: the parametric point within the element
Xpts: the element nodes
*/
template <int order, int tying_order>
TacsScalar MITCShell<order, tying_order>::getDetJacobianXptSens( TacsScalar * hXptSens,
const double * pt,
const TacsScalar Xpts[] ){
TacsScalar h = 0.0;
TacsScalar X[3], Xd[9], XdSens[9];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
shell_jacobian(order, X, Xd, N, Na, Nb, pt, Xpts);
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int k = 0; k < 3; k++ ){
XdSens[0] = XdSens[1] = XdSens[2] = 0.0;
XdSens[3] = XdSens[4] = XdSens[5] = 0.0;
XdSens[k] = Na[i];
XdSens[3+k] = Nb[i];
Tensor::crossProduct3DSens(&Xd[6], &XdSens[6],
&Xd[0], &Xd[3], &XdSens[0], &XdSens[3]);
TacsScalar snrm;
Tensor::normalize3DSens(&snrm, &Xd[6], &XdSens[6]);
h = FElibrary::jacobian3dSens(Xd, XdSens, &hXptSens[0]);
hXptSens++;
}
}
return h;
}
/*
Evaluate the strain at the specified point using the provided
set of variables
output:
strain: the strain evaluate at the specific parametric point
input:
vars: the element variable values
Xpts: the element nodal locations
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getStrain( TacsScalar strain[],
const double pt[],
const TacsScalar Xpts[],
const TacsScalar vars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain at the tying points
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
if (stiff->getTransformType() == FSDTStiffness::NATURAL ){
compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_strain<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
knots, pknots, vars, Xpts);
}
TacsScalar rot;
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Rotation matrix data
TacsScalar C[9], Ct[27];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_lr_tying_strain<order, tying_order>(g11, g22, g12, g23, g13,
knots, pknots, vars, Xpts);
large_rot_bend_strain(strain, U, Ud, C, Ct, t, tx, ztx,
normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
}
/*
Compute the strain and the derivative of the strain with respect to
the nodal locations.
output:
strain: the strain evaluate at the pamametric point pt
strainXptSens: the derivative of the strain w.r.t. the nodal locations
input:
pt: the parametric point within the element
vars: the element variables
Xpts: the nodal locations
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addStrainXptSens( TacsScalar fXptSens[],
const double pt[],
const TacsScalar scale,
const TacsScalar strainSens[],
const TacsScalar Xpts[],
const TacsScalar vars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
TacsScalar dnormal[9*NUM_NODES], dnormal_xi[9*NUM_NODES],
dnormal_eta[9*NUM_NODES];
// The derivative of the determinant of the Jacobian and the
// sensitivity of the drilling rotation
TacsScalar dh[3*NUM_NODES], srot[3*NUM_NODES];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar dt[27*NUM_NODES], dtx[27*NUM_NODES], dztx[27*NUM_NODES];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial strain components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the tensorial tying strain components
TacsScalar dg11[3*NUM_G11*NUM_NODES], dg22[3*NUM_G22*NUM_NODES],
dg12[3*NUM_G12*NUM_NODES];
TacsScalar dg13[3*NUM_G13*NUM_NODES], dg23[3*NUM_G23*NUM_NODES];
// The strain and the derivative of the strain w.r.t. nodes
TacsScalar strain[NUM_STRESSES];
TacsScalar strainXptSens[3*NUM_STRESSES*NUM_NODES];
// Zero out the strain sensitivity
memset(strainXptSens, 0, 3*NUM_STRESSES*NUM_NODES*sizeof(TacsScalar));
// Evaluate the tying interpolation
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
// Evaluate the displacements and their derivatives
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
compute_transform_sens(dh, t, dt, tx, dtx, ztx, dztx,
normal, dnormal,
normal_xi, dnormal_xi,
normal_eta, dnormal_eta,
Xd, Xdd, Na, Nb, Naa, Nab, Nbb, NUM_NODES);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
compute_transform_refaxis_sens(dh, t, dt, tx, dtx, ztx, dztx,
normal, dnormal,
normal_xi, dnormal_xi,
normal_eta, dnormal_eta, axis,
Xd, Xdd, Na, Nb, Naa, Nab, Nbb, NUM_NODES);
}
if (type == LARGE_ROTATION){
// Rotation matrix data
TacsScalar C[9], Ct[27];
// Evaluate the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_lr_tying_strain_sens<order, tying_order>(g11, g22, g12, g23, g13,
dg11, dg22, dg12, dg23, dg13,
knots, pknots, vars, Xpts);
large_rot_bend_strain_sens(strain, strainXptSens,
U, Ud, C, Ct, t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi, dnormal_xi,
normal_eta, dnormal_eta, 3*NUM_NODES);
}
else {
compute_tying_strain_sens<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
dg11, dg22, dg12, dg23, dg13,
knots, pknots, vars, Xpts);
TacsScalar rot;
if (type == LINEAR){
linear_bend_strain_sens(strain, strainXptSens,
&rot, srot, U, Ud,
t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi, dnormal_xi,
normal_eta, dnormal_eta, 3*NUM_NODES);
}
else {
nonlinear_bend_strain_sens(strain, strainXptSens,
&rot, srot, U, Ud,
t, dt, tx, dtx, ztx, dztx,
normal, dnormal, normal_xi, dnormal_xi,
normal_eta, dnormal_eta, 3*NUM_NODES);
}
}
// Evaluate the strain interpolation at this point
add_tying_strain_sens<tying_order>(strain, strainXptSens, tx, dtx,
g11, g22, g12, g23, g13,
dg11, dg22, dg12, dg23, dg13,
N11, N22, N12);
// Add the product of the input sensitivity and the derivative of the
// strain w.r.t. the node locations to the input vector
TacsScalar *s = strainXptSens;
for ( int i = 0; i < 3*NUM_NODES; i++ ){
for ( int j = 0; j < NUM_STRESSES; j++, s++ ){
fXptSens[i] += scale*s[0]*strainSens[j];
}
}
}
/*
Compute the derivative of the point-wise strain with respect to the
element variables, multiply the derivative by a strain sensitivity
vector and add the result, times a scalar multiple, to the outputt
array. This can be used to evaluate the derivative of functions of
the strain with respect to the state variables using the chain rule.
output:
elementSens: the output array - same length as the number of elem variables
input:
pt: parametric point used to evaluate the derivative [-1, 1]^{2}
strainSens: the sensitivity of each strain component
vars: the element variables
Xpts: the element nodal locations
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addStrainSVSens( TacsScalar strainSVSens[],
const double pt[],
const TacsScalar scale,
const TacsScalar strainSens[],
const TacsScalar Xpts[],
const TacsScalar vars[] ){
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The tensorial components of the strain
TacsScalar g11[NUM_G11], g22[NUM_G22];
TacsScalar g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
TacsScalar dinplane_rot[NUM_VARIABLES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
if (stiff->getTransformType() == FSDTStiffness::NATURAL ){
compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
if (type == LARGE_ROTATION){
// Rotational matrix data
TacsScalar C[9], Ct[27], Ctt[54];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
compute_2nd_rate_matrix(Ctt, c1, s1, c2, s2, c3, s3);
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
large_rot_bend_bmat(B, NUM_NODES, N, Na, Nb, U, Ud, C, Ct, Ctt,
t, tx, ztx, normal, normal_xi, normal_eta);
}
else {
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
if (type == LINEAR){
linear_bend_bmat(B, dinplane_rot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
nonlinear_bend_bmat(B, dinplane_rot, NUM_NODES,
N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
}
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
for ( int k = 0; k < NUM_VARIABLES; k++ ){
strainSVSens[k] += scale*strain_product(strainSens, &B[k*NUM_STRESSES]);
}
}
/*
Get the partition of unity shape functions and their derivatives
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getPartUnityShapeFunctions( const double pt[],
double N[],
double Na[],
double Nb[] ){
N[0] = 0.25*(1.0 - pt[0])*(1.0 - pt[1]);
N[1] = 0.25*(1.0 + pt[0])*(1.0 - pt[1]);
N[2] = 0.25*(1.0 - pt[0])*(1.0 + pt[1]);
N[3] = 0.25*(1.0 + pt[0])*(1.0 + pt[1]);
Na[0] =-0.25*(1.0 - pt[1]);
Na[1] = 0.25*(1.0 - pt[1]);
Na[2] =-0.25*(1.0 + pt[1]);
Na[3] = 0.25*(1.0 + pt[1]);
Nb[0] =-0.25*(1.0 - pt[0]);
Nb[1] =-0.25*(1.0 + pt[0]);
Nb[2] = 0.25*(1.0 - pt[0]);
Nb[3] = 0.25*(1.0 + pt[0]);
}
/*
Add the localized error term to the input.
This localization is based on a partition of unity constraint that
distributes the error to nodes.
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addLocalizedError( double time, TacsScalar err[],
const TacsScalar adjoint[],
const TacsScalar Xpts[],
const TacsScalar vars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The derivatives of the displacement strain
TacsScalar b11[3*NUM_NODES*NUM_G11], b22[3*NUM_NODES*NUM_G22];
TacsScalar b12[3*NUM_NODES*NUM_G12];
TacsScalar b13[NUM_VARIABLES*NUM_G13], b23[NUM_VARIABLES*NUM_G23];
// The strain an rotation matrices
TacsScalar strain[NUM_STRESSES], stress[NUM_STRESSES];
TacsScalar drot[NUM_VARIABLES];
TacsScalar B[NUM_STRESSES*NUM_VARIABLES];
// Determine the knots/pknots from the lower-order element
const double *low_knots = NULL;
const double *low_pknots = NULL;
if (tying_order == 3){
low_knots = MITCShellFirstOrderKnots;
}
else {
FElibrary::getGaussPtsWts(tying_order-1, &low_knots, NULL);
}
FElibrary::getGaussPtsWts(tying_order-2, &low_pknots, NULL);
// Evaluate the strain/bmatrix at the tying points
if (type == LARGE_ROTATION){
compute_lr_tying_bmat<order, tying_order>(g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
compute_lr_tying_strain<order, tying_order-1>(g11, g22, g12, g23, g13,
low_knots, low_pknots,
vars, Xpts);
}
else {
// Compute the B-mat contribution from the full residual
compute_tying_bmat<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
b11, b22, b12, b23, b13,
knots, pknots, vars, Xpts);
if (order == 3 && tying_order == 3){
TacsScalar Xpts2nd[12], vars2nd[24];
for ( int j = 0; j < 2; j++ ){
for ( int i = 0; i < 2; i++ ){
for ( int k = 0; k < 3; k++ ){
Xpts2nd[3*(i + 2*j)+k] = Xpts[3*(2*i + 6*j)+k];
}
for ( int k = 0; k < 6; k++ ){
vars2nd[6*(i + 2*j)+k] = vars[6*(2*i + 6*j)+k];
}
}
}
// Compute the strain contribution from the lower-order element
compute_tying_strain<order-1, tying_order-1>((type == LINEAR),
g11, g22, g12, g23, g13,
low_knots, low_pknots,
vars2nd, Xpts2nd);
}
else {
// Compute the strain contribution from the lower-order element
compute_tying_strain<order, tying_order-1>((type == LINEAR),
g11, g22, g12, g23, g13,
low_knots, low_pknots,
vars, Xpts);
}
}
// Perform the integration over a larger domain
const double *pts, *wts;
int npts = FElibrary::getGaussPtsWts(order, &pts, &wts);
for ( int m = 0; m < npts; m++ ){
for ( int n = 0; n < npts; n++ ){
// Set the quadrature point
double pt[2];
pt[0] = pts[n];
pt[1] = pts[m];
// Evaluate the stiffness at the parametric point within the
// element
TacsScalar At[6], Bt[6], Dt[6], Ats[3];
TacsScalar kpenalty = stiff->getStiffness(pt, At, Bt, Dt, Ats);
// Calculate the shape functions and the Jacobian/Hessian of the
// shell position at the quadrature point
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
// Compute the transformation from the global coordinates to
// local shell coordinates
TacsScalar h = 0.0;
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
h = compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
h = compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
h = wts[n]*wts[m]*h;
// Compute the strain and rotation at the qudrature point
TacsScalar rot = 0.0;
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
linear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud,
t, tx, ztx,
normal, normal_xi, normal_eta);
nonlinear_bend_bmat(B, drot, NUM_NODES,
N, Na, Nb, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Rotation matrix data
TacsScalar C[9], Ct[27];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
// Calculate the deformation at the current point...
large_rot_bend_strain(strain, U, Ud, C, Ct, t, tx, ztx,
normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_bmat<tying_order>(B, NUM_NODES, tx,
b11, b22, b12, b23, b13,
N11, N22, N12);
// Evaluate the strain interpolation using the lower-order
// element tying points
tying_interpolation<tying_order-1>(pt, N11, N22, N12,
low_knots, low_pknots);
add_tying_strain<tying_order-1>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
// Compute the stress at the current Gauss point
stiff->calculateStress(At, Bt, Dt, Ats, strain, stress);
const TacsScalar *adj = adjoint;
const TacsScalar *b = B;
const TacsScalar *br = drot;
// Compute the local product of the stress/strain
TacsScalar product = 0.0;
for ( int i = 0; i < NUM_NODES; i++ ){
for ( int ii = 0; ii < NUM_DISPS; ii++ ){
product += adj[ii]*h*(strain_product(b, stress) + kpenalty*rot*br[0]);
b += NUM_STRESSES;
br++;
}
adj += NUM_DISPS;
}
// Evaluate the partition of unity constraint
double Np[4], Npa[4], Npb[4];
getPartUnityShapeFunctions(pt, Np, Npa, Npb);
for ( int node = 0; node < 4; node++ ){
// Add the result to the localized error
err[(node % 2)*(order-1) +
(node/2)*order*(order-1)] += Np[node]*product;
}
}
}
}
/*
Determine the number of nodes and elements for visualization
generated by the data in this element. Note that higher-order
elements are broken down into bi-linear elements for visualization.
output:
nelems: the number of visualization elements
nnodes: the number of nodes used for visualization
ncsr: the number of entries in a CSR-type data structure used
to store the connectivity
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::addOutputCount( int * nelems,
int * nnodes, int * ncsr ){
*nelems += (order-1)*(order-1);
*nnodes += order*order;
*ncsr += 4*(order-1)*(order-1);
}
/*
Get the output data from this element and place it in a real
array for visualization later. The values generated for visualization
are determined by a bit-wise selection variable 'out_type' which is
can be used to simultaneously write out different data. Note that this
is why the bitwise operation & is used below.
The output may consist of the following:
- the nodal locations
- the displacements and rotations
- the strains or strains within the element
- extra variables that are used for optimization
output:
data: the data to write to the file (eventually)
input:
out_type: the bit-wise variable used to specify what data to generate
vars: the element variables
Xpts: the element nodal locations
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getOutputData( unsigned int out_type,
double * data, int ld_data,
const TacsScalar Xpts[],
const TacsScalar vars[] ){
// Geometric data
TacsScalar X[3], Xd[9], Xdd[9];
TacsScalar normal[3], normal_xi[3], normal_eta[3];
// Transformation and the transformation derivative w.r.t. zeta
TacsScalar t[9], tx[9], ztx[9];
TacsScalar U[NUM_DISPS], Ud[2*NUM_DISPS];
double N[NUM_NODES], Na[NUM_NODES], Nb[NUM_NODES];
double Naa[NUM_NODES], Nab[NUM_NODES], Nbb[NUM_NODES];
// Interpolations for the shear components
double N11[NUM_G11], N22[NUM_G22], N12[NUM_G12];
// The interpolated tensorial shear components
TacsScalar g11[NUM_G11], g22[NUM_G22], g12[NUM_G12];
TacsScalar g13[NUM_G13], g23[NUM_G23];
// The stress and strain values
TacsScalar stress[NUM_STRESSES], strain[NUM_STRESSES];
if (type == LARGE_ROTATION){
compute_lr_tying_strain<order, tying_order>(g11, g22, g12, g23, g13,
knots, pknots, vars, Xpts);
}
else {
compute_tying_strain<order, tying_order>((type == LINEAR),
g11, g22, g12, g23, g13,
knots, pknots, vars, Xpts);
}
for ( int m = 0; m < order; m++ ){
for ( int n = 0; n < order; n++ ){
double pt[2];
pt[0] = -1.0 + 2.0/(order - 1.0 )*n;
pt[1] = -1.0 + 2.0/(order - 1.0 )*m;
// Calculate the shape functions
shell_hessian(order, X, Xd, Xdd,
N, Na, Nb, Naa, Nab, Nbb,
pt, Xpts);
compute_shell_Ud(NUM_NODES, U, Ud, vars, N, Na, Nb);
if (stiff->getTransformType() == FSDTStiffness::NATURAL){
compute_transform(t, tx, ztx, normal, normal_xi, normal_eta,
Xd, Xdd);
}
else {
const TacsScalar * axis = stiff->getRefAxis();
compute_transform_refaxis(t, tx, ztx, normal, normal_xi,
normal_eta, axis, Xd, Xdd);
}
// Evaluate the strain
TacsScalar rot;
if (type == LINEAR){
linear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else if (type == NONLINEAR){
nonlinear_bend_strain(strain, &rot, U, Ud, t, tx, ztx,
normal, normal_xi, normal_eta);
}
else {
// Rotational matrix data
TacsScalar C[9], Ct[27];
// Compute the rotation matrices
TacsScalar c1 = cos(U[3]), s1 = sin(U[3]);
TacsScalar c2 = cos(U[4]), s2 = sin(U[4]);
TacsScalar c3 = cos(U[5]), s3 = sin(U[5]);
compute_rate_matrix(C, Ct, c1, s1, c2, s2, c3, s3);
// Evaluate the strain
large_rot_bend_strain(strain, U, Ud, C, Ct, t, tx, ztx,
normal, normal_xi, normal_eta);
}
// Evaluate the strain interpolation at this point
tying_interpolation<tying_order>(pt, N11, N22, N12,
knots, pknots);
add_tying_strain<tying_order>(strain, tx,
g11, g22, g12, g23, g13,
N11, N22, N12);
int index = 0;
int p = n + m*order;
if (out_type & TACSElement::OUTPUT_NODES){
for ( int k = 0; k < 3; k++ ){
data[index+k] = TacsRealPart(Xpts[3*p+k]);
}
index += 3;
}
if (out_type & TACSElement::OUTPUT_DISPLACEMENTS){
for ( int k = 0; k < NUM_DISPS; k++ ){
data[index+k] = TacsRealPart(vars[NUM_DISPS*p+k]);
}
index += NUM_DISPS;
}
if (out_type & TACSElement::OUTPUT_STRAINS){
for ( int k = 0; k < NUM_STRESSES; k++ ){
data[index+k] = TacsRealPart(strain[k]);
}
index += NUM_STRESSES;
}
if (out_type & TACSElement::OUTPUT_STRESSES){
// Evaluate the stiffness at the current point
// and then calculate the stress
stiff->calculateStress(pt, strain, stress);
for ( int k = 0; k < NUM_STRESSES; k++ ){
data[index+k] = TacsRealPart(stress[k]);
}
index += NUM_STRESSES;
}
if (out_type & TACSElement::OUTPUT_EXTRAS){
// Compute the failure value
TacsScalar lambda;
stiff->failure(pt, strain, &lambda);
data[index] = TacsRealPart(lambda);
// Compute the buckling constraint value
TacsScalar bval;
stiff->buckling(strain, &bval);
data[index+1] = TacsRealPart(bval);
data[index+2] = TacsRealPart(stiff->getDVOutputValue(0, pt));
data[index+3] = TacsRealPart(stiff->getDVOutputValue(1, pt));
index += NUM_EXTRAS;
}
if (out_type & TACSElement::OUTPUT_COORDINATES){
// t is the transform from the global coordinates to the
// local coordinates.
for ( int i = 0; i < 3; i++ ){
for ( int j = 0; j < 3; j++ ){
data[index + 3*i + j] = TacsRealPart(t[3*i + j]);
}
}
index += 9;
}
data += ld_data;
}
}
}
/*
Get the element connectivity for visualization purposes. Since each
element consists of a series of sub-elements used for visualization,
we also need the connectivity of these visualization elements.
output:
con: the connectivity of the local visualization elements contributed
by this finite-element
input:
node: the node offset number - so that this connectivity is more or
less global
*/
template <int order, int tying_order>
void MITCShell<order, tying_order>::getOutputConnectivity( int * con, int node ){
int p = 0;
for ( int m = 0; m < order-1; m++ ){
for ( int n = 0; n < order-1; n++ ){
con[4*p] = node + n + m*order;
con[4*p+1] = node + n+1 + m*order;
con[4*p+2] = node + n+1 + (m+1)*order;
con[4*p+3] = node + n + (m+1)*order;
p++;
}
}
}
#endif
|
3df074fd23521d19e5452f33cd865315530248ff
|
2fbf96bb69f954dbf6bbf13661b0492de9b3b4b1
|
/uva/uva10931.cpp
|
9b2c025d48bc7017fc6a2f434bdedd381b5ec494
|
[] |
no_license
|
timothywangdev/Programming-Contests
|
432d0e6719cf2c910d24416dfacb46abb046a735
|
dcd58694bd66536222f2ffd78b025af5a38aab4f
|
refs/heads/master
| 2023-08-02T06:57:22.724822
| 2021-10-08T19:06:32
| 2021-10-08T19:06:32
| 16,039,238
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 475
|
cpp
|
uva10931.cpp
|
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
unsigned long long N;
int main(){
while(cin>>N){
if(!N)break;
bitset<32> b(N);
string s=b.to_string();
int counter=0;
int index=-1;
for(int i=0;i<s.size();i++){
counter+=(s[i]=='1');
if(s[i]=='1'&&index==-1){
index=i;
}
}
s=s.substr(index,s.length()-index);
cout<<"The parity of "<<s<<" is "<<counter<<" (mod 2)."<<endl;
}
return 0;
}
|
e105920da15bb697ff07b96e731dffab7af83806
|
cddab5f9563b09fced009ea893f29dd4578cced7
|
/scene/scenenode.h
|
ea6eeafafbd94a97da6322979d2ad5f3ef3323cb
|
[] |
no_license
|
chunsen-ok/SoftwareRenderer
|
41544f7d3a7f08d708a6bf1ec4d964b40c448c85
|
0d43f7a8ccbd07c84a48922b28edc323436fd9c9
|
refs/heads/master
| 2021-10-22T04:52:22.907512
| 2019-03-08T08:40:00
| 2019-03-08T08:40:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 607
|
h
|
scenenode.h
|
#ifndef SCENENODE_H
#define SCENENODE_H
#include "math/vector.h"
#include "math/matrix.h"
#include <vector>
class SceneNode
{
public:
SceneNode(const std::vector<Point2D> &shape, SceneNode *parent=nullptr);
~SceneNode();
void addChild(SceneNode *child);
Transform2D &transform() { return mTransform; }
Point2D transformedData(size_t i) const;
const std::vector<Point2D> &data() const { return mShape; }
private:
SceneNode *mParent{nullptr};
std::vector<SceneNode*> mChildren;
Transform2D mTransform;
std::vector<Point2D> mShape;
};
#endif // SCENENODE_H
|
a944f5cc5c94715e9dc12be375cefcbc98fc3350
|
cc6fdf2faf12f8a610422e07b30b0cd0f1b81cb7
|
/jabber_connection.cpp
|
619b94b761016e02813e0d0a4bedc799e109c019
|
[] |
no_license
|
tomasdubec/lekuba
|
f5c72fddebd1fefe07c0575c2e26326a62678cf5
|
abc7894e5aced7ec56a96fc4168aec0b6f8dc653
|
refs/heads/master
| 2021-01-01T19:38:42.147715
| 2007-10-20T22:22:01
| 2007-10-20T22:22:01
| 37,517,442
| 0
| 0
| null | 2015-06-19T07:58:11
| 2015-06-16T08:21:14
|
C++
|
UTF-8
|
C++
| false
| false
| 19,242
|
cpp
|
jabber_connection.cpp
|
#include "jabber_connection.h"
#include <string>
#include <signal.h>
//#include <mhash.h>
#include <ctime>
#include <string.h>
#include <openssl/md5.h>
void jabberConnection::debugPrint(string txt){
#ifdef _DEBUG_
cerr << txt << endl;
#endif
}
string jabberConnection::base64encode(string text){
int a=0, delka=text.length(), i=0, vyslDelka = (text.length() / 3) * 4 + 1;
char ret[vyslDelka];
string *rets, retst;
char base64table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
memset(ret, '\0', vyslDelka);
for(;delka>2;delka-=3){
ret[i++] = base64table[(text[a] >> 2)];
ret[i++] = base64table[((text[a] << 4) & 0x30) | (text[a+1] >> 4)];
ret[i++] = base64table[((text[a+1] & 0x0f) << 2) | (text[a+2] >> 6)];
ret[i++] = base64table[(text[a+2] & 0x3f)];
a += 3;
}
switch(delka){
case 2: ret[i++] = base64table[(text[a] >> 2) & 0x3f];
ret[i++] = base64table[((text[a] << 4) & 0x30) | (text[a+1] >> 4)];
ret[i++] = base64table[(text[a+1] << 2) & 0x3c];
ret[i++] = '=';
break;
case 1: ret[i++] = base64table[(text[a] >> 2) & 0x3f];
ret[i++] = base64table[(text[a] << 4) & 0x30];
ret[i++] = '=';
ret[i++] = '=';
break;
}
ret[i]='\0';
//rets = new string(ret);
retst = ret;
return retst;
//return *rets;
}
string jabberConnection::base64decode(string co){
int a=0, delka, i=0;
string buf, ret;
ret = co+co;
delka = co.length();
for(a=0;a<co.length();a++){
if(co[a] >= 'A' && co[a] <= 'Z'){
co[a] = co[a] - 'A';
continue;
}
if(co[a] >= 'a' && co[a] <= 'z'){
co[a] = co[a] - 'a' + 26;
continue;
}
if(co[a] >= '0' && co[a] <= '9'){
co[a] = co[a] - '0' + 52;
continue;
}
if(co[a] == '/'){
co[a] = 63;
continue;
}
if(co[a] == '+'){
co[a] = 62;
continue;
}
if(co[a] == '='){
co[a] = 0;
continue;
}
}
for(a=0;delka>=4;delka-=4){
ret[i++] = (co[a] << 2) | (co[a+1] >> 4);
ret[i++] = (co[a+1] << 4) | (co[a+2] >> 2);
ret[i++] = (co[a+2] << 6) | (co[a+3] & 0x3f);
a+=4;
}
ret = ret.substr(0,i);
ret = ret.substr(0,ret.find_first_of('\0')); //they may be some zeros on the end (remains after those equals)
return ret;
}
/*
void jabberConnection::startReadThread(void){
pthread_attr_t attr;
debugPrint("\nStarting new thread\n");
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&readThread, &attr, readStanza, (void *)this);
if(!readThread)
debugPrint("error creating thread");
}
void jabberConnection::thrTerm(int signal){
//debugPrint("************* vlakno konci ****************");
exit(0);
}
void *jabberConnection::readStanza(void *th){
jabberConnection *t = (jabberConnection *)th;
string buffer;
rcvStanzaIter iter;
rcvStanza_ tmp;
xmlParserWrap xmlPar;
signal(SIGTERM, t->thrTerm);
#ifdef _DEBUG_
cout << "************* vlakno se hlasi do sluzby ****************\n";
#endif
while(true){
t->con >> buffer;
if(xmlPar.parse(buffer)){ //ignore anything that's no parseable
switch(xmlPar.getType()){
case MESSAGE:
tmp.from = xmlPar.getArg("from");
tmp.to = xmlPar.getArg("to");
tmp.id = xmlPar.getArg("id");
tmp.type = xmlPar.getArg("type");
tmp.data = xmlPar.getContent();
t->inStanza.push_back(tmp);
break;
case ROSTER_IQ:
tmp.from = xmlPar.getArg("from");
tmp.to = xmlPar.getArg("to");
tmp.id = xmlPar.getArg("id");
tmp.type = xmlPar.getArg("type");
tmp.data = buffer;
t->inStanza.push_back(tmp);
break;
}
}
}
}
*/
string jabberConnection::genA1hex(string nonce, string cnonce, string authzid, string realm){
unsigned char buf[16];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, username.c_str(), username.length());
MD5_Update(&context, ":", 1);
if(realm != "") MD5_Update(&context, realm.c_str(), realm.length());
MD5_Update(&context, ":", 1);
MD5_Update(&context, password.c_str(), password.length());
MD5_Final(buf, &context); //hash(username::password)
MD5_Init(&context);
MD5_Update(&context, buf, 16);
MD5_Update(&context, ":", 1);
MD5_Update(&context, nonce.c_str(), nonce.length());
MD5_Update(&context, ":", 1);
MD5_Update(&context, cnonce.c_str(), cnonce.length());
if(authzid != ""){
MD5_Update(&context, ":", 1);
MD5_Update(&context, authzid.c_str(), authzid.length());
}
MD5_Final(buf, &context); //hash(hash(username::password):nonce:cnonce:authzid) == A1
return hex(buf, 16);
}
string jabberConnection::genA2hex(string qop){
unsigned char buf[16];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, "AUTHENTICATE:xmpp/", 18);
MD5_Update(&context, server.c_str(), server.length());
if(qop == "auth-conf" || qop == "auth-int")
MD5_Update(&context, ":00000000000000000000000000000000", 33);
MD5_Final(buf, &context); //hash(AUTHENTICATE:xmpp/server)
return hex(buf, 16);
}
string jabberConnection::genA2Shex(string qop){
unsigned char buf[16];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, ":xmpp/", 6);
MD5_Update(&context, server.c_str(), server.length());
if(qop == "auth-conf" || qop == "auth-int")
MD5_Update(&context, ":00000000000000000000000000000000", 33);
MD5_Final(buf, &context); //hash(AUTHENTICATE:xmpp/server)
return hex(buf, 16);
}
string jabberConnection::genResponseHex(string nonce, string cnonce, string qop, string A1, string A2){
unsigned char buf[16];
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, A1.c_str(), A1.length());
MD5_Update(&context, ":", 1);
MD5_Update(&context, nonce.c_str(), nonce.length());
MD5_Update(&context, ":", 1);
MD5_Update(&context, "00000001", 8);
MD5_Update(&context, ":", 1);
MD5_Update(&context, cnonce.c_str(), cnonce.length());
MD5_Update(&context, ":", 1);
MD5_Update(&context, qop.c_str(), qop.length());
MD5_Update(&context, ":", 1);
MD5_Update(&context, A2.c_str(), A2.length());
MD5_Final(buf, &context); //response
return hex(buf, 16);
}
string jabberConnection::hex(unsigned char *in, int delka){
int i, h, l;
string sout;
unsigned char *out;
out = (unsigned char *)malloc(2 * delka * sizeof(unsigned char *) + 1);
for(i = 0; i < delka; i++) {
h = in[i] & 0xf0;
h >>= 4;
l = in[i] & 0x0f;
out[i * 2] = (h >= 0x0 && h <= 0x9) ? (h + 0x30) : (h + 0x57);
out[i * 2 + 1] = (l >= 0x0 && l <= 0x9) ? (l + 0x30) : (l + 0x57);
}
out[i * 2] = '\0';
sout = (char *)out;
free(out);
return sout;
}
string jabberConnection::parseDigest(string digest, string prop){
string tmp,firstHalf, secondHalf;
int index=0, newindex=0;
digest = digest.substr(0,digest.length())+","; //libxml adds two zero chars at the end
while(index != -1){
if(index == 0) index--; //that's just for the first iteration.
newindex = digest.find_first_of(',', ++index);
tmp = digest.substr(index, newindex-index); // in tmp we now have something like property=value or property="value" or proprty='value'
//is the first part the property we are looking for?
firstHalf = tmp.substr(0, tmp.find_first_of('='));
if(firstHalf == prop){
//if it is what we are looking for, read the actual value and remove qotes
secondHalf = tmp.substr(tmp.find_first_of('=')+1, tmp.length());
if(secondHalf[0] == '"'){
secondHalf = secondHalf.substr(1, secondHalf.length()-2);
}
else if(secondHalf[0] == '\''){
secondHalf = secondHalf.substr(1, secondHalf.length()-2);
}
return secondHalf;
}
else{
index = newindex;
}
}
return "";
}
bool jabberConnection::doSASLMD5(void){
string chal, tmp;
xmlParserWrap xmlPar;
char buf[6]="00000";
con << xmlStanza::xmlSASLauth("DIGEST-MD5");
try{
con >> tmp;
}
catch(string e){
cout << e << endl;
exit(1);
}
xmlPar.parse(tmp);
if(xmlPar.getType() == CHALLENGE){
try{
chal = xmlPar.getContent();
chal = base64decode(chal);
}
catch(const char* e){
cerr << "xmlStanza error: " << e << endl;
}
//generate our cnonce
srand((unsigned)time(0));
int rint = rand()%25;
string cnonce;
for(int q=0;q<25;q++){
cnonce += ('a'+rint);
rint = rand()%25;
}
cnonce = hex((unsigned char *)cnonce.c_str(), cnonce.length());
cnonce = cnonce.substr(0,48); //RFC suggests 64 bits of entropy, so we're way better than that
string nonce = parseDigest(chal, "nonce");
string authzid = parseDigest(chal, "authzid");
string realm = parseDigest(chal, "realm");
string qop = parseDigest(chal, "qop");
//cout << parseDigest(chal, "algorithm") << ", " << parseDigest(chal, "algorithm").length() << endl;
string A1 = genA1hex(nonce, cnonce, authzid, realm);
string A2 = genA2hex(qop);
string response = genResponseHex(nonce, cnonce, qop, A1, A2);
string resp = "charset=utf-8,username=\""+username+"\"";
if(realm != "") resp += ",realm=\""+realm+"\"";
resp += ",nonce=\""+nonce+"\",nc=00000001,cnonce=\""+cnonce+"\",digest-uri=\"xmpp/"+server+"\",response="+response+",qop="+qop;
con << xmlStanza::xmlSASLresponse(base64encode(resp));
con >> tmp;
//expecting another challenge or failure
xmlPar.parse(tmp);
if(xmlPar.getType() == CHALLENGE){
chal = xmlPar.getContent();
chal = base64decode(chal);
A2 = genA2Shex(qop);
//cout << "\n'" << response.length() << "'\n'" << resp.length() << "'" << endl;
if(parseDigest(chal, "rspauth") != genResponseHex(nonce, cnonce, qop, A1, A2)){
//uh-oh, what the ...
debugPrint("SASL authentication failed: wrong rspauth");
return false;
}
con << xmlStanza::xmlSASLresponse("");
con >> tmp;
xmlPar.parse(tmp);
if(xmlPar.getType() != SASL_SUCCESS){
debugPrint("SASL authentication failed after second response");
return false;
}
return true;
}
else if(xmlPar.getType() == SASL_FAILURE){
cerr << "SASL authentication failed with error: "+xmlPar.getSASLError() << endl;
return false;
}
else{
debugPrint("SASL authentication failed, unexpected xml received:\t\n"+chal);
return false;
}
}
return true;
}
bool jabberConnection::doSASLPLAIN(void){
string tmp;
xmlParserWrap xmlPar;
unsigned char *in, *out;
int in_len, out_len;
tmp = '\0' + username + '\0' + password;
/*cout << tmp << endl;
in_len = tmp.size() + 1;
out_len = in_len * 2;
in = (unsigned char *)malloc(tmp.size() * sizeof(unsigned char));
strncpy((char *)in, tmp.c_str(), in_len);
in[in_len] = 0;
out = (unsigned char *)malloc(out_len * sizeof(unsigned char));
fprintf(stdout, "iso: %s\n", in);
if(isolat1ToUTF8(out, &out_len, in, &in_len) > 0){
out[out_len] = 0;
fprintf(stdout, "utf8: %s\nin_len: %i, out_len: %i\n", out, in_len, out_len);
}
else
cerr << "error converting to utf8\n";
tmp = (char *)out;
cout << "tmp: " << tmp << endl;
exit(1);*/
con << xmlStanza::xmlSASLauthPLAIN(base64encode(tmp));
try{
con >> tmp;
}
catch(string e){
cerr << e << endl;
exit(1);
}
xmlPar.parse(tmp);
if(xmlPar.getType() != SASL_SUCCESS){
debugPrint("SASL PLAIN authentication failed. Wrong password?");
return false;
}
return true;
}
/******************** public ************************/
jabberConnection::jabberConnection(string newjid, string pass, string srvr, int prt, bool tls){
int atpos, slashpos;
string host;
stat = OFFLINE;
stav = S_OFF;
atpos = newjid.find_last_of('@');
slashpos = newjid.find_first_of('/');
username = newjid.substr(0, atpos);
useTls = tls;
if(slashpos != string::npos){
server = newjid.substr(atpos+1, slashpos - atpos-1);
resource = newjid.substr(slashpos+1);
}
else
server = newjid.substr(atpos+1);
/* if(srvr == "no server")
host = server;
else*/
if(srvr == "talk.google.com"){
server = newjid.substr(newjid.find_first_of('@') + 1, newjid.find_last_of('@') - newjid.find_first_of('@') - 1);
}
password = pass;
con.setHost(srvr);
// con.setHost(host);
con.setPort(prt);
#ifdef _DEBUG_
cout << "parsed JID:\n\tusername:\t" << username << endl;
cout << "\tpassword:\t" << password << endl;
cout << "\tserver:\t\t" << server << endl;
cout << "\tresource:\t" << resource << endl << endl;
#endif
thr = NULL;
}
jabberConnection::~jabberConnection(void){
if(thr)
delete thr;
logout(NONE);
}
void jabberConnection::setJID(string newjid){
//jid = newjid;
}
void jabberConnection::setPassword(string newpass){
password = newpass;
}
/*
* returns number indicating result of registration:
* -1 - error not connected with registration proccess (e.g. could not connect)
* 0 - registration successful
* 1 - conflict - username already registered
* 2 - not-acceptable - not all mandatory values were filled, IM _should_ require only username and password
* 3 - service-unavailable - registration is not supported by this server
*/
int jabberConnection::registerNewAccount(void){
string tmp, id;
xmlParserWrap xmlPar;
if(!con.cnct()){
return -1;
}
//send the opening stream tag
//con << xmlStanza::xmlStream(con.getHost());
con << xmlStanza::xmlStream(server);
con >> tmp; //wait for answer
//some servers don't advertise their ability to register new accounts eventhough they support it => dont parse answer and assume register is supported
con << xmlStanza::xmlIqRegister(username, password, id);
con >> tmp; //wait for answer
xmlPar.parse(tmp);
//if we didnt get the answer to our iq, wait for it..
while(xmlPar.getArg("id") != id){
sleep(1);
con >> tmp; //wait for answer
xmlPar.parse(tmp);
}
if(xmlPar.hasSubTag("error")){
if(xmlPar.getErrorString() == "bad-request")
return -1;
else if(xmlPar.getErrorString() == "conflict")
return 1;
else if(xmlPar.getErrorString() == "not-acceptable")
return 2;
else if(xmlPar.getErrorString() == "service-unavailable")
return 3;
else
return -1;
}
else{
return 0;
}
}
int jabberConnection::changePassword(void){
string id;
rcvStanza_ st;
xmlParserWrap xmlPar;
string jid;
jid = username+"@"+server+"/"+resource;
con << xmlStanza::xmlIqChangePassword(jid, username, password, id);
while(!thr->getStanzaById(atoi(id.c_str()), st)) sleep(1);
if(!xmlPar.parse(st.data))
return -1;
if(xmlPar.hasSubTag("error")){
if(xmlPar.getErrorString() == "bad-request")
return -1;
else if(xmlPar.getErrorString() == "conflict")
return 1;
else if(xmlPar.getErrorString() == "not-acceptable")
return 2;
else if(xmlPar.getErrorString() == "service-unavailable")
return 3;
else
return -1;
}
else{
return 0;
}
}
bool jabberConnection::login(void){
string tmp, id;
int a=0;
xmlParserWrap xmlPar;
//connect to server
if(!con.cnct()){
cerr << "unable to connect to " << con.getHost() << ": " << con.getError() << endl;
return false;
}
//send the opening stream tag
con << xmlStanza::xmlStream(server);
con >> tmp; //wait for answer
//now we parse the <stream:stream> tag, i want to use libxml, so i must add closing tag for <stream:stream>
tmp += "</stream:stream>";
if(!xmlPar.parse(tmp)){
debugPrint("jabber login failed: "+xmlPar.getError());
logout(NOT_WELL_FORMED);
return false;
}
//we expect stream tag, so, anything else is wrong and we stop talking to server
if(xmlPar.getType() != STREAM){
debugPrint("jabber login failed: unexpected xml");
logout(INVALID);
return false;
}
id = xmlPar.getArg("id");
//we are expecting features tag*/
if(xmlPar.getType() != FEATURES){
//perhaps we did not managed to catch it yet
con >> tmp;
if(!xmlPar.parse(tmp)){
debugPrint("jabber login failed: "+xmlPar.getError());
logout(INVALID);
return false;
}
if(xmlPar.getType() != FEATURES){
debugPrint("jabber login failed: unexpected xml (features expected)");
logout(INVALID);
return false;
}
}
if(useTls){
//is TLS supported?
if(xmlPar.supportsTLS()){
//try to negotiate TLS
con << xmlStanza::xmlStanzaStartTLS();
con >> tmp;
if(!xmlPar.parse(tmp)){
debugPrint("jabber login failed: "+xmlPar.getError());
logout(NOT_WELL_FORMED);
return false;
}
if(xmlPar.getType() != PROCEED){
debugPrint("server announced TLS, but refuses to use it, will try non-TLS connection");
logout(INVALID);
return false;
}
if(!doSSLHandshake()){
debugPrint("ssl handshake failed");
return false;
}
//so we have successfully established TLS, lets start new stream
con << xmlStanza::xmlStream(server);
con >> tmp; //stream response
xmlPar.parse(tmp);
con >> tmp; //features
if(!xmlPar.parse(tmp)){
debugPrint("jabber login failed: "+xmlPar.getError());
logout(NOT_WELL_FORMED);
return false;
}
//we are expecting features tag
if(xmlPar.getType() != FEATURES){
debugPrint("jabber login failed: unexpected xml (features expected)");
logout(INVALID);
return false;
}
}
stat = TLS;
}
//SASL authentication
if(xmlPar.supportsMD5()){ //other then MD5 authentifications
if(!doSASLMD5()){
debugPrint("SASL authentication failed!");
return false;
}
}
else if(xmlPar.supportsPLAIN()){
if(!doSASLPLAIN()){
debugPrint("SASL authentication failed!");
return false;
}
}
else{
cerr << "no supported way of autentization detected, sory..\n";
exit(1);
}
//authentication successful, let's start new stream (this is the last time, i promise)
con << xmlStanza::xmlStream(server);
con >> tmp;
tmp += "</stream:stream>"; //just for libxml
xmlPar.parse(tmp);
if(xmlPar.getType() != STREAM){
debugPrint("Error opening new stream after SASL!");
return false;
}
if(xmlPar.getType() != FEATURES){
//we probably didn't cought it with stream
con >> tmp;
xmlPar.parse(tmp);
if(xmlPar.getType() != FEATURES){
debugPrint("<features> tag expected, but not received");
return false;
}
if(xmlPar.supportsBind()){
con << xmlStanza::xmlIqBindResource(resource);
con >> tmp;
con << xmlStanza::xmlIqSession();
con >> tmp;
}
//setStatus(S_ON);
stat = ONLINE; //huray!, we're online
//oncoming socket communication will be asynchronous, controled by separate thread
thr = new readThread(&con);
return true;
}
return false;
}
bool jabberConnection::setStatus(enumStav st){
string tmp;
switch(st){
case S_OFF:
logout(NONE);
stav = S_OFF;
break;
case S_AWAY:
con << xmlStanza::xmlPresence(5, "away");
stav = S_AWAY;
break;
case S_CHAT:
con << xmlStanza::xmlPresence(5, "chat");
stav = S_CHAT;
break;
case S_DND:
con << xmlStanza::xmlPresence(5, "dnd");
stav = S_DND;
break;
case S_NA:
con << xmlStanza::xmlPresence(5, "xa");
stav = S_NA;
break;
case S_ON:
if(stat != ONLINE)
if(!login())
return false;
con << xmlStanza::xmlPresence(5);
stav = S_ON;
break;
}
return true;
}
bool jabberConnection::logout(enumError er){
if(stat != OFFLINE){
switch(er){
case INVALID:
//send invalid-xml tag to server
break;
case NOT_WELL_FORMED:
//send xml-not-well-formed tag to server
break;
}
con << "</stream:stream>";
con.disconnect();
stat = OFFLINE;
}
return true;
}
const jabberConnection& jabberConnection::operator<<(const string& txt){
con << txt;
return *this;
}
/*bool jabberConnection::getStanzaById(int id, rcvStanza_ &ret){
rcvStanzaIter iter;
for(iter = inStanza.begin();iter != inStanza.end();iter++){
if((*iter).id == xmlStanza::itoa(id)){
ret = *iter;
return true;
}
}
return false;
}*/
|
459be824a72eae6f4baa79a19ebc5a93cc46780e
|
b179ee1c603139301b86fa44ccbbd315a148c47b
|
/engine/strings/source/TextKeys.cpp
|
b050d9d56748b1a44f7a61385c98e54b5714718e
|
[
"MIT",
"Zlib"
] |
permissive
|
prolog/shadow-of-the-wyrm
|
06de691e94c2cb979756cee13d424a994257b544
|
cd419efe4394803ff3d0553acf890f33ae1e4278
|
refs/heads/master
| 2023-08-31T06:08:23.046409
| 2023-07-08T14:45:27
| 2023-07-08T14:45:27
| 203,472,742
| 71
| 9
|
MIT
| 2023-07-08T14:45:29
| 2019-08-21T00:01:37
|
C++
|
UTF-8
|
C++
| false
| false
| 11,202
|
cpp
|
TextKeys.cpp
|
#include "TextKeys.hpp"
using namespace std;
TextKeys::TextKeys()
{
}
TextKeys::~TextKeys()
{
}
const string TextKeys::SW_TITLE = "SW_TITLE";
const string TextKeys::SW_TITLE_POEM = "SW_TITLE_POEM";
const string TextKeys::SW_TITLE_LOADING = "SW_TITLE_LOADING";
const string TextKeys::SW_TITLE_SAVING = "SW_TITLE_SAVING";
const string TextKeys::COPYRIGHT_NOTICE = "COPYRIGHT_NOTICE";
const string TextKeys::SW_TITLE_NEW_GAME = "SW_TITLE_NEW_GAME";
const string TextKeys::SW_TITLE_NEW_GAME_RANDOM = "SW_TITLE_NEW_GAME_RANDOM";
const string TextKeys::CHARACTER_ALREADY_EXISTS = "CHARACTER_ALREADY_EXISTS";
const string TextKeys::SW_TITLE_LOAD_GAME = "SW_TITLE_LOAD_GAME";
const string TextKeys::SW_TITLE_HIGH_SCORES = "SW_TITLE_HIGH_SCORES";
const string TextKeys::SW_TITLE_QUIT_GAME = "SW_TITLE_QUIT_GAME";
const string TextKeys::SW_PROBLEM_GAME_SAVED = "SW_PROBLEM_GAME_SAVED";
const string TextKeys::RANDOM_SELECTION = "RANDOM_SELECTION";
const string TextKeys::EXIT = "EXIT";
const string TextKeys::DEATH_MESSAGE = "DEATH_MESSAGE";
const string TextKeys::PLAYER_DESC = "PLAYER_DESC";
const string TextKeys::YOU = "YOU";
const string TextKeys::YOURSELF = "YOURSELF";
const string TextKeys::HIMSELF = "HIMSELF";
const string TextKeys::HERSELF = "HERSELF";
const string TextKeys::ITSELF = "ITSELF";
const string TextKeys::BOOL_TRUE = "BOOL_TRUE";
const string TextKeys::BOOL_FALSE = "BOOL_FALSE";
const string TextKeys::TOTAL = "TOTAL";
const string TextKeys::MAXIMUM_LEVEL_DIFFERENCE = "MAXIMUM_LEVEL_DIFFERENCE";
const string TextKeys::TURNS = "TURNS";
const string TextKeys::GAME_STARTED = "GAME_STARTED";
const string TextKeys::CURRENT_DATE = "CURRENT_DATE";
const string TextKeys::CHARACTER_STARTED = "CHARACTER_STARTED";
const string TextKeys::GAME_DATE = "GAME_DATE";
const string TextKeys::TOTAL_ELAPSED_TIME = "TOTAL_ELAPSED_TIME";
const string TextKeys::MAXIMUM_DEPTH_REACHED = "MAXIMUM_DEPTH_REACHED";
const string TextKeys::MORTUARY = "MORTUARY";
const string TextKeys::MORTUARY_FIRST_KILL = "MORTUARY_FIRST_KILL";
const string TextKeys::MODIFIERS = "MODIFIERS";
const string TextKeys::DEATH_DETAILS = "DEATH_DETAILS";
const string TextKeys::DEATH_DETAILS_NARRATIVE_MODE = "DEATH_DETAILS_NARRATIVE_MODE";
const string TextKeys::INDEFINITELY = "INDEFINITELY";
const string TextKeys::STATUSES = "STATUSES";
const string TextKeys::NPC_ESCAPES_MESSAGE = "NPC_ESCAPES_MESSAGE";
const string TextKeys::NPC_FLEES_MESSAGE = "NPC_FLEES_MESSAGE";
const string TextKeys::NPC_TURNS_TO_FIGHT_MESSAGE = "NPC_TURNS_TO_FIGHT_MESSAGE";
const string TextKeys::SELECT_RACE = "SELECT_RACE";
const string TextKeys::CLASS = "CLASS";
const string TextKeys::SELECT_CLASS = "SELECT_CLASS";
const string TextKeys::SELECT_DEITY = "SELECT_DEITY";
const string TextKeys::SELECT_STARTING_LOCATION = "SELECT_STARTING_LOCATION";
const string TextKeys::SELECT_SAVED_GAME = "SELECT_SAVED_GAME";
const string TextKeys::DEITIES = "DEITIES";
const string TextKeys::DEITY = "DEITY";
const string TextKeys::DEITY_GONE = "DEITY_GONE";
const string TextKeys::AGE = "AGE";
const string TextKeys::SEX = "SEX";
const string TextKeys::SELECT_HAIR_COLOUR = "SELECT_HAIR_COLOUR";
const string TextKeys::HAIR_COLOUR = "HAIR_COLOUR";
const string TextKeys::SELECT_EYE_COLOUR = "SELECT_EYE_COLOUR";
const string TextKeys::EYE_COLOUR = "EYE_COLOUR";
const string TextKeys::RACE = "RACE";
const string TextKeys::RACES = "RACES";
const string TextKeys::SELECT_SEX = "SELECT_SEX";
const string TextKeys::SEX_MALE = "SEX_MALE";
const string TextKeys::SEX_MALE_ABRV = "SEX_MALE_ABRV";
const string TextKeys::SEX_FEMALE = "SEX_FEMALE";
const string TextKeys::SEX_FEMALE_ABRV = "SEX_FEMALE_ABRV";
const string TextKeys::SEX_NOT_SPECIFIED = "SEX_NOT_SPECIFIED";
const string TextKeys::SEX_NOT_SPECIFIED_ABRV = "SEX_NOT_SPECIFIED_ABRV";
const string TextKeys::SELECT_EQUIPMENT_WORN_LOCATION = "SELECT_EQUIPMENT_WORN_LOCATION";
const string TextKeys::RACE_1_NAME = "RACE_1_NAME";
const string TextKeys::RACE_1_SHORT_DESC = "RACE_1_SHORT_DESC";
const string TextKeys::RACE_1_DESC = "RACE_1_DESC";
const string TextKeys::RACE_2_NAME = "RACE_2_NAME";
const string TextKeys::RACE_2_SHORT_DESC = "RACE_2_SHORT_DESC";
const string TextKeys::RACE_2_DESC = "RACE_2_DESC";
const string TextKeys::RACE_3_NAME = "RACE_3_NAME";
const string TextKeys::RACE_3_SHORT_DESC = "RACE_3_SHORT_DESC";
const string TextKeys::RACE_3_DESC = "RACE_3_DESC";
const string TextKeys::RACE_4_NAME = "RACE_4_NAME";
const string TextKeys::RACE_4_SHORT_DESC = "RACE_4_SHORT_DESC";
const string TextKeys::RACE_4_DESC = "RACE_4_DESC";
const string TextKeys::RACE_5_NAME = "RACE_5_NAME";
const string TextKeys::RACE_5_SHORT_DESC = "RACE_5_SHORT_DESC";
const string TextKeys::RACE_5_DESC = "RACE_5_DESC";
const string TextKeys::RACE_6_NAME = "RACE_6_NAME";
const string TextKeys::RACE_6_SHORT_DESC = "RACE_6_SHORT_DESC";
const string TextKeys::RACE_6_DESC = "RACE_6_DESC";
const string TextKeys::RACE_7_NAME = "RACE_7_NAME";
const string TextKeys::RACE_7_SHORT_DESC = "RACE_7_SHORT_DESC";
const string TextKeys::RACE_7_DESC = "RACE_7_DESC";
const string TextKeys::RACE_8_NAME = "RACE_8_NAME";
const string TextKeys::RACE_8_SHORT_DESC = "RACE_8_SHORT_DESC";
const string TextKeys::RACE_8_DESC = "RACE_8_DESC";
const string TextKeys::RACE_9_NAME = "RACE_9_NAME";
const string TextKeys::RACE_9_SHORT_DESC = "RACE_9_SHORT_DESC";
const string TextKeys::RACE_9_DESC = "RACE_8_DESC";
const string TextKeys::RACE_10_NAME = "RACE_10_NAME";
const string TextKeys::RACE_10_SHORT_DESC = "RACE_10_SHORT_DESC";
const string TextKeys::RACE_10_DESC = "RACE_10_DESC";
const string TextKeys::STRENGTH = "STRENGTH";
const string TextKeys::STRENGTH_ABRV = "STRENGTH_ABRV";
const string TextKeys::DEXTERITY = "DEXTERITY";
const string TextKeys::DEXTERITY_ABRV = "DEXTERITY_ABRV";
const string TextKeys::AGILITY = "AGILITY";
const string TextKeys::AGILITY_ABRV = "AGILITY_ABRV";
const string TextKeys::HEALTH = "HEALTH";
const string TextKeys::HEALTH_ABRV = "HEALTH_ABRV";
const string TextKeys::INTELLIGENCE = "INTELLIGENCE";
const string TextKeys::INTELLIGENCE_ABRV = "INTELLIGENCE_ABRV";
const string TextKeys::WILLPOWER = "WILLPOWER";
const string TextKeys::WILLPOWER_ABRV = "WILLPOWER_ABRV";
const string TextKeys::CHARISMA = "CHARISMA";
const string TextKeys::CHARISMA_ABRV = "CHARISMA_ABRV";
const string TextKeys::SPEED = "SPEED";
const string TextKeys::SPEED_ABRV = "SPEED_ABRV";
const string TextKeys::HIT_POINTS = "HIT_POINTS";
const string TextKeys::HIT_POINTS_ABRV = "HIT_POINTS_ABRV";
const string TextKeys::ARCANA_POINTS = "ARCANA_POINTS";
const string TextKeys::ARCANA_POINTS_ABRV = "ARCANA_POINTS_ABRV";
const string TextKeys::RANGE_ABRV = "RANGE_ABRV";
const string TextKeys::EVADE = "EVADE";
const string TextKeys::EVADE_ABRV = "EVADE_ABRV";
const string TextKeys::SOAK = "SOAK";
const string TextKeys::SOAK_ABRV = "SOAK_ABRV";
const string TextKeys::ALIGNMENT = "ALIGNMENT";
const string TextKeys::ALIGNMENT_GOOD = "ALIGNMENT_GOOD";
const string TextKeys::ALIGNMENT_GOOD_ABRV = "ALIGNMENT_GOOD_ABRV";
const string TextKeys::ALIGNMENT_EVIL = "ALIGNMENT_EVIL";
const string TextKeys::ALIGNMENT_EVIL_ABRV = "ALIGNMENT_EVIL_ABRV";
const string TextKeys::ALIGNMENT_NEUTRAL = "ALIGNMENT_NEUTRAL";
const string TextKeys::ALIGNMENT_NEUTRAL_ABRV = "ALIGNMENT_NEUTRAL_ABRV";
const string TextKeys::LEVEL = "LEVEL";
const string TextKeys::LEVEL_ABRV = "LEVEL_ABRV";
const string TextKeys::EXPERIENCE = "EXPERIENCE";
const string TextKeys::WINNER = "WINNER";
const string TextKeys::WINNER_EVIL = "WINNER_EVIL";
const string TextKeys::WINNER_GODSLAYER = "WINNER_GODSLAYER";
const string TextKeys::DAMAGE_MELEE = "DAMAGE_MELEE";
const string TextKeys::DAMAGE_RANGED = "DAMAGE_RANGED";
const string TextKeys::DAMAGE_PIERCING = "DAMAGE_PIERCING";
const string TextKeys::DAMAGE_CHAOTIC = "DAMAGE_CHAOTIC";
const string TextKeys::DAMAGE_VORPAL = "DAMAGE_VORPAL";
const string TextKeys::DAMAGE_DRAINING = "DAMAGE_DRAINING";
const string TextKeys::DAMAGE_ETHEREAL = "DAMAGE_ETHEREAL";
const string TextKeys::DAMAGE_INCORPOREAL = "DAMAGE_INCORPOREAL";
const string TextKeys::DAMAGE_SCYTHING = "DAMAGE_SCYTHING";
const string TextKeys::DAMAGE_EXPLOSIVE = "DAMAGE_EXPLOSIVE";
const string TextKeys::DAMAGE_SLAYS = "DAMAGE_SLAYS";
const string TextKeys::ATTACK_DETAILS = "ATTACK_DETAILS";
const string TextKeys::EQUIPMENT = "EQUIPMENT";
const string TextKeys::INVENTORY = "INVENTORY";
const string TextKeys::INVENTORY_FILTERED = "INVENTORY_FILTERED";
const string TextKeys::GENERATED_ARTIFACTS = "GENERATED_ARTIFACTS";
const string TextKeys::DECISION_CONFIRM_RANGED_MELEE_ATTACK = "DECISION_CONFIRM_RANGED_MELEE_ATTACK";
const string TextKeys::DECISION_CONFIRM_KEY = "DECISION_CONFIRM_KEY";
const string TextKeys::DECISION_DENY_KEY = "DECISION_DENY_KEY";
const string TextKeys::DECISION_LEAVE_AREA = "DECISION_LEAVE_AREA";
const string TextKeys::DECISION_QUIT_GAME = "DECISION_QUIT_GAME";
const string TextKeys::DECISION_JUMP_INTO_WATER = "DECISION_JUMP_INTO_WATER";
const string TextKeys::DECISION_SAVE_GAME = "DECISION_SAVE_GAME";
const string TextKeys::DECISION_ATTACK_FRIENDLY_CREATURE = "DECISION_ATTACK_FRIENDLY_CREATURE";
const string TextKeys::DECISION_SWITCH_FRIENDLY_CREATURE = "DECISION_SWITCH_FRIENDLY_CREATURE";
const string TextKeys::DECISION_SQUEEZE_FRIENDLY_CREATURE = "DECISION_SQUEEZE_FRIENDLY_CREATURE";
const string TextKeys::DECISION_RESIST_SWITCH = "DECISION_RESIST_SWITCH";
const string TextKeys::DECISION_STEAL_FRIENDLY_CREATURE = "DECISION_STEAL_FRIENDLY_CREATURE";
const string TextKeys::DECISION_CREATE_IDENTIFIED_DUMP = "DECISION_CREATE_IDENTIFIED_DUMP";
const string TextKeys::DECISION_USE_LUA_CONSOLE = "DECISION_USE_LUA_CONSOLE";
const string TextKeys::SCORE_SUPPRESSED_LUA_NARRATIVE = "SCORE_SUPPRESSED_LUA_NARRATIVE";
const string TextKeys::GAIN_LEVEL = "GAIN_LEVEL";
const string TextKeys::UNARMED = "UNARMED";
const string TextKeys::SOMETHING = "SOMETHING";
const string TextKeys::EVERYTHING = "EVERYTHING";
const string TextKeys::LATEST_MESSAGES = "LATEST_MESSAGES";
const string TextKeys::FRIENDLY = "FRIENDLY";
const string TextKeys::FOLLOWER = "FOLLOWER";
const string TextKeys::DUMPING_CHARACTER_FAILED = "DUMPING_CHARACTER_FAILED";
const string TextKeys::NO_NEW_CHARACTERS = "NO_NEW_CHARACTERS";
const string TextKeys::MEMBERSHIPS = "MEMBERSHIPS";
const string TextKeys::NOT_APPLICABLE_ABRV = "NOT_APPLICABLE_ABRV";
const string TextKeys::CARRYING_CAPACITY = "CARRYING_CAPACITY";
const string TextKeys::ARTIFACT = "ARTIFACT";
const string TextKeys::AUTOCURSING = "AUTOCURSING";
const string TextKeys::GENERIC_MESSAGE = "GENERIC_MESSAGE";
const string TextKeys::PACIFIED = "PACIFIED";
const string TextKeys::TAMED = "TAMED";
const string TextKeys::REQUIRES = "REQUIRES";
const string TextKeys::THE_WORLD_MAP = "THE_WORLD_MAP";
const string TextKeys::NO_CREATURES_GENERATED = "NO_CREATURES_GENERATED";
const string TextKeys::DEFAULT_CLASS_NAME_SID = "DEFAULT_CLASS_NAME_SID";
|
76bf6229a315811771827ea07ee7a0c1889af1b2
|
a35a353b09358d25b45a7ee04701245018afbeeb
|
/Image-processing-algorithm/Color Space Conversion/rgb2hsv.cpp
|
328f5dbefd48713125b07e85f6c67b48c1eff07a
|
[] |
no_license
|
KenSporger/Digital-Image-Processing-Course
|
56900bea2a7e6f83c78d123c39f032b4126a5e87
|
9fa8feee8b2de65038889702b6338a943ec83cde
|
refs/heads/master
| 2021-03-15T08:28:05.873605
| 2020-08-26T03:02:56
| 2020-08-26T03:02:56
| 246,837,259
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,148
|
cpp
|
rgb2hsv.cpp
|
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
// RGB模型转到HSV模型
Mat RGB2HSV(Mat src)
{
int rows = src.rows;
int cols = src.cols;
Mat dst(rows, cols, CV_8UC3);
for (int i = 0; i < rows; i++){
for (int j=0; j< cols; j++){
uchar r = src.at<Vec3b>(i, j)[0];
uchar g = src.at<Vec3b>(i, j)[1];
uchar b = src.at<Vec3b>(i, j)[2];
uchar maxVal = max(r, max(g, b));
uchar minVal = min(r, min(g, b));
float diffMaxMin = maxVal - minVal;
float hue;
if (maxVal == r) hue = 30 * (g - b) / diffMaxMin;
else if (maxVal == g) hue = 60 + 30 * (b - r) / diffMaxMin;
else hue = 120 + 30 * (r - g) / diffMaxMin;
//Opencv中S和V的范围为0~255,而H的范围是0~180
//V = max(r,g,b)
//V:[0,255]
dst.at<Vec3b>(i, j)[2] = maxVal;
//S = (V-min(r,g,b))/V
//S:[0,1] -> 255*S:[0,255]
dst.at<Vec3b>(i, j)[1] = (maxVal == 0) ? 0 : 255 * (diffMaxMin / maxVal);
//H = 30*(g-b)/(V-min(r,g,b)) ,V=r
//H = 60+30*(b-r)/(V-min(r,g,b)) ,V=g
//H = 120+30*(r-g)/(V-min(r,g,b)) ,V=b
//H = H+180 if H<0;
//H:[0,180]
dst.at<Vec3b>(i, j)[0] = (hue < 0) ? (180 + hue + 0.5) : hue;
}
}
return dst;
}
//HSV转到RGB,过程就是公式的逆推
Mat HSV2RGB(Mat src)
{
int rows = src.rows;
int cols = src.cols;
// 本程序使用6个level表示色调范围 0:[0,30] 1:[30,60] 2:[60,90] 3:[90,120] 4:[120,150] 5:[150,180]
// 定义各level对应的色调值
int standard[6] = {0, 60, 60, 120, 120, 180};
//定义各level对应的符号
int symbol[6] = {1, -1, 1, -1, 1, -1};
Mat dst(rows, cols, CV_8UC3);
for (int i = 0; i < rows; i++){
for (int j=0; j< cols; j++){
uchar b, g, r;
uchar h = src.at<Vec3b>(i, j)[0];
uchar s = src.at<Vec3b>(i, j)[1];
uchar v = src.at<Vec3b>(i, j)[2];
// s=255*(max-min)/max
float diffMaxMin = s * v / 255.0;
// 计算所属level
int level = h / 30;
// 以level3,level4为例,使用的公式为H = 120+30*(r-g)/(V-min(r,g,b)) ,V=b
// standard=120,则(h - standard[level]) / 30.0* diffMaxMin等于(r-g)
// diffMidMin=midVal - minVal 必须是大于零的
// 当level=3时,r-g<0,而symbol=-1,使得diffMidMin=g-r大于了0
// 当level=5时,r-g>0,而symbol=1,使得diffMidMin=r-g大于了0
int diffMidMin = symbol[level] * (h - standard[level]) / 30.0 * diffMaxMin;
int maxVal = v;
int minVal = v - diffMaxMin;
// diffMidMin = midVal - minVal
int midVal = minVal + diffMidMin;
// 0和5的level红色是最大值,1和2的level绿色是最大值,3和4的level蓝色是最大值
switch (level){
case 0: r = maxVal; g = midVal; b = minVal; break;
case 1: r = midVal; g = maxVal; b = minVal; break;
case 2: r = minVal; g = maxVal; b = midVal; break;
case 3: r = minVal; g = midVal ; b = maxVal; break;
case 4: r = midVal; g = minVal ; b = maxVal; break;
case 5: r = maxVal; g = minVal ; b = midVal; break;
default: break;
}
dst.at<Vec3b>(i, j)[0] = r;
dst.at<Vec3b>(i, j)[1] = g;
dst.at<Vec3b>(i, j)[2] = b;
}
}
return dst;
}
int main()
{
Mat img = imread("img/numbers.jpg");
Mat hsv,reImg;
Mat hsv_channels[3];
//BGR->RGB
cvtColor(img, img, COLOR_BGR2RGB);
// cvtColor(img,hsv,COLOR_RGB2HSV);
hsv = RGB2HSV(img);
// cvtColor(hsv,reImg,COLOR_HSV2RGB);
reImg = HSV2RGB(hsv);
split(hsv,hsv_channels);
imshow("img",img);
imshow("h",hsv_channels[0]);
imshow("s",hsv_channels[1]);
imshow("v",hsv_channels[2]);
imshow("reImg",reImg);
waitKey(0);
}
|
1ccc5b8f5839859f17db6ad0a962b01b0a8ebac3
|
103eca6c82eec3bd5fa3a9d28fa65446564e4bd4
|
/abcdsat_p21/simp/Algebraic.cc
|
e6942a2f48f2195a5f3e4d3a20d9c3790101e2df
|
[] |
no_license
|
jingchaochen/abcdsat_p21
|
c0df8973e8fa9232da5dab12b8a1c2f0518a505c
|
cb5e67aaa2669aa3c111596656e4168d79219268
|
refs/heads/main
| 2023-04-10T11:16:07.528238
| 2021-04-20T08:20:56
| 2021-04-20T08:20:56
| 359,734,474
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,359
|
cc
|
Algebraic.cc
|
#include "global.hpp"
#include "Algebraic.hpp"
#include "CNFtheory.hpp"
#include "Breaking.hpp"
#include "Graph.hpp"
#include <stdio.h>
#include <limits.h>
using namespace std;
void Permutation::addFromTo(uint from, uint to) {
if (from != to && from < 2 * nVars && to < 2 * nVars) { // only ID's < 2*nVars represent literals
perm[from] = to;
domain.push_back(from);
image.push_back(to);
if (!sign(from)) {
posDomain.push_back(from);
}
}
}
Permutation::Permutation(){
hash=0;
maxCycleSize = 1;
}
Permutation::Permutation(std::vector<std::pair<uint, uint> >& tuples) {
for (auto tup : tuples) {
addFromTo(tup.first, tup.second);
}
hash = 0;
maxCycleSize = 1;
}
Permutation::Permutation(std::vector<uint>& row1, std::vector<uint>& row2) {
for (uint i = 0; i < row1.size() && i < row2.size(); ++i) {
uint from = row1[i];
uint to = row2[i];
addFromTo(from, to);
addFromTo(to, from);
}
hash = 0;
maxCycleSize = 1;
}
uint Permutation::getImage(uint from) {
auto it = perm.find(from);
if (it != perm.end()) {
return it->second;
} else {
return from;
}
}
bool Permutation::getImage(std::vector<uint>& orig, std::vector<uint>& img) {
img.clear();
img.reserve(orig.size());
bool result = false;
for (auto lit : orig) {
uint image = getImage(lit);
img.push_back(image);
result = result || image != lit;
}
return result;
}
// printing cycles
void Permutation::print() {
/*
for (auto lit : getCycleReprs()) {
//std::clog << "c (";
vector<uint> cyc;
getCycle(lit, cyc);
for (auto s : cyc) {
// std::clog << decode(s) << " ";
}
//std::clog << ")";
}
//std::clog << std::endl;
*/
}
void Permutation::getCycle(uint lit, std::vector<uint>& orb) {
orb.clear();
orb.push_back(lit);
uint sym = getImage(lit);
while (sym != lit) {
orb.push_back(sym);
sym = getImage(sym);
}
}
bool Permutation::isInvolution() {
return getMaxCycleSize() == 2;
}
bool Permutation::permutes(uint lit) {
return perm.count(lit) > 0;
}
uint Permutation::supportSize() {
return domain.size();
}
bool Permutation::isIdentity() {
return supportSize() == 0;
}
// TODO: expand this detection method with "non-binary involutions"
bool Permutation::formsMatrixWith(sptr<Permutation> other) {
if (supportSize() != other->supportSize() || !isInvolution() || !other->isInvolution()) {
return false;
}
for (auto lit : getCycleReprs()) {
uint sym = perm[lit];
uint lit_mpd = other->getImage(lit);
uint sym_mpd = other->getImage(sym);
if (lit_mpd == sym_mpd ||
(lit == lit_mpd && sym == sym_mpd) ||
(lit != lit_mpd && sym != sym_mpd)) {
return false;
}
}
return true;
}
pair<sptr<Permutation>, sptr<Permutation> > Permutation::getLargest(sptr<Permutation> other) {
if (other->supportSize() > supportSize()) {
return
{
other, shared_from_this()
};
} else {
return
{
shared_from_this(), other
};
}
}
void Permutation::getSharedLiterals(sptr<Permutation> other, vector<uint>& shared) {
shared.clear();
pair<sptr<Permutation>, sptr<Permutation> > ordered = getLargest(other);
for (auto lit : ordered.second->posDomain) {
if (ordered.first->permutes(lit)) {
shared.push_back(lit);
shared.push_back(neg(lit));
}
}
}
std::vector<uint>& Permutation::getCycleReprs() {
if (cycleReprs.size() == 0 && supportSize() > 0) { // calculate cycles
unordered_set<uint> marked;
for (auto lit : domain) { // TODO: probably possible to replace with more efficient posDomain
if (marked.count(lit) == 0) {
cycleReprs.push_back(lit);
vector<uint> cyc;
getCycle(lit, cyc);
for (auto s : cyc) {
marked.insert(s);
}
if (cyc.size() > maxCycleSize) {
maxCycleSize = cyc.size();
}
}
}
}
return cycleReprs;
}
uint Permutation::getMaxCycleSize() {
if (maxCycleSize == 1) {
getCycleReprs();
}
return maxCycleSize;
}
uint Permutation::getNbCycles() {
return getCycleReprs().size();
}
bool Permutation::equals(sptr<Permutation> other) {
if (supportSize() != other->supportSize()
|| getMaxCycleSize() != other->getMaxCycleSize()
|| getNbCycles() != other->getNbCycles()) {
return false;
}
for (uint i = 0; i < supportSize(); ++i) {
if (image[i] != other->getImage(domain[i])) {
return false;
}
}
return true;
}
// =========Group=========================
void Group::add(sptr<Permutation> p) {
permutations.push_back(p);
support.insert(p->domain.cbegin(), p->domain.cend());
}
void Group::addMatrix(sptr<Matrix> m) {
matrices.push_back(m);
cleanPermutations(m);
if (verbosity > 1) {
// std::clog << "c Matrix with " << m->nbRows() << " rows and " << m->nbColumns() / 2 << " columns detected" << std::endl;
if (verbosity > 2) {
m->print();
}
}
}
void Group::print() {
for (auto p : permutations) {
p->print();
}
}
// Adds to matrix 3 rows if an initialmatrix is found.
// The first added row is the shared row.
// The matrix is then maximally extended with new rows given the detected permutations for this group.
sptr<Matrix> Group::getInitialMatrix() {
std::map<uint, std::vector<sptr<Permutation> > > involutions; // indexed by size
for (auto p : permutations) {
if (p->isInvolution()) {
involutions[p->supportSize()].push_back(p); // so all involutions are at the vector at the index of their size
}
}
sptr<Matrix> result(new Matrix());
for (auto it = involutions.cbegin(); it != involutions.cend(); ++it) { // looping over all involution sizes
for (uint i = 0; i < it->second.size(); ++i) {
for (uint j = i + 1; j < it->second.size(); ++j) { // looping over all unordered pairs of involutions
if (it->second[i]->formsMatrixWith(it->second[j])) {
vector<uint>* shared = new vector<uint>();
it->second[i]->getSharedLiterals(it->second[j], *shared);
vector<uint>* row_i = new vector<uint>();
vector<uint>* row_j = new vector<uint>();
for (auto lit : *shared) {
row_i->push_back(it->second[i]->getImage(lit));
row_j->push_back(it->second[j]->getImage(lit));
}
result->add(shared);
result->add(row_i);
result->add(row_j);
maximallyExtend(result, 0);
return result;
}
}
}
}
return nullptr;
}
uint Group::getNbMatrices() {
return matrices.size();
}
uint Group::getNbRowSwaps() {
uint result = 0;
for (auto m : matrices) {
result += m->nbRows()*(m->nbRows() - 1) / 2;
}
return result;
}
void Group::addMatrices() {
sptr<Matrix> matrix = getInitialMatrix(); // if possible, gives an initial matrix
while (matrix != nullptr) {
uint oldNbRows = 0;
while (oldNbRows < matrix->nbRows()) {
// find stabilizer group for all lits but those in the last row of the matrix
for (uint i = oldNbRows; i < matrix->nbRows() - 1; ++i) {
// fix all lits but the last row
theory->getGraph()->setUniqueColor(*matrix->getRow(i));
}
oldNbRows = matrix->nbRows();
std::vector<sptr<Permutation> > symgens;
theory->getGraph()->getSymmetryGenerators(symgens);
// now test stabilizer generators on the (former) last row
for (auto p : symgens) {
matrix->tryToAddNewRow(p, oldNbRows - 1, theory);
add(p);
}
// for all new rows, test all permutations for this group if they generate a new row
maximallyExtend(matrix, oldNbRows);
}
addMatrix(matrix);
checkColumnInterchangeability(matrix);
// fix lits of last row as well
theory->getGraph()->setUniqueColor(*matrix->getRow(matrix->nbRows() - 1));
matrix = getInitialMatrix();
}
}
void Group::checkColumnInterchangeability(sptr<Matrix> m) {
// create first column
std::vector<uint>* first = new std::vector<uint>();
uint firstCol;
for (firstCol = 0; firstCol < m->nbColumns(); ++firstCol) {
if (!sign(m->getLit(0, firstCol))) { // found first col starting with positive lit
for (uint j = 0; j < m->nbRows(); ++j) {
uint l = m->getLit(j, firstCol);
first->push_back(l);
first->push_back(neg(l));
}
break;
}
}
sptr<Matrix> newM(new Matrix());
newM->add(first);
// test for all swaps of first column with another one
for (uint i = firstCol + 1; i < m->nbColumns(); ++i) {
if (!sign(m->getLit(0, i))) { // found other col starting with positive lit
std::vector<uint>* other = new std::vector<uint>();
for (uint j = 0; j < m->nbRows(); ++j) {
uint l = m->getLit(j, i);
other->push_back(l);
other->push_back(neg(l));
}
// create swap of column i with column firstCol
Permutation swap(*first, *other);
if (theory->isSymmetry(swap)) {
newM->add(other);
} else {
delete other;
}
}
}
if (newM->nbRows() > 2) { // at least 3 rows needed to be of use for symmetry breaking
addMatrix(newM);
}
}
void Group::cleanPermutations(sptr<Matrix> matrix) {
// remove all permutations generated by the current set of matrices
for (int i = permutations.size() - 1; i >= 0; --i) {
sptr<Permutation> p = permutations.at(i);
if (p->supportSize() % matrix->nbColumns() != 0) {
continue; // can not be a row permutation
}
sptr<Permutation> reduct = matrix->testMembership(p);
if (reduct->isIdentity()) {
swapErase(permutations, i);
}
}
}
void Group::maximallyExtend(sptr<Matrix> matrix, uint indexOfFirstNewRow) {
for (uint i = indexOfFirstNewRow; i < matrix->nbRows(); ++i) {
// investigate for new rows
for (auto p : permutations) {
matrix->tryToAddNewRow(p, i, theory);
}
}
}
uint Group::getSize() {
return permutations.size();
}
// NOTE: does not support groups with matrices as generators
// NOTE: erases permutations for this group
void Group::getDisjointGenerators(std::vector<sptr<Group> >& subgroups) {
// calculate maximal subsets of generators with pairwise disjoint supports
subgroups.clear();
while (permutations.size() > 0) {
uint previoussize = 0;
sptr<Group> current(new Group());
current->add(permutations.back());
permutations.pop_back();
while (current->getSize() > previoussize) {
previoussize = current->getSize();
for (int i = permutations.size() - 1; i >= 0; --i) {
if (not isDisjoint(current->support, permutations[i]->posDomain)) { // it suffices to check that the positive literals occur in the group support
current->add(permutations[i]);
swapErase(permutations, i);
}
}
}
subgroups.push_back(current);
}
}
bool Group::permutes(uint lit) {
return support.count(lit) > 0;
}
uint Group::getSupportSize() {
return support.size();
}
void eliminateNonStabilizers(std::vector<sptr<Permutation> >& permutations, uint lit) {
for (uint i = 0; i < permutations.size(); ++i) {
if (permutations.at(i)->permutes(lit)) {
permutations[i] = permutations.back();
permutations.pop_back();
--i;
}
}
}
void getOrbits2(const std::vector<sptr<Permutation> >& permutations, std::vector<sptr<std::vector<uint> > >& orbits) {
// find positively supported literals
std::unordered_set<uint> posSupport;
for (auto p : permutations) {
for (auto l : p->posDomain) {
posSupport.insert(l);
}
}
// partition posSupport in orbits
std::unordered_set<uint> visitedLits;
for (auto l : posSupport) {
if (visitedLits.insert(l).second) { // lit did not yet occur in visitedLits
sptr<std::vector<uint> > newOrbit(new std::vector<uint>());
newOrbit->push_back(l);
for (uint i = 0; i < newOrbit->size(); ++i) {
for (auto p : permutations) {
uint sym = p->getImage(newOrbit->at(i));
if (visitedLits.insert(sym).second) {
newOrbit->push_back(sym);
}
}
}
orbits.push_back(newOrbit);
}
}
}
void getPosLitOccurrenceCount(const std::vector<sptr<Permutation> >& permutations, std::unordered_map<uint, uint>& lits2occ) {
for (auto p : permutations) {
for (auto l : p->posDomain) {
lits2occ[l]++; // using the fact that uint value-initializes to 0
}
}
}
void Group::addBinaryClausesTo(Breaker& brkr, std::vector<uint>& out_order, const std::unordered_set<uint>& excludedLits) {
// now, look for literals with large orbits (of a stabilizer group for smaller literals) as first elements of the order
std::vector<sptr<Permutation> > perms = permutations;
while (perms.size() > 0) {
// as long as we have some permutations stabilizing everything in order so far, continue looking for other literals to add to the order
// figure out which literal is:
// 0) a non-excluded variable
// 1) in _a_ largest orbit with non-excluded variables
// 2) has the lowest occurrence of literals adhering to 0) and 1)
std::vector<sptr<std::vector<uint> > > orbs;
getOrbits2(perms, orbs);
std::unordered_map<uint, uint> lits2occ;
getPosLitOccurrenceCount(perms, lits2occ);
sptr<std::vector<uint> > finalOrb(new std::vector<uint>());
uint finalLit = UINT_MAX;
uint finalOccurrence = UINT_MAX;
for (auto o : orbs) {
// check whether o is bigger
if (o->size() < finalOrb->size()) { // note the strict inequality (see condition 1)
continue;
}
// check whether o contains a positive non-excluded lit
for (auto l : *o) {
if (excludedLits.count(l) == 0 && lits2occ.count(l) > 0 && lits2occ[l] < finalOccurrence) {
// success!
finalLit = l;
finalOccurrence = lits2occ[l];
finalOrb = o;
}
}
}
if (finalOrb->size() > 0) {
// success!
// for all literals in its orbit, add binary clause
for (auto l : *finalOrb) {
if (l == finalLit) {
continue;
}
brkr.addBinClause(neg(finalLit), l); // add finalLit => l, since there's a symmetry generated by perms that maps finalLit to l
}
// add lit to order
out_order.push_back(finalLit);
// continue with stabilizer subgroup
eliminateNonStabilizers(perms, finalLit);
} else {
// no more orbits left with positive non-excluded vars
perms.clear();
}
}
}
// NOTE: the order is a list of literals, such that for each literal l, neg(l) is not in the order
void Group::getOrderAndAddBinaryClausesTo(Breaker& brkr, std::vector<uint>& out_order) {
// first, figure out which literals occur in the matrix, since their order is fixed.
std::unordered_set<uint> matrixLits;
for (auto m : matrices) {
for (uint i = 0; i < m->nbRows(); ++i) {
for (auto lit : *m->getRow(i)) {
matrixLits.insert(lit);
}
}
}
if (useBinaryClauses) {
// if (verbosity > 1) {
// std::clog << "c Adding binary symmetry breaking clauses for group..." << std::endl;
// }
addBinaryClausesTo(brkr, out_order, matrixLits);
}
// now, add all literals that are not matrix literals and not yet in the order by their occurrence count
// first, add ordered lits to matrixLits
for (auto l : out_order) {
matrixLits.insert(l);
matrixLits.insert(neg(l));
}
// then create map ordering lits not occurring in matrixLits by their occurrence
std::unordered_map<uint, uint> lits2occ;
getPosLitOccurrenceCount(permutations, lits2occ);
std::multimap<uint, uint> occ2lit;
for (auto it : lits2occ) {
if (matrixLits.count(it.first) == 0) {
occ2lit.insert({it.second, it.first});
}
}
// lastly, add those sorted lits to the order
for (auto it : occ2lit) {
out_order.push_back(it.second);
}
// ok, all that is left is to add the matrix lits
matrixLits.clear(); // use this set to avoid double addition of literals occurring in more than one matrix, and avoid addition of negative literals to order
for (auto m : matrices) {
for (uint i = 0; i < m->nbRows(); ++i) {
for (auto l : *m->getRow(i)) {
if (matrixLits.insert(l).second) {
matrixLits.insert(neg(l));
out_order.push_back(l);
// note how this approach works when matrices contain rows of lits (as opposed to rows of vars)
}
}
}
}
}
void Group::addBreakingClausesTo(Breaker& brkr) {
std::vector<uint> order;
getOrderAndAddBinaryClausesTo(brkr, order);
//if (verbosity > 1) {
// std::clog << "c order: ";
// for (auto x : order) {
// std::clog << decode(x) << " ";
// }
// std::clog << endl;
// }
// add clauses based on detected symmetries
for (auto p : permutations) {
brkr.addRegSym(p, order);
}
// add clauses based on detected matrices
// std::clog << "c matrices=" << matrices.size();
for (auto m : matrices) {
// std::clog << "m->nbRows=" << m->nbRows();
// getchar();
for (uint idx = 0; idx < m->nbRows() - 1; ++idx) {
sptr<Permutation> rowswap(new Permutation(*m->getRow(idx), *m->getRow(idx + 1)));
brkr.addRowSym(rowswap, order);
}
}
}
// =================MATRIX======================
Matrix::Matrix() {
}
Matrix::~Matrix() {
for (auto rw : rows) {
delete rw;
}
}
void Matrix::print() {
/*
for (auto row : rows) {
for (auto lit : *row) {
// std::clog << decode(lit) << " ";
}
//std::clog << std::endl;
}
*/
}
void Matrix::add(std::vector<uint>* row) {
for (uint i = 0; i < row->size(); ++i) {
rowco.insert({row->at(i), rows.size()});
colco.insert({row->at(i), i});
}
rows.push_back(row);
}
uint Matrix::nbRows() {
return rows.size();
}
uint Matrix::nbColumns() {
if (nbRows() > 0) {
return rows[0]->size();
} else {
return 0;
}
}
std::vector<uint>* Matrix::getRow(uint rowindex) {
return rows[rowindex];
}
void Matrix::tryToAddNewRow(sptr<Permutation> p, uint rowIndex, CNF* theory) {
// checks whether the image of the current row can be used as a new row
std::vector<uint>* image = new vector<uint>();
for (auto lit : *getRow(rowIndex)) {
uint sym = p->getImage(lit);
if (permutes(sym)) {
delete image;
return;
} else {
image->push_back(sym);
}
}
// create new row-swapping permutation, test whether it is a symmetry, add the resulting row
Permutation rowSwap(*getRow(rowIndex), *image);
if (theory->isSymmetry(rowSwap)) {
add(image);
} else {
delete image;
return;
}
}
bool Matrix::permutes(uint x) {
return rowco.count(x) > 0;
}
uint Matrix::getLit(uint row, uint column) {
return rows.at(row)->at(column);
}
uint Matrix::getRowNb(uint x) {
return rowco.at(x);
}
uint Matrix::getColumnNb(uint x) {
return colco.at(x);
}
sptr<Permutation> Matrix::testMembership(const sptr<Permutation> p) {
/**
* NOTE:
* We use the first column as base for the matrix.
* A stabilizer chain then is formed by all submatrices formed by removing the upmost row.
* A corresponding set of basic orbits is formed by taking as ith orbit (Delta_i) the first elements of row i to row last.
* A representative function (u_i) for each ith step in the stabilizer chain then maps row j to the swap of row i and j (with j>=i).
*
* We follow here algorithm 2.5.1 from http://www.maths.usyd.edu.au/u/murray/research/essay.pdf
*/
std::unordered_set<uint> basic_orbit; // Delta^i's
for (uint i = 0; i < nbRows(); ++i) {
basic_orbit.insert(getLit(i, 0)); // creating Delta^0
}
sptr<Permutation> g = p;
for (uint l = 0; l < nbRows(); ++l) {
uint beta_l = getLit(l, 0);
uint beta_l_g = g->getImage(beta_l);
if (basic_orbit.count(beta_l_g) == 0) {
return g; // no permutation generated by this matrix
} else {
g = getProductWithRowsWap(g, l, getRowNb(beta_l_g));
if (g->isIdentity()) {
return g;
}
basic_orbit.erase(beta_l); // creating Delta^{l+1}
}
}
return g;
}
sptr<Permutation> Matrix::getProductWithRowsWap(const sptr<Permutation> p, uint r1, uint r2) {
if (r1 == r2) {
return p;
} else if (p->isIdentity()) {
sptr<Permutation> result(new Permutation(*getRow(r1), *getRow(r2)));
return result;
}
std::vector<std::pair<uint, uint> > protoPerm;
// add lit-image pairs permuted by rowswap but not by p
for (uint i = 0; i < nbColumns(); ++i) {
if (!p->permutes(getLit(r1, i))) {
protoPerm.push_back({getLit(r1, i), getLit(r2, i)});
}
if (!p->permutes(getLit(r2, i))) {
protoPerm.push_back({getLit(r2, i), getLit(r1, i)});
}
}
// add lit-image pairs permuted by p
for (uint i = 0; i < p->supportSize(); ++i) {
uint orig = p->domain.at(i);
uint img = p->image.at(i);
if (permutes(img)) {
uint rowind = getRowNb(img);
uint colind = getColumnNb(img);
if (rowind == r1) {
protoPerm.push_back({orig, getLit(r2, colind)});
} else if (rowind == r2) {
protoPerm.push_back({orig, getLit(r1, colind)});
} else {
protoPerm.push_back({orig, img});
}
} else {
protoPerm.push_back({orig, img});
}
}
sptr<Permutation> result(new Permutation(protoPerm));
return result;
}
|
0353e4a9641c8d67e33b59eca69181749491b73c
|
586a03f4b93fd031f5eb677c7a43add038a4bc93
|
/tests/testId3.cc
|
7dfaa1fa55051a8f2e45506e5adfd8ced090e52b
|
[] |
no_license
|
kmz42/cudacomp
|
7d8b5e0f57cc15df4dbed0d573535f404025e221
|
ee519a126dfb595c4ddb14195322277c90d36e6a
|
refs/heads/master
| 2022-09-19T08:23:50.922986
| 2017-05-19T02:31:39
| 2017-05-19T02:31:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 53
|
cc
|
testId3.cc
|
int _cc_main() {
int x = 10;
return y * 2;
}
|
f9e4cd35becfbc76e4187e16f2ede350f2824c19
|
7ba254b6e04238d482c62420781fa995719a984c
|
/mpac_mproc/pac-soc/pac-d2-bus.h
|
8f07f6b3d886278e518dc16d7e2e95c2a66d2ece
|
[] |
no_license
|
cuibixiong/multicore-simulation
|
25d3ba38ad1270e19868e297fa6af484606ed638
|
8b22030c2e264fee08ff92f315a2948e45de9012
|
refs/heads/master
| 2021-01-01T05:35:34.857120
| 2013-05-26T16:04:22
| 2013-05-26T16:04:22
| 10,299,972
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 86,819
|
h
|
pac-d2-bus.h
|
#ifndef PAC_D2_BUS_H_INCLUDED
#define PAC_D2_BUS_H_INCLUDED
#include <systemc.h>
using namespace sc_core;
using namespace sc_dt;
using namespace std;
#include "tlm.h"
#include "tlm_utils/simple_target_socket.h"
#include "tlm_utils/simple_initiator_socket.h"
#include "tlm_utils/peq_with_get.h"
#include "pac-trans-extension.h"
#include "pac-bus.h"
#include "pac-profiling.h"
#define DBG_CORE_M1_MEM 0
#define DBG_CORE_BIU 1
#define DBG_CORE_ICU 2
#define DBG_CORE_DMU 3
#define DBG_CORE_DMA 4
#define DBG_M2_MEM 5
#define DBG_M2_ICU 6
#define DBG_M2_DMU 7
#define DBG_M2_DMA 8
#define DBG_C2CC_INTERFACE 9
#define DBG_DDR_MEM 10
#define DBG_SYS_DMA 11
extern sc_core::sc_event soc_core_req_event[DSPNUM]; // 4 core request event
extern int soc_core_req_bit_mask[DSPNUM]; //m1 m2 ddr finish bit mask
struct d2_dcache_addr {
unsigned int offset:8;
unsigned int index:8;
unsigned int tag:16;
};
struct d2_dcache_flag {
unsigned int invalid:1;
unsigned int dirty:1;
unsigned int reserved:6;
unsigned int index:8;
unsigned int tag:16;
};
struct d2_dcache_line {
struct d2_dcache_flag flag;
unsigned char *insn;
};
#ifndef PAC_SOC_PROFILE
struct D2_Bus:public sc_core::sc_module, public pac_bus
{
private:
unsigned int r_lock, w_lock;
struct sim_arg *multi_sim_arg;
unsigned int d2_dcache_type;
unsigned int d2_dcache_size;
unsigned int d2_dcache_line_size;
struct d2_dcache_line *d2_dcache_mem;
unsigned int m1_bus_base_array[DSPNUM], m1_bus_size_array[DSPNUM];
unsigned int m1_bus_base_array_no_mem[DSPNUM], m1_bus_size_array_no_mem[DSPNUM];
unsigned int m2_bus_base, m2_bus_size;
unsigned int m2_bus_base_no_mem, m2_bus_size_no_mem;
unsigned int biu_bus_base, biu_bus_size;
unsigned int sysdma_base, sysdma_size;
unsigned int c2cc_base, c2cc_size;
unsigned int i;
public:
tlm_utils::simple_initiator_socket_tagged < D2_Bus > m1_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_initiator_socket_tagged < D2_Bus > m2_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_initiator_socket_tagged < D2_Bus > biu_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_initiator_socket_tagged < D2_Bus > dmu_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_target_socket_tagged < D2_Bus > d2_bus_targ_socket_tagged[DSPNUM+1]; //connect to core_bus dma_bus
tlm_utils::peq_with_get < tlm::tlm_generic_payload > m1_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > m2_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > biu_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > dmu_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > d2_bus_RequestPEQ;
SC_HAS_PROCESS(D2_Bus);
public:
D2_Bus(sc_module_name _name, struct sim_arg *arg)
: sc_core::sc_module(_name)
, multi_sim_arg(arg)
, m1_bus_ResponsePEQ("m1_bus_ResponsePEQ")
, m2_bus_ResponsePEQ("m2_bus_ResponsePEQ")
, biu_bus_ResponsePEQ("biu_bus_ResponsePEQ")
, dmu_bus_ResponsePEQ("dmu_bus_Response")
, d2_bus_RequestPEQ("d2_bus_RequestPEQ")
{
d2_dcache_type = multi_arg(d2_cache, d2_cache_type);
d2_dcache_size = multi_arg(d2_cache, d2_cache_size);
d2_dcache_line_size = multi_arg(d2_cache, d2_cache_line_size);
d2_dcache_mem = new d2_dcache_line[d2_dcache_size / d2_dcache_line_size];
for (i = 0; i < (d2_dcache_size / d2_dcache_line_size); i++) {
d2_dcache_mem[i].insn = new unsigned char[d2_dcache_line_size];
}
for (i = 0; i < (d2_dcache_size / d2_dcache_line_size); i++) {
d2_dcache_mem[i].flag.tag = 0;
d2_dcache_mem[i].flag.index = 0;
d2_dcache_mem[i].flag.reserved = 0;
d2_dcache_mem[i].flag.invalid = 1;
d2_dcache_mem[i].flag.dirty = 0;
memset(d2_dcache_mem[i].insn, 0, d2_dcache_line_size);
}
for (i = 0; i < DSPNUM; i++) {
m1_bus_base_array[i] = multi_arg(pacdsp[i], core_base);
m1_bus_size_array[i] = multi_arg(pacdsp[i].m1_mem, dmem_m1_size)
+ multi_arg(pacdsp[i].res1, res1_size)
+ multi_arg(pacdsp[i].biu, biu_size)
+ multi_arg(pacdsp[i].icu, icu_size)
+ multi_arg(pacdsp[i].dmu, dmu_size)
+ multi_arg(pacdsp[i].dma, dma_size)
+ multi_arg(pacdsp[i].res2, res2_size);
m1_bus_base_array_no_mem[i] = m1_bus_base_array[i] + multi_arg(pacdsp[i].m1_mem, dmem_m1_size);
m1_bus_size_array_no_mem[i] = multi_arg(pacdsp[i].res1, res1_size)
+ multi_arg(pacdsp[i].biu, biu_size)
+ multi_arg(pacdsp[i].icu, icu_size)
+ multi_arg(pacdsp[i].dmu, dmu_size)
+ multi_arg(pacdsp[i].dma, dma_size)
+ multi_arg(pacdsp[i].res2, res2_size);
}
m2_bus_base = multi_arg(m2_mem, dmem_m2_base);
m2_bus_size = multi_arg(m2_mem, dmem_m2_size)
+ multi_arg(l2_icu, l2_icu_size)
+ multi_arg(m2_dmu, m2_dmu_size)
+ multi_arg(m2_dma, m2_dma_size)
+ multi_arg(sem, sem_size)
+ multi_arg(c2cc, c2cc_size);
m2_bus_base_no_mem = m2_bus_base + multi_arg(m2_mem, dmem_m2_size);
m2_bus_size_no_mem = multi_arg(l2_icu, l2_icu_size)
+ multi_arg(m2_dmu, m2_dmu_size)
+ multi_arg(m2_dma, m2_dma_size)
+ multi_arg(sem, sem_size)
+ multi_arg(c2cc, c2cc_size);
biu_bus_base = multi_arg(ddr_mem, ddr_memory_base);
biu_bus_size = multi_arg(ddr_mem, ddr_memory_size);
sysdma_base = multi_arg(sys_dma, sys_dma_base);
sysdma_size = multi_arg(sys_dma, sys_dma_size);
c2cc_base = multi_arg(c2cc, c2cc_base);
c2cc_size = multi_arg(c2cc, c2cc_size);
for (i = 0; i < DSPNUM; i++) {
m1_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
m2_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
biu_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
dmu_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
}
for (i = 0; i < (DSPNUM + 1); i++) {
d2_bus_targ_socket_tagged[i].register_nb_transport_fw(this, &D2_Bus::nb_transport_fw, i);
d2_bus_targ_socket_tagged[i].register_b_transport(this, &D2_Bus::b_transport, i);
}
SC_THREAD(D2_Bus_Request_Thread);
}
~D2_Bus()
{}
private:
void D2_Bus_Request_Thread()
{
unsigned int i, len, offset;
tlm::tlm_sync_enum ret;
tlm::tlm_generic_payload *trans_ptr;
trans_extension *ext_ptr;
unsigned char *ptr;
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_core::sc_time t = sc_core::SC_ZERO_TIME;
sc_dt::uint64 addr;
int skip, core_id;
tlm::tlm_command cmd;
while (true) {
wait(d2_bus_RequestPEQ.get_event());
while (true) {
trans_ptr = d2_bus_RequestPEQ.get_next_transaction();
if (trans_ptr == NULL)
break;
skip = 0;
addr = trans_ptr->get_address();
cmd = trans_ptr->get_command();
trans_ptr->get_extension(ext_ptr);
ptr = trans_ptr->get_data_ptr();
len = trans_ptr->get_data_length();
core_id = GET_CORE(ext_ptr->inst_core_range);
//if (cmd == tlm::TLM_WRITE_COMMAND) {
// printf("write addr 0x%08x\r\n", addr);
//} else {
// printf("read addr 0x%08x\r\n", addr);
//}
//uncached
if (cmd == tlm::TLM_READ_COMMAND) {
lock(r_lock);
if (((addr >= m1_bus_base_array_no_mem[core_id])
&& ((addr + len) < (m1_bus_base_array_no_mem[core_id] + m1_bus_size_array_no_mem[core_id])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
skip = 1;
} else if ((addr >= m2_bus_base_no_mem)
&& ((addr + len) < (m2_bus_base_no_mem + m2_bus_size_no_mem))){
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
skip = 1;
} else if ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size))) {
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
skip = 1;
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array_no_mem[i])
&& ((addr + len) < (m1_bus_base_array_no_mem[i] + m1_bus_size_array_no_mem[i]))) {
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
skip = 1;
break;
}
}
}
unlock(r_lock);
} else if (cmd == tlm::TLM_WRITE_COMMAND) {
lock(w_lock);
if (((addr >= m1_bus_base_array_no_mem[core_id])
&& ((addr + len) < (m1_bus_base_array_no_mem[core_id] + m1_bus_size_array_no_mem[core_id])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_mem_write(*trans_ptr, ext_ptr->inst_core_range);
skip = 1;
} else if ((addr >= m2_bus_base_no_mem)
&& ((addr + len) < (m2_bus_base_no_mem + m2_bus_size_no_mem))){
m2_mem_write(*trans_ptr, ext_ptr->inst_core_range);
skip = 1;
} else if ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size))) {
ddr_mem_write(*trans_ptr, ext_ptr->inst_core_range);
skip = 1;
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array_no_mem[i])
&& ((addr + len) < (m1_bus_base_array_no_mem[i] + m1_bus_size_array_no_mem[i]))) {
dmu_mem_write(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
skip = 1;
break;
}
}
}
unlock(w_lock);
}
//cached
if (skip == 0) {
if (cmd == tlm::TLM_READ_COMMAND) {
lock(r_lock);
for (offset = 0; offset < len; offset++) {
struct d2_dcache_addr iaddr = *(struct d2_dcache_addr *)&(addr);
//invalid or not
if ((d2_dcache_mem[iaddr.index].flag.invalid == 1))
{
sc_dt::uint64 read_addr = (addr & ~(d2_dcache_line_size - 1));
unsigned int read_length = d2_dcache_line_size;
trans_ptr->set_address(read_addr);
trans_ptr->set_data_length(read_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_READ_COMMAND);
if ((read_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((read_addr + read_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((read_addr + read_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((read_addr + read_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((read_addr >= multi_arg(pacdsp[i], core_base))
&& ((read_addr + read_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No read mem address (0x%llx) in simulator\r\n", read_addr);
//debug_inst[core_id] = 1;
}
}
d2_dcache_mem[iaddr.index].flag.dirty = 0;
} else {
if (d2_dcache_mem[iaddr.index].flag.tag != iaddr.tag) {
//replace or not
if (d2_dcache_mem[iaddr.index].flag.dirty == 1) {
//dirty or not
sc_dt::uint64 write_addr = (d2_dcache_mem[iaddr.index].flag.tag << 16)
| (iaddr.index << 8);
unsigned int write_length = d2_dcache_line_size;
trans_ptr->set_address(write_addr);
trans_ptr->set_data_length(write_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_WRITE_COMMAND);
lock(w_lock);
if ((write_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((write_addr + write_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((write_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((write_addr + write_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((write_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((write_addr + write_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((write_addr >= multi_arg(pacdsp[i], core_base))
&& ((write_addr + write_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_write(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No write mem address (0x%llx) in simulator\r\n", write_addr);
//debug_inst[core_id] = 1;
}
}
//d2_dcache_mem[iaddr.index].flag.invalid = 1;
//d2_dcache_mem[iaddr.index].flag.tag = 0;
memset(d2_dcache_mem[iaddr.index].insn, 0, d2_dcache_line_size);
d2_dcache_mem[iaddr.index].flag.dirty = 0;
unlock(w_lock);
}
sc_dt::uint64 read_addr = (addr & ~(d2_dcache_line_size - 1));
unsigned int read_length = d2_dcache_line_size;
trans_ptr->set_address(read_addr);
trans_ptr->set_data_length(read_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_READ_COMMAND);
if ((read_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((read_addr + read_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((read_addr + read_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((read_addr + read_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((read_addr >= multi_arg(pacdsp[i], core_base))
&& ((read_addr + read_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No read mem address (0x%llx) in simulator\r\n", read_addr);
//debug_inst[core_id] = 1;
}
}
}
}
*ptr = d2_dcache_mem[iaddr.index].insn[addr & (d2_dcache_line_size - 1)];
d2_dcache_mem[iaddr.index].flag.invalid = 0;
d2_dcache_mem[iaddr.index].flag.tag = iaddr.tag;
addr++;
ptr++;
}
unlock(r_lock);
} else if (cmd == tlm::TLM_WRITE_COMMAND) {
//write to main mem/cache
lock(w_lock);
for (offset = 0; offset < len; offset++) {
struct d2_dcache_addr iaddr = *(struct d2_dcache_addr *)&(addr);
//invalid or not
if ((d2_dcache_mem[iaddr.index].flag.invalid == 0))
{
if (d2_dcache_mem[iaddr.index].flag.tag != iaddr.tag) {
//replace or not
if (d2_dcache_mem[iaddr.index].flag.dirty == 1) {
//dirty or not
sc_dt::uint64 write_addr = (d2_dcache_mem[iaddr.index].flag.tag << 16)
| (iaddr.index << 8) ;
unsigned int write_length = d2_dcache_line_size;
trans_ptr->set_address(write_addr);
trans_ptr->set_data_length(write_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_WRITE_COMMAND);
if ((write_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((write_addr + write_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((write_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((write_addr + write_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((write_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((write_addr + write_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((write_addr >= multi_arg(pacdsp[i], core_base))
&& ((write_addr + write_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_write(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No write mem address (0x%llx) in simulator\r\n", write_addr);
//debug_inst[core_id] = 1;
}
}
//d2_dcache_mem[iaddr.index].flag.invalid = 1;
//d2_dcache_mem[iaddr.index].flag.tag = 0;
memset(d2_dcache_mem[iaddr.index].insn, 0, d2_dcache_line_size);
d2_dcache_mem[iaddr.index].flag.dirty = 0;
sc_dt::uint64 read_addr = (addr & ~(d2_dcache_line_size - 1));
unsigned int read_length = d2_dcache_line_size;
trans_ptr->set_address(read_addr);
trans_ptr->set_data_length(read_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_READ_COMMAND);
lock(r_lock);
if ((read_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((read_addr + read_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((read_addr + read_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((read_addr + read_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((read_addr >= multi_arg(pacdsp[i], core_base))
&& ((read_addr + read_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No read mem address (0x%llx) in simulator\r\n", read_addr);
//debug_inst[core_id] = 1;
}
}
unlock(r_lock);
} else {
//no-dirty
sc_dt::uint64 read_addr = (addr & ~(d2_dcache_line_size - 1));
unsigned int read_length = d2_dcache_line_size;
trans_ptr->set_address(read_addr);
trans_ptr->set_data_length(read_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_READ_COMMAND);
lock(r_lock);
if ((read_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((read_addr + read_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((read_addr + read_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((read_addr + read_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((read_addr >= multi_arg(pacdsp[i], core_base))
&& ((read_addr + read_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No read mem address (0x%llx) in simulator\r\n", read_addr);
//debug_inst[core_id] = 1;
}
}
unlock(r_lock);
}
}
} else {
sc_dt::uint64 read_addr = (addr & ~(d2_dcache_line_size - 1));
unsigned int read_length = d2_dcache_line_size;
trans_ptr->set_address(read_addr);
trans_ptr->set_data_length(read_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_READ_COMMAND);
lock(r_lock);
if ((read_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((read_addr + read_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((read_addr + read_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((read_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((read_addr + read_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((read_addr >= multi_arg(pacdsp[i], core_base))
&& ((read_addr + read_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No read mem address (0x%llx) in simulator\r\n", read_addr);
//debug_inst[core_id] = 1;
}
}
d2_dcache_mem[iaddr.index].flag.dirty = 0;
unlock(r_lock);
}
if (d2_dcache_type == 1) { //write_back
d2_dcache_mem[iaddr.index].insn[addr & (d2_dcache_line_size - 1)] = *ptr;
d2_dcache_mem[iaddr.index].flag.invalid = 0;
d2_dcache_mem[iaddr.index].flag.tag = iaddr.tag;
d2_dcache_mem[iaddr.index].flag.dirty = 1;
} else { //write through
d2_dcache_mem[iaddr.index].insn[addr & (d2_dcache_line_size - 1)] = *ptr;
d2_dcache_mem[iaddr.index].flag.invalid = 0;
d2_dcache_mem[iaddr.index].flag.tag = iaddr.tag;
d2_dcache_mem[iaddr.index].flag.dirty = 0;
sc_dt::uint64 write_addr = (d2_dcache_mem[iaddr.index].flag.tag << 16)
| (iaddr.index << 8) ;
unsigned int write_length = d2_dcache_line_size;
trans_ptr->set_address(write_addr);
trans_ptr->set_data_length(write_length);
trans_ptr->set_data_ptr(d2_dcache_mem[iaddr.index].insn);
trans_ptr->set_command(tlm::TLM_WRITE_COMMAND);
if ((write_addr >= multi_arg(pacdsp[core_id], core_base))
&& ((write_addr + write_length) < (multi_arg(pacdsp[core_id], core_base)
+ multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size))))
{
m1_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((write_addr >= multi_arg(m2_mem, dmem_m2_base))
&& ((write_addr + write_length) < (multi_arg(m2_mem, dmem_m2_base)
+ multi_arg(m2_mem, dmem_m2_size))))
{
m2_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((write_addr >= multi_arg(ddr_mem, ddr_memory_base))
&& ((write_addr + write_length) < (multi_arg(ddr_mem, ddr_memory_base)
+ multi_arg(ddr_mem, ddr_memory_size))))
{
ddr_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((write_addr >= multi_arg(pacdsp[i], core_base))
&& ((write_addr + write_length)
< (multi_arg(pacdsp[i], core_base)
+ multi_arg(pacdsp[i].m1_mem, dmem_m1_size))))
{
dmu_mem_write(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No write mem address (0x%llx) in simulator\r\n", write_addr);
//debug_inst[core_id] = 1;
}
}
}
addr++;
ptr++;
}
unlock(w_lock);
}
}
tlm::tlm_phase phase = tlm::BEGIN_RESP;
PendingTransactionsIterator it = mPendingTransactions.find(trans_ptr);
ret = d2_bus_targ_socket_tagged[it->second.from]->nb_transport_bw(*trans_ptr, phase, t);
mPendingTransactions.erase(it);
}
}
}
private:
int d2_cache_read(tlm::tlm_generic_payload *trans_ptr)
{
return CACHE_MISS;
}
int d2_cache_write(tlm::tlm_generic_payload *trans_ptr)
{
return CACHE_MISS;
}
int dbg_d2cache_read(tlm::tlm_generic_payload &trans)
{
return CACHE_MISS;
}
int dbg_d2cache_write(tlm::tlm_generic_payload &trans)
{
return CACHE_MISS;
}
void m1_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M1_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m1_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(m1_bus_ResponsePEQ.get_event());
trans = m1_bus_ResponsePEQ.get_next_transaction();
}
void m1_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M1_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m1_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(m1_bus_ResponsePEQ.get_event());
trans = m1_bus_ResponsePEQ.get_next_transaction();
}
void m2_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 1;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M2_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m2_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(m2_bus_ResponsePEQ.get_event());
trans = m2_bus_ResponsePEQ.get_next_transaction();
}
void m2_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 1;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M2_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m2_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(m2_bus_ResponsePEQ.get_event());
trans = m2_bus_ResponsePEQ.get_next_transaction();
}
void ddr_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 2;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, DDR_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
biu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(biu_bus_ResponsePEQ.get_event());
trans = biu_bus_ResponsePEQ.get_next_transaction();
}
void ddr_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 2;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, DDR_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
biu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(biu_bus_ResponsePEQ.get_event());
trans = biu_bus_ResponsePEQ.get_next_transaction();
}
void dmu_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
switch (inst_mode) {
case INST_SC:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_SC, core_id, M1_RANGE);
break;
case INST_C1:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C1, core_id, M1_RANGE);
break;
case INST_C2:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C2, core_id, M1_RANGE);
break;
default:
break;
}
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
dmu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(dmu_bus_ResponsePEQ.get_event());
trans = dmu_bus_ResponsePEQ.get_next_transaction();
}
void dmu_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
switch (inst_mode) {
case INST_SC:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_SC, core_id, M1_RANGE);
break;
case INST_C1:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C1, core_id, M1_RANGE);
break;
case INST_C2:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C2, core_id, M1_RANGE);
break;
default:
break;
}
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
dmu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
tlm::tlm_generic_payload *trans;
wait(dmu_bus_ResponsePEQ.get_event());
trans = dmu_bus_ResponsePEQ.get_next_transaction();
}
private:
tlm::tlm_sync_enum nb_transport_bw(int portId, tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_time &delay)
{
sc_dt::uint64 addr;
unsigned int len;
trans_extension *ext_ptr;
trans.get_extension(ext_ptr);
int core_id = GET_CORE(ext_ptr->inst_core_range);
addr = trans.get_address();
len = trans.get_data_length();
if (phase == tlm::BEGIN_RESP) {
if (ext_ptr->flag == ISS_DATA) {
if (((addr >= m1_bus_base_array[core_id])
&& ((addr + len) < (m1_bus_base_array[core_id] + m1_bus_size_array[core_id])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_bus_ResponsePEQ.notify(trans, delay);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))) {
m2_bus_ResponsePEQ.notify(trans, delay);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))) {
biu_bus_ResponsePEQ.notify(trans, delay);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i]) && ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
dmu_bus_ResponsePEQ.notify(trans, delay);
break;
}
}
}
}
}
return tlm::TLM_COMPLETED;
}
int dbg_addr_valid(int *core_id, int range, unsigned int addr, int len)
{
unsigned int i;
int ret = -1;
switch (range) {
case DBG_CORE_M1_MEM:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) + multi_arg(pacdsp[i].m1_mem, dmem_m1_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) + multi_arg(pacdsp[i].m1_mem, dmem_m1_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_BIU:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset) +
multi_arg(pacdsp[i].biu, biu_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].biu, biu_offset) + multi_arg(pacdsp[i].biu, biu_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset) +
multi_arg(pacdsp[i].biu, biu_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].biu, biu_offset) + multi_arg(pacdsp[i].biu, biu_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_ICU:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset) +
multi_arg(pacdsp[i].icu, icu_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].icu, icu_offset) + multi_arg(pacdsp[i].icu, icu_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset) +
multi_arg(pacdsp[i].icu, icu_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].icu, icu_offset) + multi_arg(pacdsp[i].icu, icu_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_DMU:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset) +
multi_arg(pacdsp[i].dmu, dmu_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dmu, dmu_offset) + multi_arg(pacdsp[i].dmu, dmu_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset) +
multi_arg(pacdsp[i].dmu, dmu_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dmu, dmu_offset) + multi_arg(pacdsp[i].dmu, dmu_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_DMA:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset) +
multi_arg(pacdsp[i].dma, dma_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dma, dma_offset) + multi_arg(pacdsp[i].dma, dma_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset) +
multi_arg(pacdsp[i].dma, dma_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dma, dma_offset) + multi_arg(pacdsp[i].dma, dma_size))) {
ret = 2;
break;
}
}
break;
case DBG_M2_MEM:
if ((addr >= multi_arg(m2_mem, dmem_m2_base)) && (addr < multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size)) && ((addr + len) < multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size))) {
ret = 1;
} else if ((addr >= multi_arg(m2_mem, dmem_m2_base)) && (addr < multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size)) && ((addr + len) >= multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size))) {
ret = 2;
}
break;
case DBG_M2_ICU:
if ((addr >= multi_arg(l2_icu, l2_icu_base)) && (addr < multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size)) && ((addr + len) < multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size))) {
ret = 1;
} else if ((addr >= multi_arg(l2_icu, l2_icu_base)) && (addr < multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size)) && ((addr + len) >= multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size))) {
ret = 2;
}
break;
case DBG_M2_DMU:
if ((addr >= multi_arg(m2_dmu, m2_dmu_base)) &&
(addr < multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size)) &&
((addr + len) < multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size))) {
ret = 1;
} else if ((addr >= multi_arg(m2_dmu, m2_dmu_base)) &&
(addr < multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size)) &&
((addr + len) >= multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size))) {
ret = 2;
}
break;
case DBG_M2_DMA:
if ((addr >= multi_arg(m2_dma, m2_dma_base)) &&
(addr < multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size)) &&
((addr + len) < multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size))) {
ret = 1;
} else if ((addr >= multi_arg(m2_dma, m2_dma_base)) &&
(addr < multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size)) &&
((addr + len) >= multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size))) {
ret = 2;
}
break;
case DBG_C2CC_INTERFACE:
if ((addr >= multi_arg(c2cc, c2cc_base)) &&
(addr < multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size)) &&
((addr + len) < multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size))) {
ret = 1;
} else if ((addr >= multi_arg(c2cc, c2cc_base)) &&
(addr < multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size)) &&
((addr + len) >= multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size))) {
ret = 2;
}
break;
case DBG_DDR_MEM:
if ((addr >= multi_arg(ddr_mem, ddr_memory_base)) &&
(addr < multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size)) &&
((addr + len) < multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size))) {
ret = 1;
} else if ((addr >= multi_arg(ddr_mem, ddr_memory_base)) &&
(addr < multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size)) &&
((addr + len) >= multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size))) {
ret = 2;
}
break;
case DBG_SYS_DMA:
if ((addr >= multi_arg(sys_dma, sys_dma_base)) &&
(addr < multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size)) &&
((addr + len) < multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size))) {
ret = 1;
} else if ((addr >= multi_arg(sys_dma, sys_dma_base)) &&
(addr < multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size)) &&
((addr + len) >= multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size))) {
ret = 2;
}
break;
default:
ret = -1;
break;
}
return ret;
}
tlm::tlm_sync_enum nb_transport_fw(int id, tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_time & t)
{
if(phase == tlm::BEGIN_REQ) {
addPendingTransaction(trans, 0, id);
d2_bus_RequestPEQ.notify(trans, t);
}
return tlm::TLM_ACCEPTED;
}
void b_transport(int id, tlm::tlm_generic_payload & trans, sc_time & t)
{
trans_extension *ext_ptr;
trans.get_extension(ext_ptr);
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 addr = trans.get_address();
unsigned int len = trans.get_data_length();
sc_time delay = sc_core::SC_ZERO_TIME;
unsigned int range;
int ret;
int core_id = 0, miss = 0;
int length = len;
int coreid = GET_CORE(ext_ptr->inst_core_range);
//flush dcache
unsigned int i;
unsigned int offset;
tlm::tlm_generic_payload cache_trans;
lock(w_lock);
for (offset = 0; offset < (d2_dcache_size / d2_dcache_line_size); offset++) {
if (d2_dcache_mem[offset].flag.dirty == 1) {
sc_dt::uint64 write_addr = (d2_dcache_mem[offset].flag.tag << 16)
| (offset << 8);
unsigned int write_length = d2_dcache_line_size;
cache_trans.set_address(write_addr);
cache_trans.set_data_length(write_length);
cache_trans.set_data_ptr(d2_dcache_mem[offset].insn);
cache_trans.set_command(tlm::TLM_WRITE_COMMAND);
if ((write_addr >= m2_bus_base) && ((write_addr + write_length) < (m2_bus_base + m2_bus_size))){
m2_bus_init_socket_tagged[0]->b_transport(cache_trans, delay);
} else if (((write_addr >= biu_bus_base) && ((write_addr + write_length) < (biu_bus_base + biu_bus_size))))
{
biu_bus_init_socket_tagged[0]->b_transport(cache_trans, delay);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((write_addr >= m1_bus_base_array[i])
&& ((write_addr + write_length) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
m1_bus_init_socket_tagged[i]->b_transport(cache_trans, delay);
break;
}
}
}
}
//set all to invalid
d2_dcache_mem[offset].flag.tag = 0;
d2_dcache_mem[offset].flag.index = 0;
d2_dcache_mem[offset].flag.reserved = 0;
d2_dcache_mem[offset].flag.invalid = 1;
d2_dcache_mem[offset].flag.dirty = 0;
memset(d2_dcache_mem[offset].insn, 0, d2_dcache_line_size);
}
unlock(w_lock);
if (cmd == tlm::TLM_READ_COMMAND) {
lock(r_lock);
for (range = DBG_CORE_M1_MEM; range <= DBG_SYS_DMA; range++) {
ret = dbg_addr_valid(&core_id, range, addr, len);
if (ret == 1) {
break;
} else if (ret == 2) {
printf("addr(0x%llx) + len(0x%08x) is out of memory range(%d)\r\n", addr, len, range);
switch (range) {
case DBG_CORE_M1_MEM:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].m1_mem, dmem_m1_offset)
- multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size) + 1;
break;
case DBG_CORE_BIU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].biu, biu_offset) - multi_arg(pacdsp[core_id].biu, biu_size) + 1;
break;
case DBG_CORE_ICU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].icu, icu_offset) - multi_arg(pacdsp[core_id].icu, icu_size) + 1;
break;
case DBG_CORE_DMU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dmu, dmu_offset) - multi_arg(pacdsp[core_id].dmu, dmu_size) + 1;
break;
case DBG_CORE_DMA:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dma, dma_offset) - multi_arg(pacdsp[core_id].dma, dma_size) + 1;
break;
case DBG_M2_MEM:
length -= addr + length - multi_arg(m2_mem, dmem_m2_base) - multi_arg(m2_mem, dmem_m2_size) + 1;
break;
case DBG_M2_ICU:
length -= addr + length - multi_arg(l2_icu, l2_icu_base) - multi_arg(l2_icu, l2_icu_size) + 1;
break;
case DBG_M2_DMU:
length -= addr + length - multi_arg(m2_dmu, m2_dmu_base) - multi_arg(m2_dmu, m2_dmu_size) + 1;
break;
case DBG_M2_DMA:
length -= addr + length - multi_arg(m2_dma, m2_dma_base) - multi_arg(m2_dma, m2_dma_size) + 1;
break;
case DBG_C2CC_INTERFACE:
length -= addr + length - multi_arg(c2cc, c2cc_base) - multi_arg(c2cc, c2cc_size) + 1;
break;
case DBG_DDR_MEM:
length -= addr + length
- multi_arg(ddr_mem, ddr_memory_base) - multi_arg(ddr_mem, ddr_memory_size) + 1;
break;
case DBG_SYS_DMA:
length -= addr + length - multi_arg(sys_dma, sys_dma_base) - multi_arg(sys_dma, sys_dma_size) + 1;
break;
}
printf("\nNow that read mem addr(0x%llx) len(0x%08x)\r\n", addr, length);
break;
}
}
if (ret == -1) {
printf("Not that memory in simulator addr(0x%llx) len(0x%08x)\r\n", addr, length);
}
trans.set_data_length(length);
miss = dbg_d2cache_read(trans);
if (miss == CACHE_MISS) {
if (((addr >= m1_bus_base_array[coreid])
&& ((addr + len) < (m1_bus_base_array[coreid] + m1_bus_size_array[coreid])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size)))
{
m1_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))){
m2_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))){
biu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i])
&& ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i])))
{
dmu_bus_init_socket_tagged[i]->b_transport(trans, delay);
break;
}
}
if (i == DSPNUM) {
printf("b_transport No read mem address (0x%llx) in simualtor\r\n",addr);
}
}
}
unlock(r_lock);
} else if (cmd == tlm::TLM_WRITE_COMMAND) {
lock(w_lock);
for (range = DBG_CORE_M1_MEM; range <= DBG_SYS_DMA; range++) {
ret = dbg_addr_valid(&core_id, range, addr, len);
if (ret == 1) {
break;
} else if (ret == 2) {
printf("addr(0x%llx) + len(0x%08x) is out of memory range(%d)\r\n", addr, len, range);
switch (range) {
case DBG_CORE_M1_MEM:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].m1_mem, dmem_m1_offset)
- multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size) + 1;
break;
case DBG_CORE_BIU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].biu, biu_offset) - multi_arg(pacdsp[core_id].biu, biu_size) + 1;
break;
case DBG_CORE_ICU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].icu, icu_offset) - multi_arg(pacdsp[core_id].icu, icu_size) + 1;
break;
case DBG_CORE_DMU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dmu, dmu_offset) - multi_arg(pacdsp[core_id].dmu, dmu_size) + 1;
break;
case DBG_CORE_DMA:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dma, dma_offset) - multi_arg(pacdsp[core_id].dma, dma_size) + 1;
break;
case DBG_M2_MEM:
length -= addr + length - multi_arg(m2_mem, dmem_m2_base) - multi_arg(m2_mem, dmem_m2_size) + 1;
break;
case DBG_M2_ICU:
length -= addr + length - multi_arg(l2_icu, l2_icu_base) - multi_arg(l2_icu, l2_icu_size) + 1;
break;
case DBG_M2_DMU:
length -= addr + length - multi_arg(m2_dmu, m2_dmu_base) - multi_arg(m2_dmu, m2_dmu_size) + 1;
break;
case DBG_M2_DMA:
length -= addr + length - multi_arg(m2_dma, m2_dma_base) - multi_arg(m2_dma, m2_dma_size) + 1;
break;
case DBG_C2CC_INTERFACE:
length -= addr + length - multi_arg(c2cc, c2cc_base) - multi_arg(c2cc, c2cc_size) + 1;
break;
case DBG_DDR_MEM:
length -= addr + length - multi_arg(ddr_mem, ddr_memory_base)
- multi_arg(ddr_mem, ddr_memory_size) + 1;
break;
case DBG_SYS_DMA:
length -= addr + length - multi_arg(sys_dma, sys_dma_base) - multi_arg(sys_dma, sys_dma_size) + 1;
break;
}
printf("\nNow that write mem addr(0x%llx) len(0x%08x)\r\n", addr, length);
break;
}
}
if (ret == -1) {
printf("Not that memory in simulator addr(0x%llx) len(0x%08x)\r\n", addr, length);
}
trans.set_data_length(length);
miss = dbg_d2cache_write(trans);
if (miss == CACHE_MISS) {
if (((addr >= m1_bus_base_array[coreid])
&& ((addr + len) < (m1_bus_base_array[coreid] + m1_bus_size_array[coreid])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size)))
{
m1_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))){
m2_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))){
biu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i]) && ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
dmu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
break;
}
}
if (i == DSPNUM) {
printf("b_transport No write mem address(0x%llx) in simualtor\r\n",addr);
}
}
}
unlock(w_lock);
}
}
void lock(unsigned int lock)
{
//printf("lock !!\r\n");
while (lock != 0) {
printf("still lock !!\r\n");
}
lock = 1;
}
void unlock(unsigned int lock)
{
//printf("unlock !!\r\n");
lock = 0;
}
private:
void addPendingTransaction(tlm::tlm_generic_payload & trans, int to, int initiatorId)
{
const ConnectionInfo info = { initiatorId, to };
assert(mPendingTransactions.find(&trans) == mPendingTransactions.end());
mPendingTransactions[&trans] = info;
}
struct ConnectionInfo {
int from;
int to;
};
typedef std::map < tlm::tlm_generic_payload *, ConnectionInfo > PendingTransactions;
typedef PendingTransactions::iterator PendingTransactionsIterator;
private:
PendingTransactions mPendingTransactions;
};
#else //IN PAC_SOC_PROFILE
struct D2_Bus:public sc_core::sc_module, public pac_bus
{
private:
struct sim_arg *multi_sim_arg;
unsigned int m1_bus_base_array[DSPNUM], m1_bus_size_array[DSPNUM];
unsigned int m2_bus_base, m2_bus_size;
unsigned int biu_bus_base, biu_bus_size;
unsigned int sysdma_base, sysdma_size;
unsigned int c2cc_base, c2cc_size;
unsigned int i;
public:
tlm_utils::simple_initiator_socket_tagged < D2_Bus > m1_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_initiator_socket_tagged < D2_Bus > m2_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_initiator_socket_tagged < D2_Bus > biu_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_initiator_socket_tagged < D2_Bus > dmu_bus_init_socket_tagged[DSPNUM];
tlm_utils::simple_target_socket_tagged < D2_Bus > d2_bus_targ_socket_tagged[DSPNUM+1]; //connect to core_bus
tlm_utils::peq_with_get < tlm::tlm_generic_payload > m1_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > m2_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > biu_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > dmu_bus_ResponsePEQ;
tlm_utils::peq_with_get < tlm::tlm_generic_payload > d2_bus_RequestPEQ;
SC_HAS_PROCESS(D2_Bus);
public:
D2_Bus(sc_module_name _name, struct sim_arg *arg)
: sc_core::sc_module(_name)
, multi_sim_arg(arg)
, m1_bus_ResponsePEQ("m1_bus_ResponsePEQ")
, m2_bus_ResponsePEQ("m2_bus_ResponsePEQ")
, biu_bus_ResponsePEQ("biu_bus_ResponsePEQ")
, dmu_bus_ResponsePEQ("dmu_bus_ResponsePEQ")
, d2_bus_RequestPEQ("d2_bus_RequestPEQ")
{
for (i = 0; i < DSPNUM; i++) {
m1_bus_base_array[i] = multi_arg(pacdsp[i], core_base);
m1_bus_size_array[i] += multi_arg(pacdsp[i].m1_mem, dmem_m1_size)
+ multi_arg(pacdsp[i].res1, res1_size)
+ multi_arg(pacdsp[i].biu, biu_size)
+ multi_arg(pacdsp[i].icu, icu_size)
+ multi_arg(pacdsp[i].dmu, dmu_size)
+ multi_arg(pacdsp[i].dma, dma_size)
+ multi_arg(pacdsp[i].res2, res2_size);
}
m2_bus_base = multi_arg(m2_mem, dmem_m2_base);
m2_bus_size = multi_arg(m2_mem, dmem_m2_size)
+ multi_arg(l2_icu, l2_icu_size)
+ multi_arg(m2_dmu, m2_dmu_size)
+ multi_arg(m2_dma, m2_dma_size)
+ multi_arg(sem, sem_size)
+ multi_arg(c2cc, c2cc_size);
biu_bus_base = multi_arg(ddr_mem, ddr_memory_base);
biu_bus_size = multi_arg(ddr_mem, ddr_memory_size);
sysdma_base = multi_arg(sys_dma, sys_dma_base);
sysdma_size = multi_arg(sys_dma, sys_dma_size);
c2cc_base = multi_arg(c2cc, c2cc_base);
c2cc_size = multi_arg(c2cc, c2cc_size);
for (i = 0; i < DSPNUM; i++) {
m1_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
m2_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
biu_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
dmu_bus_init_socket_tagged[i].register_nb_transport_bw(this, &D2_Bus::nb_transport_bw, i);
}
for (i = 0; i < (DSPNUM + 1); i++) {
d2_bus_targ_socket_tagged[i].register_nb_transport_fw(this, &D2_Bus::nb_transport_fw, i);
d2_bus_targ_socket_tagged[i].register_b_transport(this, &D2_Bus::b_transport, i);
}
SC_THREAD(D2_Bus_Request_Thread);
}
~D2_Bus()
{}
private:
void D2_Bus_Request_Thread()
{
trans_extension *ext_ptr;
tlm::tlm_generic_payload *trans_ptr;
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_core::sc_time t = sc_core::SC_ZERO_TIME;
sc_dt::uint64 addr;
unsigned int len, i;
int cmd, core_id, miss = 0;
while (true) {
wait(d2_bus_RequestPEQ.get_event());
while(true) {
trans_ptr = d2_bus_RequestPEQ.get_next_transaction();
if (trans_ptr == NULL) {
break;
}
addr = trans_ptr->get_address();
len = trans_ptr->get_data_length();
trans_ptr->get_extension(ext_ptr);
cmd = trans_ptr->get_command();
core_id = GET_CORE(ext_ptr->inst_core_range);
if (cmd == tlm::TLM_READ_COMMAND) {
miss = d2_cache_read(trans_ptr);
if (miss == CACHE_MISS) {
if (((addr >= m1_bus_base_array[core_id])
&& ((addr + len) < (m1_bus_base_array[core_id] + m1_bus_size_array[core_id])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))) {
m2_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))) {
ddr_mem_read(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i])
&& ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
dmu_mem_read(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No read mem address (0x%llx) in simulator\r\n", addr);
//debug_inst[core_id] = 1;
}
}
}
} else if (cmd == tlm::TLM_WRITE_COMMAND) {
miss = d2_cache_write(trans_ptr);
if (miss == CACHE_MISS) {
if (((addr >= m1_bus_base_array[core_id])
&& ((addr + len) < (m1_bus_base_array[core_id] + m1_bus_size_array[core_id])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))) {
m2_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))) {
ddr_mem_write(*trans_ptr, ext_ptr->inst_core_range);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i])
&& ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
dmu_mem_write(*trans_ptr, ext_ptr->inst_core_range);
//dmu_flag |= 1 << i;
break;
}
}
if (i == DSPNUM) {
printf("No write mem address (0x%llx) in simulator\r\n", addr);
//debug_inst[core_id] = 1;
}
}
}
}
// tlm::tlm_phase phase = tlm::BEGIN_RESP;
PendingTransactionsIterator it = mPendingTransactions.find(trans_ptr);
// d2_bus_targ_socket_tagged[it->second.from]->nb_transport_bw(*trans_ptr, phase, t);
mPendingTransactions.erase(it);
}
}
}
private:
int d2_cache_read(tlm::tlm_generic_payload *trans_ptr)
{
return CACHE_MISS;
}
int d2_cache_write(tlm::tlm_generic_payload *trans_ptr)
{
return CACHE_MISS;
}
int dbg_d2cache_read(tlm::tlm_generic_payload &trans)
{
return CACHE_MISS;
}
int dbg_d2cache_write(tlm::tlm_generic_payload &trans)
{
return CACHE_MISS;
}
void m1_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M1_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m1_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(m1_bus_ResponsePEQ.get_event());
// trans = m1_bus_ResponsePEQ.get_next_transaction();
}
void m1_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M1_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m1_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(m1_bus_ResponsePEQ.get_event());
// trans = m1_bus_ResponsePEQ.get_next_transaction();
}
void m2_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 1;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M2_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m2_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(m2_bus_ResponsePEQ.get_event());
// trans = m2_bus_ResponsePEQ.get_next_transaction();
}
void m2_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 1;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, M2_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
m2_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(m2_bus_ResponsePEQ.get_event());
// trans = m2_bus_ResponsePEQ.get_next_transaction();
}
void ddr_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 2;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, DDR_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
biu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(biu_bus_ResponsePEQ.get_event());
// trans = biu_bus_ResponsePEQ.get_next_transaction();
}
void ddr_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 2;
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(inst_mode, core_id, DDR_RANGE);
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
biu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(biu_bus_ResponsePEQ.get_event());
// trans = biu_bus_ResponsePEQ.get_next_transaction();
}
void dmu_mem_read(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
switch (inst_mode) {
case INST_SC:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_SC, core_id, M1_RANGE);
break;
case INST_C1:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C1, core_id, M1_RANGE);
break;
case INST_C2:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C2, core_id, M1_RANGE);
break;
default:
break;
}
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
dmu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(dmu_bus_ResponsePEQ.get_event());
// trans = dmu_bus_ResponsePEQ.get_next_transaction();
}
void dmu_mem_write(tlm::tlm_generic_payload &trans_ptr, unsigned int inst_core)
{
trans_extension *ext_ptr;
unsigned int inst_mode = GET_INST(inst_core);
unsigned int core_id = GET_CORE(inst_core);
trans_ptr.get_extension(ext_ptr);
soc_core_req_bit_mask[core_id] |= 1 << 0;
switch (inst_mode) {
case INST_SC:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_SC, core_id, M1_RANGE);
break;
case INST_C1:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C1, core_id, M1_RANGE);
break;
case INST_C2:
ext_ptr->inst_core_range = GEN_INST_CORE_RANGE(INST_DMU_C2, core_id, M1_RANGE);
break;
default:
break;
}
tlm::tlm_phase phase = tlm::BEGIN_REQ;
sc_time delay = sc_core::SC_ZERO_TIME;
trans_ptr.set_extension(ext_ptr);
dmu_bus_init_socket_tagged[core_id]->nb_transport_fw(trans_ptr, phase, delay);
// tlm::tlm_generic_payload *trans;
// wait(dmu_bus_ResponsePEQ.get_event());
// trans = dmu_bus_ResponsePEQ.get_next_transaction();
}
private:
tlm::tlm_sync_enum nb_transport_bw(int portId, tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_time &delay)
{
// sc_dt::uint64 addr;
// unsigned int len;
// trans_extension *ext_ptr;
// trans.get_extension(ext_ptr);
// int core_id = GET_CORE(ext_ptr->inst_core_range);
// addr = trans.get_address();
// len = trans.get_data_length();
// if (phase == tlm::BEGIN_RESP) {
// if (ext_ptr->flag == ISS_DATA) {
// if (((addr >= m1_bus_base_array[core_id])
// && ((addr + len) < (m1_bus_base_array[core_id] + m1_bus_size_array[core_id])))
// || ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
// m1_bus_ResponsePEQ.notify(trans, delay);
// } else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))) {
// m2_bus_ResponsePEQ.notify(trans, delay);
// } else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
// || ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))) {
// biu_bus_ResponsePEQ.notify(trans, delay);
// } else {
// for (i = 0; i < DSPNUM; i++) {
// if ((addr >= m1_bus_base_array[i]) && ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
// dmu_bus_ResponsePEQ.notify(trans, delay);
// break;
// }
// }
// }
// }
// }
return tlm::TLM_COMPLETED;
}
int dbg_addr_valid(int *core_id, int range, unsigned int addr, int len)
{
unsigned int i;
int ret = -1;
switch (range) {
case DBG_CORE_M1_MEM:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) + multi_arg(pacdsp[i].m1_mem, dmem_m1_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].m1_mem, dmem_m1_offset) + multi_arg(pacdsp[i].m1_mem, dmem_m1_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_BIU:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset) +
multi_arg(pacdsp[i].biu, biu_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].biu, biu_offset) + multi_arg(pacdsp[i].biu, biu_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].biu, biu_offset) +
multi_arg(pacdsp[i].biu, biu_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].biu, biu_offset) + multi_arg(pacdsp[i].biu, biu_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_ICU:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset) +
multi_arg(pacdsp[i].icu, icu_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].icu, icu_offset) + multi_arg(pacdsp[i].icu, icu_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].icu, icu_offset) +
multi_arg(pacdsp[i].icu, icu_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].icu, icu_offset) + multi_arg(pacdsp[i].icu, icu_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_DMU:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset) +
multi_arg(pacdsp[i].dmu, dmu_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dmu, dmu_offset) + multi_arg(pacdsp[i].dmu, dmu_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dmu, dmu_offset) +
multi_arg(pacdsp[i].dmu, dmu_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dmu, dmu_offset) + multi_arg(pacdsp[i].dmu, dmu_size))) {
ret = 2;
break;
}
}
break;
case DBG_CORE_DMA:
for (i = 0; i < DSPNUM; i++) {
*core_id = i;
if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset) +
multi_arg(pacdsp[i].dma, dma_size)) && ((addr + len) < multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dma, dma_offset) + multi_arg(pacdsp[i].dma, dma_size))) {
ret = 1;
break;
} else if ((addr >= multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset)) &&
(addr < multi_arg(pacdsp[i], core_base) + multi_arg(pacdsp[i].dma, dma_offset) +
multi_arg(pacdsp[i].dma, dma_size)) && ((addr + len) >= multi_arg(pacdsp[i], core_base) +
multi_arg(pacdsp[i].dma, dma_offset) + multi_arg(pacdsp[i].dma, dma_size))) {
ret = 2;
break;
}
}
break;
case DBG_M2_MEM:
if ((addr >= multi_arg(m2_mem, dmem_m2_base)) && (addr < multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size)) && ((addr + len) < multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size))) {
ret = 1;
} else if ((addr >= multi_arg(m2_mem, dmem_m2_base)) && (addr < multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size)) && ((addr + len) >= multi_arg(m2_mem, dmem_m2_base) +
multi_arg(m2_mem, dmem_m2_size))) {
ret = 2;
}
break;
case DBG_M2_ICU:
if ((addr >= multi_arg(l2_icu, l2_icu_base)) && (addr < multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size)) && ((addr + len) < multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size))) {
ret = 1;
} else if ((addr >= multi_arg(l2_icu, l2_icu_base)) && (addr < multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size)) && ((addr + len) >= multi_arg(l2_icu, l2_icu_base) +
multi_arg(l2_icu, l2_icu_size))) {
ret = 2;
}
break;
case DBG_M2_DMU:
if ((addr >= multi_arg(m2_dmu, m2_dmu_base)) &&
(addr < multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size)) &&
((addr + len) < multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size))) {
ret = 1;
} else if ((addr >= multi_arg(m2_dmu, m2_dmu_base)) &&
(addr < multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size)) &&
((addr + len) >= multi_arg(m2_dmu, m2_dmu_base) + multi_arg(m2_dmu, m2_dmu_size))) {
ret = 2;
}
break;
case DBG_M2_DMA:
if ((addr >= multi_arg(m2_dma, m2_dma_base)) &&
(addr < multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size)) &&
((addr + len) < multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size))) {
ret = 1;
} else if ((addr >= multi_arg(m2_dma, m2_dma_base)) &&
(addr < multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size)) &&
((addr + len) >= multi_arg(m2_dma, m2_dma_base) + multi_arg(m2_dma, m2_dma_size))) {
ret = 2;
}
break;
case DBG_C2CC_INTERFACE:
if ((addr >= multi_arg(c2cc, c2cc_base)) &&
(addr < multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size)) &&
((addr + len) < multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size))) {
ret = 1;
} else if ((addr >= multi_arg(c2cc, c2cc_base)) &&
(addr < multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size)) &&
((addr + len) >= multi_arg(c2cc, c2cc_base) + multi_arg(c2cc, c2cc_size))) {
ret = 2;
}
break;
case DBG_DDR_MEM:
if ((addr >= multi_arg(ddr_mem, ddr_memory_base)) &&
(addr < multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size)) &&
((addr + len) < multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size))) {
ret = 1;
} else if ((addr >= multi_arg(ddr_mem, ddr_memory_base)) &&
(addr < multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size)) &&
((addr + len) >= multi_arg(ddr_mem, ddr_memory_base) + multi_arg(ddr_mem, ddr_memory_size))) {
ret = 2;
}
break;
case DBG_SYS_DMA:
if ((addr >= multi_arg(sys_dma, sys_dma_base)) &&
(addr < multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size)) &&
((addr + len) < multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size))) {
ret = 1;
} else if ((addr >= multi_arg(sys_dma, sys_dma_base)) &&
(addr < multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size)) &&
((addr + len) >= multi_arg(sys_dma, sys_dma_base) + multi_arg(sys_dma, sys_dma_size))) {
ret = 2;
}
break;
default:
ret = -1;
break;
}
return ret;
}
tlm::tlm_sync_enum nb_transport_fw(int id, tlm::tlm_generic_payload &trans, tlm::tlm_phase &phase, sc_time & t)
{
if(phase == tlm::BEGIN_REQ) {
addPendingTransaction(trans, 0, id);
d2_bus_RequestPEQ.notify(trans, t);
}
return tlm::TLM_ACCEPTED;
}
void b_transport(int id, tlm::tlm_generic_payload & trans, sc_time & t)
{
trans_extension *ext_ptr;
trans.get_extension(ext_ptr);
tlm::tlm_command cmd = trans.get_command();
sc_dt::uint64 addr = trans.get_address();
unsigned int len = trans.get_data_length();
sc_time delay = sc_core::SC_ZERO_TIME;
unsigned int range;
int ret;
int core_id = 0, miss = 0;
int length = len;
int coreid = GET_CORE(ext_ptr->inst_core_range);
if (cmd == tlm::TLM_READ_COMMAND) {
for (range = DBG_CORE_M1_MEM; range <= DBG_SYS_DMA; range++) {
ret = dbg_addr_valid(&core_id, range, addr, len);
if (ret == 1) {
break;
} else if (ret == 2) {
printf("addr(0x%llx) + len(0x%08x) is out of memory range(%d)\r\n", addr, len, range);
switch (range) {
case DBG_CORE_M1_MEM:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].m1_mem, dmem_m1_offset) - multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size) + 1;
break;
case DBG_CORE_BIU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].biu, biu_offset) - multi_arg(pacdsp[core_id].biu, biu_size) + 1;
break;
case DBG_CORE_ICU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].icu, icu_offset) - multi_arg(pacdsp[core_id].icu, icu_size) + 1;
break;
case DBG_CORE_DMU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dmu, dmu_offset) - multi_arg(pacdsp[core_id].dmu, dmu_size) + 1;
break;
case DBG_CORE_DMA:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dma, dma_offset) - multi_arg(pacdsp[core_id].dma, dma_size) + 1;
break;
case DBG_M2_MEM:
length -= addr + length - multi_arg(m2_mem, dmem_m2_base) - multi_arg(m2_mem, dmem_m2_size) + 1;
break;
case DBG_M2_ICU:
length -= addr + length - multi_arg(l2_icu, l2_icu_base) - multi_arg(l2_icu, l2_icu_size) + 1;
break;
case DBG_M2_DMU:
length -= addr + length - multi_arg(m2_dmu, m2_dmu_base) - multi_arg(m2_dmu, m2_dmu_size) + 1;
break;
case DBG_M2_DMA:
length -= addr + length - multi_arg(m2_dma, m2_dma_base) - multi_arg(m2_dma, m2_dma_size) + 1;
break;
case DBG_C2CC_INTERFACE:
length -= addr + length - multi_arg(c2cc, c2cc_base) - multi_arg(c2cc, c2cc_size) + 1;
break;
case DBG_DDR_MEM:
length -= addr + length - multi_arg(ddr_mem, ddr_memory_base) - multi_arg(ddr_mem, ddr_memory_size) + 1;
break;
case DBG_SYS_DMA:
length -= addr + length - multi_arg(sys_dma, sys_dma_base) - multi_arg(sys_dma, sys_dma_size) + 1;
break;
}
printf("\nNow that read mem addr(0x%llx) len(0x%08x)\r\n", addr, length);
break;
}
}
if (ret == -1) {
printf("Not that memory in simulator addr(0x%llx) len(0x%08x)\r\n", addr, length);
}
trans.set_data_length(length);
miss = dbg_d2cache_read(trans);
if (miss == CACHE_MISS) {
if (((addr >= m1_bus_base_array[coreid]) && ((addr + len) < (m1_bus_base_array[coreid] + m1_bus_size_array[coreid])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))){
m2_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))){
biu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i]) && ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
dmu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
break;
}
}
if (i == DSPNUM) {
printf("No read mem address(0x%llx) in simualtor\r\n",addr);
}
}
}
} else if (cmd == tlm::TLM_WRITE_COMMAND) {
for (range = DBG_CORE_M1_MEM; range <= DBG_SYS_DMA; range++) {
ret = dbg_addr_valid(&core_id, range, addr, len);
if (ret == 1) {
break;
} else if (ret == 2) {
printf("addr(0x%llx) + len(0x%08x) is out of memory range(%d)\r\n", addr, len, range);
switch (range) {
case DBG_CORE_M1_MEM:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].m1_mem, dmem_m1_offset) - multi_arg(pacdsp[core_id].m1_mem, dmem_m1_size) + 1;
break;
case DBG_CORE_BIU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].biu, biu_offset) - multi_arg(pacdsp[core_id].biu, biu_size) + 1;
break;
case DBG_CORE_ICU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].icu, icu_offset) - multi_arg(pacdsp[core_id].icu, icu_size) + 1;
break;
case DBG_CORE_DMU:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dmu, dmu_offset) - multi_arg(pacdsp[core_id].dmu, dmu_size) + 1;
break;
case DBG_CORE_DMA:
length -= addr + length - multi_arg(pacdsp[core_id], core_base) -
multi_arg(pacdsp[core_id].dma, dma_offset) - multi_arg(pacdsp[core_id].dma, dma_size) + 1;
break;
case DBG_M2_MEM:
length -= addr + length - multi_arg(m2_mem, dmem_m2_base) - multi_arg(m2_mem, dmem_m2_size) + 1;
break;
case DBG_M2_ICU:
length -= addr + length - multi_arg(l2_icu, l2_icu_base) - multi_arg(l2_icu, l2_icu_size) + 1;
break;
case DBG_M2_DMU:
length -= addr + length - multi_arg(m2_dmu, m2_dmu_base) - multi_arg(m2_dmu, m2_dmu_size) + 1;
break;
case DBG_M2_DMA:
length -= addr + length - multi_arg(m2_dma, m2_dma_base) - multi_arg(m2_dma, m2_dma_size) + 1;
break;
case DBG_C2CC_INTERFACE:
length -= addr + length - multi_arg(c2cc, c2cc_base) - multi_arg(c2cc, c2cc_size) + 1;
break;
case DBG_DDR_MEM:
length -= addr + length - multi_arg(ddr_mem, ddr_memory_base) - multi_arg(ddr_mem, ddr_memory_size) + 1;
break;
case DBG_SYS_DMA:
length -= addr + length - multi_arg(sys_dma, sys_dma_base) - multi_arg(sys_dma, sys_dma_size) + 1;
break;
}
printf("\nNow that write mem addr(0x%llx) len(0x%08x)\r\n", addr, length);
break;
}
}
if (ret == -1) {
printf("Not that memory in simulator addr(0x%llx) len(0x%08x)\r\n", addr, length);
}
trans.set_data_length(length);
miss = dbg_d2cache_write(trans);
if (miss == CACHE_MISS) {
if (((addr >= m1_bus_base_array[coreid]) && ((addr + len) < (m1_bus_base_array[coreid] + m1_bus_size_array[coreid])))
|| ((addr >= c2cc_base) && (addr < c2cc_base + c2cc_size))) {
m1_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if ((addr >= m2_bus_base) && ((addr + len) < (m2_bus_base + m2_bus_size))){
m2_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else if (((addr >= biu_bus_base) && ((addr + len) < (biu_bus_base + biu_bus_size)))
|| ((addr >= sysdma_base) && ((addr + len) < (sysdma_base + sysdma_size)))){
biu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
} else {
for (i = 0; i < DSPNUM; i++) {
if ((addr >= m1_bus_base_array[i]) && ((addr + len) < (m1_bus_base_array[i] + m1_bus_size_array[i]))) {
dmu_bus_init_socket_tagged[coreid]->b_transport(trans, delay);
break;
}
}
if (i == DSPNUM) {
printf("No write mem address(0x%llx) in simualtor\r\n",addr);
}
}
}
}
}
private:
void addPendingTransaction(tlm::tlm_generic_payload & trans, int to, int initiatorId)
{
const ConnectionInfo info = { initiatorId, to };
assert(mPendingTransactions.find(&trans) == mPendingTransactions.end());
mPendingTransactions[&trans] = info;
}
struct ConnectionInfo {
int from;
int to;
};
typedef std::map < tlm::tlm_generic_payload *, ConnectionInfo > PendingTransactions;
typedef PendingTransactions::iterator PendingTransactionsIterator;
private:
PendingTransactions mPendingTransactions;
};
#endif
#endif
|
f53ff7a72a0a583d41788cfcfd69f71c6f85d35e
|
a45b192a23485dead14d0e8acba0d742d205162d
|
/successwindow.cpp
|
ff9a498eade5d5cb3b1c9a2cfd705208232a0234
|
[] |
no_license
|
MohamadSerhal/ece435L-complete-project
|
d49e3b812f62a9d3676b1519725f64ad868a3d0e
|
51bda3ddef09264e7402f728c289874c36926b35
|
refs/heads/main
| 2023-01-27T11:41:32.381846
| 2020-12-02T11:25:27
| 2020-12-02T11:25:27
| 316,075,220
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,211
|
cpp
|
successwindow.cpp
|
#include "successwindow.h"
/**
* @brief successWindow::successWindow, constructor for the success window
* @file successwindow.h
* @param parent
*/
successWindow::successWindow(QWidget *parent) : QWidget(parent)
{
sucessLabel = new QLabel("SUCCESS!");
sucessLabel->setStyleSheet("font: 35px;"
"color: green;");
successMessage = new QLabel();
verticalLayout = new QVBoxLayout();
verticalLayout->addWidget(sucessLabel);
verticalLayout->addWidget(successMessage);
setLayout(verticalLayout);
}
/**
* @brief successWindow::setSuccessLabel, sets the success label
* @file successwindow.h
* @param str
*/
void successWindow::setSuccessLabel(QString str){
successMessage->setText(str);
}
/**
* @brief successWindow::setSuccessLabelPicture, sets the picture in the success window
* @file successwindow.h
* @param pic
*/
void successWindow::setSuccessLabelPicture(QPixmap pic){
successMessage->setPixmap(pic);
}
/**
* @brief successWindow::changeSuccessLabel, changes the label of the success message
* @file successwindow.h
* @param str
*/
void successWindow::changeSuccessLabel(QString str){
sucessLabel->setText(str);
}
|
6b0025754e1878cc8f4b38819506010cb1cdefb8
|
1b8bba9b8a4a655a0acc7fed805a03f32720c57e
|
/src/Menge/MengeCore/Agents/Events/EventSystem.h
|
bbfa1158cb57962c753de08527402748773afeee
|
[
"Apache-2.0"
] |
permissive
|
tcarnoldussen/Menge
|
8f42d2987189380c4784341fa9b92bff2cf1e57e
|
ce276e3014c6f7681ce1509533028b76c1f38e10
|
refs/heads/master
| 2021-02-05T05:49:25.871675
| 2020-03-06T12:06:36
| 2020-03-06T12:06:36
| 243,750,295
| 0
| 0
|
Apache-2.0
| 2020-02-28T11:47:49
| 2020-02-28T11:47:48
| null |
UTF-8
|
C++
| false
| false
| 5,643
|
h
|
EventSystem.h
|
/*
Menge Crowd Simulation Framework
Copyright and trademark 2012-17 University of North Carolina at Chapel Hill
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
or
LICENSE.txt in the root of the Menge repository.
Any questions or comments should be sent to the authors menge@cs.unc.edu
<http://gamma.cs.unc.edu/Menge/>
*/
/*!
@file EventSystem.h
@brief The definition of the core event system.
*/
#ifndef __EVENT_SYSTEM_H__
#define __EVENT_SYSTEM_H__
#include "MengeCore/mengeCommon.h"
#include <vector>
// forward declaration
class TiXmlElement;
namespace Menge {
// forward declaration
class Event;
class EventResponse;
class EventEffect;
class EventTarget;
Event* parseEvent(TiXmlElement* node, const std::string& specFldr);
class ExternalEvtTrigger;
/*!
@brief The main event engine -- causes event triggers to be evaluated and effects to be applied.
The %EventSystem drives %Menge's event mechanism. Events are added to the simulator through the
behavior specification. If no events are added to the simulator, the `EventSystem` tag can be
omitted from the behavior specification. The following example shows the syntax for declaring the
event system and provides a vague illustration for adding an event.
```{xml}
<?xml version="1.0"?>
<BFSM>
<EventSystem conservative="1">
<Target name="my_target" type="target_element" ... />
<Effect name="my_effect" type="effect_element" ... />
<Event name="my_event">
<Trigger name="something_happened" type="trigger_element" />
<Response effect="my_effect" target="my_target" />
</Event>
</EventSystem>
...
</BFSM>
```
The `<%EventSystem>` tag has a single property:
- `conservative` determines how the event system handles errors in the declaration of events. If
the value is non-null, the system is conservative and any errors in the definition of events
are treated as *fatal* errors and the program exits (having written the cause of the problem
to the log). If zero, the program will log a *warning*, omit the event, and proceed with
simulation.
*/
class MENGE_API EventSystem {
public:
/*!
@brief Constructor.
*/
EventSystem();
/*!
@brief Destructor
*/
~EventSystem();
/*!
@brief Adds an event to the system.
The system becomes the owner of the event and will take responsibility for deleting it.
@param evt The event to add to the system.
*/
void addEvent(Event* evt) { _events.push_back(evt); }
/*!
@brief Evaluates the registered events
*/
void evaluateEvents();
/*!
@brief Finalize the event system.
*/
void finalize();
/*!
@brief Parses events from an "Events" tag.
@param node The node containing the event system description.
@param behaveFldr The folder containing the behavior specification. all event paths are
defined relative to this folder.
@returns True if parsing was successful.
*/
bool parseEvents(TiXmlElement* node, const std::string& behaveFldr);
/*!
@brief Registers an external event trigger with the system.
Any external event trigger that is not added explicitly will not be available to external
systems upon query.
@param trigger The external event trigger to add to the system.
@throws An event exception if the trigger does not have a unique name.
@see listExternalTriggers()
*/
void addExternalEventTrigger(ExternalEvtTrigger* trigger);
/*!
@brief Provides the names of the external events registered with the event system.
@returns The list of trigger names.
*/
std::vector<std::string> listExternalTriggers() const;
/*!
@brief Activate the external event trigger indicated by name.
If the name doesn't refer to a known external trigger, no action will be taken.
@param name The name of the trigger to activate.
@returns True if the trigger is activated.
*/
bool activateExternalTrigger(const std::string& name);
/*!
@brief Causes an event exception to be thrown based on the the system's tolerance for event
configuration errors.
@param msg The event associated with the problem.
@throws EventException if the system is *not* conservative; i.e., configuration errors will
be noted, but simulation will continue.
@throws EventFatalException if the system *is* conservative.
*/
static void finalizeException(const std::string& msg);
/*!
@brief Global variable to indicate how event configuration errors should be handled.
If true, event configuration errors result in fatal exceptions, if false they are merely
warnings.
*/
static bool CONSERVATIVE_SETUP;
friend class Event;
friend class EventEffect;
friend class EventTarget;
friend class EventResponse;
friend Event* parseEvent(TiXmlElement* node, const std::string& specFldr);
protected:
/*!
@brief The events to process.
*/
std::vector<Event*> _events;
/*!
@brief A mapping from target names to targets.
*/
HASH_MAP<std::string, EventTarget*> _targets;
/*!
@brief A mapping from effect names to effects.
*/
HASH_MAP<std::string, EventEffect*> _effects;
/*!
@brief The external event triggers.
*/
HASH_MAP<std::string, ExternalEvtTrigger*> _externalTriggers;
};
} // namespace Menge
#endif // __EVENT_SYSTEM_H__
|
43dbf25d5ea5de459ff9bb78af8c9434e3c91d3e
|
e2786af7fd38346ef1dd5ebeb1f7f65a528e2e14
|
/examples/hotplug.cpp
|
0f3157dcf009e9b0b54d717680712e8f5842c6a4
|
[
"BSD-2-Clause"
] |
permissive
|
analogdevicesinc/libsmu
|
cbc5dd979257e3ade2ddd14b8b5a05517071dfec
|
dbb484f004d9eb5251aa4667f5cf09b3ff5610e2
|
refs/heads/master
| 2023-05-25T18:30:48.590615
| 2022-02-10T10:15:29
| 2022-02-11T13:43:17
| 23,053,387
| 31
| 29
|
BSD-3-Clause
| 2023-02-20T20:03:46
| 2014-08-18T00:07:27
|
Python
|
UTF-8
|
C++
| false
| false
| 1,734
|
cpp
|
hotplug.cpp
|
// Simple example demonstrating hotplug support.
#include <chrono>
#include <iostream>
#include <thread>
#include <algorithm>
#include <libsmu/libsmu.hpp>
using std::cout;
using std::cerr;
using std::endl;
using namespace smu;
int main(int argc, char **argv)
{
// Create session object and add all compatible devices them to the
// session. Note that this currently doesn't handle returned errors.
Session* session = new Session();
std::vector < Device* > last_devices;
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
session->scan();
std::vector < Device* > available_devices = session->m_available_devices;
//check if there is any disconnected device
for (auto other_device : last_devices) {
bool found = 0;
for (auto device : available_devices) {
if (!device->m_serial.compare(other_device->m_serial)) {
found = 1;
break;
}
}
if (!found) {
cout << "Device detached!\n";
last_devices.erase(std::remove(last_devices.begin(), last_devices.end(), other_device), last_devices.end());
}
}
//check if there is any new connected device
for (auto device : available_devices) {
bool found = 0;
for (auto other_device : last_devices) {
if (!device->m_serial.compare(other_device->m_serial)) {
found = 1;
break;
}
}
if (!found) {
cout << "Device attached!\n";
}
else {
available_devices.erase(std::remove(available_devices.begin(), available_devices.end(), device), available_devices.end());
delete device;
}
}
last_devices.insert(last_devices.end(), available_devices.begin(), available_devices.end());
cout << "Number of available devices: " << last_devices.size() << '\n';
}
}
|
0c46910013169606c886e776ed7908d9b3b0aeb4
|
418aa6c4486e255f482b6c9bee12a08cda829503
|
/Common/container/simplestring.h
|
33b46e1c6c05bc3a3e8848ca42a1e610dd5b2406
|
[
"MIT"
] |
permissive
|
jjuiddong/Common
|
b21c9a98474fc45aa30b316808498381c2030ad3
|
3097b60988464000e2885a07cdd6e433e43de386
|
refs/heads/master
| 2023-08-31T07:35:31.425468
| 2023-08-29T11:38:29
| 2023-08-29T11:38:29
| 77,737,521
| 3
| 8
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,904
|
h
|
simplestring.h
|
//
// 2017-07-05, jjuiddong
// simple string
// use stack memory
//
// 2017-08-24
// - add wchar_t type
//
//
#pragma once
namespace common
{
template<class CharT, size_t MAX>
class String
{
};
template<size_t MAX>
class String<char, MAX> final
{
public:
String() {
memset(m_str, 0, sizeof(char)*MAX);
}
String(const char *str) {
const size_t len = min(strlen(str), MAX - 1);
strncpy_s(m_str, str, len);
m_str[len] = NULL;
}
String(const std::string &str) {
const size_t len = min(str.size(), MAX - 1);
strncpy_s(m_str, str.c_str(), len);
m_str[len] = NULL;
}
~String() {
}
String& Format(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vsnprintf_s(m_str, sizeof(m_str) - 1, _TRUNCATE, fmt, args);
va_end(args);
return *this;
}
void trim() {
// trim forward
for (int i = 0; i < (int)size(); ++i)
{
if ((m_str[i] == '\n') || (m_str[i] == '\t') || (m_str[i] == '\r') || (m_str[i] == ' '))
{
const size_t len = size();
common::rotateleft(m_str, i+1, len);
m_str[len - 1] = NULL;
--i;
}
else
break;
}
// trim backward
for (int i = (int)size() - 1; i >= 0; --i)
{
if ((m_str[i] == '\n') || (m_str[i] == '\t') || (m_str[i] == '\r') || (m_str[i] == ' '))
{
m_str[i] = NULL;
}
else
break;
}
}
//------------------------------------------------------------------------------------
// shlwapi
bool IsRelativePath() const {
return PathIsRelativeA(m_str) ? true : false;
}
bool IsFileExist() const {
return common::IsFileExist(m_str);
}
bool IsDirectory() const {
return common::IsDirectoryExist(m_str);
}
String convertToString(double num) const {
String str;
sprintf_s(str.m_str, "%.1f", num);
return str;
}
double roundOff(double n) const {
double d = n * 100.0f;
int i = (int)(d + 0.5);
d = (float)i / 100.0f;
return d;
}
String convertSize(size_t size) const {
static const char *SIZES[] = { "B", "KB", "MB", "GB" };
int div = 0;
size_t rem = 0;
while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES)) {
rem = (size % 1024);
div++;
size /= 1024;
}
double size_d = (float)size + (float)rem / 1024.0;
String result = convertToString(roundOff(size_d)) + " " + SIZES[div];
return result;
}
__int64 FileSize() const {
struct __stat64 buf;
if (_stat64(m_str, &buf) != 0)
return -1; // error, could use errno to find out more
return buf.st_size;
}
String FileSizeStr() const {
return convertSize((size_t)FileSize());
}
const char* GetFileExt() const {
return PathFindExtensionA(m_str);
}
const char* GetFileName() const {
return PathFindFileNameA(m_str);
}
String GetFullFileName() const {
String str;
if (IsRelativePath())
{
char curDir[MAX];
GetCurrentDirectoryA(MAX, curDir);
strcat_s(curDir, "/");
strcat_s(curDir, m_str);
GetFullPathNameA(curDir, MAX, str.m_str, NULL);
}
else
{
GetFullPathNameA(m_str, MAX, str.m_str, NULL);
}
return str;
}
String GetFilePathExceptFileName() const {
String str = *this;
PathRemoveFileSpecA(str.m_str);
return str;
}
// only return filename except extends
String GetFileNameExceptExt() const {
String str = PathFindFileNameA(m_str);
PathRemoveExtensionA(str.m_str);
return str;
}
// return full filename except extends
String GetFileNameExceptExt2() const {
String str = *this;
char *name = PathFindFileNameA(str.m_str);
PathRemoveExtensionA(name);
return str;
}
String& GetCurrentDirectory_() {
::GetCurrentDirectoryA((DWORD)SIZE, m_str);
return *this;
}
//------------------------------------------------------------------------------------
// STL
void erase(const char *str) {
char *p = (char*)find(str);
if (!p || !*p)
return;
std::rotate(p, p + strlen(str), m_str + strlen(m_str));
const int len = strlen(m_str) - strlen(str);
m_str[len] = NULL;
}
const char* find(const char *str) const {
const char *p = m_str;
while (*p)
{
const char *n = p;
const char *c = str;
while (*n && *c)
{
if (*n != *c)
break;
++n;
++c;
}
if (!*c) // found
return p;
++p; // not found
}
return NULL;
}
const char* find(const String &str) const {
return find(str.m_str);
}
char back() {
if (empty())
return NULL;
for (int i = 0; i < MAX - 1; ++i)
if (NULL == m_str[i + 1])
return m_str[i];
return NULL;
}
bool empty() const {
return m_str[0] == NULL;
}
String& lowerCase() {
std::transform(m_str, &m_str[MAX], m_str, tolower);
return *this;
}
String& upperrCase() {
std::transform(m_str, &m_str[MAX], m_str, toupper);
return *this;
}
hashcode GetHashCode() const {
boost::hash<std::string> string_hash;
return string_hash(m_str);
}
hashcode GetHashCode(const String &key) const {
boost::hash<std::string> string_hash;
return string_hash((*this + key).c_str());
}
size_t size() const {
return (size_t)strlen(m_str);
}
void clear() {
memset(m_str, 0, MAX);
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
// ETC
//std::wstring wstr() const
//{
// int len;
// int slength = (int)size() + 1;
// len = ::MultiByteToWideChar(CP_ACP, 0, m_str, slength, 0, 0);
// wchar_t buf[MAX];
// ZeroMemory(buf, sizeof(buf));
// len = min(MAX-1, len);
// ::MultiByteToWideChar(CP_ACP, 0, m_str, slength, buf, len);
// std::wstring r(buf);
// return r;
//}
String<wchar_t, MAX> wstr() const
{
int len;
int slength = (int)size() + 1;
len = ::MultiByteToWideChar(CP_ACP, 0, m_str, slength, 0, 0);
String<wchar_t, MAX> buf;
len = min(MAX - 1, (size_t)len);
::MultiByteToWideChar(CP_ACP, 0, m_str, slength, buf.m_str, len);
return buf;
}
String<wchar_t, MAX> wstrUTF8() const
{
int len;
int slength = (int)size() + 1;
len = ::MultiByteToWideChar(CP_UTF8, 0, m_str, slength, 0, 0);
String<wchar_t, MAX> buf;
len = min(MAX - 1, (size_t)len);
::MultiByteToWideChar(CP_UTF8, 0, m_str, slength, buf.m_str, len);
return buf;
}
// UTF-8 -> Default Ansi
String ansi() const
{
int len;
int slength = (int)size() + 1;
len = ::MultiByteToWideChar(CP_UTF8, 0, m_str, slength, 0, 0);
String<wchar_t, MAX> buf;
len = min(MAX - 1, (size_t)len);
::MultiByteToWideChar(CP_UTF8, 0, m_str, slength, buf.m_str, len);
String buf2;
const int len2 = ::WideCharToMultiByte(CP_ACP, 0, buf.m_str, len, 0, 0, NULL, FALSE);
::WideCharToMultiByte(CP_ACP, 0, buf.m_str, len, buf2.m_str, len2, NULL, FALSE);
return buf2;
}
// Default Ansi -> UTF-8
String utf8() const
{
int len;
int slength = (int)size() + 1;
len = ::MultiByteToWideChar(CP_ACP, 0, m_str, slength, 0, 0);
String<wchar_t, MAX> buf;
len = min(MAX - 1, (size_t)len);
::MultiByteToWideChar(CP_ACP, 0, m_str, slength, buf.m_str, len);
String buf2;
const int len2 = ::WideCharToMultiByte(CP_UTF8, 0, buf.m_str, len, 0, 0, NULL, FALSE);
::WideCharToMultiByte(CP_UTF8, 0, buf.m_str, len, buf2.m_str, len2, NULL, FALSE);
return buf2;
}
//------------------------------------------------------------------------------------
const char* c_str() const { return (const char*)m_str; }
bool operator == (const String &rhs) const {
return (size() == rhs.size()) && !strcmp(m_str, rhs.m_str);
}
bool operator == (const std::string &rhs) const {
return (size() == rhs.size()) && (rhs == m_str);
}
bool operator == (const char *str) const {
return (size() == (size_t)strlen(str)) && !strcmp(m_str, str);
}
bool operator != (const String &rhs) const {
return !(operator==(rhs));
}
bool operator != (const std::string &rhs) const {
return !(operator==(rhs));
}
bool operator != (const char *str) const {
return !(operator==(str));
}
String& operator = (const char *str) {
if (!str)
return *this;
if (m_str != str)
{
const size_t len = min(strlen(str), MAX - 1);
strncpy_s(m_str, str, len);
m_str[len] = NULL;
}
return *this;
}
String& operator = (const String &rhs) {
if (this != &rhs) {
operator = (rhs.m_str);
}
return *this;
}
String& operator = (const std::string &rhs) {
return operator = (rhs.c_str());
}
String operator + (const char *str) const {
String v;
v += *this;
v += str;
return v;
}
String operator + (const String &str) const {
String v;
v += *this;
v += str;
return v;
}
String& operator += (const char *str) {
const size_t len1 = strlen(m_str);
if (len1 >= (MAX - 1))
return *this;
const size_t len2 = strlen(str);
const size_t cpLen = min(len2, MAX-len1-1);
strncat_s(m_str, str, cpLen);
m_str[len1 + cpLen] = NULL;
return *this;
}
String& operator += (const char c) {
const size_t len1 = strlen(m_str);
if ((len1+1) >= (MAX - 1))
return *this;
m_str[len1] = c;
m_str[len1 + 1] = NULL;
return *this;
}
String& operator += (const String &str) {
if (this == &str)
return *this;
const size_t len1 = strlen(m_str);
if (len1 >= (MAX - 1))
return *this;
const size_t len2 = strlen(str.m_str);
const size_t cpLen = min(len2, MAX - len1 - 1);
strncat_s(m_str, str.m_str, cpLen);
m_str[len1 + cpLen] = NULL;
return *this;
}
bool operator < (const String &rhs) const {
return std::strcmp(m_str, rhs.m_str) < 0;
}
public:
char m_str[MAX];
const size_t SIZE = MAX;
};
template<size_t MAX>
class String<wchar_t, MAX> final
{
public:
String() {
memset(m_str, 0, sizeof(wchar_t)*MAX);
}
String(const wchar_t *str) {
const size_t len = min(wcslen(str), MAX - 1);
wcsncpy_s(m_str, str, len);
m_str[len] = NULL;
}
String(const std::wstring &str) {
const size_t len = min(str.size(), MAX - 1);
wcsncpy_s(m_str, str.c_str(), len);
m_str[len] = NULL;
}
~String() {
}
String& Format(const wchar_t* fmt, ...) {
va_list args;
va_start(args, fmt);
vswprintf_s(m_str, fmt, args);
va_end(args);
return *this;
}
//------------------------------------------------------------------------------------
// shlwapi
bool IsRelativePath() const {
return PathIsRelative(m_str) ? true : false;
}
bool IsFileExist() const {
return common::IsFileExist(m_str);
}
bool IsDirectory() const {
return common::IsDirectoryExist(m_str);
}
String convertToString(double num) const {
String str;
swprintf_s(str.m_str, L"%.1f", num);
return str;
}
double roundOff(double n) const {
double d = n * 100.0f;
int i = (int)(d + 0.5);
d = (float)i / 100.0f;
return d;
}
String convertSize(size_t size) const {
static const char *SIZES[] = { "B", "KB", "MB", "GB" };
int div = 0;
size_t rem = 0;
while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES)) {
rem = (size % 1024);
div++;
size /= 1024;
}
double size_d = (float)size + (float)rem / 1024.0;
String result = convertToString(roundOff(size_d)) + " " + SIZES[div];
return result;
}
__int64 FileSize() const {
struct __stat64 buf;
if (_wstat64(m_str, &buf) != 0)
return -1; // error, could use errno to find out more
return buf.st_size;
return 0;
}
String FileSizeStr() const {
return convertSize((size_t)FileSize());
}
const wchar_t* GetFileExt() const {
return PathFindExtensionW(m_str);
}
const wchar_t* GetFileName() const {
return PathFindFileNameW(m_str);
}
String GetFullFileName() const {
String str;
if (IsRelativePath())
{
wchar_t curDir[MAX];
GetCurrentDirectory(MAX, curDir);
wcscat_s(curDir, L"/");
wcscat_s(curDir, m_str);
GetFullPathName(curDir, MAX, str.m_str, NULL);
}
else
{
GetFullPathName(m_str, MAX, str.m_str, NULL);
}
return str;
}
String GetFilePathExceptFileName() const {
String str = *this;
PathRemoveFileSpec(str.m_str);
return str;
}
// only return filename except extends
String GetFileNameExceptExt() const {
String str = PathFindFileName(m_str);
PathRemoveExtension(str.m_str);
return str;
}
// return full filename except extends
String GetFileNameExceptExt2() const {
String str = *this;
wchar_t *name = PathFindFileName(str.m_str);
PathRemoveExtension(name);
return str;
}
//------------------------------------------------------------------------------------
// STL
void erase(const wchar_t *str) {
wchar_t *p = (wchar_t*)find(str);
if (!p || !*p)
return;
std::rotate(p, p + wcslen(str), m_str + wcslen(m_str));
const int len = wcslen(m_str) - wcslen(str);
m_str[len] = NULL;
}
const wchar_t* find(const wchar_t *str) const {
const wchar_t *p = m_str;
while (*p)
{
const wchar_t *n = p;
const wchar_t *c = str;
while (*n && *c)
{
if (*n != *c)
break;
++n;
++c;
}
if (!*c) // found
return p;
++p; // not found
}
return NULL;
}
const wchar_t* find(const String &str) const {
return find(str.m_str);
}
wchar_t back() {
if (empty())
return NULL;
for (int i = 0; i < MAX - 1; ++i)
if (NULL == m_str[i + 1])
return m_str[i];
return NULL;
}
bool empty() const {
return m_str[0] == NULL;
}
String& lowerCase() {
std::transform(m_str, &m_str[MAX], m_str, _wcslwr);
return *this;
}
String& upperrCase() {
std::transform(m_str, &m_str[MAX], m_str, _wcsupr);
return *this;
}
hashcode GetHashCode() const {
boost::hash<std::wstring> string_hash;
return string_hash(m_str + L"unique-key");
}
hashcode GetHashCode(const String &key) const {
boost::hash<std::wstring> string_hash;
return string_hash((*this + key).c_str());
}
size_t size() const {
return (size_t)wcslen(m_str);
}
void clear() {
memset(m_str, 0, sizeof(wchar_t)*MAX);
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
// ETC
//std::string str() const
//{
// const int slength = (int)size() + 1;
// int len = ::WideCharToMultiByte(CP_ACP, 0, m_str, slength, 0, 0, NULL, FALSE);
// char buf[MAX];
// ZeroMemory(buf, sizeof(buf));
// len = min(MAX - 1, len);
// ::WideCharToMultiByte(CP_ACP, 0, m_str, slength, buf, len, NULL, FALSE);
// std::string r(buf);
// return r;
//}
String<char,MAX> str() const
{
const int slength = (int)size() + 1;
int len = ::WideCharToMultiByte(CP_ACP, 0, m_str, slength, 0, 0, NULL, FALSE);
String<char, MAX> buf;
len = min(MAX - 1, (size_t)len);
::WideCharToMultiByte(CP_ACP, 0, m_str, slength, buf.m_str, len, NULL, FALSE);
return buf;
}
// Default Ansi - UTF-8
String<char, MAX> utf8() const
{
const int slength = (int)size() + 1;
int len = ::WideCharToMultiByte(CP_UTF8, 0, m_str, slength, 0, 0, NULL, FALSE);
String<char, MAX> buf;
len = min(MAX - 1, (size_t)len);
::WideCharToMultiByte(CP_UTF8, 0, m_str, slength, buf.m_str, len, NULL, FALSE);
return buf;
}
// UTF-8 -> Default Ansi
String<char, MAX> ansi() const
{
const int slength = (int)size() + 1;
int len = ::WideCharToMultiByte(CP_ACP, 0, m_str, slength, 0, 0, NULL, FALSE);
String<char, MAX> buf;
len = min(MAX - 1, (size_t)len);
::WideCharToMultiByte(CP_ACP, 0, m_str, slength, buf.m_str, len, NULL, FALSE);
return buf;
}
//------------------------------------------------------------------------------------
const wchar_t* c_str() const { return (const wchar_t*)m_str; }
bool operator == (const String &rhs) const {
return (size() == rhs.size()) && !wcscmp(m_str, rhs.m_str);
}
bool operator == (const std::wstring &rhs) const {
return (size() == rhs.size()) && (rhs == m_str);
}
bool operator == (const wchar_t *str) const {
return (size() == (size_t)wcslen(str)) && !wcscmp(m_str, str);
}
bool operator != (const String &rhs) const {
return !(operator==(rhs));
}
bool operator != (const std::wstring &rhs) const {
return !(operator==(rhs));
}
bool operator != (const wchar_t *str) const {
return !(operator==(str));
}
String& operator = (const wchar_t *str) {
if (!str)
return *this;
if (m_str != str)
{
const size_t len = min(wcslen(str), MAX - 1);
wcsncpy_s(m_str, str, len);
m_str[len] = NULL;
}
return *this;
}
String& operator = (const String &rhs) {
if (this != &rhs) {
operator = (rhs.m_str);
}
return *this;
}
String& operator = (const std::wstring &rhs) {
return operator = (rhs.c_str());
}
String operator + (const wchar_t *str) const {
String v;
v += *this;
v += str;
return v;
}
String operator + (const String &str) const {
String v;
v += *this;
v += str;
return v;
}
String& operator += (const wchar_t *str) {
const size_t len1 = wcslen(m_str);
if (len1 >= (MAX - 1))
return *this;
const size_t len2 = wcslen(str);
const size_t cpLen = min(len2, MAX - len1 - 1);
wcsncat_s(m_str, str, cpLen);
m_str[len1 + cpLen] = NULL;
return *this;
}
String& operator += (const wchar_t c) {
const size_t len1 = wcslen(m_str);
if ((len1+1) >= (MAX - 1))
return *this;
m_str[len1] = c;
m_str[len1 + 1] = NULL;
return *this;
}
String& operator += (const String &str) {
if (this == &str)
return *this;
const size_t len1 = wcslen(m_str);
if (len1 >= (MAX - 1))
return *this;
const size_t len2 = wcslen(str.m_str);
const size_t cpLen = min(len2, MAX - len1 - 1);
wcsncat_s(m_str, str.m_str, cpLen);
m_str[len1 + cpLen] = NULL;
return *this;
}
bool operator < (const String &rhs) const {
return std::wcscmp(m_str, rhs.m_str) < 0;
}
public:
wchar_t m_str[MAX];
const size_t SIZE = MAX;
};
// Define Type
typedef String<char, 16> Str16;
typedef String<char, 32> Str32;
typedef String<char, 64> Str64;
typedef String<char, 64> StrId;
typedef String<char, 128> Str128;
typedef String<char, 256> Str256;
typedef String<char, 512> Str512;
typedef String<char, 128> StrPath;
typedef String<char, 256> StrGlobalPath;
typedef String<wchar_t, 16> WStr16;
typedef String<wchar_t, 32> WStr32;
typedef String<wchar_t, 64> WStr64;
typedef String<wchar_t, 64> WStrId;
typedef String<wchar_t, 128> WStr128;
typedef String<wchar_t, 256> WStr256;
typedef String<wchar_t, 512> WStr512;
typedef String<wchar_t, 128> WStrPath;
typedef String<wchar_t, 256> WStrGlobalPath;
}
|
30d64007a3d0a20ffcf9ad2f3f2ae72b40d36e53
|
e03c05a59e5d3fd0d373012046d66c169f741dc4
|
/树状数组和线段树/C.cpp
|
2cffa520e9266a109a06063a040f0332ddbc5258
|
[
"MIT"
] |
permissive
|
Eden1114/ACM_ICPC
|
45360c97c6ecd3c586bb5d34eba3a889ad604d6b
|
4f3dea0c866e7e3fcde886e41ffe65552458666b
|
refs/heads/master
| 2021-01-20T13:58:10.476422
| 2018-07-31T08:26:59
| 2018-07-31T08:26:59
| 90,543,195
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,953
|
cpp
|
C.cpp
|
/*
*题号:
*时间:
*解题思想:线段树
*线段树,树状数组的实现一般都是[1,n] 不从0开始
*
*/
//include <bits/stdc++.h>
#include <functional>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <numeric>
#include <utility>
#include <cstring>
#include <climits>
#include <limits>
#include <string>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
#include <list>
#include <map>
#include <set>
#define F(i,a,b) for(int i = a; i < b; i++)
#define LL long long
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%I64d",&x)
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define f(i, a, b) for(int i = a; i <= b; i++)
#define ms(Arr) memset(Arr,0,sizeof(Arr));
#define CLR(arr,val) memset(arr,val,sizeof(arr))
const double eps = 1e-8;
const double pi = acos(1.0*(-1));
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
typedef long long ll;
typedef std::pair<int,int> P;
using namespace std;
//最大公因数
int gcd(int a, int b)
{
if (!b)return a;
return gcd(b, a%b);
}
//快速幂取模
int PowerMod(int a, int b, int c)
{
int ans = 1;
a = a % c;
while (b > 0)
{
if (b % 2 == 1)
ans = (ans * a) % c;
b = b / 2;
a = (a * a) % c;
}
return ans;
}
//幂函数
int p(int a, int b)
{
int ans = 1;
for (int i = 0; i < b; i++)
ans *= a;
return ans;
}
const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
int Scan()
{ // 输入外挂
int res = 0, flag = 0;
char ch;
if ((ch = getchar()) == '-')
{
flag = 1;
}
else if (ch >= '0' && ch <= '9')
{
res = ch - '0';
}
while ((ch = getchar()) >= '0' && ch <= '9')
{
res = res * 10 + (ch - '0');
}
return flag ? -res : res;
}
void Out(int a)
{ // 输出外挂
if (a < 0)
{
putchar('-');
a = -a;
}
if (a >= 10)
{
Out(a / 10);
}
putchar(a % 10 + '0');
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//long long 范围:-9223372036854775808~9223372036854775807
//int 范围:-2147483648~2147483647
//double 范围:-1.7*10^-308~1.7*10^308,15~16位有效数字
//long double 范围:-1.2*10^-4932~1.2*10^4932,18~19位有效数字
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const int M = 2e5 + 10;
struct TnT {
int l , r , max;
}T[M << 2];
int h , w , n , ans;
void build(int l , int r , int p) {
int mid = (l + r) >> 1;
T[p].l = l , T[p].r = r , T[p].max = w;
if(l == r) {
return;
}
build(l , mid , p << 1);
build(mid + 1 , r , (p << 1) | 1);
}
//初始化的线段树,所有的max都为w
//T[i].l表示
void query(int p , int c) {
if(T[p].l == T[p].r) {
T[p].max -= c;
ans = T[p].l;
return;
}
if(c <= T[p << 1].max)
query(p << 1 , c);
else
query((p << 1) | 1 , c);
T[p].max = max(T[p << 1].max , T[(p << 1) | 1].max);
}
int main(/*int argc, char *argv[]*/) {
//ios::sync_with_stdio(false);
while(scanf("%d%d%d",&h,&w,&n))
{
h = min(h, n);
build(1,h,1);
int x;
for(int i = 1;i <= n;i++)
{
scanf("%d",&x);
if(T[1].max < x)
{
printf("-1\n");
}
else
{
query(1, x);
printf("%d\n", ans);
}
}
}
return 0;
}
|
59a58a1fbadd1654aaff381000b7164165618866
|
e769678179d65e4d38fc36967eb70e48032afd44
|
/tools/plugin-create/Create.hpp
|
1d310416c6cf40f53f60aac5b5d70cca18f5a21f
|
[] |
no_license
|
Pocsel/pocsel
|
02f860c2d6d7bbdff17df09e4a5d7dfc60849c04
|
f3ec58f68719302ec10fc3312928b08566b0dd52
|
refs/heads/master
| 2021-01-23T08:56:14.496186
| 2014-12-26T00:24:14
| 2014-12-26T00:24:14
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 1,274
|
hpp
|
Create.hpp
|
#ifndef __TOOLS_PLUGIN_CREATE_CREATE_HPP__
#define __TOOLS_PLUGIN_CREATE_CREATE_HPP__
namespace Tools { namespace PluginCreate {
struct Resource
{
std::string type;
boost::filesystem::path srcFile;
boost::filesystem::path dstFile;
bool isTemporaryFile;
Resource(Resource&& rhs);
Resource(std::string type, boost::filesystem::path srcFile, boost::filesystem::path dstFile, bool temp);
~Resource();
private:
Resource(Resource const&);
Resource& operator = (Resource const&);
};
// Retourne les convertisseurs par défaults
std::map<std::string, std::function<Resource(boost::filesystem::path const&)>> GetDefaultConverter();
// fileConverters: <extention, convertisseur>
Resource Convert(boost::filesystem::path const& file, std::map<std::string, std::function<Resource(boost::filesystem::path const&)>> const& fileConverters);
std::list<Resource> ConvertAllFiles(boost::filesystem::path const& directory, std::map<std::string, std::function<Resource(boost::filesystem::path const&)>> const& fileConverters);
bool Create(boost::filesystem::path const& pluginRootDir, boost::filesystem::path const& destFile, std::list<Resource> const& resources);
}}
#endif
|
0531b5010c3dc361792a47335889a53a64d8b28f
|
5ed8b14c8b1e3ab2d713bdea52b3b3d3a0c10b3c
|
/Problems/№13.cpp
|
f0a07c734008ad33768a107296194203b5ec3fee
|
[] |
no_license
|
AiSRoV/AiSHub
|
ea0de5de6a9f6677884421fe64709c18e25f1e51
|
644d543ff3c07e1302c4bfea19d28884ceb8e236
|
refs/heads/master
| 2020-07-30T23:39:06.314081
| 2020-06-20T12:20:07
| 2020-06-20T12:20:07
| 210,401,560
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 361
|
cpp
|
№13.cpp
|
#include <iostream>
using namespace std;
int main() {
int num, z, b, x;
z = 1;
x = 2;
b = 2;
cin >> num;
if (num == 0) {
cout << 0 << endl;
}
else {
if (x <= num) {
while (x <= num) {
x = x * b;
z++;
}
}
else {
cout << 1 << endl;
}
cout << z << endl;
}
system("pause");
return 0;
}
|
2d1b75867d1bab2df7109117c1a24cd64c87b0a8
|
62ae4d743e12dadc6df7410783b64883a71eee30
|
/include/pcd/bounding_box_feature.h
|
7cb8e6131ed0fe94e6188d9adc199bd925edb294
|
[
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
zeng-hello-world/Caffe
|
bc1adf4fa4d2d52e30a6446f89d373c0958a6e5b
|
fcbd1c8871e31a5abdc40f7eac92929fd697363d
|
refs/heads/master
| 2023-06-10T04:56:03.969770
| 2017-03-24T02:55:13
| 2017-03-24T02:55:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 821
|
h
|
bounding_box_feature.h
|
// Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved
// @author erlangz(zhengwenchao@baidu.com)
// @date 2016/12/29 17:57:00
// @file bouing_box_feature.h
// @brief
#ifndef ADU_PERCEPTION_PCD_BOUING_BOX_FEATURE_H
#define ADU_PERCEPTION_PCD_BOUING_BOX_FEATURE_H
#include <opencv2/opencv.hpp>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
namespace adu {
namespace perception {
class BoundingBoxFeature {
public:
BoundingBoxFeature();
bool compute(const pcl::PointCloud<pcl::PointXYZ>::Ptr object,
std::vector<float>* bouding_box_features);
bool min_max(const pcl::PointCloud<pcl::PointXYZ>::Ptr object,
Eigen::Vector3f& min, Eigen::Vector3f& max);
};
} // namespace perception
} // namespace adu
#endif // ADU_PERCEPTION_PCD_BOUING_BOX_FEATURE_H
//
|
93fdcda644a90de7f8cc7044402691ffbcda3da1
|
e1aebabcc24cce95518ff466cfa92fb0b0ef68e5
|
/Advanced Algorithms Project 2/topSort.h
|
2049b8eab3f51acb4986216ebcfe5058625aa9e7
|
[] |
no_license
|
PillarManJ/AdvacnedAlgorithmsProject2
|
1e3ae3939bac40db3f18c57831623ec949d751fe
|
bb19472aa404116e26a6c36ba8668e83013bd2eb
|
refs/heads/master
| 2022-04-26T17:59:30.172821
| 2020-04-26T23:54:09
| 2020-04-26T23:54:09
| 254,974,855
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 225
|
h
|
topSort.h
|
#include <queue>
#include <utility>
#include <iostream>
#include <string>
#include <vector>
#include "GraphNode.h"
template <class T>
class TopSort{
vector<T> Kahns(T first);
vector<T> mDFS(T first);
};
|
85bd6b1b61073d0440f7389b59d497d6b0bbdd33
|
9db2bd0e9ee4d39ae1c3adb6bdf39e8b35a8c781
|
/Orbitersdk/Space Shuttle Ultra/vc/vc_defs.h
|
821546f1f9107da5c2ae19fb6e7519ec0f16b328
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
mrozigor/spaceshuttleultra_mirror
|
95aae304af32179a5c1f33ff1e103b874c5c39db
|
caeffa89129ba749061c8e751d254882e21417c4
|
refs/heads/master
| 2021-01-25T16:53:44.829629
| 2017-07-31T21:26:20
| 2017-07-31T21:26:20
| 101,912,508
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,057
|
h
|
vc_defs.h
|
/****************************************************************************
This file is part of Space Shuttle Ultra
VC definitions
Space Shuttle Ultra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Space Shuttle Ultra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Space Shuttle Ultra; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See http://spaceshuttleultra.sourceforge.net/license/ for more details.
**************************************************************************/
#if !defined(___SPACE_SHUTTLE_ULTRA_VC_DEFINITIONS_H_INCLUDED___)
#define ___SPACE_SHUTTLE_ULTRA_VC_DEFINITIONS_H_INCLUDED___
// ==========================================================
// panel area identifiers
// ==========================================================
// F
#define AID_F2_MIN 1000
#define AID_F2 1000
#define AID_F2_MAX 1009
#define AID_F3_MIN 1010
#define AID_F3 1010
#define AID_F3_MAX 1019
#define AID_F4_MIN 1020
#define AID_F4 1020
#define AID_F4_MAX 1029
#define AID_F6_MIN 1030
#define AID_F6 1030
#define AID_F6_MAX 1039
#define AID_F7_MIN 1040
#define AID_F7 1040
#define AID_F7_MAX 1049
#define AID_F8_MIN 1050
#define AID_F8 1050
#define AID_F8_MAX 1059
#define AID_F9_MIN 1060
#define AID_F9 1060
#define AID_F9_MAX 1069
// L
#define AID_L1_MIN 2000
#define AID_L1 2000
#define AID_L1_MAX 2009
#define AID_L10_IUS_MIN 2010
#define AID_L10_IUS 2010
#define AID_L10_IUS_MAX 2019
#define AID_L12U_CENTAUR_MIN 2020
#define AID_L12U_CENTAUR 2020
#define AID_L12U_CENTAUR_MAX 2029
#define AID_L12U_IUS_MIN 2030
#define AID_L12U_IUS 2030
#define AID_L12U_IUS_MAX 2039
#define AID_L2_MIN 2040
#define AID_L2 2040
#define AID_L2_MAX 2049
#define AID_L4_MIN 2050
#define AID_L4 2050
#define AID_L4_MAX 2059
#define AID_L9_MIN 2060
#define AID_L9 2060
#define AID_L9_MAX 2069
// C
#define AID_C2_MIN 3000
#define AID_C2 3000
#define AID_C2_WND0 3001
#define AID_C2_WND1 3002
#define AID_C2_WND2 3003
#define AID_C2_WND3 3004
#define AID_C2_MAX 3009
#define AID_C3_MIN 3010
#define AID_C3 3010
#define AID_C3_MAX 3019
// R
#define AID_R1_MIN 4000
#define AID_R1 4000
#define AID_R1_MAX 4009
#define AID_R2_MIN 4010
#define AID_R2 4010
#define AID_R2_MAX 4019
#define AID_R11_MIN 4020
#define AID_R11 4020
#define AID_R11_MAX 4029
#define AID_R13L_MIN 4030
#define AID_R13L 4030
#define AID_R13L_MAX 4039
#define AID_R4_MIN 4040
#define AID_R4 4040
#define AID_R4_MAX 4049
#define AID_R10_MIN 4050
#define AID_R10 4050
#define AID_R10_MAX 4059
#define AID_R13U_MIN 4060
#define AID_R13U 4060
#define AID_R13U_MAX 4069
// O
#define AID_O1_MIN 5000
#define AID_O1 5000
#define AID_O1_MAX 5009
#define AID_O2_MIN 5010
#define AID_O2 5010
#define AID_O2_MAX 5019
#define AID_O3_MIN 5020
#define AID_O3 5020
#define AID_O3_MAX 5029
#define AID_O6_MIN 5030
#define AID_O6 5030
#define AID_O6_MAX 5039
#define AID_O8_MIN 5040
#define AID_O8 5040
#define AID_O8_MAX 5049
#define AID_O17_MIN 5050
#define AID_O17 5050
#define AID_O17_MAX 5059
#define AID_O5_MIN 5060
#define AID_O5 5060
#define AID_O5_MAX 5069
#define AID_O7_MIN 5070
#define AID_O7 5070
#define AID_O7_MAX 5079
#define AID_O9_MIN 5080
#define AID_O9 5080
#define AID_O9_MAX 5089
#define AID_O13_MIN 5090
#define AID_O13 5090
#define AID_O13_MAX 5099
// A
#define AID_A1U_MIN 6000
#define AID_A1U 6000
#define AID_A1U_MAN 6009
#define AID_A2_MIN 6010
#define AID_A2 6010
#define AID_A2_MAX 6019
#define AID_A4_MIN 6020
#define AID_A4 6020
#define AID_A4_MAX 6029
#define AID_A6U_MIN 6030
#define AID_A6U 6030
#define AID_A6U_WND0 6031
#define AID_A6U_WND1 6032
#define AID_A6U_WND2 6033
#define AID_A6U_WND3 6034
#define AID_A6U_MAX 6039
#define AID_A7U_MIN 6040
#define AID_A7U 6040
#define AID_A7U_MAX 6049
#define AID_A7A3_MIN 6050
#define AID_A7A3 6050
#define AID_A7A3_MAX 6059
#define AID_A8_MIN 6060
#define AID_A8 6060
#define AID_A8_MAX 6069
#define AID_A8A3_MIN 6070
#define AID_A8A3 6070
#define AID_A8A3_MAX 6079
#define AID_AFTMDU_MIN 6080
#define AID_AFTMDU 6080
#define AID_AFTMDU_MAX 6089
// time until a switch gets pushed to the next position by a spring for spring-loaded switches
const double SWITCH_HOLD_TIME = 0.5;
/**
* Namespace for all VC related classes, representing visual objects
* and switches.
* Define the public contents of the VC namespace.
*/
namespace vc {
const int TB_BARBERPOLE = 0;
const int TB_STO = 1;
const int TB_LAT = 2;
const int TB_CL = 3;
const int TB_OP = 4;
const int TB_ON = 5;
const int TB_OFF = 6;
const int TB_X10 = 7;
const int TB_GRAY = 8;
const int TB_DPY = 9;
const int TB_REL = 10;
const int TB_DN = 11;
const int TB_UP = 12;
const int TB_RUN = 13;
const int TB_IPL = 14;
const int TB_ICH = 15;
const int TB_RAD = 16;
const int TB_PL = 17;
const int TB_BYP = 18;
const int MDUID_CDR1 = 0;
const int MDUID_CDR2 = 1;
const int MDUID_PLT1 = 2;
const int MDUID_PLT2 = 3;
const int MDUID_CRT1 = 4;
const int MDUID_CRT2 = 5;
const int MDUID_CRT3 = 6;
const int MDUID_CRT4 = 7;
const int MDUID_MFD1 = 8;
const int MDUID_MFD2 = 9;
const int MDUID_AFD1 = 10;
class MDU;
typedef MDU* PMDU;
};
#endif
|
b8aa1f9d7172f2d45bb146e62428562b2d29f55c
|
b3ff4c9a1ef9b314831d2049ce1e240d19033b8c
|
/Views/Concessions/manageconcessionsview.cpp
|
3f0f344e953da714585f53483e9f43b986fdfebf
|
[] |
no_license
|
Betrove/school_project
|
0884c08b460ecd1bfb1c5d26ef2f3f8245845451
|
b9afc1e4d14dbebafe0849ab0ea5fde221531387
|
refs/heads/master
| 2021-08-24T07:15:45.802900
| 2017-12-08T15:48:20
| 2017-12-08T15:48:20
| 112,995,724
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,133
|
cpp
|
manageconcessionsview.cpp
|
#include "manageconcessionsview.h"
#include "ui_manageconcessionsview.h"
#include "QMessageBox";
#include "QModelIndex"
ManageConcessionsView::ManageConcessionsView(const ServiceManager& serviceManager) :
QWidget(NULL),serviceManager(serviceManager),
ui(new Ui::ManageConcessionsView)
{
ui->setupUi(this);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
LoadConcessions();
}
ManageConcessionsView::~ManageConcessionsView()
{
delete ui;
}
void ManageConcessionsView::LoadConcessions()
{
ConcessionRepository repository;
auto items = repository.getAll();
this->ui->tableWidget->setRowCount(items.size());
for (auto r=0; r<items.size(); r++)
{
ui->tableWidget->setItem( r, 0, new QTableWidgetItem(QString::number(items[r].getId())));
ui->tableWidget->setItem( r, 1, new QTableWidgetItem(items[r].getName().c_str()));
ui->tableWidget->setItem( r, 2, new QTableWidgetItem(QString::number(items[r].getPrice())));
}
}
// add item
void ManageConcessionsView::on_pushButton_2_clicked()
{
auto view =new AddConcessionItemFormView(this->serviceManager);
this->serviceManager.getNavigationService()->Navigate(view);
}
// delete item
void ManageConcessionsView::on_pushButton_clicked()
{
ConcessionRepository repository;
QItemSelectionModel* select;
select = ui->tableWidget->selectionModel();
if(select->hasSelection())
{
int ret = QMessageBox::warning(this, tr("Delete Item"),
tr("Are you sure you want to delete item?"),
QMessageBox::Yes | QMessageBox::No
| QMessageBox::Cancel);
if(ret ==QMessageBox::Yes)
{
auto currentrow = select->currentIndex().row();
auto value =ui->tableWidget->item(currentrow,0)->text();
Concession obj;
obj.setId(atoi(value.toStdString().c_str()));
repository.deleteObject(obj);
LoadConcessions();
}
}
}
void ManageConcessionsView::on_pushButton_3_clicked()
{
}
|
d044b044c07f64bb07849399271c0654a5ff17a1
|
e83c6a83e7a97b74d0c267ae79f4c29498c236e8
|
/ParallelParticles/ParallelParticles/ParticlesExportResultAssembler.h
|
e43bfb495abe7a18faec2139d00af9ef953a8153
|
[] |
no_license
|
wws2003/StudyProjectL2
|
82854e51fb0a98d37cf06fec64c507fca5427acc
|
524acf61f489b88ba3971e0ad30830c33d9df19f
|
refs/heads/master
| 2021-01-19T06:12:39.631154
| 2015-10-21T06:16:03
| 2015-10-21T06:16:03
| 13,218,644
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 579
|
h
|
ParticlesExportResultAssembler.h
|
//
// ParticleExportResultAssembler.h
// ParallelParticles
//
// Created by wws2003 on 8/3/14.
// Copyright (c) 2014 wws2003. All rights reserved.
//
#ifndef __ParallelParticles__ParticleExportResultAssembler__
#define __ParallelParticles__ParticleExportResultAssembler__
#include <iostream>
#include "PPTypeDefs.h"
class ParticlesExportResultAssembler {
public:
ParticlesExportResultPtr createInitiatorInstance();
void destroyExportResultInstance(ParticlesExportResultPtr pInstance);
};
#endif /* defined(__ParallelParticles__ParticleExportResultAssembler__) */
|
759331475b1125885d1749f49c243e9614b1d865
|
999d9a08726f1de4c40c266f45864f06b615125e
|
/hw3.h
|
81c7d9ecd5f736c467763b0075832331abcbfac7
|
[] |
no_license
|
StevenLCY/Digital-Image-Processing
|
1e24b1a1ab9babdc130454cc230c92f7f4c1480c
|
9566bba6dfd4d9728e82fbaa804d266340983641
|
refs/heads/master
| 2020-04-08T22:41:51.984726
| 2018-12-16T15:10:44
| 2018-12-16T15:10:44
| 159,797,458
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 789
|
h
|
hw3.h
|
#ifndef HW3_H
#define HW3_H
#include <QDialog>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <vector>
namespace Ui {
class HW3;
}
class HW3 : public QDialog
{
Q_OBJECT
public:
explicit HW3(QWidget *parent = nullptr);
~HW3();
private slots:
void getFrame(cv::Mat img);
void on_boxFilter_clicked();
void on_gaussianFilter_clicked();
void on_bilateralFilter_clicked();
void on_sobelFilter_clicked();
private:
//cv::Mat convolution(cv::Mat src, std::vector<std::vector <int> > kernel, int size);
void applyConvolution(const cv::Mat &src, cv::Mat &dst, const cv::Mat &kernel);
Ui::HW3 *ui;
cv::Mat src;
signals:
void sendProcImg(const cv::Mat &img);
};
#endif // HW3_H
|
c1d417797775f7e0e28179d14f172d1df819642a
|
b4ad8495d6e353ec1dd75503da06e27c04c9e89d
|
/include/cchmc/deprecated/IndexSpace.h
|
b93aa4165211645cf1959a5d7b7020fa6525eb13
|
[
"BSD-2-Clause-Views",
"BSD-2-Clause"
] |
permissive
|
putnampp/clotho-dev
|
a0efc5346c051460abab336c783a3977dbc26bf1
|
dd6ffdb549f6669236745bbf80be6b12392ecc00
|
refs/heads/master
| 2021-01-25T06:36:32.056942
| 2014-09-15T14:28:17
| 2014-09-15T14:28:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,610
|
h
|
IndexSpace.h
|
/*******************************************************************************
* Copyright (c) 2013, Patrick P. Putnam (putnampp@gmail.com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
******************************************************************************/
#ifndef INDEX_SPACE_H_
#define INDEX_SPACE_H_
#include "common.h"
#include <cassert>
#include <cstring>
struct enumerable {
virtual uint32_t index() = 0;
virtual uint32_t limit() const = 0;
};
/*******************************************************************************
* Index space is an coordinate system where points are enumerable
*
* Coordinates are used to identify points.
*
******************************************************************************/
struct index_space : public enumerable {
virtual sizet_t rank() const = 0;
virtual void setDimensions( const uint32_t * limits, size_t rank ) = 0;
virtual void setCoordinates( const uint32_t * coords, size_t rank ) = 0;
virtual void getCoordinate( uint32_t rank ) = 0;
virtual void getCoordinates( uint32_t * coords ) = 0;
virtual void resetCoordinates( ) = 0;
};
/*******************************************************************************
* IndexSpace is a basic implementation of an index_space.
*
* It assumes that dimensions are expressed in row-major order. In other words,
* the last dimension is considered to be continuous.
*
******************************************************************************/
template < unsigned char R >
class IndexSpace : public index_space {
public:
IndexSpace( ) : m_offset(0), m_maxLimit(0), m_bUpToDate(false) {
}
/*****
* Default constructor for creating a square IndexSpace
*
* Each dimension has the same limit value
****/
IndexSpace( uint32_t limit ) : m_offset(0), m_maxIndex(0), m_bUpToDate(false) {
for( int i = 0; i < RANK; ++i ) {
this->m_dims[i] = limit;
}
}
IndexSpace( uint32_t * limits, value_t * coords, size_t rank = RANK ) : m_offset(0), m_maxIndex(0), m_bUpToDate(false) {
memcpy( this->m_dims, dims, RANK * sizeof( uint32_t ) );
memcpy( this->m_coords, coords, RANK * sizeof(uint32_t) );
calculate_index();
}
IndexSpace( const CoordinateSpace< RANK > & c ) m_bUpToDate(false) {
memcpy( this->m_dims, c.m_dims, RANK * sizeof( uint32_t ));
memcpy( this->m_coords, c.m_coords, RANK * sizeof( value_t ));
this->m_offset = c.m_offset;
}
virtual void setDimensions( const uint32_t * limits, size_t rank = RANK ) {
assert( rank <= RANK );
memcpy( m_dims, limits, rank * sizeof( uint32_t ) );
compute_dimension_offsets();
}
virtual void setCoordinates( uint32_t rank, uint32_t coord ) {
assert( rank < RANK );
assert( coord < m_dims[ rank ] );
m_coords[ rank ] = coord;
m_bUpToDate = false;
}
virtual void setCoordinates( const uint32_t * coords, size_t rank = RANK ) {
assert( 0 < rank && rank <= RANK );
// Check that each set coordinate is valid with the current space
// compute_dimension_offsets the coordinate
for( int i = 0; i < rank; ++i ) {
assert( coords[i] < m_dims[ i ] );
m_coords[i] = coords[i];
}
// all coordinates should be valid. compute_dimension_offsets the index
calculate_index();
}
virtual uint32_t getCoordinate( uint32_t rank ) {
assert( rank < RANK );
return m_coords[rank];
}
virtual void getCoordinates( uint32_t * coords ) {
assert( coords != NULL );
memcpy( coords, m_coords, RANK * sizeof(uint32_t) );
}
virtual void resetCoordinates() {
memset( m_coords, 0, RANK * sizeof( value_t ) );
m_bUpToDate = false;
}
virtual size_t rank() const {
return RANK;
}
virtual uint32_t limit() const {
return m_maxIndex;
}
virtual uint32_t index() {
if( !m_bUpToDate ) calculate_index();
return m_offset;
}
virtual ~Offset() { }
protected:
virtual void compute_dimension_offsets() {
// last dimension is continuous
m_dimOffsets[ RANK - 1 ] = 1;
for( int i = RANK; i >= 1; --i ) {
m_dimOffsets[ i - 1 ] = m_dims[ i ] * m_dimOffsets[ i ];
}
m_maxIndex = m_dimOffsets[0] * m_dims[0];
// Assume that dimensional changes have invalidated the coordinates
// therefore, just reset set them.
resetCoordinates();
}
void calculate_index() {
for( int i = 0; i < RANK; ++i ) {
assert( m_coords[i] < m_dims[ i ] );
m_offset = m_coords[ i ] * m_dimOffsets[ i ];
}
m_bUpToDate = true;
}
static const unsigned char RANK = R;
uint32_t m_coords[ RANK ];
uint32_t m_dims[ RANK ];
uint32_t m_dimOffsets[ RANK ];
uint32_t m_offset;
uint32_t m_maxIndex;
bool m_bUpToDate;
};
#endif // INDEX_SPACE_H_
|
a0b74343dc01bb5b974449d301810d0b4459185a
|
bdc67ddec677652859d5af62fb9be76e232064b8
|
/c++ learning/Others/coding test2.cpp
|
71379aaf77c2d9a8e54b6d834199d15b4f8af838
|
[] |
no_license
|
vvonth/Algorithm
|
e1491bf95740fb6037ae4834c7bd05d38db11c88
|
7847ffd9ae32410507b93226e424b6a3886c38ae
|
refs/heads/master
| 2023-02-16T18:31:36.631210
| 2021-01-10T03:35:25
| 2021-01-10T03:35:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,611
|
cpp
|
coding test2.cpp
|
//
// coding test2.cpp
// c++ learning
//
// Created by 원태희 on 16/03/2019.
// Copyright © 2019 원태희. All rights reserved.
//
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main(void){
string s;
string a;
stack<char> t;
stack <char> n;
vector<char> v;
stack<char> k;
int i;
int count=0;
int count2=0;
cin>>s;
for(i=0;i<s.size();i++)
{
if(s[i]>='A'&&s[i]<='Z')
count++;
if(s[i]>='1'&&s[i]<='9')
{
count2++;
}
}
if(count!=count2)
{
printf("error");
return 0;
}
for(i=0;i<s.size();i++)
{
if(s[i+1]>='a'&&s[i+1]<='z')
{
t.push(s[i]);
t.push(s[i+1]);
}
else if(s[i]>='A'&&s[i]<='Z')
{
t.push(s[i]);
}
else if(s[i]>='1'&&s[i]<='9')
{
n.push(s[i]);
}
}
while((!t.empty())||(!n.empty()))
{
if(n.top()!=1&&(!n.empty()))
{
v.push_back(n.top());
n.pop();
}
if((t.top()>='a'&&t.top()<='z')&&(!t.empty()))
{
v.push_back(t.top());
t.pop();
v.push_back(t.top());
t.pop();
}
else if((t.top()>='A'&&t.top()<='Z')&&(!t.empty()))
{
v.push_back(t.top());
t.pop();
}
}
for(auto x: v)
k.push(x);
while(!k.empty())
{
if(k.top()!='1')
cout<<k.top();
k.pop();
}
}
|
dc4ef86fd4c551d5b36b935eb24643031da2cc90
|
79ca7afb8c1996195029ffa16ec5f70918430bc9
|
/FileTransferProgram/Widgets.cpp
|
fff8469289ac36c7d3157ef49fa101eff4441d93
|
[] |
no_license
|
patwong92/FileTransferProgram
|
5ee345d4286261f4c54741ec1dcfe2844abadf0d
|
2be7f143d688c4e134503c02fd24866e5aa59286
|
refs/heads/master
| 2022-09-23T03:18:32.648297
| 2020-06-03T03:42:22
| 2020-06-03T03:42:22
| 240,946,964
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,885
|
cpp
|
Widgets.cpp
|
/*------------------------------------------------------------------------------------------------------------------
-- SOURCE FILE: Widgets.cpp - Provides the interface windows in the application
--
-- PROGRAM: FileTransferProgram
--
-- FUNCTIONS:
-- VOID CreateLabel(HWND hwnd, LPCTSTR text, int x, int y);
-- HWND CreateTextEntry(HWND hwnd, int num, int x, int y, int identifier);
-- HWND CreateTextEntry(HWND hwnd, TCHAR text[], int x, int y, int identifier);
-- HWND CreateButton(HWND hwnd, TCHAR text[], int x, int y, int identifier);
-- void SendOutputMessage(HWND hwnd, TCHAR text[]);
-- void SendOutputMessage(HWND hwnd, TCHAR text1[], TCHAR text2[]);
-- void SendOutputMessage(HWND hwnd, TCHAR text[], int size);
-- void ClearOutputMessage(HWND hwnd);
--
-- DATE: February 11, 2020
--
-- REVISIONS: February 18, 2020; finalized implementation
--
-- DESIGNER: Patrick Wong
--
-- PROGRAMMER: Patrick Wong
--
-- NOTES:
-- This file provides the functions to add GUI objects to the application.
----------------------------------------------------------------------------------------------------------------------*/
#include "Widgets.h"
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: CreateButton
--
-- DATE: February 11, 2020
--
-- REVISIONS: February 18, 2020; finalized implementation
--
-- DESIGNER: Patrick Wong
--
-- PROGRAMMER: Patrick Wong
--
-- INTERFACE: HWND CreateButton(HWND hwnd, TCHAR text[], int x, int y, int identifier)
-- HWND hwnd - Window handle
-- TCHAR[] text - Button label
-- int x - X-position on the window
-- int y - Y-position on the window
-- int identifier - ID of the button
--
-- RETURNS: Handle to the button
--
-- NOTES:
-- Call this function to create a button
----------------------------------------------------------------------------------------------------------------------*/
HWND CreateButton(HWND hwnd, TCHAR text[], int x, int y, int identifier)
{
HWND handle;
if ((handle = CreateWindowExA(0, "BUTTON", text, WS_BORDER | WS_VISIBLE | WS_CHILD,
x, y, 150, 30, hwnd, (HMENU) identifier, GetModuleHandle(NULL), NULL)) == NULL)
return NULL;
return handle;
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: SendOutputMessage
--
-- DATE: February 11, 2020
--
-- REVISIONS: February 18, 2020; finalized implementation
--
-- DESIGNER: Patrick Wong
--
-- PROGRAMMER: Patrick Wong
--
-- INTERFACE: void SendOutputMessage(HWND hwnd, TCHAR text[])
-- HWND hwnd - Window handle
-- TCHAR[] text - text to send
--
-- RETURNS: void
--
-- NOTES:
-- Sends text to the output box.
----------------------------------------------------------------------------------------------------------------------*/
void SendOutputMessage(HWND hwnd, TCHAR text[])
{
TCHAR message[DATA_BUFSIZE];
GetWindowText(hwnd, message, DATA_BUFSIZE);
strcat(message, text);
strcat(message, "\r\n");
SetWindowText(hwnd, message);
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: SendOutputMessage
--
-- DATE: February 11, 2020
--
-- REVISIONS: February 18, 2020; finalized implementation
--
-- DESIGNER: Patrick Wong
--
-- PROGRAMMER: Patrick Wong
--
-- INTERFACE: void SendOutputMessage(HWND hwnd, TCHAR text1[], TCHAR text2[])
-- HWND hwnd - Window handle
-- TCHAR[] text1 - Text to send
-- TCHAR[] text2 - Text to send
--
-- RETURNS: void
--
-- NOTES:
-- Concatenates two texts and sends them to the output box.
----------------------------------------------------------------------------------------------------------------------*/
void SendOutputMessage(HWND hwnd, TCHAR text1[], TCHAR text2[])
{
TCHAR message[DATA_BUFSIZE];
GetWindowText(hwnd, message, DATA_BUFSIZE);
strcat(message, text1);
strcat(message, " ");
strcat(message, text2);
strcat(message, "\r\n");
SetWindowText(hwnd, message);
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: SendOutputMessage
--
-- DATE: February 11, 2020
--
-- REVISIONS: February 18, 2020; finalized implementation
--
-- DESIGNER: Patrick Wong
--
-- PROGRAMMER: Patrick Wong
--
-- INTERFACE: void SendOutputMessage(HWND hwnd, TCHAR text1[], int size)
-- HWND hwnd - Window handle
-- TCHAR[] text - Text to send
-- int size - Size of the buffer
--
-- RETURNS: void
--
-- NOTES:
-- Given the size of the buffer, the function dynamically allocates memory to send text to thee output box.
----------------------------------------------------------------------------------------------------------------------*/
void SendOutputMessage(HWND hwnd, TCHAR text[], int size)
{
TCHAR* message = (TCHAR*)malloc(sizeof(TCHAR) * (2 * size));
if (message != NULL)
{
memset(message, 0, sizeof(TCHAR) * (2 * size));
GetWindowText(hwnd, message, sizeof(TCHAR) * (2 * size));
strncat(message, text, size);
strcat(message, "\r\n");
SetWindowText(hwnd, message);
free(message);
message = NULL;
}
}
/*------------------------------------------------------------------------------------------------------------------
-- FUNCTION: ClearOutputMessage
--
-- DATE: February 11, 2020
--
-- REVISIONS: February 18, 2020; finalized implementation
--
-- DESIGNER: Patrick Wong
--
-- PROGRAMMER: Patrick Wong
--
-- INTERFACE: void ClearOutputMessage(HWND hwnd)
-- HWND hwnd - Window handle
--
-- RETURNS: void
--
-- NOTES:
-- Clears the contents of the output box.
----------------------------------------------------------------------------------------------------------------------*/
void ClearOutputMessage(HWND hwnd)
{
TCHAR message[DATA_BUFSIZE];
GetWindowText(hwnd, message, DATA_BUFSIZE);
memset(message, 0, DATA_BUFSIZE);
SetWindowText(hwnd, message);
}
|
4bd1f133971cab9d0c932e6a0b5ee06faaa9c167
|
3984d16c69600a0883427ed01bd971b0d4d7c18b
|
/inc/include/gstreamermm-0.10/gstreamermm/private/typefind_p.h
|
d54946220a853de49903eb52bd08293a27894f4b
|
[] |
no_license
|
venkatarajasekhar/Lerdu
|
2f3db41d2f6955a2bd49ca0854c85aaf8dd60ae0
|
c4aa3b1c5fb01908d62d25d9e71c0f6165b64b7d
|
refs/heads/master
| 2020-06-18T07:41:29.511894
| 2012-10-28T15:14:48
| 2012-10-28T15:14:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 169
|
h
|
typefind_p.h
|
// -*- c++ -*-
// Generated by gtkmmproc -- DO NOT MODIFY!
#ifndef _GSTREAMERMM_TYPEFIND_P_H
#define _GSTREAMERMM_TYPEFIND_P_H
#endif /* _GSTREAMERMM_TYPEFIND_P_H */
|
de64450db13141fe6601550892c8b6c2486ae2b8
|
c9104fb66e4c5d278ddcf249cb6352a49e74664f
|
/MyDraw/textBoxGUI.h
|
519daad676575c6ce2956ce8b733ee94f80b22fb
|
[] |
no_license
|
mrsakkaro/CS390CPP
|
2c849cd12c240c315590f496e76e2e8584ca2f7c
|
f1884502703560314f0dfafdd8054b9f05883ae4
|
refs/heads/master
| 2021-01-19T13:01:10.096828
| 2015-02-20T23:50:34
| 2015-02-20T23:50:34
| 30,996,307
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 456
|
h
|
textBoxGUI.h
|
#pragma once
#include "afxwin.h"
// textBoxGUI dialog
class textBoxGUI : public CDialogEx
{
DECLARE_DYNAMIC(textBoxGUI)
public:
textBoxGUI(CWnd* pParent = NULL); // standard constructor
virtual ~textBoxGUI();
// Dialog Data
enum { IDD = IDD_DIALOG1 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
// TextBox String
CEdit textBoxString;
afx_msg void OnEnChangeEdit1();
};
|
b19bda34ae8be7bea08b45f59d025d1ebd5df628
|
a8d9117fc005fac9d674375caee0213f35e93c8f
|
/GFG/longestconsecones.cpp
|
b9b354a5520ebb208c86ec289b2cc55c395f4da7
|
[] |
no_license
|
logan0501/BIT-MAGIC-PROBLEMS
|
3a4f4daa5ce7767502383b9508f91d960fea925b
|
e893af21e18854ec5c63a08de54d2eb7d5074e4e
|
refs/heads/main
| 2023-08-03T11:39:49.613436
| 2021-09-06T14:30:56
| 2021-09-06T14:30:56
| 403,130,361
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 268
|
cpp
|
longestconsecones.cpp
|
/*
Created by logan on 05-09-2021.
*/
#include "iostream"
using namespace std;
int longestConsecOnes(int n){
int count=0;
while(n){
count++;
n=(n&(n<<1));
}
return count;
}
int main() {
cout<<longestConsecOnes(14);
return 0;
}
|
ed1cc877445ac9c1181706577037362fb1a6f881
|
fbc7e0c7223127a961a16d85a3e705d149f1e025
|
/mechsim/tests/Bunny.h
|
6e086d6b5bdb8d768a75fab7d77dab728de1fa29
|
[] |
no_license
|
nfbraun/xrp
|
f406d4c71436e27ff660cca2dc23bc649cc7d3c3
|
3b344ad4f69aaa0350c4708e001b43e66228a7a6
|
refs/heads/master
| 2016-09-10T06:50:54.646498
| 2014-07-29T18:37:19
| 2014-07-29T18:43:06
| 6,868,442
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 894
|
h
|
Bunny.h
|
#ifndef MSIM_BUNNY_H
#define MSIM_BUNNY_H
#include "Simulation.h"
#include <GL/gl.h>
class Bunny;
class BunnyState: public SimulationState {
public:
double fT;
void Draw(int) const;
// calculated with vtk
Eigen::Vector3d GetCenter() const
{ return 10.*Eigen::Vector3d(.2 * sin(fT / 8.), 0., 0.154/2.); }
Bunny* fParent;
};
class Bunny: public Simulation {
friend class BunnyState;
public:
Bunny();
double GetTimestep() { return 1./STEP_PER_SEC; }
int GetDefaultEndTime() { return 60. * STEP_PER_SEC; }
const char* GetTitle() { return TITLE; }
inline void Advance() { fCurStep++; };
BunnyState GetCurrentState();
int fCurStep;
static const int STEP_PER_SEC;
static const int INT_PER_STEP;
static const char TITLE[];
private:
GLuint GetBunnyList();
GLuint fGLList;
};
#endif
|
d87e0833f39607cc910f0d225809173668458223
|
2e6c001805d872577fb4b05d1e91bc812d1db41c
|
/answers/JS-0638/string/string.cpp
|
7550f1f3b47950b9d15068fe5e134ff251903338
|
[] |
no_license
|
fsy-juruo/noip2020-JS-Answers
|
f9e7ec8c7d86274bb8d18ecf7a9b858b11d9a8bb
|
476106a54046665e1362bee246fa83b6f0d00857
|
refs/heads/main
| 2023-01-31T02:37:52.273421
| 2020-12-05T12:27:17
| 2020-12-05T12:27:17
| 318,722,231
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,072
|
cpp
|
string.cpp
|
#include<bits/stdc++.h>
using namespace std;
void fre() {
freopen("string.in","r",stdin);
freopen("string.out","w",stdout);
}
typedef long long ll;
inline ll read() {
ll x=0;
char ch=getchar();
while(ch<'0'||ch>'9') {
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=(x<<3)+(x<<1)+ch-'0';
ch=getchar();
}
return x;
}
inline void write(ll x) {
if(x>=10)write(x/10);
putchar(x%10+'0');
}
ll cou(string x) {
ll cnt=0;
map<char,ll>mp;
ll len=x.length();
for(ll i=0; i<len; i++) {
mp[x[i]]++;
}
for(map<char,ll>::iterator it=mp.begin(); it!=mp.end(); it++) {
if(it->second%2==1)cnt++;
}
return cnt;
}
signed main() {
fre();
ll t;
cin>>t;
while(t--) {
ll cnt=0;
string x;
cin>>x;
ll len=x.length();
for(ll i=1; i<len; i++)
for(ll j=i+1; j<len; j++) {
string a=x.substr(0,i),b=x.substr(i,j-i);
string ss=x.substr(0,j);
ll ptr=0;
while(ss==x.substr(ptr,j)&&ptr+j<len) {
string c=x.substr(ptr+j,len-ptr-j);
if(cou(a)<=cou(c)) {
cnt++;
}
ptr+=j;
}
}
cout<<cnt<<endl;
}
return 0;
}
|
9ac0f13ac08bc147749287695163b6267fd7151c
|
4d32bc200a8ee823176b1096912d05bf94bb49f6
|
/Algoritma-dan-Pemrograman-1/Praktikum 1 ( Runtunan 1 )/prak1-18.cpp
|
cad976ecd88bd9e36ddc5028e2216db036093d11
|
[] |
no_license
|
Irvanabdurrahman/My-Code
|
364b890fb171dcac97090084c2dd41d0bc890d4d
|
eeed51144f0924b815f91eae48f7165ef3feb670
|
refs/heads/master
| 2016-08-04T10:05:17.847085
| 2013-05-10T13:03:32
| 2013-05-10T13:03:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 268
|
cpp
|
prak1-18.cpp
|
#include <conio.h>
#include <iostream.h>
void main()
{
clrscr();
long Upah, tahun;
cout << "Menghitung Gaji buruh Pertahun" << endl;
cout << endl;
cout << "Masukan Pertahun Kerja Anda:";
cin >> tahun;
Upah = 9000000 * tahun;
cout << "Nilai Upah: " << Upah;
getch();
}
|
e51ffde9d3897ea473e409fec8c290912279bf46
|
99250174edf7c180679b244fcb85393c40155eb7
|
/Algorithm Practice/Algorithm Practice/13458.cpp
|
3dfbb51312313d68a36b7db08dc49f3014b50688
|
[] |
no_license
|
Minyeob/Algorithm
|
b677091bdd1b578165fd58fb7e24fc1582c8d45f
|
b629eaacbd87193cf9b3876fac8443826fa8e5c5
|
refs/heads/master
| 2020-12-02T07:56:25.435592
| 2017-10-22T14:27:16
| 2017-10-22T14:27:16
| 70,489,935
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 397
|
cpp
|
13458.cpp
|
#include <cstdio>
int room[1000001];
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &room[i]);
}
int b, c;
scanf("%d %d", &b, &c);
long long count = 0;
for (int i = 0; i < n; i++)
{
count++;
int now = room[i] - b;
if (now > 0)
{
int check = now / c;
count = count + check;
if (now%c > 0)
count++;
}
}
printf("%lld", count);
}
|
3c774484c6898a458a8788bd3a2fce88634ab860
|
1501f50acc22b9e915d04df435210d68e2a907ee
|
/include/Org/BouncyCastle/Crypto/Digests/WhirlpoolDigest.hpp
|
8f430b32b9acc9b3cacf2ea2a8291b9400c13b32
|
[
"Unlicense"
] |
permissive
|
sc2ad/BeatSaber-Quest-Codegen
|
cd944128d6c7b61f2014f13313d2d6cf424df811
|
4bfd0c0f705e7a302afe6ec1ef996b5b2e3f4600
|
refs/heads/master
| 2023-03-11T11:07:22.074423
| 2023-02-28T22:15:16
| 2023-02-28T22:15:16
| 285,669,750
| 31
| 25
|
Unlicense
| 2023-02-28T22:15:18
| 2020-08-06T20:56:01
|
C++
|
UTF-8
|
C++
| false
| false
| 25,814
|
hpp
|
WhirlpoolDigest.hpp
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: Org.BouncyCastle.Crypto.IDigest
#include "Org/BouncyCastle/Crypto/IDigest.hpp"
// Including type: Org.BouncyCastle.Utilities.IMemoable
#include "Org/BouncyCastle/Utilities/IMemoable.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Type namespace: Org.BouncyCastle.Crypto.Digests
namespace Org::BouncyCastle::Crypto::Digests {
// Forward declaring type: WhirlpoolDigest
class WhirlpoolDigest;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest);
DEFINE_IL2CPP_ARG_TYPE(::Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*, "Org.BouncyCastle.Crypto.Digests", "WhirlpoolDigest");
// Type namespace: Org.BouncyCastle.Crypto.Digests
namespace Org::BouncyCastle::Crypto::Digests {
// Size: 0x58
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Crypto.Digests.WhirlpoolDigest
// [TokenAttribute] Offset: FFFFFFFF
class WhirlpoolDigest : public ::Il2CppObject/*, public ::Org::BouncyCastle::Crypto::IDigest, public ::Org::BouncyCastle::Utilities::IMemoable*/ {
public:
public:
// private readonly System.Int64[] _rc
// Size: 0x8
// Offset: 0x10
::ArrayW<int64_t> rc;
// Field size check
static_assert(sizeof(::ArrayW<int64_t>) == 0x8);
// private System.Byte[] _buffer
// Size: 0x8
// Offset: 0x18
::ArrayW<uint8_t> buffer;
// Field size check
static_assert(sizeof(::ArrayW<uint8_t>) == 0x8);
// private System.Int32 _bufferPos
// Size: 0x4
// Offset: 0x20
int bufferPos;
// Field size check
static_assert(sizeof(int) == 0x4);
// Padding between fields: bufferPos and: bitCount
char __padding2[0x4] = {};
// private System.Int16[] _bitCount
// Size: 0x8
// Offset: 0x28
::ArrayW<int16_t> bitCount;
// Field size check
static_assert(sizeof(::ArrayW<int16_t>) == 0x8);
// private System.Int64[] _hash
// Size: 0x8
// Offset: 0x30
::ArrayW<int64_t> hash;
// Field size check
static_assert(sizeof(::ArrayW<int64_t>) == 0x8);
// private System.Int64[] _K
// Size: 0x8
// Offset: 0x38
::ArrayW<int64_t> K;
// Field size check
static_assert(sizeof(::ArrayW<int64_t>) == 0x8);
// private System.Int64[] _L
// Size: 0x8
// Offset: 0x40
::ArrayW<int64_t> L;
// Field size check
static_assert(sizeof(::ArrayW<int64_t>) == 0x8);
// private System.Int64[] _block
// Size: 0x8
// Offset: 0x48
::ArrayW<int64_t> block;
// Field size check
static_assert(sizeof(::ArrayW<int64_t>) == 0x8);
// private System.Int64[] _state
// Size: 0x8
// Offset: 0x50
::ArrayW<int64_t> state;
// Field size check
static_assert(sizeof(::ArrayW<int64_t>) == 0x8);
public:
// Creating interface conversion operator: operator ::Org::BouncyCastle::Crypto::IDigest
operator ::Org::BouncyCastle::Crypto::IDigest() noexcept {
return *reinterpret_cast<::Org::BouncyCastle::Crypto::IDigest*>(this);
}
// Creating interface conversion operator: i_IDigest
inline ::Org::BouncyCastle::Crypto::IDigest* i_IDigest() noexcept {
return reinterpret_cast<::Org::BouncyCastle::Crypto::IDigest*>(this);
}
// Creating interface conversion operator: operator ::Org::BouncyCastle::Utilities::IMemoable
operator ::Org::BouncyCastle::Utilities::IMemoable() noexcept {
return *reinterpret_cast<::Org::BouncyCastle::Utilities::IMemoable*>(this);
}
// Creating interface conversion operator: i_IMemoable
inline ::Org::BouncyCastle::Utilities::IMemoable* i_IMemoable() noexcept {
return reinterpret_cast<::Org::BouncyCastle::Utilities::IMemoable*>(this);
}
// Get static field: static private readonly System.Int32[] SBOX
static ::ArrayW<int> _get_SBOX();
// Set static field: static private readonly System.Int32[] SBOX
static void _set_SBOX(::ArrayW<int> value);
// Get static field: static private readonly System.Int64[] C0
static ::ArrayW<int64_t> _get_C0();
// Set static field: static private readonly System.Int64[] C0
static void _set_C0(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C1
static ::ArrayW<int64_t> _get_C1();
// Set static field: static private readonly System.Int64[] C1
static void _set_C1(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C2
static ::ArrayW<int64_t> _get_C2();
// Set static field: static private readonly System.Int64[] C2
static void _set_C2(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C3
static ::ArrayW<int64_t> _get_C3();
// Set static field: static private readonly System.Int64[] C3
static void _set_C3(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C4
static ::ArrayW<int64_t> _get_C4();
// Set static field: static private readonly System.Int64[] C4
static void _set_C4(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C5
static ::ArrayW<int64_t> _get_C5();
// Set static field: static private readonly System.Int64[] C5
static void _set_C5(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C6
static ::ArrayW<int64_t> _get_C6();
// Set static field: static private readonly System.Int64[] C6
static void _set_C6(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int64[] C7
static ::ArrayW<int64_t> _get_C7();
// Set static field: static private readonly System.Int64[] C7
static void _set_C7(::ArrayW<int64_t> value);
// Get static field: static private readonly System.Int16[] EIGHT
static ::ArrayW<int16_t> _get_EIGHT();
// Set static field: static private readonly System.Int16[] EIGHT
static void _set_EIGHT(::ArrayW<int16_t> value);
// Get instance field reference: private readonly System.Int64[] _rc
[[deprecated("Use field access instead!")]] ::ArrayW<int64_t>& dyn__rc();
// Get instance field reference: private System.Byte[] _buffer
[[deprecated("Use field access instead!")]] ::ArrayW<uint8_t>& dyn__buffer();
// Get instance field reference: private System.Int32 _bufferPos
[[deprecated("Use field access instead!")]] int& dyn__bufferPos();
// Get instance field reference: private System.Int16[] _bitCount
[[deprecated("Use field access instead!")]] ::ArrayW<int16_t>& dyn__bitCount();
// Get instance field reference: private System.Int64[] _hash
[[deprecated("Use field access instead!")]] ::ArrayW<int64_t>& dyn__hash();
// Get instance field reference: private System.Int64[] _K
[[deprecated("Use field access instead!")]] ::ArrayW<int64_t>& dyn__K();
// Get instance field reference: private System.Int64[] _L
[[deprecated("Use field access instead!")]] ::ArrayW<int64_t>& dyn__L();
// Get instance field reference: private System.Int64[] _block
[[deprecated("Use field access instead!")]] ::ArrayW<int64_t>& dyn__block();
// Get instance field reference: private System.Int64[] _state
[[deprecated("Use field access instead!")]] ::ArrayW<int64_t>& dyn__state();
// public System.String get_AlgorithmName()
// Offset: 0x1EE441C
::StringW get_AlgorithmName();
// static private System.Void .cctor()
// Offset: 0x1EE3A78
static void _cctor();
// public System.Void .ctor()
// Offset: 0x1EE3F00
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static WhirlpoolDigest* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<WhirlpoolDigest*, creationType>()));
}
// public System.Void .ctor(Org.BouncyCastle.Crypto.Digests.WhirlpoolDigest originalDigest)
// Offset: 0x1EE41AC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static WhirlpoolDigest* New_ctor(::Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest* originalDigest) {
static auto ___internal__logger = ::Logger::get().WithContext("::Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<WhirlpoolDigest*, creationType>(originalDigest)));
}
// static private System.Int64 packIntoLong(System.Int32 b7, System.Int32 b6, System.Int32 b5, System.Int32 b4, System.Int32 b3, System.Int32 b2, System.Int32 b1, System.Int32 b0)
// Offset: 0x1EE3ECC
static int64_t packIntoLong(int b7, int b6, int b5, int b4, int b3, int b2, int b1, int b0);
// static private System.Int32 maskWithReductionPolynomial(System.Int32 input)
// Offset: 0x1EE3EB8
static int maskWithReductionPolynomial(int input);
// public System.Int32 GetDigestSize()
// Offset: 0x1EE4464
int GetDigestSize();
// public System.Int32 DoFinal(System.Byte[] output, System.Int32 outOff)
// Offset: 0x1EE446C
int DoFinal(::ArrayW<uint8_t> output, int outOff);
// public System.Void Reset()
// Offset: 0x1EE4698
void Reset();
// private System.Void processFilledBuffer()
// Offset: 0x1EE4760
void processFilledBuffer();
// static private System.Int64 bytesToLongFromBuffer(System.Byte[] buffer, System.Int32 startPos)
// Offset: 0x1EE4858
static int64_t bytesToLongFromBuffer(::ArrayW<uint8_t> buffer, int startPos);
// static private System.Void convertLongToByteArray(System.Int64 inputLong, System.Byte[] outputArray, System.Int32 offSet)
// Offset: 0x1EE4628
static void convertLongToByteArray(int64_t inputLong, ::ArrayW<uint8_t> outputArray, int offSet);
// private System.Void processBlock()
// Offset: 0x1EE4938
void processBlock();
// public System.Void Update(System.Byte input)
// Offset: 0x1EE5294
void Update(uint8_t input);
// private System.Void increment()
// Offset: 0x1EE530C
void increment();
// public System.Void BlockUpdate(System.Byte[] input, System.Int32 inOff, System.Int32 length)
// Offset: 0x1EE542C
void BlockUpdate(::ArrayW<uint8_t> input, int inOff, int length);
// private System.Void finish()
// Offset: 0x1EE4548
void finish();
// private System.Byte[] copyBitLength()
// Offset: 0x1EE54A4
::ArrayW<uint8_t> copyBitLength();
// public System.Int32 GetByteLength()
// Offset: 0x1EE555C
int GetByteLength();
// public Org.BouncyCastle.Utilities.IMemoable Copy()
// Offset: 0x1EE5564
::Org::BouncyCastle::Utilities::IMemoable* Copy();
// public System.Void Reset(Org.BouncyCastle.Utilities.IMemoable other)
// Offset: 0x1EE42A4
void Reset(::Org::BouncyCastle::Utilities::IMemoable* other);
}; // Org.BouncyCastle.Crypto.Digests.WhirlpoolDigest
#pragma pack(pop)
static check_size<sizeof(WhirlpoolDigest), 80 + sizeof(::ArrayW<int64_t>)> __Org_BouncyCastle_Crypto_Digests_WhirlpoolDigestSizeCheck;
static_assert(sizeof(WhirlpoolDigest) == 0x58);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::get_AlgorithmName
// Il2CppName: get_AlgorithmName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::get_AlgorithmName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "get_AlgorithmName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::packIntoLong
// Il2CppName: packIntoLong
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (*)(int, int, int, int, int, int, int, int)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::packIntoLong)> {
static const MethodInfo* get() {
static auto* b7 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b6 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b5 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b4 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b3 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b2 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b1 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* b0 = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "packIntoLong", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{b7, b6, b5, b4, b3, b2, b1, b0});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::maskWithReductionPolynomial
// Il2CppName: maskWithReductionPolynomial
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(int)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::maskWithReductionPolynomial)> {
static const MethodInfo* get() {
static auto* input = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "maskWithReductionPolynomial", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::GetDigestSize
// Il2CppName: GetDigestSize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::GetDigestSize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "GetDigestSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::DoFinal
// Il2CppName: DoFinal
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)(::ArrayW<uint8_t>, int)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::DoFinal)> {
static const MethodInfo* get() {
static auto* output = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* outOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "DoFinal", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{output, outOff});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Reset)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::processFilledBuffer
// Il2CppName: processFilledBuffer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::processFilledBuffer)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "processFilledBuffer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::bytesToLongFromBuffer
// Il2CppName: bytesToLongFromBuffer
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int64_t (*)(::ArrayW<uint8_t>, int)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::bytesToLongFromBuffer)> {
static const MethodInfo* get() {
static auto* buffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* startPos = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "bytesToLongFromBuffer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{buffer, startPos});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::convertLongToByteArray
// Il2CppName: convertLongToByteArray
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(int64_t, ::ArrayW<uint8_t>, int)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::convertLongToByteArray)> {
static const MethodInfo* get() {
static auto* inputLong = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg;
static auto* outputArray = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* offSet = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "convertLongToByteArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputLong, outputArray, offSet});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::processBlock
// Il2CppName: processBlock
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::processBlock)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "processBlock", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)(uint8_t)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Update)> {
static const MethodInfo* get() {
static auto* input = &::il2cpp_utils::GetClassFromName("System", "Byte")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::increment
// Il2CppName: increment
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::increment)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "increment", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::BlockUpdate
// Il2CppName: BlockUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)(::ArrayW<uint8_t>, int, int)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::BlockUpdate)> {
static const MethodInfo* get() {
static auto* input = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg;
static auto* inOff = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "BlockUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{input, inOff, length});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::finish
// Il2CppName: finish
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::finish)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "finish", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::copyBitLength
// Il2CppName: copyBitLength
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::copyBitLength)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "copyBitLength", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::GetByteLength
// Il2CppName: GetByteLength
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::GetByteLength)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "GetByteLength", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Copy
// Il2CppName: Copy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Org::BouncyCastle::Utilities::IMemoable* (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)()>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Copy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "Copy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Reset
// Il2CppName: Reset
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::*)(::Org::BouncyCastle::Utilities::IMemoable*)>(&Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest::Reset)> {
static const MethodInfo* get() {
static auto* other = &::il2cpp_utils::GetClassFromName("Org.BouncyCastle.Utilities", "IMemoable")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Org::BouncyCastle::Crypto::Digests::WhirlpoolDigest*), "Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{other});
}
};
|
d2d7185196ed8943b6c481fc788ba50bd5cff8ab
|
1668222f02e3a0b23f59010335ed6d68c6abd03c
|
/CS 330/enrollment/courseseq.cpp
|
a972e01ed4bb7d83f7070249d0b06588ef144fab
|
[] |
no_license
|
idiotredoc/ODUCS330
|
b497cc3988e2d7f3b4a27956ee524e308013290d
|
dd5350155114b155fc8ccda4704ae45cd2a5e97f
|
refs/heads/master
| 2020-04-06T05:09:00.025761
| 2013-07-26T03:13:03
| 2013-07-26T03:13:03
| 26,942,858
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,358
|
cpp
|
courseseq.cpp
|
#include "courseseq.h"
#include <cassert>
#include <utility>
using namespace std;
using namespace std::rel_ops;
// Constructors & assignment
CourseSequence::CourseSequence()
: theSize(0), theFront(0), theBack(0)
{}
CourseSequence::CourseSequence(const CourseSequence& seq)
: theSize(0), theFront(0), theBack(0)
{
for (Position p = seq.theFront; p != 0; p = p->next)
addToBack(p->data);
}
CourseSequence::~CourseSequence()
{
clear();
}
CourseSequence& CourseSequence::operator= (const CourseSequence& seq)
{
if (theFront != seq.theFront)
{
clear();
for (Position p = seq.theFront; p != 0; p = p->next)
addToBack(p->data);
}
return *this;
}
// General info
unsigned CourseSequence::size() const
{
return theSize;
}
bool CourseSequence::operator== (const CourseSequence& seq) const
{
if (theSize != seq.theSize)
return false;
ConstPosition p1 = theFront;
ConstPosition p2 = seq.theFront;
while (p1 != 0)
{
if (p1->data != p2->data)
return false;
p1 = p1->next;
p2 = p2->next;
}
return true;
}
CourseSequence::ConstCourseRef
CourseSequence::at(CourseSequence::ConstPosition pos) const
{
assert (pos != 0);
return pos->data;
}
CourseSequence::CourseRef
CourseSequence::at(CourseSequence::Position pos)
{
assert (pos != 0);
return pos->data;
}
CourseSequence::Position CourseSequence::front()
{
return theFront;
}
CourseSequence::ConstPosition CourseSequence::front() const
{
return theFront;
}
CourseSequence::Position CourseSequence::back()
{
return theBack;
}
CourseSequence::ConstPosition CourseSequence::back() const
{
return theBack;
}
CourseSequence::ConstPosition
CourseSequence::getNext (CourseSequence::ConstPosition pos) const
{
assert (pos != 0);
return pos->next;
}
CourseSequence::Position
CourseSequence::getNext (CourseSequence::Position pos)
{
assert (pos != 0);
return pos->next;
}
CourseSequence::ConstPosition
CourseSequence::getPrevious (CourseSequence::ConstPosition pos) const
{
assert (pos != 0);
return pos->prev;
}
CourseSequence::Position
CourseSequence::getPrevious (CourseSequence::Position pos)
{
assert (pos != 0);
return pos->prev;
}
// Searching
CourseSequence::ConstPosition
CourseSequence::find(CourseSequence::ConstCourseRef key) const
{
ConstPosition p = theFront;
while (p != 0 && !(p->data == key))
p = p->next;
return p;
}
CourseSequence::Position
CourseSequence::find(CourseSequence::ConstCourseRef key)
{
Position p = theFront;
while (p != 0 && !(p->data == key))
p = p->next;
return p;
}
// search for first element that is >= input value - return NULL if not found
CourseSequence::ConstPosition
CourseSequence::findFirstGreaterEqual
(CourseSequence::ConstCourseRef key) const
{
ConstPosition p = theFront;
while (p != 0 && (key < p->data))
p = p->next;
return p;
}
CourseSequence::Position
CourseSequence::findFirstGreaterEqual(CourseSequence::ConstCourseRef key)
{
Position p = theFront;
while (p != 0 && (key < p->data))
p = p->next;
return p;
}
// Adding and removing elements
void CourseSequence::addToFront (CourseSequence::ConstCourseRef value)
{
if (theFront == 0)
{
theFront = theBack = new CourseSequenceNode (value, 0, 0);
}
else
{
Position oldFirst = theFront;
theFront = oldFirst->prev = new CourseSequenceNode (value, 0, oldFirst);
}
++theSize;
}
void CourseSequence::addToBack (CourseSequence::ConstCourseRef value)
{
if (theBack == 0)
{
theFront = theBack = new CourseSequenceNode (value, 0, 0);
}
else
{
Position oldLast = theBack;
theBack = oldLast->next = new CourseSequenceNode (value, oldLast, 0);
}
++theSize;
}
void CourseSequence::addAfter (CourseSequence::Position pos,
CourseSequence::ConstCourseRef value)
{
assert (pos != 0);
Position newNode = new CourseSequenceNode(value, pos, pos->next);
if (pos->next != 0)
pos->next->prev = newNode;
pos->next = newNode;
if (theBack == pos)
theBack = newNode;
++theSize;
}
void CourseSequence::addBefore (CourseSequence::Position pos,
CourseSequence::ConstCourseRef value)
{
assert (pos != 0);
Position newNode = new CourseSequenceNode(value, pos->prev, pos);
if (pos->prev != 0)
pos->prev->next = newNode;
pos->prev = newNode;
if (theFront == pos)
theFront = newNode;
++theSize;
}
void CourseSequence::removeFront()
{
assert (theSize > 0);
Position oldFront = theFront;
theFront = theFront->next;
if (theFront != 0)
theFront->prev = 0;
else
theBack = 0;
delete oldFront;
--theSize;
}
void CourseSequence::removeBack()
{
assert (theSize > 0);
Position oldLast = theBack;
theBack = theBack->prev;
if (theBack != 0)
theBack->next = 0;
else
theFront = 0;
delete oldLast;
--theSize;
}
void CourseSequence::remove (CourseSequence::Position pos)
{
assert (pos != 0);
if (pos == theFront)
removeFront();
else if (pos == theBack)
removeBack();
else
{
pos->next->prev = pos->prev;
pos->prev->next = pos->next;
delete pos;
--theSize;
}
}
void CourseSequence::clear()
{
Position p = theFront;
while (p != 0)
{
Position nxt = p->next;
delete p;
p = nxt;
}
theFront = theBack = 0;
theSize = 0;
}
|
17ba4c55326ea18bf02b51d744461d20126fca94
|
66286815cc5aa5e2598056060cc3a14d6bf297ef
|
/src/app/gui/painting/gitems/AbstractRangeItem.cpp
|
5f06e32d31e3e03a28e5eccaff0575873e1d46a8
|
[] |
no_license
|
lukeulrich/alignshop-qt
|
07b022d8b15a75a7474e13f7c0ef3c0e43275577
|
030614f8fcc6c5bb4f6ed7f10987b5e5d11fe764
|
refs/heads/master
| 2020-07-28T03:06:04.528197
| 2016-11-10T21:19:41
| 2016-11-10T21:19:41
| 73,421,548
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,782
|
cpp
|
AbstractRangeItem.cpp
|
/****************************************************************************
**
** Copyright (C) 2011 Agile Genomics, LLC
** All rights reserved.
** Author: Luke Ulrich
**
****************************************************************************/
#include "AbstractRangeItem.h"
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// Public methods
/**
* @returns ClosedIntRange
*/
ClosedIntRange AbstractRangeItem::range() const
{
return range_;
}
/**
* @returns QPointF
*/
QPointF AbstractRangeItem::rangeCenter() const
{
QPointF point = this->boundingRect().center();
point.setX(leftPositionFromUnit(range_.begin_) + (rightPositionFromUnit(range_.end_) - leftPositionFromUnit(range_.begin_)) / 2.);
return point;
}
/**
* @param newStart [int]
* @returns bool
*/
bool AbstractRangeItem::setStart(int newStart)
{
if (newStart == range_.begin_)
return true;
int oldStart = range_.begin_;
range_.begin_ = newStart;
if (!setStartImpl(newStart))
{
range_.begin_ = oldStart;
return false;
}
emit startChanged(range_.begin_);
return true;
}
/**
* @param newStop [int]
* @returns bool
*/
bool AbstractRangeItem::setStop(int newStop)
{
if (newStop == range_.end_)
return true;
int oldStop = range_.end_;
range_.end_ = newStop;
if (!setStopImpl(newStop))
{
range_.end_ = oldStop;
return false;
}
emit stopChanged(range_.end_);
return true;
}
/**
* @returns int
*/
int AbstractRangeItem::start() const
{
return range_.begin_;
}
/**
* @returns int
*/
int AbstractRangeItem::stop() const
{
return range_.end_;
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// Protected constructors
/**
* The totalLength argument denotes the entire length of the item being modeled - it does not indicate the difference
* between the start and stop. The start and stop arguments denote the current range within length (1 based).
*
* @param start [int]
* @param stop [int]
* @param totalLength [int]
* @param parentItem [QGraphicsItem *]
*/
AbstractRangeItem::AbstractRangeItem(int start, int stop, int totalLength, QGraphicsItem *parentItem)
: AbstractLinearItem(totalLength, parentItem),
range_(start, stop)
{
}
/**
* The totalLength argument denotes the entire length of the item being modeled - it does not indicate the range
* length.
*
* @param range [const ClosedIntRange &]
* @param totalLength [int]
* @param parentItem [QGraphicsItem *]
*/
AbstractRangeItem::AbstractRangeItem(const ClosedIntRange &range, int totalLength, QGraphicsItem *parentItem)
: AbstractLinearItem(totalLength, parentItem),
range_(range)
{
}
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// Protected methods
/**
* Default implementation checks that newStart is between [1 .. current stop] inclusive.
*
* @param newStart [int]
* @returns bool
*/
bool AbstractRangeItem::setStartImpl(int newStart)
{
return newStart >= 1 && newStart <= range_.end_;
}
/**
* Default implementation checks that newStop is between [current start .. length] inclusive.
*
* @param newStop [int]
* @returns bool
*/
bool AbstractRangeItem::setStopImpl(int newStop)
{
return newStop >= range_.begin_ && newStop <= length();
}
|
8af6c6ca97aea5fd8588ee649681fb027670e032
|
c72d02e7fe0e7c0ee2ade87332917e70baf067ea
|
/실습/GameFramework/PP14.MInputHandler/Game.cpp
|
09b9689c8d49da28d4eca5988dce9ed8ff4dad91
|
[
"IJG",
"LicenseRef-scancode-warranty-disclaimer",
"Libpng",
"LicenseRef-scancode-unknown-license-reference",
"libtiff",
"BSD-3-Clause",
"Zlib"
] |
permissive
|
Kwon-Kiseok/GameFramework.20142304
|
e797d873b0a841a38aa7309fc7640f6816d7d132
|
f9685a9f6db9ad3d5772dd1f1a5fa03334206f85
|
refs/heads/master
| 2020-03-27T15:26:17.546401
| 2018-11-11T15:21:54
| 2018-11-11T15:21:54
| 146,717,913
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 2,676
|
cpp
|
Game.cpp
|
#include "Game.h"
bool Game::init(const char*title, int xpos, int ypos,
int width, int height, bool fullscreen)
{
//main.cpp에서 m_bRunning 으로 게임 반복문의 조건을 보고 있음
//Game.h 에서 m_bRunning 이 false 값으로 초기화 되어있기 때문에
//init이 될 때 게임이 돌아간다는 것을 보여주기 위해 true로 할당해줌
m_bRunning = true;
if (SDL_Init(SDL_INIT_EVERYTHING) >= 0)
{
m_pWindow = SDL_CreateWindow("HOSEO BAR",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_SHOWN);
if (m_pWindow != 0)
{
m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
}
SDL_SetRenderDrawColor(m_pRenderer, 255, 0, 0, 255);
//텍스쳐 등록
if (!TheTextureManager::Instance()->load("Assets/animate-alpha.png", "animate", m_pRenderer))
{
return false;
}
if (!TheTextureManager::Instance()->load("Assets/simhyang.png", "mob1", m_pRenderer))
{
return false;
}
if (!TheTextureManager::Instance()->load("Assets/red.png", "mob2", m_pRenderer))
{
return false;
}
if (!TheTextureManager::Instance()->load("Assets/Bullet.png", "bullet", m_pRenderer))
{
return false;
}
if (!TheTextureManager::Instance()->load("Assets/Wall.png", "wall", m_pRenderer))
{
return false;
}
if (!TheTextureManager::Instance()->load("Assets/BrokenWall.png", "bwall", m_pRenderer))
{
return false;
}
//벡터 m_gameObjects 의 제일 뒤쪽에 각 게임오브젝트들을 넣어줌
m_gameObjects.push_back(new Player(new LoaderParams(100, 100, 128, 82, "animate")));
m_gameObjects.push_back(new Enemy(new LoaderParams(300, 300, 128, 82, "animate")));
m_gameObjects.push_back(new Monster(new LoaderParams(0, 50, 64, 64, "mob1")));
m_gameObjects.push_back(new Monster(new LoaderParams(0, 100, 64, 64, "mob2")));
m_gameObjects.push_back(new Wall(new LoaderParams(500, 100, 64, 64, "wall")));
}
else
{
return 1;
}
return true;
}
void Game::render()
{
SDL_RenderClear(m_pRenderer);
//벡터STL에 넣어준 오브젝트들을 그려준다. push_back 해준 오브젝트들을 탐색하며 draw 함수 실행
for (std::vector<GameObject*>::size_type i = 0; i != m_gameObjects.size(); i++)
{
m_gameObjects[i]->draw();
}
SDL_RenderPresent(m_pRenderer);
}
void Game::update()
{
for (std::vector<GameObject*>::size_type i = 0; i != m_gameObjects.size(); i++)
{
m_gameObjects[i]->update();
}
}
void Game::clean()
{
std::cout << "cleaning game\n";
SDL_DestroyWindow(m_pWindow);
SDL_DestroyRenderer(m_pRenderer);
SDL_Quit();
TheInputHandler::Instance()->clean();
}
void Game::handleEvents()
{
TheInputHandler::Instance()->update();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.