text
stringlengths
54
60.6k
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkIPLFileNameList.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <stdlib.h> #include "itkIPLFileNameList.h" #include <assert.h> #include <string.h> #include <ctype.h> #include <list> #include <functional> namespace itk { struct IPLFileSortInfo_ascend_compare : public std::greater<IPLFileSortInfo *> { private: int qsort_IPLFileSortInfo_ascend_compar (IPLFileSortInfo *item1,IPLFileSortInfo *item2) { const int ImageNoDiff= item1->GetimageNumber() - item2->GetimageNumber(); if( ImageNoDiff < 0) { return -1; } if( ImageNoDiff > 0 ) { return 1; } const int echoNumDiff=item1->GetechoNumber() - item2->GetechoNumber(); if (echoNumDiff < 0) { return -1; } else if (echoNumDiff > 0 ) { return 1; } const float sliceGap = item1->GetSliceLocation() - item2->GetSliceLocation(); if (sliceGap < 0.0) { return -1; } if (sliceGap > 0.0) { return 1; } return item2->GetimageFileName() < item1->GetimageFileName(); } public: bool operator()(IPLFileSortInfo *item1,IPLFileSortInfo *item2) { return qsort_IPLFileSortInfo_ascend_compar(item1,item2) < 0; } }; struct IPLFileSortInfo_descend_compare : public std::greater<IPLFileSortInfo *> { private: int qsort_IPLFileSortInfo_descend_compar (IPLFileSortInfo *item1, IPLFileSortInfo *item2) { const int ImageNoDiff= item1->GetimageNumber() - item2->GetimageNumber(); if( ImageNoDiff < 0) { return 1; } if( ImageNoDiff > 0 ) { return -1; } const int echoNumDiff=item1->GetechoNumber() - item2->GetechoNumber(); if ( echoNumDiff < 0) { return 1; } if ( echoNumDiff > 0) { return -1; } const float sliceGap = item1->GetSliceLocation() - item2->GetSliceLocation(); if (sliceGap < 0.0) { return 1; } if (sliceGap > 0.0) { return -1; } return item1->GetimageFileName() >= item2->GetimageFileName(); } public: bool operator()(IPLFileSortInfo *item1,IPLFileSortInfo *item2) { return qsort_IPLFileSortInfo_descend_compar(item1,item2) < 0; } }; void IPLFileNameList:: sortImageListAscend () { IPLFileSortInfo_ascend_compare comp; // qsort (fnList->Info, fnList->numImageInfoStructs, sizeof (IPLFileSortInfo), // qsort_IPLFileSortInfo_ascend_compar); m_List.sort<IPLFileSortInfo_ascend_compare>(comp); return; } void IPLFileNameList:: sortImageListDescend () { // qsort (fnList->Info, fnList->numImageInfoStructs, sizeof (IPLFileSortInfo), // qsort_IPLFileSortInfo_descend_compar); IPLFileSortInfo_descend_compare comp; m_List.sort<IPLFileSortInfo_descend_compare>(comp); return; } } <commit_msg>FIX: Another try at satisfying VC syntax for binary funtion arguments<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkIPLFileNameList.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <stdlib.h> #include "itkIPLFileNameList.h" #include <assert.h> #include <string.h> #include <ctype.h> #include <list> #include <functional> namespace itk { struct IPLFileSortInfo_ascend_compare : public std::greater<IPLFileSortInfo *> { private: int qsort_IPLFileSortInfo_ascend_compar (IPLFileSortInfo *item1,IPLFileSortInfo *item2) { const int ImageNoDiff= item1->GetimageNumber() - item2->GetimageNumber(); if( ImageNoDiff < 0) { return -1; } if( ImageNoDiff > 0 ) { return 1; } const int echoNumDiff=item1->GetechoNumber() - item2->GetechoNumber(); if (echoNumDiff < 0) { return -1; } else if (echoNumDiff > 0 ) { return 1; } const float sliceGap = item1->GetSliceLocation() - item2->GetSliceLocation(); if (sliceGap < 0.0) { return -1; } if (sliceGap > 0.0) { return 1; } return item2->GetimageFileName() < item1->GetimageFileName(); } public: bool operator()(IPLFileSortInfo *item1,IPLFileSortInfo *item2) { return qsort_IPLFileSortInfo_ascend_compar(item1,item2) < 0; } }; struct IPLFileSortInfo_descend_compare : public std::greater<IPLFileSortInfo *> { private: int qsort_IPLFileSortInfo_descend_compar (IPLFileSortInfo *item1, IPLFileSortInfo *item2) { const int ImageNoDiff= item1->GetimageNumber() - item2->GetimageNumber(); if( ImageNoDiff < 0) { return 1; } if( ImageNoDiff > 0 ) { return -1; } const int echoNumDiff=item1->GetechoNumber() - item2->GetechoNumber(); if ( echoNumDiff < 0) { return 1; } if ( echoNumDiff > 0) { return -1; } const float sliceGap = item1->GetSliceLocation() - item2->GetSliceLocation(); if (sliceGap < 0.0) { return 1; } if (sliceGap > 0.0) { return -1; } return item1->GetimageFileName() >= item2->GetimageFileName(); } public: bool operator()(IPLFileSortInfo *item1,IPLFileSortInfo *item2) { return qsort_IPLFileSortInfo_descend_compar(item1,item2) < 0; } }; void IPLFileNameList:: sortImageListAscend () { #if 0 IPLFileSortInfo_ascend_compare comp; // qsort (fnList->Info, fnList->numImageInfoStructs, sizeof (IPLFileSortInfo), // qsort_IPLFileSortInfo_ascend_compar); m_List.sort<IPLFileSortInfo_ascend_compare>(comp); #else m_List.sort( IPLFileSortInfo_ascend_compare() ); #endif return; } void IPLFileNameList:: sortImageListDescend () { // qsort (fnList->Info, fnList->numImageInfoStructs, sizeof (IPLFileSortInfo), // qsort_IPLFileSortInfo_descend_compar); #if 0 IPLFileSortInfo_descend_compare comp; m_List.sort<IPLFileSortInfo_descend_compare>(comp); #else m_List.sort( IPLFileSortInfo_descend_compare() ); #endif return; } } <|endoftext|>
<commit_before>// Copyright 2013 Sean McKenna // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // object sub-classes (e.g. sphere, plane, triangular mesh OBJ) // import triangular mesh & BVH storage class #include "cyCodeBase/cyTriMesh.h" #include "cyCodeBase/cyBVH.h" // namespace using namespace scene; // Sphere definition class Sphere: public Object{ public: // constructor Sphere(){ center.Set(0, 0, 0); radius = 1.0; } // intsersect a ray against the unit sphere // ray must be transformed into model space, first bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){ // pre-compute values for quadratic solution Point pos = r.pos - center; float A = r.dir % r.dir; float B = 2.0 * pos % r.dir; float C = pos % pos - radius * radius; float det = (B * B) - (4 * A * C); // if the ray intersects, compute the z-buffer value if(det >= 0){ float z1 = (-B - sqrt(det)) / (2.0 * A); float z2 = (-B + sqrt(det)) / (2.0 * A); // determine if we have a back hit if(z1 * z2 < 0.0) h.front = false; // if hit is too close, assume it is a back-face hit else if(z1 <= getBias()) h.front = false; // check closest z-buffer value, if positive (ahead of our ray) if(z1 > getBias()){ h.z = z1; // compute surface intersection and normal h.p = r.pos + z1 * r.dir; h.n = h.p.GetNormalized(); // return true, ray is hit return true; // check the next ray, if necessary }else if(z2 > getBias()){ h.z = z2; // compute surface intersection and normal h.p = r.pos + z2 * r.dir; h.n = h.p.GetNormalized(); // return true, ray is hit return true; // otherwise, all z-buffer values are negative, return false }else return false; } // otherwise, return false (no ray hit) else return false; } // get sphere bounding box BoundingBox getBoundBox(){ return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0); } private: // sphere center and its radius Point center; float radius; }; // Plane definition (a "unit" plane) class Plane: public Object{ public: // intersect a ray against the "unit" plane bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){ // only compute for rays not parallel to the unit plane if(r.dir.z > getBias() || r.dir.z < getBias()){ // compute distance along ray direction to plane float t = -r.pos.z / r.dir.z; // only accept hits in front of ray (with some bias) if(t > getBias()){ // compute the hit point Point hit = r.pos + t * r.dir; // only allow a hit to occur if on the "unit" plane if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){ // detect back face hits if(r.pos.z < 0.0) h.front = false; // distance to hit h.z = t; // set hit point, normal, and return hit info h.p = hit; h.n = Point(0.0, 0.0, 1.0); return true; } } } // when no ray hits the "unit" plane return false; } // get plane bounding box BoundingBox getBoundBox(){ return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0); } }; // Triangular Mesh Object definition (from an OBJ file) class TriObj: public Object, private cyTriMesh{ public: // intersect a ray against the triangular mesh bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){ // check our BVH for triangular faces, update hit info bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID()); // return hit info from intersecting rays in the BVH faces return triang; } // get triangular mesh bounding box BoundingBox getBoundBox(){ return BoundingBox(GetBoundMin(), GetBoundMax()); } // when loading a triangular mesh, get its bounding box bool load(const char *file){ bvh.Clear(); if(!LoadFromFileObj(file)) return false; if(!HasNormals()) ComputeNormals(); ComputeBoundingBox(); bvh.SetMesh(this,4); return true; } private: // add BVH for each triangular mesh cyBVHTriMesh bvh; // intersect a ray with a single triangle (Moller-Trumbore algorithm) bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){ bool mt = false; if(mt){ // grab vertex points Point a = V(F(faceID).v[0]); Point b = V(F(faceID).v[1]); Point c = V(F(faceID).v[2]); // compute edge vectors Point e1 = b - a; Point e2 = c - a; // calculate first vector, P Point P = r.dir ^ e2; // calculate the determinant of the matrix equation float determ = e1 % P; // only continue for valid determinant ranges if(abs(determ) > getBias()){ // calculate second vector, T Point T = r.pos - a; // calculate a barycentric component (u) float u = T % P; // only allow valid barycentric values if(u > -getBias() && u < determ * (1.0 + getBias())){ // calculate a normal of the ray with an edge vector Point Q = T ^ e1; // calculate a barycentric component (v) float v = r.dir % Q; // only allow valid barycentric values if(v > -getBias() && v + u < determ * (1.0 + getBias())){ // update barycentric coordinates v /= determ; u /= determ; // compute the barycentric coordinates for interpolating values Point bc = Point(1.0 - u - v, u, v); // calculate the distance to hit the triangle float t = (e2 % Q) / determ; // only allow valid distances to hit if(t > getBias() && t < h.z){ // distance to hit h.z = t; // set hit point, normal h.p = GetPoint(faceID, bc); h.n = GetNormal(faceID, bc); // detect back face hits if(determ < 0.0) h.front = false; // return hit info return true; } } } } // when no ray hits the triangular face return false; // normal ray tracing }else{ // grab face vertices and compute face normal Point a = V(F(faceID).v[0]); Point b = V(F(faceID).v[1]); Point c = V(F(faceID).v[2]); Point n = (b - a) ^ (c - a); // ignore rays nearly parallel to surface if(r.dir % n > getBias() || r.dir % n < -getBias()){ // compute distance along ray direction to plane float t = -((r.pos - a) % n) / (r.dir % n); // only accept hits in front of ray (with some bias) & closer hits if(t > getBias() && t < h.z){ // compute hit point Point hit = r.pos + t * r.dir; // simplify problem into 2D by removing the greatest normal component Point2 a2; Point2 b2; Point2 c2; Point2 hit2; if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){ a2 = Point2(a.y, a.z); b2 = Point2(b.y, b.z); c2 = Point2(c.y, c.z); hit2 = Point2(hit.y, hit.z); }else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){ a2 = Point2(a.x, a.z); b2 = Point2(b.x, b.z); c2 = Point2(c.x, c.z); hit2 = Point2(hit.x, hit.z); }else{ a2 = Point2(a.x, a.y); b2 = Point2(b.x, b.y); c2 = Point2(c.x, c.y); hit2 = Point2(hit.x, hit.y); } // compute the area of the triangular face (in 2D) float area = (b2 - a2) ^ (c2 - a2); // compute smaller areas of the face, in 2D // aka, computation of the barycentric coordinates float alpha = ((b2 - a2) ^ (hit2 - a2)) / area; if(alpha > -getBias() && alpha < 1.0 + getBias()){ float beta = ((hit2 - a2) ^ (c2 - a2)) / area; if(beta > -getBias() && alpha + beta < 1.0 + getBias()){ // interpolate the normal based on barycentric coordinates Point bc = Point(1.0 - alpha - beta, beta, alpha); // distance to hit h.z = t; // set hit point, normal h.p = GetPoint(faceID, bc); h.n = GetNormal(faceID, bc); // return hit info return true; } } } } // when no ray hits the triangular face return false; } } // cast a ray into a BVH node, seeing which triangular faces may get hit bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){ // grab node's bounding box BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID)); // does ray hit the node bounding box? bool hit = b.intersectRay(r, h.z); // recurse through child nodes if we hit node if(hit){ // only recursively call function if not at a leaf node if(!bvh.IsLeafNode(nodeID)){ // keep traversing the BVH hierarchy for hits int c1 = bvh.GetFirstChildNode(nodeID); int c2 = bvh.GetSecondChildNode(nodeID); bool hit1 = traceBVHNode(r, h, face, c1); bool hit2 = traceBVHNode(r, h, face, c2); // if we get no hit if(!hit1 && !hit2) hit = false; // for leaf nodes, trace ray into each triangular face }else{ // get triangular faces of the hit BVH node const unsigned int* faces = bvh.GetNodeElements(nodeID); int size = bvh.GetNodeElementCount(nodeID); // trace the ray into each triangular face, tracking hits hit = false; for(int i = 0; i < size; i++){ bool hit1 = intersectTriangle(r, h, face, faces[i]); if(!hit && hit1) hit = true; } } } // return if we hit a face within this node return hit; } }; <commit_msg>after testing, know that moller-trumbore algorithm is faster for this scene<commit_after>// Copyright 2013 Sean McKenna // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // object sub-classes (e.g. sphere, plane, triangular mesh OBJ) // import triangular mesh & BVH storage class #include "cyCodeBase/cyTriMesh.h" #include "cyCodeBase/cyBVH.h" // namespace using namespace scene; // Sphere definition class Sphere: public Object{ public: // constructor Sphere(){ center.Set(0, 0, 0); radius = 1.0; } // intsersect a ray against the unit sphere // ray must be transformed into model space, first bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){ // pre-compute values for quadratic solution Point pos = r.pos - center; float A = r.dir % r.dir; float B = 2.0 * pos % r.dir; float C = pos % pos - radius * radius; float det = (B * B) - (4 * A * C); // if the ray intersects, compute the z-buffer value if(det >= 0){ float z1 = (-B - sqrt(det)) / (2.0 * A); float z2 = (-B + sqrt(det)) / (2.0 * A); // determine if we have a back hit if(z1 * z2 < 0.0) h.front = false; // if hit is too close, assume it is a back-face hit else if(z1 <= getBias()) h.front = false; // check closest z-buffer value, if positive (ahead of our ray) if(z1 > getBias()){ h.z = z1; // compute surface intersection and normal h.p = r.pos + z1 * r.dir; h.n = h.p.GetNormalized(); // return true, ray is hit return true; // check the next ray, if necessary }else if(z2 > getBias()){ h.z = z2; // compute surface intersection and normal h.p = r.pos + z2 * r.dir; h.n = h.p.GetNormalized(); // return true, ray is hit return true; // otherwise, all z-buffer values are negative, return false }else return false; } // otherwise, return false (no ray hit) else return false; } // get sphere bounding box BoundingBox getBoundBox(){ return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0); } private: // sphere center and its radius Point center; float radius; }; // Plane definition (a "unit" plane) class Plane: public Object{ public: // intersect a ray against the "unit" plane bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){ // only compute for rays not parallel to the unit plane if(r.dir.z > getBias() || r.dir.z < getBias()){ // compute distance along ray direction to plane float t = -r.pos.z / r.dir.z; // only accept hits in front of ray (with some bias) if(t > getBias()){ // compute the hit point Point hit = r.pos + t * r.dir; // only allow a hit to occur if on the "unit" plane if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){ // detect back face hits if(r.pos.z < 0.0) h.front = false; // distance to hit h.z = t; // set hit point, normal, and return hit info h.p = hit; h.n = Point(0.0, 0.0, 1.0); return true; } } } // when no ray hits the "unit" plane return false; } // get plane bounding box BoundingBox getBoundBox(){ return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0); } }; // Triangular Mesh Object definition (from an OBJ file) class TriObj: public Object, private cyTriMesh{ public: // intersect a ray against the triangular mesh bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){ // check our BVH for triangular faces, update hit info bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID()); // return hit info from intersecting rays in the BVH faces return triang; } // get triangular mesh bounding box BoundingBox getBoundBox(){ return BoundingBox(GetBoundMin(), GetBoundMax()); } // when loading a triangular mesh, get its bounding box bool load(const char *file){ bvh.Clear(); if(!LoadFromFileObj(file)) return false; if(!HasNormals()) ComputeNormals(); ComputeBoundingBox(); bvh.SetMesh(this,4); return true; } private: // add BVH for each triangular mesh cyBVHTriMesh bvh; // intersect a ray with a single triangle (Moller-Trumbore algorithm) bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){ bool mt = true; if(mt){ // grab vertex points Point a = V(F(faceID).v[0]); Point b = V(F(faceID).v[1]); Point c = V(F(faceID).v[2]); // compute edge vectors Point e1 = b - a; Point e2 = c - a; // calculate first vector, P Point P = r.dir ^ e2; // calculate the determinant of the matrix equation float determ = e1 % P; // only continue for valid determinant ranges if(abs(determ) > getBias()){ // calculate second vector, T Point T = r.pos - a; // calculate a barycentric component (u) float u = T % P; // only allow valid barycentric values if(u > -getBias() && u < determ * (1.0 + getBias())){ // calculate a normal of the ray with an edge vector Point Q = T ^ e1; // calculate a barycentric component (v) float v = r.dir % Q; // only allow valid barycentric values if(v > -getBias() && v + u < determ * (1.0 + getBias())){ // update barycentric coordinates v /= determ; u /= determ; // compute the barycentric coordinates for interpolating values Point bc = Point(1.0 - u - v, u, v); // calculate the distance to hit the triangle float t = (e2 % Q) / determ; // only allow valid distances to hit if(t > getBias() && t < h.z){ // distance to hit h.z = t; // set hit point, normal h.p = GetPoint(faceID, bc); h.n = GetNormal(faceID, bc); // detect back face hits if(determ < 0.0) h.front = false; // return hit info return true; } } } } // when no ray hits the triangular face return false; // normal ray tracing }else{ // grab face vertices and compute face normal Point a = V(F(faceID).v[0]); Point b = V(F(faceID).v[1]); Point c = V(F(faceID).v[2]); Point n = (b - a) ^ (c - a); // ignore rays nearly parallel to surface if(r.dir % n > getBias() || r.dir % n < -getBias()){ // compute distance along ray direction to plane float t = -((r.pos - a) % n) / (r.dir % n); // only accept hits in front of ray (with some bias) & closer hits if(t > getBias() && t < h.z){ // compute hit point Point hit = r.pos + t * r.dir; // simplify problem into 2D by removing the greatest normal component Point2 a2; Point2 b2; Point2 c2; Point2 hit2; if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){ a2 = Point2(a.y, a.z); b2 = Point2(b.y, b.z); c2 = Point2(c.y, c.z); hit2 = Point2(hit.y, hit.z); }else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){ a2 = Point2(a.x, a.z); b2 = Point2(b.x, b.z); c2 = Point2(c.x, c.z); hit2 = Point2(hit.x, hit.z); }else{ a2 = Point2(a.x, a.y); b2 = Point2(b.x, b.y); c2 = Point2(c.x, c.y); hit2 = Point2(hit.x, hit.y); } // compute the area of the triangular face (in 2D) float area = (b2 - a2) ^ (c2 - a2); // compute smaller areas of the face, in 2D // aka, computation of the barycentric coordinates float alpha = ((b2 - a2) ^ (hit2 - a2)) / area; if(alpha > -getBias() && alpha < 1.0 + getBias()){ float beta = ((hit2 - a2) ^ (c2 - a2)) / area; if(beta > -getBias() && alpha + beta < 1.0 + getBias()){ // interpolate the normal based on barycentric coordinates Point bc = Point(1.0 - alpha - beta, beta, alpha); // distance to hit h.z = t; // set hit point, normal h.p = GetPoint(faceID, bc); h.n = GetNormal(faceID, bc); // return hit info return true; } } } } // when no ray hits the triangular face return false; } } // cast a ray into a BVH node, seeing which triangular faces may get hit bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){ // grab node's bounding box BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID)); // does ray hit the node bounding box? bool hit = b.intersectRay(r, h.z); // recurse through child nodes if we hit node if(hit){ // only recursively call function if not at a leaf node if(!bvh.IsLeafNode(nodeID)){ // keep traversing the BVH hierarchy for hits int c1 = bvh.GetFirstChildNode(nodeID); int c2 = bvh.GetSecondChildNode(nodeID); bool hit1 = traceBVHNode(r, h, face, c1); bool hit2 = traceBVHNode(r, h, face, c2); // if we get no hit if(!hit1 && !hit2) hit = false; // for leaf nodes, trace ray into each triangular face }else{ // get triangular faces of the hit BVH node const unsigned int* faces = bvh.GetNodeElements(nodeID); int size = bvh.GetNodeElementCount(nodeID); // trace the ray into each triangular face, tracking hits hit = false; for(int i = 0; i < size; i++){ bool hit1 = intersectTriangle(r, h, face, faces[i]); if(!hit && hit1) hit = true; } } } // return if we hit a face within this node return hit; } }; <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "JoinMenu.h" /* system headers */ #include <string> #include <vector> /* common implementation headers */ #include "FontManager.h" /* local implementation headers */ #include "StartupInfo.h" #include "MainMenu.h" #include "HUDDialogStack.h" #include "MenuDefaultKey.h" #include "ServerStartMenu.h" #include "ServerMenu.h" #include "Protocol.h" #include "HUDuiControl.h" #include "HUDuiLabel.h" #include "HUDuiTypeIn.h" #include "HUDuiList.h" #include "TimeKeeper.h" /* from playing.h */ StartupInfo* getStartupInfo(); void joinGame(); JoinMenu* JoinMenu::activeMenu = NULL; JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL) { // cache font face ID int fontFace = MainMenu::getFontFace(); // add controls std::vector<HUDuiControl*>& list = getControls(); StartupInfo* info = getStartupInfo(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Join Game"); list.push_back(label); findServer = new HUDuiLabel; findServer->setFontFace(fontFace); findServer->setString("Find Server"); list.push_back(findServer); connectLabel = new HUDuiLabel; connectLabel->setFontFace(fontFace); connectLabel->setString("Connect"); list.push_back(connectLabel); callsign = new HUDuiTypeIn; callsign->setFontFace(fontFace); callsign->setLabel("Callsign:"); callsign->setMaxLength(CallSignLen - 1); callsign->setString(info->callsign); list.push_back(callsign); password = new HUDuiTypeIn; password->setObfuscation(true); password->setFontFace(fontFace); password->setLabel("Password:"); password->setMaxLength(CallSignLen - 1); password->setString(info->password); list.push_back(password); team = new HUDuiList; team->setFontFace(fontFace); team->setLabel("Team:"); team->setCallback(teamCallback, NULL); std::vector<std::string>& teams = team->getList(); // these do not need to be in enum order, but must match getTeam() & setTeam() teams.push_back(std::string(Team::getName(AutomaticTeam))); teams.push_back(std::string(Team::getName(RogueTeam))); teams.push_back(std::string(Team::getName(RedTeam))); teams.push_back(std::string(Team::getName(GreenTeam))); teams.push_back(std::string(Team::getName(BlueTeam))); teams.push_back(std::string(Team::getName(PurpleTeam))); teams.push_back(std::string(Team::getName(ObserverTeam))); team->update(); setTeam(info->team); list.push_back(team); server = new HUDuiTypeIn; server->setFontFace(fontFace); server->setLabel("Server:"); server->setMaxLength(64); server->setString(info->serverName); list.push_back(server); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port = new HUDuiTypeIn; port->setFontFace(fontFace); port->setLabel("Port:"); port->setMaxLength(5); port->setString(buffer); list.push_back(port); email = new HUDuiTypeIn; email->setFontFace(fontFace); email->setLabel("Email:"); email->setMaxLength(EmailLen - 1); email->setString(info->email); list.push_back(email); startServer = new HUDuiLabel; startServer->setFontFace(fontFace); startServer->setString("Start Server"); list.push_back(startServer); status = new HUDuiLabel; status->setFontFace(fontFace); status->setString(""); list.push_back(status); failedMessage = new HUDuiLabel; failedMessage->setFontFace(fontFace); failedMessage->setString(""); list.push_back(failedMessage); initNavigation(list, 1, list.size() - 3); } JoinMenu::~JoinMenu() { delete serverStartMenu; delete serverMenu; } HUDuiDefaultKey* JoinMenu::getDefaultKey() { return MenuDefaultKey::getInstance(); } void JoinMenu::show() { activeMenu = this; StartupInfo* info = getStartupInfo(); // set fields callsign->setString(info->callsign); password->setString(info->password); setTeam(info->team); server->setString(info->serverName); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port->setString(buffer); // clear status setStatus(""); setFailedMessage(""); } void JoinMenu::dismiss() { loadInfo(); activeMenu = NULL; } void JoinMenu::loadInfo() { // load startup info with current settings StartupInfo* info = getStartupInfo(); strcpy(info->callsign, callsign->getString().c_str()); strcpy(info->password, password->getString().c_str()); info->team = getTeam(); strcpy(info->serverName, server->getString().c_str()); info->serverPort = atoi(port->getString().c_str()); strcpy(info->email, email->getString().c_str()); } void JoinMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == startServer) { if (!serverStartMenu) serverStartMenu = new ServerStartMenu; HUDDialogStack::get()->push(serverStartMenu); } else if (focus == findServer) { if (!serverMenu) serverMenu = new ServerMenu; HUDDialogStack::get()->push(serverMenu); } else if (focus == connectLabel) { // load startup info loadInfo(); // make sure we've got what we need StartupInfo* info = getStartupInfo(); if (info->callsign[0] == '\0') { setStatus("You must enter a callsign."); return; } if (info->serverName[0] == '\0') { setStatus("You must enter a server."); return; } if (info->serverPort <= 0 || info->serverPort > 65535) { char buffer[60]; sprintf(buffer, "Port is invalid. Try %d.", ServerPort); setStatus(buffer); return; } // let user know we're trying setStatus("Trying..."); // schedule attempt to join game joinGame(); } } void JoinMenu::setFailedMessage(const char* msg) { failedMessage->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(MainMenu::getFontFace(), failedMessage->getFontSize(), failedMessage->getString()); failedMessage->setPosition(center - 0.5f * width, failedMessage->getY()); } TeamColor JoinMenu::getTeam() const { return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1); } void JoinMenu::setTeam(TeamColor teamcol) { team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1); } void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *) { status->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(status->getFontFace(), status->getFontSize(), status->getString()); status->setPosition(center - 0.5f * width, status->getY()); } void JoinMenu::teamCallback(HUDuiControl*, void*) { // do nothing (for now) } void JoinMenu::resize(int width, int height) { HUDDialog::resize(width, height); // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 36.0f; center = 0.5f * (float)width; FontManager &fm = FontManager::instance(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, ""); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width - 0.5f * titleWidth); y -= 0.6f * titleHeight; list[1]->setFontSize(fontSize); const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, ""); const int count = list.size(); for (int i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; if (i <= 2 || i == 7) y -= 0.5f * h; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>spacing<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "JoinMenu.h" /* system headers */ #include <string> #include <vector> /* common implementation headers */ #include "FontManager.h" /* local implementation headers */ #include "StartupInfo.h" #include "MainMenu.h" #include "HUDDialogStack.h" #include "MenuDefaultKey.h" #include "ServerStartMenu.h" #include "ServerMenu.h" #include "Protocol.h" #include "HUDuiControl.h" #include "HUDuiLabel.h" #include "HUDuiTypeIn.h" #include "HUDuiList.h" #include "TimeKeeper.h" /* from playing.h */ StartupInfo* getStartupInfo(); void joinGame(); JoinMenu* JoinMenu::activeMenu = NULL; JoinMenu::JoinMenu() : serverStartMenu(NULL), serverMenu(NULL) { // cache font face ID int fontFace = MainMenu::getFontFace(); // add controls std::vector<HUDuiControl*>& list = getControls(); StartupInfo* info = getStartupInfo(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Join Game"); list.push_back(label); findServer = new HUDuiLabel; findServer->setFontFace(fontFace); findServer->setString("Find Server"); list.push_back(findServer); connectLabel = new HUDuiLabel; connectLabel->setFontFace(fontFace); connectLabel->setString("Connect"); list.push_back(connectLabel); callsign = new HUDuiTypeIn; callsign->setFontFace(fontFace); callsign->setLabel("Callsign:"); callsign->setMaxLength(CallSignLen - 1); callsign->setString(info->callsign); list.push_back(callsign); password = new HUDuiTypeIn; password->setObfuscation(true); password->setFontFace(fontFace); password->setLabel("Password:"); password->setMaxLength(CallSignLen - 1); password->setString(info->password); list.push_back(password); team = new HUDuiList; team->setFontFace(fontFace); team->setLabel("Team:"); team->setCallback(teamCallback, NULL); std::vector<std::string>& teams = team->getList(); // these do not need to be in enum order, but must match getTeam() & setTeam() teams.push_back(std::string(Team::getName(AutomaticTeam))); teams.push_back(std::string(Team::getName(RogueTeam))); teams.push_back(std::string(Team::getName(RedTeam))); teams.push_back(std::string(Team::getName(GreenTeam))); teams.push_back(std::string(Team::getName(BlueTeam))); teams.push_back(std::string(Team::getName(PurpleTeam))); teams.push_back(std::string(Team::getName(ObserverTeam))); team->update(); setTeam(info->team); list.push_back(team); server = new HUDuiTypeIn; server->setFontFace(fontFace); server->setLabel("Server:"); server->setMaxLength(64); server->setString(info->serverName); list.push_back(server); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port = new HUDuiTypeIn; port->setFontFace(fontFace); port->setLabel("Port:"); port->setMaxLength(5); port->setString(buffer); list.push_back(port); email = new HUDuiTypeIn; email->setFontFace(fontFace); email->setLabel("Email:"); email->setMaxLength(EmailLen - 1); email->setString(info->email); list.push_back(email); startServer = new HUDuiLabel; startServer->setFontFace(fontFace); startServer->setString("Start Server"); list.push_back(startServer); status = new HUDuiLabel; status->setFontFace(fontFace); status->setString(""); list.push_back(status); failedMessage = new HUDuiLabel; failedMessage->setFontFace(fontFace); failedMessage->setString(""); list.push_back(failedMessage); initNavigation(list, 1, list.size() - 3); } JoinMenu::~JoinMenu() { delete serverStartMenu; delete serverMenu; } HUDuiDefaultKey* JoinMenu::getDefaultKey() { return MenuDefaultKey::getInstance(); } void JoinMenu::show() { activeMenu = this; StartupInfo* info = getStartupInfo(); // set fields callsign->setString(info->callsign); password->setString(info->password); setTeam(info->team); server->setString(info->serverName); char buffer[10]; sprintf(buffer, "%d", info->serverPort); port->setString(buffer); // clear status setStatus(""); setFailedMessage(""); } void JoinMenu::dismiss() { loadInfo(); activeMenu = NULL; } void JoinMenu::loadInfo() { // load startup info with current settings StartupInfo* info = getStartupInfo(); strcpy(info->callsign, callsign->getString().c_str()); strcpy(info->password, password->getString().c_str()); info->team = getTeam(); strcpy(info->serverName, server->getString().c_str()); info->serverPort = atoi(port->getString().c_str()); strcpy(info->email, email->getString().c_str()); } void JoinMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == startServer) { if (!serverStartMenu) serverStartMenu = new ServerStartMenu; HUDDialogStack::get()->push(serverStartMenu); } else if (focus == findServer) { if (!serverMenu) serverMenu = new ServerMenu; HUDDialogStack::get()->push(serverMenu); } else if (focus == connectLabel) { // load startup info loadInfo(); // make sure we've got what we need StartupInfo* info = getStartupInfo(); if (info->callsign[0] == '\0') { setStatus("You must enter a callsign."); return; } if (info->serverName[0] == '\0') { setStatus("You must enter a server."); return; } if (info->serverPort <= 0 || info->serverPort > 65535) { char buffer[60]; sprintf(buffer, "Port is invalid. Try %d.", ServerPort); setStatus(buffer); return; } // let user know we're trying setStatus("Trying..."); // schedule attempt to join game joinGame(); } } void JoinMenu::setFailedMessage(const char* msg) { failedMessage->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(MainMenu::getFontFace(), failedMessage->getFontSize(), failedMessage->getString()); failedMessage->setPosition(center - 0.5f * width, failedMessage->getY()); } TeamColor JoinMenu::getTeam() const { return team->getIndex() == 0 ? AutomaticTeam : TeamColor(team->getIndex() - 1); } void JoinMenu::setTeam(TeamColor teamcol) { team->setIndex(teamcol == AutomaticTeam ? 0 : int(teamcol) + 1); } void JoinMenu::setStatus(const char* msg, const std::vector<std::string> *) { status->setString(msg); FontManager &fm = FontManager::instance(); const float width = fm.getStrLength(status->getFontFace(), status->getFontSize(), status->getString()); status->setPosition(center - 0.5f * width, status->getY()); } void JoinMenu::teamCallback(HUDuiControl*, void*) { // do nothing (for now) } void JoinMenu::resize(int width, int height) { HUDDialog::resize(width, height); // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 36.0f; center = 0.5f * (float)width; FontManager &fm = FontManager::instance(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, ""); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width - 0.5f * titleWidth); y -= 0.6f * titleHeight; list[1]->setFontSize(fontSize); const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, ""); const int count = list.size(); for (int i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; if (i <= 2 || i == 8) y -= 0.5f * h; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before><commit_msg>574 - Sum It Up<commit_after><|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "MainMenu.h" /* common implementation headers */ #include "TextureManager.h" #include "FontManager.h" /* local implementation headers */ #include "FontSizer.h" #include "HelpMenu.h" #include "HUDDialogStack.h" #include "LocalPlayer.h" #include "JoinMenu.h" #include "OptionsMenu.h" #include "QuitMenu.h" #include "HUDuiImage.h" #include "HUDuiLabel.h" #include "playing.h" #include "LocalFontFace.h" LocalFontFace* MainMenu::fontFace = NULL; MainMenu::MainMenu() : HUDDialog(), joinMenu(NULL), optionsMenu(NULL), quitMenu(NULL) { if (!fontFace) fontFace = LocalFontFace::create("sansSerifFont"); } void MainMenu::createControls() { TextureManager &tm = TextureManager::instance(); HUDuiControl* label; HUDuiImage* textureLabel; // clear controls std::vector<HUDuiElement*>& listHUD = getElements(); for (unsigned int i = 0; i < listHUD.size(); i++) delete listHUD[i]; listHUD.clear(); getNav().clear(); // load title int title = tm.getTextureID("title"); // add controls textureLabel = new HUDuiImage; textureLabel->setTexture(title); addControl(textureLabel); label = createLabel("Up/Down arrows to move, Enter to select, Esc to dismiss"); addControl(label, false); join = createLabel("Join Game"); addControl(join); options = createLabel("Options"); addControl(options); help = createLabel("Help"); addControl(help); LocalPlayer* myTank = LocalPlayer::getMyTank(); if (!(myTank == NULL)) { leave = createLabel("Leave Game"); addControl(leave); } else { leave = NULL; } quit = createLabel("Quit"); addControl(quit); initNavigation(); } HUDuiControl* MainMenu::createLabel(const char* string) { HUDuiLabel* control = new HUDuiLabel; control->setFontFace(getFontFace()); control->setString(string); return control; } MainMenu::~MainMenu() { // destroy submenus delete joinMenu; delete optionsMenu; delete quitMenu; HelpMenu::done(); /* release font * note that it is NOT valid to call getFontFace if there is not an active * instance of MainMenu, even though it's static. */ LocalFontFace::release(fontFace); } const LocalFontFace* MainMenu::getFontFace() { return fontFace; } HUDuiDefaultKey* MainMenu::getDefaultKey() { return MenuDefaultKey::getInstance(); } void MainMenu::execute() { HUDuiControl* _focus = getNav().get(); if (_focus == join) { if (!joinMenu) joinMenu = new JoinMenu; HUDDialogStack::get()->push(joinMenu); } else if (_focus == options) { if (!optionsMenu) optionsMenu = new OptionsMenu; HUDDialogStack::get()->push(optionsMenu); } else if (_focus == help) { HUDDialogStack::get()->push(HelpMenu::getHelpMenu()); } else if (_focus == leave) { leaveGame(); // myTank should be NULL now, recreate menu createControls(); resize(width, height); } else if (_focus == quit) { if (!quitMenu) quitMenu = new QuitMenu; HUDDialogStack::get()->push(quitMenu); } } void MainMenu::resize(int _width, int _height) { HUDDialog::resize(_width, _height); FontSizer fs = FontSizer(_width, _height); std::vector<HUDuiElement*>& listHUD = getElements(); HUDuiLabel* hint = (HUDuiLabel*)listHUD[1]; FontManager &fm = FontManager::instance(); const LocalFontFace* fontFace = getFontFace(); // main menu title, use a big font fs.setMin(0, 5); const float titleSize = fs.getFontSize(fontFace->getFMFace(), "titleFontSize"); // main menu instructions fs.setMin(20, 20); const float tinyFontSize = fs.getFontSize(fontFace->getFMFace(), "hudFontSize"); // main menu items fs.setMin(10, 10); const float fontSize = fs.getFontSize(fontFace->getFMFace(), "headerFontSize"); // reposition title HUDuiImage* title = (HUDuiImage*)listHUD[0]; title->setSize((float)_width, titleSize); // scale appropriately to center properly TextureManager &tm = TextureManager::instance(); float texHeight = (float)tm.getInfo(title->getTexture()).y; float texWidth = (float)tm.getInfo(title->getTexture()).x; float titleWidth = (texWidth / texHeight) * titleSize; title->setSize(titleWidth, titleSize); float x = 0.5f * ((float)_width - titleWidth); float y = (float)_height - titleSize * 1.25f; title->setPosition(x, y); // reposition instructions hint->setFontSize(tinyFontSize); const float hintWidth = fm.getStringWidth(fontFace->getFMFace(), tinyFontSize, hint->getString().c_str()); y -= 1.25f * fm.getStringHeight(fontFace->getFMFace(), tinyFontSize); hint->setPosition(0.5f * ((float)_width - hintWidth), y); y -= 1.5f * fm.getStringHeight(fontFace->getFMFace(), fontSize); // reposition menu items ("Options" is centered, rest aligned to it) const float firstWidth = fm.getStringWidth(fontFace->getFMFace(), fontSize, ((HUDuiLabel*)listHUD[3])->getString().c_str()); x = 0.5f * ((float)_width - firstWidth); const int count = (const int)listHUD.size(); for (int i = 2; i < count; i++) { HUDuiLabel* label = (HUDuiLabel*)listHUD[i]; label->setFontSize(fontSize); label->setPosition(x, y); y -= 1.2f * fm.getStringHeight(fontFace->getFMFace(), fontSize); } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>no need to declare a variable that we already have hangin' around<commit_after>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "MainMenu.h" /* common implementation headers */ #include "TextureManager.h" #include "FontManager.h" /* local implementation headers */ #include "FontSizer.h" #include "HelpMenu.h" #include "HUDDialogStack.h" #include "LocalPlayer.h" #include "JoinMenu.h" #include "OptionsMenu.h" #include "QuitMenu.h" #include "HUDuiImage.h" #include "HUDuiLabel.h" #include "playing.h" #include "LocalFontFace.h" LocalFontFace* MainMenu::fontFace = NULL; MainMenu::MainMenu() : HUDDialog(), joinMenu(NULL), optionsMenu(NULL), quitMenu(NULL) { if (!fontFace) fontFace = LocalFontFace::create("sansSerifFont"); } void MainMenu::createControls() { TextureManager &tm = TextureManager::instance(); HUDuiControl* label; HUDuiImage* textureLabel; // clear controls std::vector<HUDuiElement*>& listHUD = getElements(); for (unsigned int i = 0; i < listHUD.size(); i++) delete listHUD[i]; listHUD.clear(); getNav().clear(); // load title int title = tm.getTextureID("title"); // add controls textureLabel = new HUDuiImage; textureLabel->setTexture(title); addControl(textureLabel); label = createLabel("Up/Down arrows to move, Enter to select, Esc to dismiss"); addControl(label, false); join = createLabel("Join Game"); addControl(join); options = createLabel("Options"); addControl(options); help = createLabel("Help"); addControl(help); LocalPlayer* myTank = LocalPlayer::getMyTank(); if (!(myTank == NULL)) { leave = createLabel("Leave Game"); addControl(leave); } else { leave = NULL; } quit = createLabel("Quit"); addControl(quit); initNavigation(); } HUDuiControl* MainMenu::createLabel(const char* string) { HUDuiLabel* control = new HUDuiLabel; control->setFontFace(getFontFace()); control->setString(string); return control; } MainMenu::~MainMenu() { // destroy submenus delete joinMenu; delete optionsMenu; delete quitMenu; HelpMenu::done(); /* release font * note that it is NOT valid to call getFontFace if there is not an active * instance of MainMenu, even though it's static. */ LocalFontFace::release(fontFace); } const LocalFontFace* MainMenu::getFontFace() { return fontFace; } HUDuiDefaultKey* MainMenu::getDefaultKey() { return MenuDefaultKey::getInstance(); } void MainMenu::execute() { HUDuiControl* _focus = getNav().get(); if (_focus == join) { if (!joinMenu) joinMenu = new JoinMenu; HUDDialogStack::get()->push(joinMenu); } else if (_focus == options) { if (!optionsMenu) optionsMenu = new OptionsMenu; HUDDialogStack::get()->push(optionsMenu); } else if (_focus == help) { HUDDialogStack::get()->push(HelpMenu::getHelpMenu()); } else if (_focus == leave) { leaveGame(); // myTank should be NULL now, recreate menu createControls(); resize(width, height); } else if (_focus == quit) { if (!quitMenu) quitMenu = new QuitMenu; HUDDialogStack::get()->push(quitMenu); } } void MainMenu::resize(int _width, int _height) { HUDDialog::resize(_width, _height); FontSizer fs = FontSizer(_width, _height); std::vector<HUDuiElement*>& listHUD = getElements(); HUDuiLabel* hint = (HUDuiLabel*)listHUD[1]; FontManager &fm = FontManager::instance(); // main menu title, use a big font fs.setMin(0, 5); const float titleSize = fs.getFontSize(fontFace->getFMFace(), "titleFontSize"); // main menu instructions fs.setMin(20, 20); const float tinyFontSize = fs.getFontSize(fontFace->getFMFace(), "hudFontSize"); // main menu items fs.setMin(10, 10); const float fontSize = fs.getFontSize(fontFace->getFMFace(), "headerFontSize"); // reposition title HUDuiImage* title = (HUDuiImage*)listHUD[0]; title->setSize((float)_width, titleSize); // scale appropriately to center properly TextureManager &tm = TextureManager::instance(); float texHeight = (float)tm.getInfo(title->getTexture()).y; float texWidth = (float)tm.getInfo(title->getTexture()).x; float titleWidth = (texWidth / texHeight) * titleSize; title->setSize(titleWidth, titleSize); float x = 0.5f * ((float)_width - titleWidth); float y = (float)_height - titleSize * 1.25f; title->setPosition(x, y); // reposition instructions hint->setFontSize(tinyFontSize); const float hintWidth = fm.getStringWidth(fontFace->getFMFace(), tinyFontSize, hint->getString().c_str()); y -= 1.25f * fm.getStringHeight(fontFace->getFMFace(), tinyFontSize); hint->setPosition(0.5f * ((float)_width - hintWidth), y); y -= 1.5f * fm.getStringHeight(fontFace->getFMFace(), fontSize); // reposition menu items ("Options" is centered, rest aligned to it) const float firstWidth = fm.getStringWidth(fontFace->getFMFace(), fontSize, ((HUDuiLabel*)listHUD[3])->getString().c_str()); x = 0.5f * ((float)_width - firstWidth); const int count = (const int)listHUD.size(); for (int i = 2; i < count; i++) { HUDuiLabel* label = (HUDuiLabel*)listHUD[i]; label->setFontSize(fontSize); label->setPosition(x, y); y -= 1.2f * fm.getStringHeight(fontFace->getFMFace(), fontSize); } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <cfloat> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <stdio.h> #include <string> const double PI = 3.1415926536; const int angle2step = 120; typedef struct angles { float a; float b; float r; } angles; typedef struct xyz { float x; float y; float z; } xyz; using namespace std; angles cal_angle(xyz coord); string f_dirsteps(xyz curr, xyz next); string num2str(int i); int main() { int num = 2 * PI / 0.05; float an = 0; ofstream out("out.txt"); xyz curr = {280, 0, -250}; xyz next = {280, 0, -280}; /* out << f_dirsteps(curr, next); curr = next; int i; int j; */ /* for (j = 0; j < 30; j += 1) { next = {200, -j, -314}; out << f_dirsteps(curr, next); curr = next; } */ int i; int j; /* for (i = 0; i < 100; i += 10) { for (j = 0; j < 80; j += 1) { next = {280 - i, -j, -280}; out << f_dirsteps(curr, next); curr = next; } next = {280 - i, -j, -250}; out << f_dirsteps(curr, next); curr = next; next = {280 - i - 10, 0, -250}; out << f_dirsteps(curr, next); curr = next; } next = {280, 0, -250}; out << f_dirsteps(curr, next); curr = next; for (j = 0; j < 80; j += 10) { for (i = 0; i < 100; i += 1) { next = {280 - i, -j, -280}; out << f_dirsteps(curr, next); curr = next; } next = {280 - i, -j, -250}; out << f_dirsteps(curr, next); curr = next; next = {280, -j - 10, -250}; out << f_dirsteps(curr, next); curr = next; } */ /* xyz next = {0, -200, -250}; xyz dot1 = {-200, 0, -250}; xyz dot2 = {190, -50, -250}; xyz dot3 = {190, -50, -282}; xyz dot4 = {160, -60, -250}; xyz dot5 = {160, -60, -282}; xyz dot6 = {170, -70, -250}; xyz dot7 = {170, -70, -285}; // out << f_dirsteps(curr, next); out << f_dirsteps(curr, next); out << f_dirsteps(next, dot1); /*out << f_dirsteps(next, dot2); out << f_dirsteps(dot2, dot3); out << f_dirsteps(dot3, dot2); out << f_dirsteps(dot2, dot4); out << f_dirsteps(dot4, dot5); out << f_dirsteps(dot5, dot4); out << f_dirsteps(dot4, dot6); out << f_dirsteps(dot6, dot7); out << f_dirsteps(dot7, dot6); out << f_dirsteps(dot6, curr); */ /* xyz next = {200, 0, -200}; out << f_dirsteps(curr, next); curr = next; next = {200, 0, -290}; out << f_dirsteps(curr, next); curr = next; */ for (int i = 0; i < PI * 20; i++) { next.x = 200 * cos(an); next.y = -200 * sin(an); next.z = -290; out << f_dirsteps(curr, next); an += 0.05; curr = next; next = {280, 0, -250}; out << f_dirsteps(curr, next); /* for (int j = 200; j > 0; j -= 3) { next.x = 100; next.y = -j; next.z = -296; out << f_dirsteps(curr, next); curr = next; } */ // next = {200, 0, -250}; // out << f_dirsteps(curr, next); /* // xyz dot1 = {100, 100, -260}; xyz dot2 = {200, 100, -260}; xyz dot3 = {200, 0, -260}; out << f_dirsteps(curr, next); out << f_dirsteps(next, dot2); // out << f_dirsteps(dot1, dot2); out << f_dirsteps(dot2, dot3); out << f_dirsteps(dot3, curr); */ out.close(); return 0; } angles cal_angle(xyz coord) { float p = 0.0; angles angle; p = sqrt(coord.x * coord.x + coord.y * coord.y + coord.z * coord.z); if (coord.x <= 0) angle.a = asin(-coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI; else angle.a = asin(coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI + 180; coord.y = coord.y + 80 * sin(angle.a); coord.x = coord.x + 80 * cos(angle.a); p = sqrt(coord.x * coord.x + coord.y * coord.y + coord.z * coord.z); if (coord.x <= 0) angle.a = asin(-coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI; else angle.a = asin(coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) * 180 / PI + 180; angle.b = (acos((45 / p) + (p / 500)) + asin(-coord.z / p)) * 180 / PI; angle.r = (acos((p * p - 22500) / (400 * p)) + acos(-coord.z / p)) * 180 / PI; return angle; } string f_dirsteps(xyz curr, xyz next) { string fpath = "$"; angles curr_angles = cal_angle(curr); angles next_angles = cal_angle(next); float angle_a = next_angles.a - curr_angles.a; float angle_b = next_angles.b - curr_angles.b; float angle_r = next_angles.r - curr_angles.r; if (angle_a > 0) fpath = fpath + "1" + num2str(round(angle_a * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_a * angle2step)) + "#"; if (angle_b > 0) fpath = fpath + "1" + num2str(round(angle_b * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_b * angle2step)) + "#"; if (angle_r > 0) fpath = fpath + "1" + num2str(round(angle_r * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_r * angle2step)) + "#"; fpath = fpath + "@"; return fpath; } string num2str(int i) { stringstream ss; ss << i; return ss.str(); }<commit_msg>to ensure both high speed and precision<commit_after>#include <cfloat> #include <cmath> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <stdio.h> #include <string> const double PI = 3.1415926535897932384626433832795; const float angle2step = 6875.4935; typedef struct angles { float a; float b; float r; } angles; typedef struct xyz { float x; float y; float z; } xyz; using namespace std; angles cal_angle(xyz coord); string f_dirsteps(xyz curr, xyz next); string num2str(int i); int main() { int num = 2 * PI / 0.05; float an = 0; ofstream out("out.txt"); xyz curr = {230, 0, -250}; // xyz next = {180, 0, -250}; // out << f_dirsteps(curr, next); // curr = next; /* int i; int j; */ /* for (j = 0; j < 30; j += 1) { next = {200, -j, -314}; out << f_dirsteps(curr, next); curr = next; } */ int i; int j; /* for (i = 0; i < 100; i += 10) { for (j = 0; j < 80; j += 1) { next = {280 - i, -j, -280}; out << f_dirsteps(curr, next); curr = next; } next = {280 - i, -j, -250}; out << f_dirsteps(curr, next); curr = next; next = {280 - i - 10, 0, -250}; out << f_dirsteps(curr, next); curr = next; } next = {280, 0, -250}; out << f_dirsteps(curr, next); curr = next; for (j = 0; j < 80; j += 10) { for (i = 0; i < 100; i += 1) { next = {280 - i, -j, -280}; out << f_dirsteps(curr, next); curr = next; } next = {280 - i, -j, -250}; out << f_dirsteps(curr, next); curr = next; next = {280, -j - 10, -250}; out << f_dirsteps(curr, next); curr = next; } */ /* xyz next = {0, -200, -250}; xyz dot1 = {-200, 0, -250}; xyz dot2 = {190, -50, -250}; xyz dot3 = {190, -50, -282}; xyz dot4 = {160, -60, -250}; xyz dot5 = {160, -60, -282}; xyz dot6 = {170, -70, -250}; xyz dot7 = {170, -70, -285}; // out << f_dirsteps(curr, next); out << f_dirsteps(curr, next); out << f_dirsteps(next, dot1); /*out << f_dirsteps(next, dot2); out << f_dirsteps(dot2, dot3); out << f_dirsteps(dot3, dot2); out << f_dirsteps(dot2, dot4); out << f_dirsteps(dot4, dot5); out << f_dirsteps(dot5, dot4); out << f_dirsteps(dot4, dot6); out << f_dirsteps(dot6, dot7); out << f_dirsteps(dot7, dot6); out << f_dirsteps(dot6, curr); */ /* xyz next = {200, 0, -200}; out << f_dirsteps(curr, next); curr = next; next = {200, 0, -290}; out << f_dirsteps(curr, next); curr = next; */ /*for (int i = 0; i < PI * 200; i++) { next.x = 220 + 60 * cos(an); next.y = -100 + 60 * sin(an); next.z = -272; // - next.x / 20 - next.y / 17; out << f_dirsteps(curr, next); an += 0.01; curr = next; }*/ xyz next = {230, -150, -250}; out << f_dirsteps(curr, next); curr = next; next = {230, -150, -280}; out << f_dirsteps(curr, next); curr = next; next = {230, -150, -250}; out << f_dirsteps(curr, next); curr = next; next = {280, 0, -250}; out << f_dirsteps(curr, next); /* for (int j = 200; j > 0; j -= 3) { next.x = 100; next.y = -j; next.z = -296; out << f_dirsteps(curr, next); curr = next; } */ // next = {200, 0, -250}; // out << f_dirsteps(curr, next); /* // xyz dot1 = {100, 100, -260}; xyz dot2 = {200, 100, -260}; xyz dot3 = {200, 0, -260}; out << f_dirsteps(curr, next); out << f_dirsteps(next, dot2); // out << f_dirsteps(dot1, dot2); out << f_dirsteps(dot2, dot3); out << f_dirsteps(dot3, curr); */ out.close(); return 0; } angles cal_angle(xyz coord) { float p = 0.0; angles angle; if (coord.x >= 0) angle.a = asin(coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)); else angle.a = asin(-coord.y / sqrt(coord.x * coord.x + coord.y * coord.y)) - PI; coord.y = coord.y - 80 * sin(angle.a); coord.x = coord.x - 80 * cos(angle.a); p = sqrt(coord.x * coord.x + coord.y * coord.y + coord.z * coord.z); angle.b = (acos((45 / p) + (p / 500)) + asin(-coord.z / p)); angle.r = (acos((p * p - 22500) / (400 * p)) + acos(-coord.z / p)); return angle; } string f_dirsteps(xyz curr, xyz next) { string fpath = "$"; angles curr_angles = cal_angle(curr); angles next_angles = cal_angle(next); float angle_a = next_angles.a - curr_angles.a; float angle_b = next_angles.b - curr_angles.b; float angle_r = next_angles.r - curr_angles.r; if (angle_a >= 0) fpath = fpath + "1" + num2str(round(angle_a * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_a * angle2step)) + "#"; if (angle_b >= 0) fpath = fpath + "1" + num2str(round(angle_b * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_b * angle2step)) + "#"; if (angle_r >= 0) fpath = fpath + "1" + num2str(round(angle_r * angle2step)) + "#"; else fpath = fpath + "0" + num2str(round(-angle_r * angle2step)) + "#"; fpath = fpath + "@"; return fpath; } string num2str(int i) { stringstream ss; ss << i; return ss.str(); } <|endoftext|>
<commit_before>#include "Database.h" Database::Database() : QObject() { QProcess p; #ifdef Q_WS_WIN p.start(QString("cmd.exe /c %1").arg("sqlite3 db.sqlite < sql.sql && sqlite3 db.sqlite")); #else p.start(QString("sh -c \"%1\"").arg("sqlite3 db.sqlite < sql.sql; sqlite3 db.sqlite")); #endif if (p.waitForStarted(500)) { p.write(".separator '|'\r\n"); p.write(".import events.csv Events\r\n"); p.waitForFinished(1000); qDebug() << p.readAllStandardOutput(); } else qDebug() << "Failed to import recorded events into SQLite database."; p.close(); this->db = QSqlDatabase::addDatabase("QSQLITE"); this->db.setDatabaseName("./db.sqlite"); if (!this->db.open()) { qDebug() << "Database connection could not be established: " << this->db.lastError().text(); exit(1); } filteredEvents = new QVector<Event*>(); } void Database::loadEvents(int start, int stop) { QSqlQuery query("SELECT time_, input_type, event_type, widget, details FROM Events WHERE time_ >= ? AND time_ <= ?"); query.addBindValue(start); query.addBindValue(stop); if (query.exec()) { filteredEvents->clear(); while (query.next()) { int time = query.value(0).toInt(); QString inputType = query.value(1).toString(); QString eventType = query.value(2).toString(); QString widget = query.value(3).toString(); QString details = query.value(4).toString(); Event *event = new Event(time, inputType, eventType, widget, details); filteredEvents->append(event); } emit eventsLoaded(filteredEvents); } else qDebug() << "Failed to execute query: " << query.lastError().text(); } int Database::getMinEventTime() { QSqlQuery query("SELECT MIN(time_) FROM Events;"); if (query.exec()) { if(query.next()) return query.value(0).toInt(); } else qDebug() << "Failed to execute query: " << query.lastError().text(); return 0; } int Database::getMaxEventTime() { QSqlQuery query("SELECT MAX(time_) FROM Events;"); if (query.exec()) { if(query.next()) return query.value(0).toInt(); } else qDebug() << "Failed to execute query: " << query.lastError().text(); return 0; } void Database::close() { if (this->db.isOpen()) this->db.close(); // this->db.removeDatabase(); } <commit_msg>Fixed the 'QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.' error.<commit_after>#include "Database.h" Database::Database() : QObject() { QProcess p; #ifdef Q_WS_WIN p.start(QString("cmd.exe /c %1").arg("sqlite3 db.sqlite < sql.sql && sqlite3 db.sqlite")); #else p.start(QString("sh -c \"%1\"").arg("sqlite3 db.sqlite < sql.sql; sqlite3 db.sqlite")); #endif if (p.waitForStarted(500)) { p.write(".separator '|'\r\n"); p.write(".import events.csv Events\r\n"); p.waitForFinished(1000); qDebug() << p.readAllStandardOutput(); } else qDebug() << "Failed to import recorded events into SQLite database."; p.close(); this->db = QSqlDatabase::addDatabase("QSQLITE"); this->db.setDatabaseName("./db.sqlite"); if (!this->db.open()) { qDebug() << "Database connection could not be established: " << this->db.lastError().text(); exit(1); } filteredEvents = new QVector<Event*>(); } void Database::loadEvents(int start, int stop) { QSqlQuery query("SELECT time_, input_type, event_type, widget, details FROM Events WHERE time_ >= ? AND time_ <= ?"); query.addBindValue(start); query.addBindValue(stop); if (query.exec()) { filteredEvents->clear(); while (query.next()) { int time = query.value(0).toInt(); QString inputType = query.value(1).toString(); QString eventType = query.value(2).toString(); QString widget = query.value(3).toString(); QString details = query.value(4).toString(); Event *event = new Event(time, inputType, eventType, widget, details); filteredEvents->append(event); } emit eventsLoaded(filteredEvents); } else qDebug() << "Failed to execute query: " << query.lastError().text(); } int Database::getMinEventTime() { QSqlQuery query("SELECT MIN(time_) FROM Events;"); if (query.exec()) { if(query.next()) return query.value(0).toInt(); } else qDebug() << "Failed to execute query: " << query.lastError().text(); return 0; } int Database::getMaxEventTime() { QSqlQuery query("SELECT MAX(time_) FROM Events;"); if (query.exec()) { if(query.next()) return query.value(0).toInt(); } else qDebug() << "Failed to execute query: " << query.lastError().text(); return 0; } void Database::close() { this->db = QSqlDatabase(); } <|endoftext|>
<commit_before>#include "../../include/MazeCard.h" #include <iostream> #include <stdio.h> using namespace std; MazeCard::MazeCard() { this->_type = "-"; } /** * Deserialization constructor * * @param props Properties expected vector of size 3 * type|treasure|path */ MazeCard::MazeCard(vector<string> props) { if (props.size() > 2) { this->_type = props[0][0]; this->_treasureId = atoi(props[1].c_str()); for (int i = 0; i < 4; i++) this->path[i] = (props[2][i] == '1'); } } /** * Constructor * @param type Type of the card */ MazeCard::MazeCard(string type) { this->initPath(); this->_type = type; this->setPath(type); } MazeCard::~MazeCard() { //dtor } /** * Creates new instance of MazeCard * * @param type Type of the card */ MazeCard MazeCard::create(string type) { return MazeCard(type); } /** * Controls if there's path * * @param dir Path direction */ bool MazeCard::canGo(MazeCard::CANGO dir) { return this->path[dir]; } /** * Turns card to right */ void MazeCard::turnRight() { bool newPath[4]; for (int i = 0; i < 3; i++) { newPath[i + 1] = this->path[i]; } newPath[0] = this->path[3]; for (int i = 0; i < 4; i++) this->path[i] = newPath[i]; } /** * Returns the type of a card */ string MazeCard::type() { return this->_type; } /** * Returns treasure Id, -1 if there's none */ int MazeCard::getTreasure() { return this->_treasureId; } /** * Sets treasure * * @param id Treasure Id */ void MazeCard::setTreasure(int id) { this->_treasureId = id; } /** * Checks whether there's a treasure on the card. */ bool MazeCard::isTreasure() { return this->_treasureId > - 1; } /** * Returns string representing current path */ string MazeCard::getStringPath() { string ret; for (int i; i < 4; i++) { ret += (this->path[i]) ? "1" : "0"; } return ret; } /** * Explicit initialization of the path array */ void MazeCard::initPath() { for(int i = 0; i < 4; i++) this->path[i] = false; } /** * Sets path from the card * * @param type Card type */ void MazeCard::setPath(string type) { if (type == "C") { this->path[LEFT] = true; this->path[UP] = true; } else if (type == "L") { this->path[LEFT] = true; this->path[RIGHT] = true; } else if (type == "F") { this->path[LEFT] = true; this->path[UP] = true; this->path[RIGHT] = true; } } /** * Serializes MazeCard */ string MazeCard::toString() { ostringstream serial; serial << this->_type << "/"; serial << this->_treasureId << "/"; serial << this->getStringPath() << ";"; return serial.str(); } /** * Deserializes MazeCard */ MazeCard MazeCard::fromString(string s) { auto props = split(s, '/'); return MazeCard(props); } <commit_msg>Fixed save method<commit_after>#include "../../include/MazeCard.h" #include <iostream> #include <stdio.h> using namespace std; MazeCard::MazeCard() { this->_type = "-"; } /** * Deserialization constructor * * @param props Properties expected vector of size 3 * type|treasure|path */ MazeCard::MazeCard(vector<string> props) { if (props.size() > 2) { this->_type = props[0][0]; this->_treasureId = atoi(props[1].c_str()); for (int i = 0; i < 4; i++) this->path[i] = (props[2][i] == '1'); } } /** * Constructor * @param type Type of the card */ MazeCard::MazeCard(string type) { this->initPath(); this->_type = type; this->setPath(type); } MazeCard::~MazeCard() { //dtor } /** * Creates new instance of MazeCard * * @param type Type of the card */ MazeCard MazeCard::create(string type) { return MazeCard(type); } /** * Controls if there's path * * @param dir Path direction */ bool MazeCard::canGo(MazeCard::CANGO dir) { return this->path[dir]; } /** * Turns card to right */ void MazeCard::turnRight() { bool newPath[4]; for (int i = 0; i < 3; i++) { newPath[i + 1] = this->path[i]; } newPath[0] = this->path[3]; for (int i = 0; i < 4; i++) this->path[i] = newPath[i]; } /** * Returns the type of a card */ string MazeCard::type() { return this->_type; } /** * Returns treasure Id, -1 if there's none */ int MazeCard::getTreasure() { return this->_treasureId; } /** * Sets treasure * * @param id Treasure Id */ void MazeCard::setTreasure(int id) { this->_treasureId = id; } /** * Checks whether there's a treasure on the card. */ bool MazeCard::isTreasure() { return this->_treasureId > - 1; } /** * Returns string representing current path */ string MazeCard::getStringPath() { string ret; for (int i = 0; i < 4; i++) { ret += (this->path[i]) ? "1" : "0"; } return ret; } /** * Explicit initialization of the path array */ void MazeCard::initPath() { for(int i = 0; i < 4; i++) this->path[i] = false; } /** * Sets path from the card * * @param type Card type */ void MazeCard::setPath(string type) { if (type == "C") { this->path[LEFT] = true; this->path[UP] = true; } else if (type == "L") { this->path[LEFT] = true; this->path[RIGHT] = true; } else if (type == "F") { this->path[LEFT] = true; this->path[UP] = true; this->path[RIGHT] = true; } } /** * Serializes MazeCard */ string MazeCard::toString() { ostringstream serial; serial << this->_type << "/"; serial << this->_treasureId << "/"; serial << this->getStringPath() << ";"; return serial.str(); } /** * Deserializes MazeCard */ MazeCard MazeCard::fromString(string s) { auto props = split(s, '/'); return MazeCard(props); } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2017 ScyllaDB */ #include <seastar/core/linux-aio.hh> #include <unistd.h> #include <sys/syscall.h> #include <atomic> #include <algorithm> namespace seastar { namespace internal { struct linux_aio_ring { uint32_t id; uint32_t nr; std::atomic<uint32_t> head; std::atomic<uint32_t> tail; uint32_t magic; uint32_t compat_features; uint32_t incompat_features; uint32_t header_length; }; static linux_aio_ring* to_ring(::aio_context_t io_context) { return reinterpret_cast<linux_aio_ring*>(uintptr_t(io_context)); } static bool usable(const linux_aio_ring* ring) { return ring->magic == 0xa10a10a1 && ring->incompat_features == 0; } int io_setup(int nr_events, ::aio_context_t* io_context) { return ::syscall(SYS_io_setup, nr_events, io_context); } int io_destroy(::aio_context_t io_context) { return ::syscall(SYS_io_destroy, io_context); } int io_submit(::aio_context_t io_context, long nr, ::iocb** iocbs) { return ::syscall(SYS_io_submit, io_context, nr, iocbs); } int io_cancel(::aio_context_t io_context, ::iocb* iocb, ::io_event* result) { return ::syscall(SYS_io_cancel, io_context, iocb, result); } int io_getevents(::aio_context_t io_context, long min_nr, long nr, ::io_event* events, const ::timespec* timeout, bool force_syscall) { auto ring = to_ring(io_context); if (usable(ring) && !force_syscall) { // Try to complete in userspace, if enough available events, // or if the timeout is zero // We're the only writer to ->head, so we can load with memory_order_relaxed (assuming // only a single thread calls io_getevents()). auto head = ring->head.load(std::memory_order_relaxed); // The kernel will write to the ring from an interrupt and then release with a write // to ring->tail, so we must memory_order_acquire here. auto tail = ring->tail.load(std::memory_order_acquire); // kernel writes from interrupts auto available = tail - head; if (tail < head) { available += ring->nr; } if (available >= uint32_t(min_nr) || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0)) { if (!available) { return 0; } auto ring_events = reinterpret_cast<const ::io_event*>(uintptr_t(io_context) + ring->header_length); auto now = std::min<uint32_t>(nr, available); auto start = ring_events + head; auto end = start + now; if (head + now > ring->nr) { end -= ring->nr; } if (end > start) { std::copy(start, end, events); } else { auto p = std::copy(start, ring_events + ring->nr, events); std::copy(ring_events, end, p); } head += now; if (head >= ring->nr) { head -= ring->nr; } // The kernel will read ring->head and update its view of how many entries // in the ring are available, so memory_order_release to make sure any ring // accesses are completed before the update to ring->head is visible. ring->head.store(head, std::memory_order_release); return now; } } return ::syscall(SYS_io_getevents, io_context, min_nr, nr, events, timeout); } } } <commit_msg>linux-aio: reduce conditional branching in io_getevents<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2017 ScyllaDB */ #include <seastar/core/linux-aio.hh> #include <unistd.h> #include <sys/syscall.h> #include <atomic> #include <algorithm> namespace seastar { namespace internal { struct linux_aio_ring { uint32_t id; uint32_t nr; std::atomic<uint32_t> head; std::atomic<uint32_t> tail; uint32_t magic; uint32_t compat_features; uint32_t incompat_features; uint32_t header_length; }; static linux_aio_ring* to_ring(::aio_context_t io_context) { return reinterpret_cast<linux_aio_ring*>(uintptr_t(io_context)); } static bool usable(const linux_aio_ring* ring) { return ring->magic == 0xa10a10a1 && ring->incompat_features == 0; } int io_setup(int nr_events, ::aio_context_t* io_context) { return ::syscall(SYS_io_setup, nr_events, io_context); } int io_destroy(::aio_context_t io_context) { return ::syscall(SYS_io_destroy, io_context); } int io_submit(::aio_context_t io_context, long nr, ::iocb** iocbs) { return ::syscall(SYS_io_submit, io_context, nr, iocbs); } int io_cancel(::aio_context_t io_context, ::iocb* iocb, ::io_event* result) { return ::syscall(SYS_io_cancel, io_context, iocb, result); } int io_getevents(::aio_context_t io_context, long min_nr, long nr, ::io_event* events, const ::timespec* timeout, bool force_syscall) { auto ring = to_ring(io_context); if (usable(ring) && !force_syscall) { // Try to complete in userspace, if enough available events, // or if the timeout is zero // We're the only writer to ->head, so we can load with memory_order_relaxed (assuming // only a single thread calls io_getevents()). auto head = ring->head.load(std::memory_order_relaxed); // The kernel will write to the ring from an interrupt and then release with a write // to ring->tail, so we must memory_order_acquire here. auto tail = ring->tail.load(std::memory_order_acquire); // kernel writes from interrupts auto available = tail - head; if (tail < head) { available += ring->nr; } if (available >= uint32_t(min_nr) || (timeout && timeout->tv_sec == 0 && timeout->tv_nsec == 0)) { if (!available) { return 0; } auto ring_events = reinterpret_cast<const ::io_event*>(uintptr_t(io_context) + ring->header_length); auto now = std::min<uint32_t>(nr, available); auto start = ring_events + head; head += now; if (head < ring->nr) { std::copy(start, start + now, events); } else { head -= ring->nr; auto p = std::copy(start, ring_events + ring->nr, events); std::copy(ring_events, ring_events + head, p); } // The kernel will read ring->head and update its view of how many entries // in the ring are available, so memory_order_release to make sure any ring // accesses are completed before the update to ring->head is visible. ring->head.store(head, std::memory_order_release); return now; } } return ::syscall(SYS_io_getevents, io_context, min_nr, nr, events, timeout); } } } <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; Expr lerp(Expr a, Expr b, Expr alpha) { return (1.0f - alpha)*a + alpha*b; } int main(int argc, char **argv) { if (argc < 2) { printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n" "(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n"); return 0; } UniformImage input(Float(32), 2); Uniform<float> r_sigma; int s_sigma = atoi(argv[1]); Var x, y, z, c; // Add a boundary condition Func clamped; clamped(x, y) = input(clamp(x, 0, input.width()), clamp(y, 0, input.height())); // Construct the bilateral grid RVar i(0, s_sigma), j(0, s_sigma); Expr val = clamped(x * s_sigma + i - s_sigma/2, y * s_sigma + j - s_sigma/2); val = clamp(val, 0.0f, 1.0f); Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f); Func grid; grid(x, y, zi, c) += select(c == 0, val, 1.0f); // Blur the grid using a five-tap filter Func blurx, blury, blurz; blurx(x, y, z) = grid(x-2, y, z) + grid(x-1, y, z)*4 + grid(x, y, z)*6 + grid(x+1, y, z)*4 + grid(x+1, y, z); blury(x, y, z) = blurx(x, y-2, z) + blurx(x, y-1, z)*4 + blurx(x, y, z)*6 + blurx(x, y+1, z)*4 + blurx(x, y+2, z); blurz(x, y, z) = blury(x, y, z-2) + blury(x, y, z-1)*4 + blury(x, y, z)*6 + blury(x, y, z+1)*4 + blury(x, y, z+2); // Take trilinear samples to compute the output val = clamp(clamped(x, y), 0.0f, 1.0f); Expr zv = val * (1.0f/r_sigma); zi = cast<int>(zv); Expr zf = zv - zi; Expr xf = cast<float>(x % s_sigma) / s_sigma; Expr yf = cast<float>(y % s_sigma) / s_sigma; Expr xi = x/s_sigma; Expr yi = y/s_sigma; Func interpolated; interpolated(x, y) = lerp(lerp(lerp(blurz(xi, yi, zi), blurz(xi+1, yi, zi), xf), lerp(blurz(xi, yi+1, zi), blurz(xi+1, yi+1, zi), xf), yf), lerp(lerp(blurz(xi, yi, zi+1), blurz(xi+1, yi, zi+1), xf), lerp(blurz(xi, yi+1, zi+1), blurz(xi+1, yi+1, zi+1), xf), yf), zf); // Normalize Func smoothed; smoothed(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1); #ifndef USE_GPU // Best schedule for CPU printf("Compiling for CPU\n"); grid.root().parallel(z); grid.update().transpose(y, c).transpose(x, c).transpose(i, c).transpose(j, c).parallel(y); blurx.root().parallel(z).vectorize(x, 4); blury.root().parallel(z).vectorize(x, 4); blurz.root().parallel(z).vectorize(x, 4); smoothed.root().parallel(y).vectorize(x, 4); #else printf("Compiling for GPU"); Var gridz = grid.arg(2); grid.transpose(y, gridz).transpose(x, gridz).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 16, 16); grid.update().transpose(y, c).transpose(x, c).transpose(i, c).transpose(j, c) .root().cudaTile(x, y, 16, 16); c = blurx.arg(3); blurx.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 8, 8); c = blury.arg(3); blury.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 8, 8); c = blurz.arg(3); blurz.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 8, 8); smoothed.root().cudaTile(x, y, s_sigma, s_sigma); #endif smoothed.compileToFile("bilateral_grid", {r_sigma, input}); // Compared to Sylvain Paris' implementation from his webpage (on // which this is based), for filter params s_sigma 0.1, on a 4 megapixel // input, on a four core x86 (2 socket core2 mac pro) // Filter s_sigma: 2 4 8 16 32 // Paris (ms): 5350 1345 472 245 184 // Us (ms): 383 142 77 62 65 // Speedup: 14 9.5 6.1 3.9 2.8 // Our schedule and inlining are roughly the same as his, so the // gain is all down to vectorizing and parallelizing. In general // for larger blurs our win shrinks to roughly the number of // cores, as the stages we don't vectorize as well dominate (we // don't vectorize them well because they do gathers and scatters, // which don't work well on x86). For smaller blurs, our win // grows, because the stages that we vectorize take up all the // time. return 0; } <commit_msg>Fix typo in bilateral_grid algorithm<commit_after>#include "Halide.h" using namespace Halide; Expr lerp(Expr a, Expr b, Expr alpha) { return (1.0f - alpha)*a + alpha*b; } int main(int argc, char **argv) { if (argc < 2) { printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n" "(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n"); return 0; } UniformImage input(Float(32), 2); Uniform<float> r_sigma; int s_sigma = atoi(argv[1]); Var x, y, z, c; // Add a boundary condition Func clamped; clamped(x, y) = input(clamp(x, 0, input.width()), clamp(y, 0, input.height())); // Construct the bilateral grid RVar i(0, s_sigma), j(0, s_sigma); Expr val = clamped(x * s_sigma + i - s_sigma/2, y * s_sigma + j - s_sigma/2); val = clamp(val, 0.0f, 1.0f); Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f); Func grid; grid(x, y, zi, c) += select(c == 0, val, 1.0f); // Blur the grid using a five-tap filter Func blurx, blury, blurz; blurx(x, y, z) = grid(x-2, y, z) + grid(x-1, y, z)*4 + grid(x, y, z)*6 + grid(x+1, y, z)*4 + grid(x+2, y, z); blury(x, y, z) = blurx(x, y-2, z) + blurx(x, y-1, z)*4 + blurx(x, y, z)*6 + blurx(x, y+1, z)*4 + blurx(x, y+2, z); blurz(x, y, z) = blury(x, y, z-2) + blury(x, y, z-1)*4 + blury(x, y, z)*6 + blury(x, y, z+1)*4 + blury(x, y, z+2); // Take trilinear samples to compute the output val = clamp(clamped(x, y), 0.0f, 1.0f); Expr zv = val * (1.0f/r_sigma); zi = cast<int>(zv); Expr zf = zv - zi; Expr xf = cast<float>(x % s_sigma) / s_sigma; Expr yf = cast<float>(y % s_sigma) / s_sigma; Expr xi = x/s_sigma; Expr yi = y/s_sigma; Func interpolated; interpolated(x, y) = lerp(lerp(lerp(blurz(xi, yi, zi), blurz(xi+1, yi, zi), xf), lerp(blurz(xi, yi+1, zi), blurz(xi+1, yi+1, zi), xf), yf), lerp(lerp(blurz(xi, yi, zi+1), blurz(xi+1, yi, zi+1), xf), lerp(blurz(xi, yi+1, zi+1), blurz(xi+1, yi+1, zi+1), xf), yf), zf); // Normalize Func smoothed; smoothed(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1); #ifndef USE_GPU // Best schedule for CPU printf("Compiling for CPU\n"); grid.root().parallel(z); grid.update().transpose(y, c).transpose(x, c).transpose(i, c).transpose(j, c).parallel(y); blurx.root().parallel(z).vectorize(x, 4); blury.root().parallel(z).vectorize(x, 4); blurz.root().parallel(z).vectorize(x, 4); smoothed.root().parallel(y).vectorize(x, 4); #else printf("Compiling for GPU"); Var gridz = grid.arg(2); grid.transpose(y, gridz).transpose(x, gridz).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 16, 16); grid.update().transpose(y, c).transpose(x, c).transpose(i, c).transpose(j, c) .root().cudaTile(x, y, 16, 16); c = blurx.arg(3); blurx.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 8, 8); c = blury.arg(3); blury.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 8, 8); c = blurz.arg(3); blurz.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c) .root().cudaTile(x, y, 8, 8); smoothed.root().cudaTile(x, y, s_sigma, s_sigma); #endif smoothed.compileToFile("bilateral_grid", {r_sigma, input}); // Compared to Sylvain Paris' implementation from his webpage (on // which this is based), for filter params s_sigma 0.1, on a 4 megapixel // input, on a four core x86 (2 socket core2 mac pro) // Filter s_sigma: 2 4 8 16 32 // Paris (ms): 5350 1345 472 245 184 // Us (ms): 383 142 77 62 65 // Speedup: 14 9.5 6.1 3.9 2.8 // Our schedule and inlining are roughly the same as his, so the // gain is all down to vectorizing and parallelizing. In general // for larger blurs our win shrinks to roughly the number of // cores, as the stages we don't vectorize as well dominate (we // don't vectorize them well because they do gathers and scatters, // which don't work well on x86). For smaller blurs, our win // grows, because the stages that we vectorize take up all the // time. return 0; } <|endoftext|>
<commit_before>/* -*- C++ -*- */ /** * @file dlvhex.cpp * @author Roman Schindlauer * @date Thu Apr 28 15:00:10 2005 * * @brief main(). * * */ #include <iostream> #include <sstream> #include <vector> #include "dlvhex/Atom.h" #include "dlvhex/Interpretation.h" #include "dlvhex/GraphProcessor.h" #include "dlvhex/globals.h" #include "dlvhex/helper.h" #include "dlvhex/errorHandling.h" unsigned parser_line; const char *parser_file; unsigned parser_errors = 0; const char* WhoAmI; /** * @brief Stores the rules of the program in a structure. */ Rules IDB; /** * @brief Stores the facts of the program in a structure. */ GAtomSet EDB; //std::vector<EXTATOM> externalAtoms; /** * @brief Print logo. */ void printLogo() { std::cout << "DLVHEX [build " << __DATE__ #ifdef __GNUC__ << " gcc " << __VERSION__ #endif << "]" << std::endl << std::endl; } /** * @brief Print usage help. */ void printUsage(std::ostream &out, bool full) { out << "usage: " << WhoAmI << " [-silent]" << " [-filter=foo,bar,...]" << " [filename [filename [...]]]" << std::endl << std::endl; if (full) { } return; } /** * @brief Print a fatal error message and terminate. */ void InternalError (const char *msg) { std::cerr << std::endl << "An internal error occurred (" << msg << ")." << std::endl << "Please contact <roman@kr.tuwien.ac.at>!" << std::endl; exit (99); } #include "dlvhex/PluginContainer.h" #include "dlvhex/DependencyGraph.h" extern "C" FILE* inputin; // Where LEX reads its input from extern int inputparse(); #include <sys/types.h> #include <sys/dir.h> #include <dirent.h> // // definition for getwd ie MAXPATHLEN etc // #include <sys/param.h> #include <stdio.h> #include <dlfcn.h> #include "dlvhex/ProgramBuilder.h" #include "dlvhex/GraphProcessor.h" int main (int argc, char *argv[]) { WhoAmI = argv[0]; // // Option handling // bool optionPipe = false; bool optionSilent = false; std::vector<std::string> optionFilter; std::vector<std::string> allFiles; for (int j = 1; j < argc; j++) { if (argv[j][0] == '-') { if (!strcmp(argv[j],"-fo")) global::optionNoPredicate = false; else if (!strcmp(argv[j], "-silent")) optionSilent = true; else if (!strncmp(argv[j], "-filter=", 8)) optionFilter = helper::stringExplode(std::string(argv[j] + 8), ","); else if (!strcmp(argv[j], "--")) // optionPipe = true; { std::cout << "Piping not working yet, sorry!" << std::endl; exit(-1); } else if (!strcmp(argv[j], "-h") || !strcmp(argv[j], "-help")) { printLogo(); printUsage(std::cout, false); exit(0); } else { // TODO: // for now: don't consider unknown options! printLogo(); printUsage(std::cout,true); exit(-1); } } else { // TODO: test for file existence! allFiles.push_back(argv[j]); } } if (!optionSilent) printLogo(); // // no file and no stdin? // if ((allFiles.size() == 0) && !optionPipe) { printUsage(std::cerr,false); exit(-1); } // // look for all shared libraries we find // int count, i; struct dirent **files; std::string filename; count = scandir(PLUGIN_DIR, &files, 0, alphasort); for (i = 1; i < count + 1; ++i) { filename = files[i - 1]->d_name; if (filename.substr(0,9) == "libdlvhex") { if (filename.substr(filename.size() - 3, 3) == ".so") { //cout << "Opening " << filename << "..." << std::endl; // TODO: test if we really have to add the slash to the path! filename = (std::string)PLUGIN_DIR + '/' + filename; PluginContainer::Instance()->importPlugin(filename); } } } /* std::string hoSwitch; if (global::optionNoPredicate) hoSwitch = "-dlw:higherorder "; else hoSwitch = ""; if (optionPipe) { parser_file=""; parser_line=1; inputin=stdin; inputparse(); } else { for (std::vector<std::string>::const_iterator f = allFiles.begin(); f != allFiles.end(); f++) { parser_file = f->c_str(); std::string execPreParser("dlt -silent -preparsing " + hoSwitch + *f); FILE *preparser; if ((preparser = popen(execPreParser.c_str(), "r")) == NULL) { std::cerr << "unable to call preparser: " << execPreParser << std::endl; exit(1); } parser_line = 0; inputin = preparser; try { inputparse (); } catch (generalError& e) { std::cerr << e.getErrorMsg() << std::endl; exit(1); } fclose (inputin); } } */ if (optionPipe) { parser_file = ""; parser_line = 1; inputin = stdin; inputparse(); } else { for (std::vector<std::string>::const_iterator f = allFiles.begin(); f != allFiles.end(); f++) { parser_file = f->c_str(); FILE* fp = fopen(parser_file, "r"); // // we start line numbering with 1 // parser_line = 1; inputin = fp; try { inputparse (); } catch (generalError& e) { std::cerr << e.getErrorMsg() << std::endl; exit(1); } } } if( parser_errors ) { std::cerr << "Aborting due to parser errors." << std::endl; exit(1); } // testing the parser: /* ProgramDLVBuilder dlvprogram(global::optionNoPredicate); for (Rules::const_iterator r = IDB.begin(); r != IDB.end(); r++) dlvprogram.buildRule(*r); std::cout << "parser test: " << std::endl; std::cout << "IDB: " << std::endl << dlvprogram.getString() << std::endl; std::cout << "EDB: " << std::endl; printGAtomSet(EDB, std::cout, 0); std::cout << std::endl; //exit(0); */ /* for (vector<EXTATOM>::const_iterator r = externalAtoms.begin(); r != externalAtoms.end(); r++) std::cout << (*r) << std::endl; */ GraphBuilder* sgb = new SimpleGraphBuilder; DependencyGraph dg(IDB, sgb); GraphProcessor gp(&dg); try { gp.run(EDB); } catch (generalError &e) { std::cerr << e.getErrorMsg() << std::endl; exit(1); } std::ostringstream finaloutput; GAtomSet* res; GAtomSet filtered; Interpretation iout; while ((res = gp.getNextModel()) != NULL) { iout.replaceBy(*res); if (optionFilter.size() > 0) { GAtomSet g; for (std::vector<std::string>::const_iterator f = optionFilter.begin(); f != optionFilter.end(); f++) { iout.matchPredicate(*f, g); filtered.insert(g.begin(), g.end()); } } else { filtered = (*iout.getAtomSet()); } printGAtomSet(filtered, finaloutput, 0); finaloutput << std::endl; } for (std::vector<std::string>::const_iterator l = global::Messages.begin(); l != global::Messages.end(); l++) std::cout << *l << std::endl; std::cout << finaloutput.str() << std::endl; // // escape quotes for shell command execution with echo! // /* helper::escapeQuotes(result); std::string execPostParser("echo \"" + result + "\" | dlt -silent -postparsing"); FILE *postparser; if ((postparser = popen(execPostParser.c_str(), "r")) == NULL) { std::cerr << "unable to call postparser" << std::endl; exit(1); } char buf[1000]; std::vector<std::string> resultlines; while (!feof(postparser)) { if (fgets(buf, 1000, postparser) != NULL) std::cout << buf; } */ } <commit_msg>started documentation index page<commit_after>/* -*- C++ -*- */ /** * @file dlvhex.cpp * @author Roman Schindlauer * @date Thu Apr 28 15:00:10 2005 * * @brief main(). * */ /** @mainpage dlvhex Documentation * * @section intro_sec Introduction * * TODO * * @section install_sec Installation * * TODO * * @section Writing Plugins for dlvhex * * see \ref plugininterface_page "The Plugin Interface" */ #include <iostream> #include <sstream> #include <vector> #include "dlvhex/Atom.h" #include "dlvhex/Interpretation.h" #include "dlvhex/GraphProcessor.h" #include "dlvhex/globals.h" #include "dlvhex/helper.h" #include "dlvhex/errorHandling.h" unsigned parser_line; const char *parser_file; unsigned parser_errors = 0; const char* WhoAmI; /** * @brief Stores the rules of the program in a structure. */ Rules IDB; /** * @brief Stores the facts of the program in a structure. */ GAtomSet EDB; //std::vector<EXTATOM> externalAtoms; /** * @brief Print logo. */ void printLogo() { std::cout << "DLVHEX [build " << __DATE__ #ifdef __GNUC__ << " gcc " << __VERSION__ #endif << "]" << std::endl << std::endl; } /** * @brief Print usage help. */ void printUsage(std::ostream &out, bool full) { out << "usage: " << WhoAmI << " [-silent]" << " [-filter=foo,bar,...]" << " [filename [filename [...]]]" << std::endl << std::endl; if (full) { } return; } /** * @brief Print a fatal error message and terminate. */ void InternalError (const char *msg) { std::cerr << std::endl << "An internal error occurred (" << msg << ")." << std::endl << "Please contact <roman@kr.tuwien.ac.at>!" << std::endl; exit (99); } #include "dlvhex/PluginContainer.h" #include "dlvhex/DependencyGraph.h" extern "C" FILE* inputin; // Where LEX reads its input from extern int inputparse(); #include <sys/types.h> #include <sys/dir.h> #include <dirent.h> // // definition for getwd ie MAXPATHLEN etc // #include <sys/param.h> #include <stdio.h> #include <dlfcn.h> #include "dlvhex/ProgramBuilder.h" #include "dlvhex/GraphProcessor.h" int main (int argc, char *argv[]) { WhoAmI = argv[0]; // // Option handling // bool optionPipe = false; bool optionSilent = false; std::vector<std::string> optionFilter; std::vector<std::string> allFiles; for (int j = 1; j < argc; j++) { if (argv[j][0] == '-') { if (!strcmp(argv[j],"-fo")) global::optionNoPredicate = false; else if (!strcmp(argv[j], "-silent")) optionSilent = true; else if (!strncmp(argv[j], "-filter=", 8)) optionFilter = helper::stringExplode(std::string(argv[j] + 8), ","); else if (!strcmp(argv[j], "--")) // optionPipe = true; { std::cout << "Piping not working yet, sorry!" << std::endl; exit(-1); } else if (!strcmp(argv[j], "-h") || !strcmp(argv[j], "-help")) { printLogo(); printUsage(std::cout, false); exit(0); } else { // TODO: // for now: don't consider unknown options! printLogo(); printUsage(std::cout,true); exit(-1); } } else { // TODO: test for file existence! allFiles.push_back(argv[j]); } } if (!optionSilent) printLogo(); // // no file and no stdin? // if ((allFiles.size() == 0) && !optionPipe) { printUsage(std::cerr,false); exit(-1); } // // look for all shared libraries we find // int count, i; struct dirent **files; std::string filename; count = scandir(PLUGIN_DIR, &files, 0, alphasort); for (i = 1; i < count + 1; ++i) { filename = files[i - 1]->d_name; if (filename.substr(0,9) == "libdlvhex") { if (filename.substr(filename.size() - 3, 3) == ".so") { //cout << "Opening " << filename << "..." << std::endl; // TODO: test if we really have to add the slash to the path! filename = (std::string)PLUGIN_DIR + '/' + filename; PluginContainer::Instance()->importPlugin(filename); } } } /* std::string hoSwitch; if (global::optionNoPredicate) hoSwitch = "-dlw:higherorder "; else hoSwitch = ""; if (optionPipe) { parser_file=""; parser_line=1; inputin=stdin; inputparse(); } else { for (std::vector<std::string>::const_iterator f = allFiles.begin(); f != allFiles.end(); f++) { parser_file = f->c_str(); std::string execPreParser("dlt -silent -preparsing " + hoSwitch + *f); FILE *preparser; if ((preparser = popen(execPreParser.c_str(), "r")) == NULL) { std::cerr << "unable to call preparser: " << execPreParser << std::endl; exit(1); } parser_line = 0; inputin = preparser; try { inputparse (); } catch (generalError& e) { std::cerr << e.getErrorMsg() << std::endl; exit(1); } fclose (inputin); } } */ if (optionPipe) { parser_file = ""; parser_line = 1; inputin = stdin; inputparse(); } else { for (std::vector<std::string>::const_iterator f = allFiles.begin(); f != allFiles.end(); f++) { parser_file = f->c_str(); FILE* fp = fopen(parser_file, "r"); // // we start line numbering with 1 // parser_line = 1; inputin = fp; try { inputparse (); } catch (generalError& e) { std::cerr << e.getErrorMsg() << std::endl; exit(1); } } } if( parser_errors ) { std::cerr << "Aborting due to parser errors." << std::endl; exit(1); } // testing the parser: /* ProgramDLVBuilder dlvprogram(global::optionNoPredicate); for (Rules::const_iterator r = IDB.begin(); r != IDB.end(); r++) dlvprogram.buildRule(*r); std::cout << "parser test: " << std::endl; std::cout << "IDB: " << std::endl << dlvprogram.getString() << std::endl; std::cout << "EDB: " << std::endl; printGAtomSet(EDB, std::cout, 0); std::cout << std::endl; //exit(0); */ /* for (vector<EXTATOM>::const_iterator r = externalAtoms.begin(); r != externalAtoms.end(); r++) std::cout << (*r) << std::endl; */ GraphBuilder* sgb = new SimpleGraphBuilder; DependencyGraph dg(IDB, sgb); GraphProcessor gp(&dg); try { gp.run(EDB); } catch (generalError &e) { std::cerr << e.getErrorMsg() << std::endl; exit(1); } std::ostringstream finaloutput; GAtomSet* res; GAtomSet filtered; Interpretation iout; while ((res = gp.getNextModel()) != NULL) { iout.replaceBy(*res); if (optionFilter.size() > 0) { GAtomSet g; for (std::vector<std::string>::const_iterator f = optionFilter.begin(); f != optionFilter.end(); f++) { iout.matchPredicate(*f, g); filtered.insert(g.begin(), g.end()); } } else { filtered = (*iout.getAtomSet()); } printGAtomSet(filtered, finaloutput, 0); finaloutput << std::endl; } for (std::vector<std::string>::const_iterator l = global::Messages.begin(); l != global::Messages.end(); l++) std::cout << *l << std::endl; std::cout << finaloutput.str() << std::endl; // // escape quotes for shell command execution with echo! // /* helper::escapeQuotes(result); std::string execPostParser("echo \"" + result + "\" | dlt -silent -postparsing"); FILE *postparser; if ((postparser = popen(execPostParser.c_str(), "r")) == NULL) { std::cerr << "unable to call postparser" << std::endl; exit(1); } char buf[1000]; std::vector<std::string> resultlines; while (!feof(postparser)) { if (fgets(buf, 1000, postparser) != NULL) std::cout << buf; } */ } <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_DEFAULT_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_DEFAULT_HH #include <memory> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/configtree.hh> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/expression.hh> #include <dune/pymor/functions.hh> #include <dune/pymor/functions/default.hh> #include "interfaces.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Default : public ProblemInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > { protected: typedef ProblemInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType; public: typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType; using typename BaseType::EntityType; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::RangeFieldType; using BaseType::dimRange; using typename BaseType::DiffusionFactorType; using typename BaseType::DiffusionTensorType; using typename BaseType::FunctionType; typedef typename DiffusionFactorType::NonparametricType NonparametricDiffusionFactorType; typedef typename DiffusionTensorType::NonparametricType NonparametricDiffusionTensorType; typedef typename FunctionType::NonparametricType NonparametricFunctionType; private: typedef Pymor::Function::NonparametricDefault< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > DiffusionFactorWrapperType; typedef Pymor::Function::NonparametricDefault < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > DiffusiontensorWrapperType; typedef Pymor::Function::NonparametricDefault< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionWrapperType; public: static std::string static_id() { return BaseType::static_id() + ".default"; } static Stuff::Common::ConfigTree default_config(const std::string sub_name = "") { Stuff::Common::ConfigTree config; // diffusion factor typedef Pymor::Function::Checkerboard< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > CheckerBoardFunctionType; config.add(CheckerBoardFunctionType::default_config(), "diffusion_factor"); config["diffusion_factor.parameter_name"] = "diffusion_factor"; config["diffusion_factor.name"] = "diffusion_factor"; config["diffusion_factor.type"] = CheckerBoardFunctionType::static_id(); // diffusion tensor typedef Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > ConstantFunctionType; config.add(ConstantFunctionType::default_config(), "diffusion_tensor"); config["diffusion_tensor.name"] = "diffusion_tensor"; config["diffusion_tensor.type"] = ConstantFunctionType::static_id(); // force typedef Stuff::Functions::Expression< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType; config["force.variable"] = "x"; config["force.expression"] = "1.0"; config["force.order"] = "0"; config["force.name"] = "force"; config["force.type"] = ExpressionFunctionType::static_id(); // dirichlet values config["dirichlet.variable"] = "x"; config["dirichlet.expression"] = "0.1*x[0]"; config["dirichlet.order"] = "1"; config["dirichlet.name"] = "dirichlet"; config["dirichlet.type"] = ExpressionFunctionType::static_id(); // neumann values config["neumann.variable"] = "x"; config["neumann.expression"] = "1.0"; config["neumann.order"] = "0"; config["neumann.name"] = "neumann"; config["neumann.type"] = ExpressionFunctionType::static_id(); if (sub_name.empty()) return config; else { Stuff::Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Stuff::Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { const Stuff::Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; return std::unique_ptr< ThisType >(new ThisType(create_scalar_function("diffusion_factor", cfg), create_matrix_function("diffusion_tensor", cfg), create_vector_function("force", cfg), create_vector_function("dirichlet", cfg), create_vector_function("neumann", cfg))); } // ... create(...) Default(const std::shared_ptr< const NonparametricDiffusionFactorType >& diff_fac, const std::shared_ptr< const NonparametricDiffusionTensorType >& diff_ten, const std::shared_ptr< const NonparametricFunctionType >& forc, const std::shared_ptr< const NonparametricFunctionType >& dir, const std::shared_ptr< const NonparametricFunctionType >& neum) : diffusion_factor_(std::make_shared< DiffusionFactorWrapperType >(diff_fac)) , diffusion_tensor_(std::make_shared< DiffusiontensorWrapperType >(diff_ten)) , force_(std::make_shared< FunctionWrapperType >(forc)) , dirichlet_(std::make_shared< FunctionWrapperType >(dir)) , neumann_(std::make_shared< FunctionWrapperType >(neum)) {} Default(const std::shared_ptr< const DiffusionFactorType >& diff_fac, const std::shared_ptr< const DiffusionTensorType >& diff_ten, const std::shared_ptr< const FunctionType >& forc, const std::shared_ptr< const FunctionType >& dir, const std::shared_ptr< const FunctionType >& neum) : diffusion_factor_(diff_fac) , diffusion_tensor_(diff_ten) , force_(forc) , dirichlet_(dir) , neumann_(neum) { this->inherit_parameter_type(diffusion_factor_->parameter_type(), "diffusion_factor"); this->inherit_parameter_type(diffusion_tensor_->parameter_type(), "diffusion_tensor"); this->inherit_parameter_type(force_->parameter_type(), "force"); this->inherit_parameter_type(dirichlet_->parameter_type(), "dirichlet"); this->inherit_parameter_type(neumann_->parameter_type(), "neumann"); } Default(const ThisType& other) = delete; ThisType& operator=(const ThisType& other) = delete; virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".default"; } virtual const DiffusionFactorType& diffusion_factor() const DS_OVERRIDE { return *diffusion_factor_; } virtual const DiffusionTensorType& diffusion_tensor() const DS_OVERRIDE { return *diffusion_tensor_; } virtual const FunctionType& force() const DS_OVERRIDE { return *force_; } virtual const FunctionType& dirichlet() const DS_OVERRIDE { return *dirichlet_; } virtual const FunctionType& neumann() const DS_OVERRIDE { return *neumann_; } protected: static std::shared_ptr< Pymor::AffinelyDecomposableFunctionInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > > create_scalar_function(const std::string& id, const Stuff::Common::ConfigTree& config) { typedef Stuff::Functions::Expression< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > ExpressionFunctionType; typedef Pymor::AffinelyDecomposableFunctions< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > FunctionsProvider; const Stuff::Common::ConfigTree cfg = config.sub(id); const std::string type = cfg.get("type", ExpressionFunctionType::static_id()); return FunctionsProvider::create(type, cfg); } // ... create_scalar_function(...) static std::shared_ptr< Pymor::AffinelyDecomposableFunctionInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > > create_vector_function(const std::string& id, const Stuff::Common::ConfigTree& config) { typedef Stuff::Functions::Expression< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > ExpressionFunctionType; typedef Pymor::AffinelyDecomposableFunctions< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > FunctionsProvider; const Stuff::Common::ConfigTree cfg = config.sub(id); const std::string type = cfg.get("type", ExpressionFunctionType::static_id()); return FunctionsProvider::create(type, cfg); } // ... create_vector_function(...) static std::shared_ptr< Pymor::AffinelyDecomposableFunctionInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > > create_matrix_function(const std::string& id, const Stuff::Common::ConfigTree& config) { typedef Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > ConstantFunctionType; typedef Pymor::AffinelyDecomposableFunctions< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > FunctionsProvider; const Stuff::Common::ConfigTree cfg = config.sub(id); const std::string type = cfg.get("type", ConstantFunctionType::static_id()); return FunctionsProvider::create(type, cfg); } // ... create_matrix_function(...) std::shared_ptr< const DiffusionFactorType > diffusion_factor_; std::shared_ptr< const DiffusionTensorType > diffusion_tensor_; std::shared_ptr< const FunctionType > force_; std::shared_ptr< const FunctionType > dirichlet_; std::shared_ptr< const FunctionType > neumann_; }; // class Default } // namespace Problems } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_DEFAULT_HH <commit_msg>[linearelliptic.problems.default] whitespace<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_DEFAULT_HH #define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_DEFAULT_HH #include <memory> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/configtree.hh> #include <dune/stuff/functions/constant.hh> #include <dune/stuff/functions/expression.hh> #include <dune/pymor/functions.hh> #include <dune/pymor/functions/default.hh> #include "interfaces.hh" namespace Dune { namespace HDD { namespace LinearElliptic { namespace Problems { template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class Default : public ProblemInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > { protected: typedef ProblemInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType; public: typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType; using typename BaseType::EntityType; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::RangeFieldType; using BaseType::dimRange; using typename BaseType::DiffusionFactorType; using typename BaseType::DiffusionTensorType; using typename BaseType::FunctionType; typedef typename DiffusionFactorType::NonparametricType NonparametricDiffusionFactorType; typedef typename DiffusionTensorType::NonparametricType NonparametricDiffusionTensorType; typedef typename FunctionType::NonparametricType NonparametricFunctionType; private: typedef Pymor::Function::NonparametricDefault< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > DiffusionFactorWrapperType; typedef Pymor::Function::NonparametricDefault < EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > DiffusiontensorWrapperType; typedef Pymor::Function::NonparametricDefault< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionWrapperType; public: static std::string static_id() { return BaseType::static_id() + ".default"; } static Stuff::Common::ConfigTree default_config(const std::string sub_name = "") { Stuff::Common::ConfigTree config; // diffusion factor typedef Pymor::Function::Checkerboard< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1 > CheckerBoardFunctionType; config.add(CheckerBoardFunctionType::default_config(), "diffusion_factor"); config["diffusion_factor.parameter_name"] = "diffusion_factor"; config["diffusion_factor.name"] = "diffusion_factor"; config["diffusion_factor.type"] = CheckerBoardFunctionType::static_id(); // diffusion tensor typedef Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > ConstantFunctionType; config.add(ConstantFunctionType::default_config(), "diffusion_tensor"); config["diffusion_tensor.name"] = "diffusion_tensor"; config["diffusion_tensor.type"] = ConstantFunctionType::static_id(); // force typedef Stuff::Functions::Expression< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ExpressionFunctionType; config["force.variable"] = "x"; config["force.expression"] = "1.0"; config["force.order"] = "0"; config["force.name"] = "force"; config["force.type"] = ExpressionFunctionType::static_id(); // dirichlet values config["dirichlet.variable"] = "x"; config["dirichlet.expression"] = "0.1*x[0]"; config["dirichlet.order"] = "1"; config["dirichlet.name"] = "dirichlet"; config["dirichlet.type"] = ExpressionFunctionType::static_id(); // neumann values config["neumann.variable"] = "x"; config["neumann.expression"] = "1.0"; config["neumann.order"] = "0"; config["neumann.name"] = "neumann"; config["neumann.type"] = ExpressionFunctionType::static_id(); if (sub_name.empty()) return config; else { Stuff::Common::ConfigTree tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Stuff::Common::ConfigTree config = default_config(), const std::string sub_name = static_id()) { const Stuff::Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; return std::unique_ptr< ThisType >(new ThisType(create_scalar_function("diffusion_factor", cfg), create_matrix_function("diffusion_tensor", cfg), create_vector_function("force", cfg), create_vector_function("dirichlet", cfg), create_vector_function("neumann", cfg))); } // ... create(...) Default(const std::shared_ptr< const NonparametricDiffusionFactorType >& diff_fac, const std::shared_ptr< const NonparametricDiffusionTensorType >& diff_ten, const std::shared_ptr< const NonparametricFunctionType >& forc, const std::shared_ptr< const NonparametricFunctionType >& dir, const std::shared_ptr< const NonparametricFunctionType >& neum) : diffusion_factor_(std::make_shared< DiffusionFactorWrapperType >(diff_fac)) , diffusion_tensor_(std::make_shared< DiffusiontensorWrapperType >(diff_ten)) , force_(std::make_shared< FunctionWrapperType >(forc)) , dirichlet_(std::make_shared< FunctionWrapperType >(dir)) , neumann_(std::make_shared< FunctionWrapperType >(neum)) {} Default(const std::shared_ptr< const DiffusionFactorType >& diff_fac, const std::shared_ptr< const DiffusionTensorType >& diff_ten, const std::shared_ptr< const FunctionType >& forc, const std::shared_ptr< const FunctionType >& dir, const std::shared_ptr< const FunctionType >& neum) : diffusion_factor_(diff_fac) , diffusion_tensor_(diff_ten) , force_(forc) , dirichlet_(dir) , neumann_(neum) { this->inherit_parameter_type(diffusion_factor_->parameter_type(), "diffusion_factor"); this->inherit_parameter_type(diffusion_tensor_->parameter_type(), "diffusion_tensor"); this->inherit_parameter_type(force_->parameter_type(), "force"); this->inherit_parameter_type(dirichlet_->parameter_type(), "dirichlet"); this->inherit_parameter_type(neumann_->parameter_type(), "neumann"); } Default(const ThisType& other) = delete; ThisType& operator=(const ThisType& other) = delete; virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".default"; } virtual const DiffusionFactorType& diffusion_factor() const DS_OVERRIDE { return *diffusion_factor_; } virtual const DiffusionTensorType& diffusion_tensor() const DS_OVERRIDE { return *diffusion_tensor_; } virtual const FunctionType& force() const DS_OVERRIDE { return *force_; } virtual const FunctionType& dirichlet() const DS_OVERRIDE { return *dirichlet_; } virtual const FunctionType& neumann() const DS_OVERRIDE { return *neumann_; } protected: static std::shared_ptr< Pymor::AffinelyDecomposableFunctionInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > > create_scalar_function(const std::string& id, const Stuff::Common::ConfigTree& config) { typedef Stuff::Functions::Expression< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > ExpressionFunctionType; typedef Pymor::AffinelyDecomposableFunctions< EntityType, DomainFieldType, dimDomain, RangeFieldType, 1, 1 > FunctionsProvider; const Stuff::Common::ConfigTree cfg = config.sub(id); const std::string type = cfg.get("type", ExpressionFunctionType::static_id()); return FunctionsProvider::create(type, cfg); } // ... create_scalar_function(...) static std::shared_ptr< Pymor::AffinelyDecomposableFunctionInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > > create_vector_function(const std::string& id, const Stuff::Common::ConfigTree& config) { typedef Stuff::Functions::Expression< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > ExpressionFunctionType; typedef Pymor::AffinelyDecomposableFunctions< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange, 1 > FunctionsProvider; const Stuff::Common::ConfigTree cfg = config.sub(id); const std::string type = cfg.get("type", ExpressionFunctionType::static_id()); return FunctionsProvider::create(type, cfg); } // ... create_vector_function(...) static std::shared_ptr< Pymor::AffinelyDecomposableFunctionInterface< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > > create_matrix_function(const std::string& id, const Stuff::Common::ConfigTree& config) { typedef Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > ConstantFunctionType; typedef Pymor::AffinelyDecomposableFunctions< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimDomain, dimDomain > FunctionsProvider; const Stuff::Common::ConfigTree cfg = config.sub(id); const std::string type = cfg.get("type", ConstantFunctionType::static_id()); return FunctionsProvider::create(type, cfg); } // ... create_matrix_function(...) std::shared_ptr< const DiffusionFactorType > diffusion_factor_; std::shared_ptr< const DiffusionTensorType > diffusion_tensor_; std::shared_ptr< const FunctionType > force_; std::shared_ptr< const FunctionType > dirichlet_; std::shared_ptr< const FunctionType > neumann_; }; // class Default } // namespace Problems } // namespace LinearElliptic } // namespace HDD } // namespace Dune #endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_DEFAULT_HH <|endoftext|>
<commit_before>// // Example to connect multiple vehicles and make them take off and land in parallel. //./multiple_drones udp://:14540 udp://:14541 // // Author: Julian Oes <julian@oes.ch> // Author: Shayaan Haider (via Slack) #include <dronecode_sdk/dronecode_sdk.h> #include <dronecode_sdk/plugins/action/action.h> #include <dronecode_sdk/plugins/telemetry/telemetry.h> #include <chrono> #include <cstdint> #include <iostream> #include <thread> using namespace dronecode_sdk; using namespace std::this_thread; using namespace std::chrono; static void takeoff_land(System &system); #define ERROR_CONSOLE_TEXT "\033[31m" // Turn text on console red #define TELEMETRY_CONSOLE_TEXT "\033[34m" // Turn text on console blue #define NORMAL_CONSOLE_TEXT "\033[0m" // Restore normal console colour int main(int argc, char **argv) // The input looks like this ./multiple_drones udp://:14540 udp://:14541 { if (argc == 1) { std::cout << ERROR_CONSOLE_TEXT << "Please specify connection" << NORMAL_CONSOLE_TEXT << std::endl; ; return 1; } DronecodeSDK dc; // the loop below adds the number of ports the sdk monitors. for (int i = 1; i < argc; ++i) { ConnectionResult connection_result = dc.add_any_connection(argv[i]); if (connection_result != ConnectionResult::SUCCESS) { std::cout << ERROR_CONSOLE_TEXT << "Connection error: " << connection_result_str(connection_result) << NORMAL_CONSOLE_TEXT << std::endl; ; return 1; } } bool discovered_system = false; std::cout << "Waiting to discover system..." << std::endl; dc.register_on_discover([&discovered_system](uint64_t uuid) { std::cout << "Discovered system with UUID: " << uuid << std::endl; discovered_system = true; }); // We usually receive heartbeats at 1Hz, therefore we should find a system after around 2 // seconds. sleep_for(seconds(2)); if (!discovered_system) { std::cout << ERROR_CONSOLE_TEXT << "No system found, exiting." << NORMAL_CONSOLE_TEXT << std::endl; return 1; } std::vector<std::thread> threads; for (auto uuid : dc.system_uuids()) { System &system = dc.system(uuid); std::thread t(&takeoff_land, std::ref(system)); threads.push_back(std::move(t)); } for (auto &t : threads) { t.join(); } return 0; } void takeoff_land(System &system) { auto telemetry = std::make_shared<Telemetry>(system); auto action = std::make_shared<Action>(system); // We want to listen to the altitude of the drone at 1 Hz. const Telemetry::Result set_rate_result = telemetry->set_rate_position(1.0); if (set_rate_result != Telemetry::Result::SUCCESS) { std::cout << ERROR_CONSOLE_TEXT << "Setting rate failed:" << Telemetry::result_str(set_rate_result) << NORMAL_CONSOLE_TEXT << std::endl; return; } // Set up callback to monitor altitude while the vehicle is in flight telemetry->position_async([](Telemetry::Position position) { std::cout << TELEMETRY_CONSOLE_TEXT // set to blue << "Altitude: " << position.relative_altitude_m << " m" << NORMAL_CONSOLE_TEXT // set to default color again << std::endl; }); // Check if vehicle is ready to arm while (telemetry->health_all_ok() != true) { std::cout << "Vehicle is getting ready to arm" << std::endl; sleep_for(seconds(1)); } // Arm vehicle std::cout << "Arming..." << std::endl; const Action::Result arm_result = action->arm(); if (arm_result != Action::Result::SUCCESS) { std::cout << ERROR_CONSOLE_TEXT << "Arming failed:" << Action::result_str(arm_result) << NORMAL_CONSOLE_TEXT << std::endl; // return ; } // Take off std::cout << "Taking off..." << std::endl; const Action::Result takeoff_result = action->takeoff(); if (takeoff_result != Action::Result::SUCCESS) { std::cout << ERROR_CONSOLE_TEXT << "Takeoff failed:" << Action::result_str(takeoff_result) << NORMAL_CONSOLE_TEXT << std::endl; // return ; } // Let it hover for a bit before landing again. sleep_for(seconds(20)); std::cout << "Landing..." << std::endl; const Action::Result land_result = action->land(); if (land_result != Action::Result::SUCCESS) { std::cout << ERROR_CONSOLE_TEXT << "Land failed:" << Action::result_str(land_result) << NORMAL_CONSOLE_TEXT << std::endl; // return ; } // Check if vehicle is still in air while (telemetry->in_air()) { std::cout << "Vehicle is landing..." << std::endl; sleep_for(seconds(1)); } std::cout << "Landed!" << std::endl; // We are relying on auto-disarming but let's keep watching the telemetry for a bit longer. sleep_for(seconds(5)); std::cout << "Finished..." << std::endl; return; } <commit_msg>multiple_drones: some minor improvements<commit_after>// // Example to connect multiple vehicles and make them take off and land in parallel. //./multiple_drones udp://:14540 udp://:14541 // // Author: Julian Oes <julian@oes.ch> // Author: Shayaan Haider (via Slack) #include <dronecode_sdk/dronecode_sdk.h> #include <dronecode_sdk/plugins/action/action.h> #include <dronecode_sdk/plugins/telemetry/telemetry.h> #include <cstdint> #include <iostream> #include <thread> #include <chrono> using namespace dronecode_sdk; using namespace std::this_thread; using namespace std::chrono; static void takeoff_and_land(System &system); #define ERROR_CONSOLE_TEXT "\033[31m" // Turn text on console red #define TELEMETRY_CONSOLE_TEXT "\033[34m" // Turn text on console blue #define NORMAL_CONSOLE_TEXT "\033[0m" // Restore normal console colour int main(int argc, char *argv[]) { if (argc == 1) { std::cerr << ERROR_CONSOLE_TEXT << "Please specify connection" << NORMAL_CONSOLE_TEXT << std::endl; return 1; } DronecodeSDK dc; // the loop below adds the number of ports the sdk monitors. for (int i = 1; i < argc; ++i) { ConnectionResult connection_result = dc.add_any_connection(argv[i]); if (connection_result != ConnectionResult::SUCCESS) { std::cerr << ERROR_CONSOLE_TEXT << "Connection error: " << connection_result_str(connection_result) << NORMAL_CONSOLE_TEXT << std::endl; return 1; } } bool discovered_system = false; std::cout << "Waiting to discover system..." << std::endl; dc.register_on_discover([&discovered_system](uint64_t uuid) { std::cout << "Discovered system with UUID: " << uuid << std::endl; discovered_system = true; }); // We usually receive heartbeats at 1Hz, therefore we should find a system after around 2 // seconds. sleep_for(seconds(2)); if (!discovered_system) { std::cerr << ERROR_CONSOLE_TEXT << "No system found, exiting." << NORMAL_CONSOLE_TEXT << std::endl; return 1; } std::vector<std::thread> threads; for (auto uuid : dc.system_uuids()) { System &system = dc.system(uuid); std::thread t(&takeoff_and_land, std::ref(system)); threads.push_back(std::move(t)); } for (auto &t : threads) { t.join(); } return 0; } void takeoff_and_land(System &system) { auto telemetry = std::make_shared<Telemetry>(system); auto action = std::make_shared<Action>(system); // We want to listen to the altitude of the drone at 1 Hz. const Telemetry::Result set_rate_result = telemetry->set_rate_position(1.0); if (set_rate_result != Telemetry::Result::SUCCESS) { std::cerr << ERROR_CONSOLE_TEXT << "Setting rate failed:" << Telemetry::result_str(set_rate_result) << NORMAL_CONSOLE_TEXT << std::endl; return; } // Set up callback to monitor altitude while the vehicle is in flight telemetry->position_async([](Telemetry::Position position) { std::cout << TELEMETRY_CONSOLE_TEXT // set to blue << "Altitude: " << position.relative_altitude_m << " m" << NORMAL_CONSOLE_TEXT // set to default color again << std::endl; }); // Check if vehicle is ready to arm while (telemetry->health_all_ok() != true) { std::cout << "Vehicle is getting ready to arm" << std::endl; sleep_for(seconds(1)); } // Arm vehicle std::cout << "Arming..." << std::endl; const Action::Result arm_result = action->arm(); if (arm_result != Action::Result::SUCCESS) { std::cerr << ERROR_CONSOLE_TEXT << "Arming failed:" << Action::result_str(arm_result) << NORMAL_CONSOLE_TEXT << std::endl; } // Take off std::cout << "Taking off..." << std::endl; const Action::Result takeoff_result = action->takeoff(); if (takeoff_result != Action::Result::SUCCESS) { std::cerr << ERROR_CONSOLE_TEXT << "Takeoff failed:" << Action::result_str(takeoff_result) << NORMAL_CONSOLE_TEXT << std::endl; } // Let it hover for a bit before landing again. sleep_for(seconds(20)); std::cout << "Landing..." << std::endl; const Action::Result land_result = action->land(); if (land_result != Action::Result::SUCCESS) { std::cerr << ERROR_CONSOLE_TEXT << "Land failed:" << Action::result_str(land_result) << NORMAL_CONSOLE_TEXT << std::endl; } // Check if vehicle is still in air while (telemetry->in_air()) { std::cout << "Vehicle is landing..." << std::endl; sleep_for(seconds(1)); } std::cout << "Landed!" << std::endl; // We are relying on auto-disarming but let's keep watching the telemetry for a bit longer. sleep_for(seconds(5)); std::cout << "Finished..." << std::endl; return; } <|endoftext|>
<commit_before>#include <QByteArray> #include <QFile> #include <QDateTime> #include <QSslKey> #include <QSslCertificate> #include "keybuilder.h" #include "certificaterequestbuilder.h" #include "certificaterequest.h" #include "certificatebuilder.h" #include "certificate.h" QT_USE_NAMESPACE_CERTIFICATE int main(int argc, char **argv) { // // Create the CA key // QSslKey cakey = KeyBuilder::generate( QSsl::Rsa, KeyBuilder::StrengthNormal ); QFile k("ca.key"); k.open(QIODevice::WriteOnly); k.write(cakey.toPem()); k.close(); CertificateRequestBuilder careqbuilder; careqbuilder.setVersion(1); careqbuilder.setKey(cakey); careqbuilder.addNameEntry(Certificate::EntryCountryName, "GB"); careqbuilder.addNameEntry(Certificate::EntryOrganizationName, "Westpoint CA Key"); careqbuilder.addNameEntry(Certificate::EntryOrganizationName, "West"); careqbuilder.addNameEntry(Certificate::EntryCommonName, "www.example.com"); // Sign the request CertificateRequest careq = careqbuilder.signedRequest(cakey); // // Export the results // QFile f("ca.req"); f.open(QIODevice::WriteOnly); f.write(careq.toPem()); f.close(); // // Now make a certificate // CertificateBuilder builder; builder.setRequest(careq); builder.setVersion(3); builder.setSerial("helloworld"); builder.setActivationTime(QDateTime::currentDateTimeUtc()); builder.setExpirationTime(QDateTime::currentDateTimeUtc()); builder.setBasicConstraints(true); builder.setKeyUsage(CertificateBuilder::UsageCrlSign|CertificateBuilder::UsageKeyCertSign); builder.addSubjectKeyIdentifier(); QSslCertificate cacert = builder.signedCertificate(cakey); QFile c("ca.crt"); c.open(QIODevice::WriteOnly); c.write(cacert.toPem()); c.close(); // // Create the leaf // builder.setSerial("XXXXXXXXXXXXXXXXXXXXXXX"); QSslCertificate leafcert = builder.signedCertificate(cacert, cakey); QFile d("leaf.crt"); d.open(QIODevice::WriteOnly); d.write(leafcert.toPem()); d.close(); } <commit_msg>Make the create_signed_certificate example much better.<commit_after>#include <QByteArray> #include <QFile> #include <QDateTime> #include <QSslKey> #include <QSslCertificate> #include "keybuilder.h" #include "certificaterequestbuilder.h" #include "certificaterequest.h" #include "certificatebuilder.h" #include "certificate.h" QT_USE_NAMESPACE_CERTIFICATE void save_key(const QString &filename, const QSslKey &key) { QFile k(filename); k.open(QIODevice::WriteOnly); k.write(key.toPem()); k.close(); } void save_request(const QString &filename, CertificateRequest &req) { QFile k(filename); k.open(QIODevice::WriteOnly); k.write(req.toPem()); k.close(); } void save_certificate(const QString &filename, const QSslCertificate &crt) { QFile k(filename); k.open(QIODevice::WriteOnly); k.write(crt.toPem()); k.close(); } int main(int argc, char **argv) { // // Create the CA key // QSslKey cakey = KeyBuilder::generate(QSsl::Rsa, KeyBuilder::StrengthNormal); save_key("ca.key", cakey); CertificateRequestBuilder careqbuilder; careqbuilder.setVersion(1); careqbuilder.setKey(cakey); careqbuilder.addNameEntry(Certificate::EntryCountryName, "GB"); careqbuilder.addNameEntry(Certificate::EntryOrganizationName, "Westpoint CA Key"); careqbuilder.addNameEntry(Certificate::EntryOrganizationName, "Westpoint"); // Sign the request CertificateRequest careq = careqbuilder.signedRequest(cakey); save_request("ca.req", careq); // // Now make a certificate // CertificateBuilder cabuilder; cabuilder.setRequest(careq); cabuilder.setVersion(3); cabuilder.setSerial("helloworld"); cabuilder.setActivationTime(QDateTime::currentDateTimeUtc()); cabuilder.setExpirationTime(QDateTime::currentDateTimeUtc()); cabuilder.setBasicConstraints(true); cabuilder.setKeyUsage(CertificateBuilder::UsageCrlSign|CertificateBuilder::UsageKeyCertSign); cabuilder.addSubjectKeyIdentifier(); QSslCertificate cacert = cabuilder.signedCertificate(cakey); save_certificate("ca.crt", cacert); // // Create the leaf // QSslKey leafkey = KeyBuilder::generate(QSsl::Rsa, KeyBuilder::StrengthNormal); save_key("leaf.key", leafkey); CertificateRequestBuilder leafreqbuilder; leafreqbuilder.setVersion(1); leafreqbuilder.setKey(leafkey); leafreqbuilder.addNameEntry(Certificate::EntryCountryName, "GB"); leafreqbuilder.addNameEntry(Certificate::EntryOrganizationName, "Westpoint"); leafreqbuilder.addNameEntry(Certificate::EntryCommonName, "www.example.com"); CertificateRequest leafreq = leafreqbuilder.signedRequest(leafkey); save_request("leaf.req", careq); CertificateBuilder leafbuilder; leafbuilder.setRequest(leafreq); leafbuilder.setVersion(3); leafbuilder.setSerial("iamaleaf"); leafbuilder.setActivationTime(QDateTime::currentDateTimeUtc()); leafbuilder.setExpirationTime(QDateTime::currentDateTimeUtc()); leafbuilder.setBasicConstraints(false); leafbuilder.addKeyPurpose(CertificateBuilder::PurposeWebServer); leafbuilder.setKeyUsage(CertificateBuilder::UsageKeyAgreement|CertificateBuilder::UsageKeyEncipherment); leafbuilder.addSubjectKeyIdentifier(); QSslCertificate leafcert = leafbuilder.signedCertificate(cacert, cakey); save_certificate("leaf.crt", leafcert); } <|endoftext|>
<commit_before>#include <avalon/GameCenter.h> namespace avalon { void GameCenter::login() { } bool GameCenter::showAchievements() { return false; } void GameCenter::postAchievement(const char* idName, int percentComplete) { } void GameCenter::clearAllAchievements() { } bool GameCenter::showScores() { return false; } void GameCenter::postScore(const char* idName, int score) { } void GameCenter::clearAllScores() { } } // namespace avalon <commit_msg>remove unused default android GameCenter class<commit_after><|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2015 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "libmesh/cell_prism.h" #include "libmesh/cell_prism6.h" #include "libmesh/face_quad4.h" #include "libmesh/face_tri3.h" namespace libMesh { // ------------------------------------------------------------ // Prism class static member initializations // We need to require C++11... const Real Prism::_master_points[18][3] = { {0, 0, -1}, {1, 0, -1}, {0, 1, -1}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}, {0.5, 0, -1}, {0.5, 0.5, -1}, {0, 0.5, -1}, {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0.5, 0, 1}, {0.5, 0.5, 1}, {0, 0.5, 1}, {0.5, 0, 0}, {0.5, 0.5, 0}, {0, 0.5, 0} }; // ------------------------------------------------------------ // Prism class member functions dof_id_type Prism::key (const unsigned int s) const { libmesh_assert_less (s, this->n_sides()); switch (s) { case 0: // the triangular face at z=0 case 4: // the triangular face at z=1 return this->compute_key (this->node(Prism6::side_nodes_map[s][0]), this->node(Prism6::side_nodes_map[s][1]), this->node(Prism6::side_nodes_map[s][2])); case 1: // the quad face at y=0 case 2: // the other quad face case 3: // the quad face at x=0 return this->compute_key (this->node(Prism6::side_nodes_map[s][0]), this->node(Prism6::side_nodes_map[s][1]), this->node(Prism6::side_nodes_map[s][2]), this->node(Prism6::side_nodes_map[s][3])); default: libmesh_error_msg("Invalid side " << s); } libmesh_error_msg("We'll never get here!"); return 0; } UniquePtr<Elem> Prism::side (const unsigned int i) const { libmesh_assert_less (i, this->n_sides()); Elem* face = NULL; switch (i) { case 0: // the triangular face at z=0 { face = new Tri3; face->set_node(0) = this->get_node(0); face->set_node(1) = this->get_node(2); face->set_node(2) = this->get_node(1); break; } case 1: // the quad face at y=0 { face = new Quad4; face->set_node(0) = this->get_node(0); face->set_node(1) = this->get_node(1); face->set_node(2) = this->get_node(4); face->set_node(3) = this->get_node(3); break; } case 2: // the other quad face { face = new Quad4; face->set_node(0) = this->get_node(1); face->set_node(1) = this->get_node(2); face->set_node(2) = this->get_node(5); face->set_node(3) = this->get_node(4); break; } case 3: // the quad face at x=0 { face = new Quad4; face->set_node(0) = this->get_node(2); face->set_node(1) = this->get_node(0); face->set_node(2) = this->get_node(3); face->set_node(3) = this->get_node(5); break; } case 4: // the triangular face at z=1 { face = new Tri3; face->set_node(0) = this->get_node(3); face->set_node(1) = this->get_node(4); face->set_node(2) = this->get_node(5); break; } default: libmesh_error_msg("Invalid side i = " << i); } return UniquePtr<Elem>(face); } bool Prism::is_child_on_side(const unsigned int c, const unsigned int s) const { libmesh_assert_less (c, this->n_children()); libmesh_assert_less (s, this->n_sides()); for (unsigned int i = 0; i != 4; ++i) if (Prism6::side_elems_map[s][i] == c) return true; return false; } bool Prism::is_edge_on_side(const unsigned int e, const unsigned int s) const { libmesh_assert_less (e, this->n_edges()); libmesh_assert_less (s, this->n_sides()); return (is_node_on_side(Prism6::edge_nodes_map[e][0],s) && is_node_on_side(Prism6::edge_nodes_map[e][1],s)); } const unsigned short int Prism::_second_order_vertex_child_number[18] = { 99,99,99,99,99,99, // Vertices 0,1,0,0,1,2,3,4,3, // Edges 0,1,0 // Faces }; const unsigned short int Prism::_second_order_vertex_child_index[18] = { 99,99,99,99,99,99, // Vertices 1,2,2,3,4,5,4,5,5, // Edges 4,5,5 // Faces }; const unsigned short int Prism::_second_order_adjacent_vertices[9][2] = { { 0, 1}, // vertices adjacent to node 6 { 1, 2}, // vertices adjacent to node 7 { 0, 2}, // vertices adjacent to node 8 { 0, 3}, // vertices adjacent to node 9 { 1, 4}, // vertices adjacent to node 10 { 2, 5}, // vertices adjacent to node 11 { 3, 4}, // vertices adjacent to node 12 { 4, 5}, // vertices adjacent to node 13 { 3, 5} // vertices adjacent to node 14 }; } // namespace libMesh <commit_msg>Refactor Prism::side(s)<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2015 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "libmesh/cell_prism.h" #include "libmesh/cell_prism6.h" #include "libmesh/face_quad4.h" #include "libmesh/face_tri3.h" namespace libMesh { // ------------------------------------------------------------ // Prism class static member initializations // We need to require C++11... const Real Prism::_master_points[18][3] = { {0, 0, -1}, {1, 0, -1}, {0, 1, -1}, {0, 0, 1}, {1, 0, 1}, {0, 1, 1}, {0.5, 0, -1}, {0.5, 0.5, -1}, {0, 0.5, -1}, {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0.5, 0, 1}, {0.5, 0.5, 1}, {0, 0.5, 1}, {0.5, 0, 0}, {0.5, 0.5, 0}, {0, 0.5, 0} }; // ------------------------------------------------------------ // Prism class member functions dof_id_type Prism::key (const unsigned int s) const { libmesh_assert_less (s, this->n_sides()); switch (s) { case 0: // the triangular face at z=0 case 4: // the triangular face at z=1 return this->compute_key (this->node(Prism6::side_nodes_map[s][0]), this->node(Prism6::side_nodes_map[s][1]), this->node(Prism6::side_nodes_map[s][2])); case 1: // the quad face at y=0 case 2: // the other quad face case 3: // the quad face at x=0 return this->compute_key (this->node(Prism6::side_nodes_map[s][0]), this->node(Prism6::side_nodes_map[s][1]), this->node(Prism6::side_nodes_map[s][2]), this->node(Prism6::side_nodes_map[s][3])); default: libmesh_error_msg("Invalid side " << s); } libmesh_error_msg("We'll never get here!"); return 0; } UniquePtr<Elem> Prism::side (const unsigned int i) const { libmesh_assert_less (i, this->n_sides()); Elem* face = NULL; // Set up the type of element switch (i) { case 0: // the triangular face at z=0 case 4: // the triangular face at z=1 { face = new Tri3; break; } case 1: // the quad face at y=0 case 2: // the other quad face case 3: // the quad face at x=0 { face = new Quad4; break; } default: libmesh_error_msg("Invalid side i = " << i); } // Set the nodes for (unsigned n=0; n<face->n_nodes(); ++n) face->set_node(n) = this->get_node(Prism6::side_nodes_map[i][n]); return UniquePtr<Elem>(face); } bool Prism::is_child_on_side(const unsigned int c, const unsigned int s) const { libmesh_assert_less (c, this->n_children()); libmesh_assert_less (s, this->n_sides()); for (unsigned int i = 0; i != 4; ++i) if (Prism6::side_elems_map[s][i] == c) return true; return false; } bool Prism::is_edge_on_side(const unsigned int e, const unsigned int s) const { libmesh_assert_less (e, this->n_edges()); libmesh_assert_less (s, this->n_sides()); return (is_node_on_side(Prism6::edge_nodes_map[e][0],s) && is_node_on_side(Prism6::edge_nodes_map[e][1],s)); } const unsigned short int Prism::_second_order_vertex_child_number[18] = { 99,99,99,99,99,99, // Vertices 0,1,0,0,1,2,3,4,3, // Edges 0,1,0 // Faces }; const unsigned short int Prism::_second_order_vertex_child_index[18] = { 99,99,99,99,99,99, // Vertices 1,2,2,3,4,5,4,5,5, // Edges 4,5,5 // Faces }; const unsigned short int Prism::_second_order_adjacent_vertices[9][2] = { { 0, 1}, // vertices adjacent to node 6 { 1, 2}, // vertices adjacent to node 7 { 0, 2}, // vertices adjacent to node 8 { 0, 3}, // vertices adjacent to node 9 { 1, 4}, // vertices adjacent to node 10 { 2, 5}, // vertices adjacent to node 11 { 3, 4}, // vertices adjacent to node 12 { 4, 5}, // vertices adjacent to node 13 { 3, 5} // vertices adjacent to node 14 }; } // namespace libMesh <|endoftext|>
<commit_before>/* * Copyright 2013-2016 Christian Lockley * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <getopt.h> #include "watchdogd.hpp" #include "init.hpp" #include "sub.hpp" #include "testdir.hpp" #include "multicall.hpp" int SetSchedulerPolicy(int priority) { struct sched_param param; param.sched_priority = priority; if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &param) < 0) { assert(errno != ESRCH); fprintf(stderr, "watchdogd: sched_setscheduler failed %s\n", MyStrerror(errno)); return -1; } return 0; } int InitializePosixMemlock(void) { if (mlockall(MCL_CURRENT | MCL_FUTURE) < 0) { fprintf(stderr, "watchdogd: unable to lock memory %s\n", MyStrerror(errno)); return -1; } return 0; } static void PrintHelpIdentify(void); int ParseCommandLine(int *argc, char **argv, struct cfgoptions *cfg) { int opt = 0; const struct option longOptions[] = { {"no-action", no_argument, 0, 'q'}, {"foreground", no_argument, 0, 'F'}, {"debug", no_argument, 0, 'd'}, {"force", no_argument, 0, 'f'}, {"sync", no_argument, 0, 's'}, {"softboot", no_argument, 0, 'b'}, {"daemonize", no_argument, 0, 'D'}, {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"config-file", required_argument, 0, 'c'}, {"loop-exit", required_argument, 0, 'X'}, {"loglevel", required_argument, 0, 'l'}, {"identify", no_argument, 0, 'i'}, {0, 0, 0, 0} }; char const * const loglevels[] = { "\x1b[1mnone", "err", "info", "notice", "debug\x1B[0m"}; int tmp = 0; while ((opt = getopt_long(*argc, argv, "iDhqsfFbVvndc:X:l:", longOptions, &tmp)) != -1) { switch (opt) { case 'n': case 'd': case 'F': cfg->options &= !DAEMONIZE; break; case 'c': cfg->confile = optarg; break; case 's': cfg->options |= SYNC; break; case 'q': cfg->options |= NOACTION; break; case 'l': if (LogUpTo(optarg, true) == false) { return -1; } cfg->options |= LOGLVLSETCMDLN; break; case 'f': cfg->options |= FORCE; break; case 'b': cfg->options |= SOFTBOOT; break; case 'v': cfg->options |= VERBOSE; break; case 'X': cfg->loopExit = ConvertStringToInt(optarg); if (cfg->loopExit <= 0) { Logmsg(LOG_ERR, "optarg must be greater than 0 for X option"); return -1; } break; case 'i': cfg->options |= IDENTIFY; break; case 'D': cfg->options |= DAEMONIZE; break; case 'V': PrintVersionString(); return 1; case 'h': if (cfg->options & IDENTIFY) { PrintHelpIdentify(); } else { Usage(); } return 1; case '?': switch (optopt) { case 'l': fprintf(stderr, "Valid loglevels are:\n"); for (size_t i = 0; i < ARRAY_SIZE(loglevels); i++) { if (isatty(STDOUT_FILENO) == 0 && i == 0) { fprintf(stderr, " %s\n", loglevels[i]+4); continue; } else if (isatty(STDOUT_FILENO) == 0 && i + 1 == ARRAY_SIZE(loglevels)) { char const * const tmp = loglevels[i]; fprintf(stderr, " "); for (size_t j = 0; tmp[j] != '\x1b'; j++) { fprintf(stderr, "%c", tmp[j]); } fprintf(stderr, "\n"); } else { fprintf(stderr, " %s\n", loglevels[i]); } } break; } return -1; default: if (cfg->options & IDENTIFY) { PrintHelpIdentify(); } else { Usage(); } return -1; } } if (optind < *argc) { struct stat buf = {0}; stat(argv[optind], &buf); if (!S_ISCHR(buf.st_mode)) { fprintf(stderr, "watchdogd: %s is an invalid device file\n", argv[optind]); return -1; } cfg->devicepath = argv[optind]; cfg->options |= BUSYBOXDEVOPTCOMPAT; } return 0; } int GetDefaultPriority(void) { int ret = sched_get_priority_min(SCHED_RR); if (ret < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return ret; } return ret; } int CheckPriority(int priority) { int max = 0; int min = 0; max = sched_get_priority_max(SCHED_RR); if (max < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return -1; } min = sched_get_priority_min(SCHED_RR); if (min < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return -1; } if (priority < min) { return -2; } if (priority > max) { return -2; } return 0; } int PrintVersionString(void) { printf("%s\n", PACKAGE_STRING); printf("Copyright 2013-2016 Christian Lockley. All rights reserved.\n"); printf("Licensed under the Apache License, Version 2.0.\n"); printf("There is NO WARRANTY, to the extent permitted by law.\n"); return 0; } static void PrintHelpIdentify(void) { char *buf = NULL; Wasprintf(&buf, "Usage: %s [OPTION]", GetExeName()); assert(buf != NULL); if (buf == NULL) { abort(); } char const * const help[][2] = { {buf, ""}, {"Get watchdog device status.", ""}, {"", ""}, {" -c, --config-file ", "path to configuration file"}, {" -i, --identify", "identify hardware watchdog"}, {" -h, --help", "this help"}, {" -V, --version", "print version info"}, }; for (size_t i = 0; i < ARRAY_SIZE(help); i += 1) { bool isterm = isatty(STDOUT_FILENO) == 1; long col = GetConsoleColumns(); if (col >= 80) { //KLUGE col += col / 2; } long len = 0; if (isterm && i > 2) { printf("\x1B[1m"); } len += printf("%-22s", help[i][0]); if (isterm && i > 2) { printf("\x1B[22m"); } char *ptr = strdup(help[i][1]); if (ptr == NULL) { perror(PACKAGE_NAME); return; } char *save = NULL; char *tmp = strtok_r(ptr, " ", &save); if (isterm) { printf("\e[1;34m"); } while (tmp != NULL) { len += strlen(tmp); if (len > col) { if (col < 80) { printf("\n"); } len = printf(" "); len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } else { len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } } if (isterm) { printf("\x1B[39m\x1B[22m"); } free(ptr); printf("\n"); } free(buf); } static void PrintHelpMain(void) { //Emulate the gnu --help output. const char *const help[][2] = { {"Usage: " PACKAGE_NAME " [OPTION]", ""}, {"A watchdog daemon for linux.", ""}, {"", ""}, {" -b, --softboot", "ignore file open errors"}, {" -c, --config-file ", "path to configuration file"}, {" -D, --daemonize ", "daemonize after startup"}, {" -f, --force", "force a ping interval or timeout even if the ping interval is less than the timeout"}, {" -i, --identify", "identify hardware watchdog"}, {" -l, --loglevel", "sets max loglevel none, err, info, notice, debug"}, {" -s, --sync", "sync file-systems regularly"}, {" -h, --help", "this help"}, {" -V, --version", "print version info"}, {isatty(STDOUT_FILENO) == 1 ? " -X, --loop-exit \033[4mnum\033[0m ": " -X, --loop-exit num", " Run for 'num' loops then exit"} }; for (size_t i = 0; i < ARRAY_SIZE(help); i += 1) { bool isterm = isatty(STDOUT_FILENO) == 1; long col = GetConsoleColumns(); if (col >= 80) { //KLUGE col += col / 2; } long len = 0; if (isterm && i > 2) { printf("\x1B[1m"); } len += printf("%-22s", help[i][0]); if (isterm && i > 2) { printf("\x1B[22m"); } char *ptr = strdup(help[i][1]); if (ptr == NULL) { perror(PACKAGE_NAME); return; } char *save = NULL; char *tmp = strtok_r(ptr, " ", &save); if (isterm) { printf("\e[1;34m"); } while (tmp != NULL) { len += strlen(tmp); if (len > col) { if (col < 80) { printf("\n"); } len = printf(" "); len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } else { len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } } if (isterm) { printf("\x1B[39m\x1B[22m"); } free(ptr); printf("\n"); } } int Usage(void) { if (strcasecmp(GetExeName(), "wd_identify") == 0 || strcasecmp(GetExeName(), "wd_identify.sh") == 0) { PrintHelpIdentify(); } else { PrintHelpMain(); } return 0; } <commit_msg>update version string<commit_after>/* * Copyright 2013-2016 Christian Lockley * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <getopt.h> #include "watchdogd.hpp" #include "init.hpp" #include "sub.hpp" #include "testdir.hpp" #include "multicall.hpp" int SetSchedulerPolicy(int priority) { struct sched_param param; param.sched_priority = priority; if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &param) < 0) { assert(errno != ESRCH); fprintf(stderr, "watchdogd: sched_setscheduler failed %s\n", MyStrerror(errno)); return -1; } return 0; } int InitializePosixMemlock(void) { if (mlockall(MCL_CURRENT | MCL_FUTURE) < 0) { fprintf(stderr, "watchdogd: unable to lock memory %s\n", MyStrerror(errno)); return -1; } return 0; } static void PrintHelpIdentify(void); int ParseCommandLine(int *argc, char **argv, struct cfgoptions *cfg) { int opt = 0; const struct option longOptions[] = { {"no-action", no_argument, 0, 'q'}, {"foreground", no_argument, 0, 'F'}, {"debug", no_argument, 0, 'd'}, {"force", no_argument, 0, 'f'}, {"sync", no_argument, 0, 's'}, {"softboot", no_argument, 0, 'b'}, {"daemonize", no_argument, 0, 'D'}, {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'}, {"config-file", required_argument, 0, 'c'}, {"loop-exit", required_argument, 0, 'X'}, {"loglevel", required_argument, 0, 'l'}, {"identify", no_argument, 0, 'i'}, {0, 0, 0, 0} }; char const * const loglevels[] = { "\x1b[1mnone", "err", "info", "notice", "debug\x1B[0m"}; int tmp = 0; while ((opt = getopt_long(*argc, argv, "iDhqsfFbVvndc:X:l:", longOptions, &tmp)) != -1) { switch (opt) { case 'n': case 'd': case 'F': cfg->options &= !DAEMONIZE; break; case 'c': cfg->confile = optarg; break; case 's': cfg->options |= SYNC; break; case 'q': cfg->options |= NOACTION; break; case 'l': if (LogUpTo(optarg, true) == false) { return -1; } cfg->options |= LOGLVLSETCMDLN; break; case 'f': cfg->options |= FORCE; break; case 'b': cfg->options |= SOFTBOOT; break; case 'v': cfg->options |= VERBOSE; break; case 'X': cfg->loopExit = ConvertStringToInt(optarg); if (cfg->loopExit <= 0) { Logmsg(LOG_ERR, "optarg must be greater than 0 for X option"); return -1; } break; case 'i': cfg->options |= IDENTIFY; break; case 'D': cfg->options |= DAEMONIZE; break; case 'V': PrintVersionString(); return 1; case 'h': if (cfg->options & IDENTIFY) { PrintHelpIdentify(); } else { Usage(); } return 1; case '?': switch (optopt) { case 'l': fprintf(stderr, "Valid loglevels are:\n"); for (size_t i = 0; i < ARRAY_SIZE(loglevels); i++) { if (isatty(STDOUT_FILENO) == 0 && i == 0) { fprintf(stderr, " %s\n", loglevels[i]+4); continue; } else if (isatty(STDOUT_FILENO) == 0 && i + 1 == ARRAY_SIZE(loglevels)) { char const * const tmp = loglevels[i]; fprintf(stderr, " "); for (size_t j = 0; tmp[j] != '\x1b'; j++) { fprintf(stderr, "%c", tmp[j]); } fprintf(stderr, "\n"); } else { fprintf(stderr, " %s\n", loglevels[i]); } } break; } return -1; default: if (cfg->options & IDENTIFY) { PrintHelpIdentify(); } else { Usage(); } return -1; } } if (optind < *argc) { struct stat buf = {0}; stat(argv[optind], &buf); if (!S_ISCHR(buf.st_mode)) { fprintf(stderr, "watchdogd: %s is an invalid device file\n", argv[optind]); return -1; } cfg->devicepath = argv[optind]; cfg->options |= BUSYBOXDEVOPTCOMPAT; } return 0; } int GetDefaultPriority(void) { int ret = sched_get_priority_min(SCHED_RR); if (ret < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return ret; } return ret; } int CheckPriority(int priority) { int max = 0; int min = 0; max = sched_get_priority_max(SCHED_RR); if (max < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return -1; } min = sched_get_priority_min(SCHED_RR); if (min < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return -1; } if (priority < min) { return -2; } if (priority > max) { return -2; } return 0; } int PrintVersionString(void) { printf("%s\n", PACKAGE_STRING); printf("Copyright 2013-2017 Christian Lockley. All rights reserved.\n"); printf("Licensed under the Apache License, Version 2.0.\n"); printf("There is NO WARRANTY, to the extent permitted by law.\n"); return 0; } static void PrintHelpIdentify(void) { char *buf = NULL; Wasprintf(&buf, "Usage: %s [OPTION]", GetExeName()); assert(buf != NULL); if (buf == NULL) { abort(); } char const * const help[][2] = { {buf, ""}, {"Get watchdog device status.", ""}, {"", ""}, {" -c, --config-file ", "path to configuration file"}, {" -i, --identify", "identify hardware watchdog"}, {" -h, --help", "this help"}, {" -V, --version", "print version info"}, }; for (size_t i = 0; i < ARRAY_SIZE(help); i += 1) { bool isterm = isatty(STDOUT_FILENO) == 1; long col = GetConsoleColumns(); if (col >= 80) { //KLUGE col += col / 2; } long len = 0; if (isterm && i > 2) { printf("\x1B[1m"); } len += printf("%-22s", help[i][0]); if (isterm && i > 2) { printf("\x1B[22m"); } char *ptr = strdup(help[i][1]); if (ptr == NULL) { perror(PACKAGE_NAME); return; } char *save = NULL; char *tmp = strtok_r(ptr, " ", &save); if (isterm) { printf("\e[1;34m"); } while (tmp != NULL) { len += strlen(tmp); if (len > col) { if (col < 80) { printf("\n"); } len = printf(" "); len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } else { len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } } if (isterm) { printf("\x1B[39m\x1B[22m"); } free(ptr); printf("\n"); } free(buf); } static void PrintHelpMain(void) { //Emulate the gnu --help output. const char *const help[][2] = { {"Usage: " PACKAGE_NAME " [OPTION]", ""}, {"A watchdog daemon for linux.", ""}, {"", ""}, {" -b, --softboot", "ignore file open errors"}, {" -c, --config-file ", "path to configuration file"}, {" -D, --daemonize ", "daemonize after startup"}, {" -f, --force", "force a ping interval or timeout even if the ping interval is less than the timeout"}, {" -i, --identify", "identify hardware watchdog"}, {" -l, --loglevel", "sets max loglevel none, err, info, notice, debug"}, {" -s, --sync", "sync file-systems regularly"}, {" -h, --help", "this help"}, {" -V, --version", "print version info"}, {isatty(STDOUT_FILENO) == 1 ? " -X, --loop-exit \033[4mnum\033[0m ": " -X, --loop-exit num", " Run for 'num' loops then exit"} }; for (size_t i = 0; i < ARRAY_SIZE(help); i += 1) { bool isterm = isatty(STDOUT_FILENO) == 1; long col = GetConsoleColumns(); if (col >= 80) { //KLUGE col += col / 2; } long len = 0; if (isterm && i > 2) { printf("\x1B[1m"); } len += printf("%-22s", help[i][0]); if (isterm && i > 2) { printf("\x1B[22m"); } char *ptr = strdup(help[i][1]); if (ptr == NULL) { perror(PACKAGE_NAME); return; } char *save = NULL; char *tmp = strtok_r(ptr, " ", &save); if (isterm) { printf("\e[1;34m"); } while (tmp != NULL) { len += strlen(tmp); if (len > col) { if (col < 80) { printf("\n"); } len = printf(" "); len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } else { len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } } if (isterm) { printf("\x1B[39m\x1B[22m"); } free(ptr); printf("\n"); } } int Usage(void) { if (strcasecmp(GetExeName(), "wd_identify") == 0 || strcasecmp(GetExeName(), "wd_identify.sh") == 0) { PrintHelpIdentify(); } else { PrintHelpMain(); } return 0; } <|endoftext|>
<commit_before>/* * * Bacula UA authentication. Provides authentication with * the Director. * * Kern Sibbald, June MMI * * Version $Id$ * * This routine runs as a thread and must be thread reentrant. * * Basic tasks done here: * */ /* Bacula® - The Network Backup Solution Copyright (C) 2001-2007 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation plus additions that are listed in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Bacula® is a registered trademark of John Walker. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ #include "mainwindow.h" #include "bacula.h" #include "console_conf.h" #include "jcr.h" /* Commands sent to Director */ static char hello[] = "Hello %s calling\n"; /* Response from Director */ static char OKhello[] = "1000 OK:"; /* Forward referenced functions */ /* * Authenticate Director */ int authenticate_director(JCR *jcr, DIRRES *director, CONRES *cons) { BSOCK *dir = jcr->dir_bsock; int tls_local_need = BNET_TLS_NONE; int tls_remote_need = BNET_TLS_NONE; int compatible = true; char bashed_name[MAX_NAME_LENGTH]; char *password; /* * Send my name to the Director then do authentication */ if (cons) { bstrncpy(bashed_name, cons->hdr.name, sizeof(bashed_name)); bash_spaces(bashed_name); password = cons->password; } else { bstrncpy(bashed_name, "*UserAgent*", sizeof(bashed_name)); password = director->password; } /* Timeout Hello after 5 mins */ btimer_t *tid = start_bsock_timer(dir, 60 * 5); bnet_fsend(dir, hello, bashed_name); /* respond to Dir challenge */ if (!cram_md5_respond(dir, password, &tls_remote_need, &compatible) || /* Now challenge dir */ !cram_md5_challenge(dir, password, tls_local_need, compatible)) { stop_bsock_timer(tid); printf(_("%s: Director authorization problem.\n"), my_name); set_text(_("Director authorization problem.\n")); set_text(_( "Please see http://www.bacula.org/rel-manual/faq.html#AuthorizationErrors for help.\n")); return 0; } Dmsg1(6, ">dird: %s", dir->msg); if (bnet_recv(dir) <= 0) { stop_bsock_timer(tid); set_textf(_("Bad response to Hello command: ERR=%s\n"), bnet_strerror(dir)); printf(_("%s: Bad response to Hello command: ERR=%s\n"), my_name, bnet_strerror(dir)); set_text(_("The Director is probably not running.\n")); return 0; } stop_bsock_timer(tid); Dmsg1(10, "<dird: %s", dir->msg); if (strncmp(dir->msg, OKhello, sizeof(OKhello)-1) != 0) { set_text(_("Director rejected Hello command\n")); return 0; } else { set_text(dir->msg); } return 1; } <commit_msg>Update<commit_after>/* * * Bacula UA authentication. Provides authentication with * the Director. * * Kern Sibbald, June MMI * * Version $Id$ * * This routine runs as a thread and must be thread reentrant. * * Basic tasks done here: * */ /* Bacula® - The Network Backup Solution Copyright (C) 2001-2007 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation plus additions that are listed in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Bacula® is a registered trademark of John Walker. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ #include "console.h" /* Commands sent to Director */ static char hello[] = "Hello %s calling\n"; /* Response from Director */ static char OKhello[] = "1000 OK:"; /* Forward referenced functions */ /* * Authenticate Director */ int authenticate_director(JCR *jcr, DIRRES *director, CONRES *cons) { BSOCK *dir = jcr->dir_bsock; int tls_local_need = BNET_TLS_NONE; int tls_remote_need = BNET_TLS_NONE; int compatible = true; char bashed_name[MAX_NAME_LENGTH]; char *password; /* * Send my name to the Director then do authentication */ if (cons) { bstrncpy(bashed_name, cons->hdr.name, sizeof(bashed_name)); bash_spaces(bashed_name); password = cons->password; } else { bstrncpy(bashed_name, "*UserAgent*", sizeof(bashed_name)); password = director->password; } /* Timeout Hello after 5 mins */ btimer_t *tid = start_bsock_timer(dir, 60 * 5); bnet_fsend(dir, hello, bashed_name); /* respond to Dir challenge */ if (!cram_md5_respond(dir, password, &tls_remote_need, &compatible) || /* Now challenge dir */ !cram_md5_challenge(dir, password, tls_local_need, compatible)) { stop_bsock_timer(tid); printf(_("%s: Director authorization problem.\n"), my_name); set_text(_("Director authorization problem.\n")); set_text(_( "Please see http://www.bacula.org/rel-manual/faq.html#AuthorizationErrors for help.\n")); return 0; } Dmsg1(6, ">dird: %s", dir->msg); if (bnet_recv(dir) <= 0) { stop_bsock_timer(tid); set_textf(_("Bad response to Hello command: ERR=%s\n"), bnet_strerror(dir)); printf(_("%s: Bad response to Hello command: ERR=%s\n"), my_name, bnet_strerror(dir)); set_text(_("The Director is probably not running.\n")); return 0; } stop_bsock_timer(tid); Dmsg1(10, "<dird: %s", dir->msg); if (strncmp(dir->msg, OKhello, sizeof(OKhello)-1) != 0) { set_text(_("Director rejected Hello command\n")); return 0; } else { set_text(dir->msg); } return 1; } <|endoftext|>
<commit_before>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif #warning you are ugly #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "util/funcs.h" #include "configuration.h" #include "script/script.h" #include "music.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ const int Global::TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) Global::TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; void inc_speed_counter() { Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ const char * message = "Bug! Caught a memory violation. Shutting down..\n"; int dont_care = write(1, message, 48); dont_care = dont_care; // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down.."; Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(1); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } /* should probably call the janitor here or something */ static void close_paintown(){ Music::pause(); Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Data path is " << Util::getDataPath() << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; out<<"Install joystick: "<<install_joystick(JOY_TYPE_AUTODETECT)<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; out << "Initialize random number generator" << endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode(SWITCH_BACKGROUND); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); out << "Initialize network" << endl; Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <commit_msg>add some comments<commit_after>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif /* don't be a boring tuna */ #warning you are ugly #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "util/funcs.h" #include "configuration.h" #include "script/script.h" #include "music.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ const int Global::TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) Global::TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; /* game counter, controls FPS */ void inc_speed_counter(){ /* probably put input polling here, InputManager::poll() */ Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); /* if you need to count seconds for some reason.. */ void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ const char * message = "Bug! Caught a memory violation. Shutting down..\n"; int dont_care = write(1, message, 48); dont_care = dont_care; // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down.."; Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(1); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } /* should probably call the janitor here or something */ static void close_paintown(){ Music::pause(); Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Data path is " << Util::getDataPath() << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; out<<"Install joystick: "<<install_joystick(JOY_TYPE_AUTODETECT)<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; out << "Initialize random number generator" << endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode(SWITCH_BACKGROUND); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); out << "Initialize network" << endl; Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <|endoftext|>
<commit_before>/* MIT License Copyright (c) 2017 Eren Okka Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <fstream> #include "matroska.h" namespace anisthesia { namespace matroska { Buffer::Buffer(size_t size) { data_.resize(size, '\0'); } uint8_t* Buffer::data() { return !data_.empty() ? &data_.front() : nullptr; } size_t Buffer::pos() const { return pos_; } size_t Buffer::size() const { return data_.size(); } void Buffer::skip(size_t size) { pos_ += size; } bool Buffer::read_encoded_value(uint32_t& value, bool clear_leading_bits) { uint8_t base = 0x80; size_t size = 0; for ( ; size <= 8; ++size) { base = 0x80 >> size; if (!base) return false; if (data_[pos_] & base) break; } for (size_t i = 0; i <= size; ++i) { const uint8_t b = (clear_leading_bits && i == 0) ? ~base : 0xFF; value |= (data_[pos_ + i] & b) << ((size - i) * 8); } pos_ += size + 1; return true; } uint32_t Buffer::read_uint32(const size_t size) { uint32_t value = 0; for (size_t i = 0; i < size; ++i) { value |= (data_[pos_ + i] & 0xFF) << ((size - i - 1) * 8); } pos_ += size; return value; } float Buffer::read_float(const size_t size) { static_assert(sizeof(uint32_t) == sizeof(float), "Invalid float size"); switch (size) { case 4: { auto u32 = read_uint32(size); return reinterpret_cast<float&>(u32); // @TODO: Is this safe? } default: // @TODO: Do we need to handle 64-bit values? (i.e. size == 8) pos_ += size; return 0; } } std::string Buffer::read_string(const size_t size) { auto result = std::string( reinterpret_cast<const char*>(&data_.at(pos_)), size); pos_ += size; return result; } //////////////////////////////////////////////////////////////////////////////// bool ReadInfoFromFile(const std::string& path, Info& info) { std::ifstream file(path.c_str(), std::ios::in | std::ios::binary); if (!file) return false; // Determine file size file.seekg(0, std::ios::end); const size_t file_size = file.tellg(); file.seekg(0, std::ios::beg); // Check EBML header uint8_t m[sizeof(uint32_t)]; file.read(reinterpret_cast<char*>(m), sizeof(uint32_t)); const uint32_t magic = (m[0] << 24) | (m[1] << 16) | (m[2] << 8) | m[3]; if (magic != ElementId::kEBML) return false; // invalid Matroska file uint32_t timecode_scale = kDefaultTimecodeScale; uint32_t track_type = 0; for (size_t offset = 0; offset < file_size; ) { // @TODO: Improve performance. fgetc takes a LOT of time (e.g. 5 seconds for // a 1GB file) if the file isn't cached. mkvinfo is much faster. Buffer buffer(0x1000); // arbitrary size file.seekg(offset); file.read(reinterpret_cast<char*>(buffer.data()), buffer.size()); uint32_t element_id = 0; uint32_t value_size = 0; if (!buffer.read_encoded_value(element_id, false) || !buffer.read_encoded_value(value_size, true)) { return false; } switch (element_id) { default: buffer.skip(value_size); break; case ElementId::kSegment: case ElementId::kInfo: case ElementId::kTracks: case ElementId::kTrackEntry: // We don't want to skip the data of these elements break; case ElementId::kTimecodeScale: timecode_scale = buffer.read_uint32(value_size); break; case ElementId::kDuration: info.duration = std::chrono::duration_cast<duration_t>( timecode_scale_t{buffer.read_float(value_size) * timecode_scale}); break; case ElementId::kTitle: info.title = buffer.read_string(value_size); break; case ElementId::kTrackType: track_type = buffer.read_uint32(value_size); break; case ElementId::kTrackName: if (track_type == TrackType::kVideo) { info.video_track_name = buffer.read_string(value_size); } else { buffer.skip(value_size); } break; } offset += buffer.pos(); } return true; } } // namespace matroska } // namespace anisthesia <commit_msg>Fix file size conversion warning<commit_after>/* MIT License Copyright (c) 2017 Eren Okka Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <fstream> #include "matroska.h" namespace anisthesia { namespace matroska { Buffer::Buffer(size_t size) { data_.resize(size, '\0'); } uint8_t* Buffer::data() { return !data_.empty() ? &data_.front() : nullptr; } size_t Buffer::pos() const { return pos_; } size_t Buffer::size() const { return data_.size(); } void Buffer::skip(size_t size) { pos_ += size; } bool Buffer::read_encoded_value(uint32_t& value, bool clear_leading_bits) { uint8_t base = 0x80; size_t size = 0; for ( ; size <= 8; ++size) { base = 0x80 >> size; if (!base) return false; if (data_[pos_] & base) break; } for (size_t i = 0; i <= size; ++i) { const uint8_t b = (clear_leading_bits && i == 0) ? ~base : 0xFF; value |= (data_[pos_ + i] & b) << ((size - i) * 8); } pos_ += size + 1; return true; } uint32_t Buffer::read_uint32(const size_t size) { uint32_t value = 0; for (size_t i = 0; i < size; ++i) { value |= (data_[pos_ + i] & 0xFF) << ((size - i - 1) * 8); } pos_ += size; return value; } float Buffer::read_float(const size_t size) { static_assert(sizeof(uint32_t) == sizeof(float), "Invalid float size"); switch (size) { case 4: { auto u32 = read_uint32(size); return reinterpret_cast<float&>(u32); // @TODO: Is this safe? } default: // @TODO: Do we need to handle 64-bit values? (i.e. size == 8) pos_ += size; return 0; } } std::string Buffer::read_string(const size_t size) { auto result = std::string( reinterpret_cast<const char*>(&data_.at(pos_)), size); pos_ += size; return result; } //////////////////////////////////////////////////////////////////////////////// bool ReadInfoFromFile(const std::string& path, Info& info) { std::ifstream file(path.c_str(), std::ios::in | std::ios::binary); if (!file) return false; // Determine file size file.seekg(0, std::ios::end); const auto file_size = static_cast<size_t>(file.tellg()); file.seekg(0, std::ios::beg); // Check EBML header uint8_t m[sizeof(uint32_t)]; file.read(reinterpret_cast<char*>(m), sizeof(uint32_t)); const uint32_t magic = (m[0] << 24) | (m[1] << 16) | (m[2] << 8) | m[3]; if (magic != ElementId::kEBML) return false; // invalid Matroska file uint32_t timecode_scale = kDefaultTimecodeScale; uint32_t track_type = 0; for (size_t offset = 0; offset < file_size; ) { // @TODO: Improve performance. fgetc takes a LOT of time (e.g. 5 seconds for // a 1GB file) if the file isn't cached. mkvinfo is much faster. Buffer buffer(0x1000); // arbitrary size file.seekg(offset); file.read(reinterpret_cast<char*>(buffer.data()), buffer.size()); uint32_t element_id = 0; uint32_t value_size = 0; if (!buffer.read_encoded_value(element_id, false) || !buffer.read_encoded_value(value_size, true)) { return false; } switch (element_id) { default: buffer.skip(value_size); break; case ElementId::kSegment: case ElementId::kInfo: case ElementId::kTracks: case ElementId::kTrackEntry: // We don't want to skip the data of these elements break; case ElementId::kTimecodeScale: timecode_scale = buffer.read_uint32(value_size); break; case ElementId::kDuration: info.duration = std::chrono::duration_cast<duration_t>( timecode_scale_t{buffer.read_float(value_size) * timecode_scale}); break; case ElementId::kTitle: info.title = buffer.read_string(value_size); break; case ElementId::kTrackType: track_type = buffer.read_uint32(value_size); break; case ElementId::kTrackName: if (track_type == TrackType::kVideo) { info.video_track_name = buffer.read_string(value_size); } else { buffer.skip(value_size); } break; } offset += buffer.pos(); } return true; } } // namespace matroska } // namespace anisthesia <|endoftext|>
<commit_before>/* Copyright (c) 2015, 2016, Andreas Fett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cassert> #include <cstdlib> #include <cstring> #include <iobuf.h> void iobuf::fill(size_t size) { assert(wstart_ + size <= capacity_); wstart_ += size; } size_t iobuf::rsize() const { return wstart_ - rstart_; } void *iobuf::rstart() const { return static_cast<char *>(data_) + rstart_; } size_t iobuf::wsize() const { return capacity_ - wstart_; } void *iobuf::wstart() const { return static_cast<char *>(data_) + wstart_; } void iobuf::drain(size_t size) { assert(size <= rsize()); rstart_ += size; if (rstart_ == wstart_) { wstart_ = 0; rstart_ = 0; } } iobuf::iobuf() : data_(0), capacity_(0), rstart_(0), wstart_(0) { } iobuf::iobuf(size_t size) : data_(0), capacity_(0), rstart_(0), wstart_(0) { grow(size); } iobuf::~iobuf() { free(data_); } void iobuf::reserve(size_t size) { if (size == 0) { return; } if (size <= wsize()) { return; } if (rstart_ != 0) { reclaim(); } if (size <= wsize()) { return; } grow(capacity_ + (size - wsize())); } void iobuf::grow(size_t capacity) { assert(capacity > capacity_); void *n(realloc(data_, capacity)); if (n != NULL) { data_ = n; capacity_ = capacity; } } void iobuf::reclaim() { size_t srsize(rsize()); memmove(data_, rstart(), srsize); rstart_ = 0; wstart_ = srsize; } <commit_msg>iobuf: use nullptr<commit_after>/* Copyright (c) 2015, 2016, Andreas Fett All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cassert> #include <cstdlib> #include <cstring> #include <iobuf.h> void iobuf::fill(size_t size) { assert(wstart_ + size <= capacity_); wstart_ += size; } size_t iobuf::rsize() const { return wstart_ - rstart_; } void *iobuf::rstart() const { return static_cast<char *>(data_) + rstart_; } size_t iobuf::wsize() const { return capacity_ - wstart_; } void *iobuf::wstart() const { return static_cast<char *>(data_) + wstart_; } void iobuf::drain(size_t size) { assert(size <= rsize()); rstart_ += size; if (rstart_ == wstart_) { wstart_ = 0; rstart_ = 0; } } iobuf::iobuf() : data_(nullptr), capacity_(0), rstart_(0), wstart_(0) { } iobuf::iobuf(size_t size) : data_(nullptr), capacity_(0), rstart_(0), wstart_(0) { grow(size); } iobuf::~iobuf() { free(data_); } void iobuf::reserve(size_t size) { if (size == 0) { return; } if (size <= wsize()) { return; } if (rstart_ != 0) { reclaim(); } if (size <= wsize()) { return; } grow(capacity_ + (size - wsize())); } void iobuf::grow(size_t capacity) { assert(capacity > capacity_); void *n(realloc(data_, capacity)); if (n != nullptr) { data_ = n; capacity_ = capacity; } } void iobuf::reclaim() { size_t srsize(rsize()); memmove(data_, rstart(), srsize); rstart_ = 0; wstart_ = srsize; } <|endoftext|>
<commit_before>#include <aikido/planner/ompl/CRRT.hpp> #include <aikido/planner/ompl/GeometricStateSpace.hpp> #include <ompl/base/goals/GoalSampleableRegion.h> #include <ompl/tools/config/SelfConfig.h> #include <limits> namespace aikido { namespace planner { namespace ompl { //============================================================================= CRRT::CRRT(const ::ompl::base::SpaceInformationPtr &_si) : ::ompl::base::Planner(_si, "CRRT"), mCons(nullptr), mGoalBias(0.05), mMaxDistance(0.1), mLastGoalMotion(nullptr), mMaxStepsize(0.1) { auto ss = boost::dynamic_pointer_cast<GeometricStateSpace>(si_->getStateSpace()); if (!ss) { throw std::invalid_argument( "CRRT algorithm requires a GeometricStateSpace"); } specs_.approximateSolutions = true; specs_.directed = true; Planner::declareParam<double>("range", this, &CRRT::setRange, &CRRT::getRange, "0.:1.:10000."); Planner::declareParam<double>("goal_bias", this, &CRRT::setGoalBias, &CRRT::getGoalBias, "0.:.05:1."); Planner::declareParam<double>("proj_res", this, &CRRT::setProjectionResolution, &CRRT::getProjectionResolution, "0.:1.:10000."); } //============================================================================= CRRT::~CRRT(void) { freeMemory(); } //============================================================================= void CRRT::getPlannerData(::ompl::base::PlannerData &_data) const { ::ompl::base::Planner::getPlannerData(_data); std::vector<Motion *> motions; if (mNN) mNN->list(motions); if (mLastGoalMotion) _data.addGoalVertex( ::ompl::base::PlannerDataVertex(mLastGoalMotion->state)); for (unsigned int i = 0; i < motions.size(); ++i) { if (motions[i]->parent == nullptr) _data.addStartVertex(::ompl::base::PlannerDataVertex(motions[i]->state)); else _data.addEdge(::ompl::base::PlannerDataVertex(motions[i]->parent->state), ::ompl::base::PlannerDataVertex(motions[i]->state)); } } //============================================================================= void CRRT::clear(void) { ::ompl::base::Planner::clear(); mSampler.reset(); freeMemory(); if (mNN) mNN->clear(); mLastGoalMotion = nullptr; } //============================================================================= void CRRT::setGoalBias(double _goalBias) { if (_goalBias < 0.0 || _goalBias > 1.0) { std::stringstream ss; ss << "Invalid value for goal bias: " << _goalBias << ". Value must be between 0 and 1."; throw std::invalid_argument(ss.str()); } mGoalBias = _goalBias; } //============================================================================= double CRRT::getGoalBias() const { return mGoalBias; } //============================================================================= void CRRT::setRange(double _distance){ if (_distance < 0.0) { throw std::invalid_argument( "Distance must be positive on call to setRange."); } mMaxDistance = _distance; } //============================================================================= double CRRT::getRange() const { return mMaxDistance; } //============================================================================= void CRRT::setPathConstraint( constraint::ProjectablePtr _projectable) { mCons = std::move(_projectable); } //============================================================================= void CRRT::setProjectionResolution(double _resolution) { mMaxStepsize = _resolution; } //============================================================================= double CRRT::getProjectionResolution(void) const { return mMaxStepsize; } //============================================================================= void CRRT::setup(void) { ::ompl::base::Planner::setup(); ::ompl::tools::SelfConfig sc(si_, getName()); sc.configurePlannerRange(mMaxDistance); if (!mNN) mNN.reset(new ::ompl::NearestNeighborsGNAT<Motion *>); mNN->setDistanceFunction(boost::bind(&CRRT::distanceFunction, this, _1, _2)); } //============================================================================= void CRRT::freeMemory(void) { if (mNN) { std::vector<Motion *> motions; mNN->list(motions); for (unsigned int i = 0; i < motions.size(); ++i) { if (motions[i]->state) si_->freeState(motions[i]->state); delete motions[i]; } } } //============================================================================= ::ompl::base::PlannerStatus CRRT::solve(const ::ompl::base::PlannerTerminationCondition &_ptc) { checkValidity(); ::ompl::base::Goal *goal = pdef_->getGoal().get(); ::ompl::base::GoalSampleableRegion *goalSampleable = dynamic_cast<::ompl::base::GoalSampleableRegion *>(goal); while (const ::ompl::base::State *st = pis_.nextStart()) { Motion *motion = new Motion(si_); si_->copyState(motion->state, st); mNN->add(motion); } if (mNN->size() == 0) { return ::ompl::base::PlannerStatus::INVALID_START; } if (!mSampler) mSampler = si_->allocStateSampler(); Motion *solution = nullptr; Motion *approxsol = nullptr; double approxdif = std::numeric_limits<double>::infinity(); Motion *rmotion = new Motion(si_); ::ompl::base::State *rstate = rmotion->state; ::ompl::base::State *xstate = si_->allocState(); /* temp state */ bool foundgoal = false; while (_ptc == false) { /* sample random state (with goal biasing) */ if (goalSampleable && mRng.uniform01() < mGoalBias && goalSampleable->canSample()) goalSampleable->sampleGoal(rstate); else mSampler->sampleUniform(rstate); // Continue on invalid sample if (!si_->isValid(rstate)) { continue; } /* find closest state in the tree */ Motion *nmotion = mNN->nearest(rmotion); /* Perform a constrained extension */ double bestdist = std::numeric_limits<double>::infinity(); Motion *bestmotion = constrainedExtend(_ptc, nmotion, rmotion->state, xstate, goal, bestdist, foundgoal); if (foundgoal) { solution = bestmotion; break; } else if (bestdist < approxdif) { approxdif = bestdist; approxsol = bestmotion; } } bool solved = false; bool approximate = false; if (solution == nullptr) { solution = approxsol; approximate = true; } if (solution != nullptr) { mLastGoalMotion = solution; /* construct the solution path */ std::vector<Motion *> mpath; while (solution != nullptr) { mpath.push_back(solution); solution = solution->parent; } /* set the solution path */ ::ompl::geometric::PathGeometric *path = new ::ompl::geometric::PathGeometric(si_); for (int i = mpath.size() - 1; i >= 0; --i) path->append(mpath[i]->state); pdef_->addSolutionPath(::ompl::base::PathPtr(path), approximate, approxdif); solved = true; } si_->freeState(xstate); if (rmotion->state) si_->freeState(rmotion->state); delete rmotion; return ::ompl::base::PlannerStatus(solved, approximate); } //============================================================================= CRRT::Motion * CRRT::constrainedExtend(const ::ompl::base::PlannerTerminationCondition &ptc, Motion *nmotion, ::ompl::base::State *gstate, ::ompl::base::State *xstate, ::ompl::base::Goal *goal, double &dist, bool &foundgoal) { // Set up the current parent motion Motion *cmotion = nmotion; dist = std::numeric_limits<double>::infinity(); Motion *bestmotion = nmotion; // Compute the current and previous distance to the goal state double prevDistToTarget = std::numeric_limits<double>::infinity(); double distToTarget = si_->distance(cmotion->state, gstate); // TODO: Remove auto sspace = si_->getStateSpace()->as<GeometricStateSpace>()->getAikidoStateSpace(); // Loop while time remaining foundgoal = false; while (ptc == false) { if (distToTarget == 0 || std::fabs(distToTarget - prevDistToTarget) < 1e-6) { // reached target or not making progress break; } // Take a step towards the goal state si_->getStateSpace()->interpolate( cmotion->state, gstate, std::min(mMaxStepsize, distToTarget), xstate); if (mCons) { // Project the endpoint of the step auto xst = xstate->as<GeometricStateSpace::StateType>(); if (!mCons->project(xst->mState)) { // Can't project back to constraint anymore, return break; } } if (si_->checkMotion(cmotion->state, xstate)) { // Add the motion to the tree Motion *motion = new Motion(si_); si_->copyState(motion->state, xstate); motion->parent = cmotion; mNN->add(motion); cmotion = motion; double newdist = 0.0; bool satisfied = goal->isSatisfied(motion->state, &newdist); if (satisfied) { dist = newdist; bestmotion = motion; foundgoal = true; break; } if (newdist < dist) { dist = newdist; bestmotion = motion; } } else { // Extension failed validity check break; } prevDistToTarget = distToTarget; distToTarget = si_->distance(cmotion->state, gstate); } return bestmotion; } //============================================================================= ::ompl::base::PlannerStatus CRRT::solve(double solveTime) { return solve(::ompl::base::timedPlannerTerminationCondition( solveTime)); //, std::min(solveTime/100., 0.1))); } //============================================================================= double CRRT::distanceFunction(const Motion *a, const Motion *b) const { return si_->distance(a->state, b->state); } } } } <commit_msg>Fixing step in constrained extend.<commit_after>#include <aikido/planner/ompl/CRRT.hpp> #include <aikido/planner/ompl/GeometricStateSpace.hpp> #include <ompl/base/goals/GoalSampleableRegion.h> #include <ompl/tools/config/SelfConfig.h> #include <limits> namespace aikido { namespace planner { namespace ompl { //============================================================================= CRRT::CRRT(const ::ompl::base::SpaceInformationPtr &_si) : ::ompl::base::Planner(_si, "CRRT"), mCons(nullptr), mGoalBias(0.05), mMaxDistance(0.1), mLastGoalMotion(nullptr), mMaxStepsize(0.1) { auto ss = boost::dynamic_pointer_cast<GeometricStateSpace>(si_->getStateSpace()); if (!ss) { throw std::invalid_argument( "CRRT algorithm requires a GeometricStateSpace"); } specs_.approximateSolutions = true; specs_.directed = true; Planner::declareParam<double>("range", this, &CRRT::setRange, &CRRT::getRange, "0.:1.:10000."); Planner::declareParam<double>("goal_bias", this, &CRRT::setGoalBias, &CRRT::getGoalBias, "0.:.05:1."); Planner::declareParam<double>("proj_res", this, &CRRT::setProjectionResolution, &CRRT::getProjectionResolution, "0.:1.:10000."); } //============================================================================= CRRT::~CRRT(void) { freeMemory(); } //============================================================================= void CRRT::getPlannerData(::ompl::base::PlannerData &_data) const { ::ompl::base::Planner::getPlannerData(_data); std::vector<Motion *> motions; if (mNN) mNN->list(motions); if (mLastGoalMotion) _data.addGoalVertex( ::ompl::base::PlannerDataVertex(mLastGoalMotion->state)); for (unsigned int i = 0; i < motions.size(); ++i) { if (motions[i]->parent == nullptr) _data.addStartVertex(::ompl::base::PlannerDataVertex(motions[i]->state)); else _data.addEdge(::ompl::base::PlannerDataVertex(motions[i]->parent->state), ::ompl::base::PlannerDataVertex(motions[i]->state)); } } //============================================================================= void CRRT::clear(void) { ::ompl::base::Planner::clear(); mSampler.reset(); freeMemory(); if (mNN) mNN->clear(); mLastGoalMotion = nullptr; } //============================================================================= void CRRT::setGoalBias(double _goalBias) { if (_goalBias < 0.0 || _goalBias > 1.0) { std::stringstream ss; ss << "Invalid value for goal bias: " << _goalBias << ". Value must be between 0 and 1."; throw std::invalid_argument(ss.str()); } mGoalBias = _goalBias; } //============================================================================= double CRRT::getGoalBias() const { return mGoalBias; } //============================================================================= void CRRT::setRange(double _distance){ if (_distance < 0.0) { throw std::invalid_argument( "Distance must be positive on call to setRange."); } mMaxDistance = _distance; } //============================================================================= double CRRT::getRange() const { return mMaxDistance; } //============================================================================= void CRRT::setPathConstraint( constraint::ProjectablePtr _projectable) { mCons = std::move(_projectable); } //============================================================================= void CRRT::setProjectionResolution(double _resolution) { mMaxStepsize = _resolution; } //============================================================================= double CRRT::getProjectionResolution(void) const { return mMaxStepsize; } //============================================================================= void CRRT::setup(void) { ::ompl::base::Planner::setup(); ::ompl::tools::SelfConfig sc(si_, getName()); sc.configurePlannerRange(mMaxDistance); if (!mNN) mNN.reset(new ::ompl::NearestNeighborsGNAT<Motion *>); mNN->setDistanceFunction(boost::bind(&CRRT::distanceFunction, this, _1, _2)); } //============================================================================= void CRRT::freeMemory(void) { if (mNN) { std::vector<Motion *> motions; mNN->list(motions); for (unsigned int i = 0; i < motions.size(); ++i) { if (motions[i]->state) si_->freeState(motions[i]->state); delete motions[i]; } } } //============================================================================= ::ompl::base::PlannerStatus CRRT::solve(const ::ompl::base::PlannerTerminationCondition &_ptc) { checkValidity(); ::ompl::base::Goal *goal = pdef_->getGoal().get(); ::ompl::base::GoalSampleableRegion *goalSampleable = dynamic_cast<::ompl::base::GoalSampleableRegion *>(goal); while (const ::ompl::base::State *st = pis_.nextStart()) { Motion *motion = new Motion(si_); si_->copyState(motion->state, st); mNN->add(motion); } if (mNN->size() == 0) { return ::ompl::base::PlannerStatus::INVALID_START; } if (!mSampler) mSampler = si_->allocStateSampler(); Motion *solution = nullptr; Motion *approxsol = nullptr; double approxdif = std::numeric_limits<double>::infinity(); Motion *rmotion = new Motion(si_); ::ompl::base::State *rstate = rmotion->state; ::ompl::base::State *xstate = si_->allocState(); /* temp state */ bool foundgoal = false; while (_ptc == false) { /* sample random state (with goal biasing) */ if (goalSampleable && mRng.uniform01() < mGoalBias && goalSampleable->canSample()) goalSampleable->sampleGoal(rstate); else mSampler->sampleUniform(rstate); // Continue on invalid sample if (!si_->isValid(rstate)) { continue; } /* find closest state in the tree */ Motion *nmotion = mNN->nearest(rmotion); /* Perform a constrained extension */ double bestdist = std::numeric_limits<double>::infinity(); Motion *bestmotion = constrainedExtend(_ptc, nmotion, rmotion->state, xstate, goal, bestdist, foundgoal); if (foundgoal) { solution = bestmotion; break; } else if (bestdist < approxdif) { approxdif = bestdist; approxsol = bestmotion; } } bool solved = false; bool approximate = false; if (solution == nullptr) { solution = approxsol; approximate = true; } if (solution != nullptr) { mLastGoalMotion = solution; /* construct the solution path */ std::vector<Motion *> mpath; while (solution != nullptr) { mpath.push_back(solution); solution = solution->parent; } /* set the solution path */ ::ompl::geometric::PathGeometric *path = new ::ompl::geometric::PathGeometric(si_); for (int i = mpath.size() - 1; i >= 0; --i) path->append(mpath[i]->state); pdef_->addSolutionPath(::ompl::base::PathPtr(path), approximate, approxdif); solved = true; } si_->freeState(xstate); if (rmotion->state) si_->freeState(rmotion->state); delete rmotion; return ::ompl::base::PlannerStatus(solved, approximate); } //============================================================================= CRRT::Motion * CRRT::constrainedExtend(const ::ompl::base::PlannerTerminationCondition &ptc, Motion *nmotion, ::ompl::base::State *gstate, ::ompl::base::State *xstate, ::ompl::base::Goal *goal, double &dist, bool &foundgoal) { // Set up the current parent motion Motion *cmotion = nmotion; dist = std::numeric_limits<double>::infinity(); Motion *bestmotion = nmotion; // Compute the current and previous distance to the goal state double prevDistToTarget = std::numeric_limits<double>::infinity(); double distToTarget = si_->distance(cmotion->state, gstate); // Loop while time remaining foundgoal = false; while (ptc == false) { if (distToTarget == 0 || std::fabs(distToTarget - prevDistToTarget) < 1e-6) { // reached target or not making progress break; } // Take a step towards the goal state double stepLength = std::min(mMaxDistance, std::min(mMaxStepsize, distToTarget)); si_->getStateSpace()->interpolate( cmotion->state, gstate, stepLength / distToTarget, xstate); if (mCons) { // Project the endpoint of the step auto xst = xstate->as<GeometricStateSpace::StateType>(); if (!mCons->project(xst->mState)) { // Can't project back to constraint anymore, return break; } } if (si_->checkMotion(cmotion->state, xstate)) { // Add the motion to the tree Motion *motion = new Motion(si_); si_->copyState(motion->state, xstate); motion->parent = cmotion; mNN->add(motion); cmotion = motion; double newdist = 0.0; bool satisfied = goal->isSatisfied(motion->state, &newdist); if (satisfied) { dist = newdist; bestmotion = motion; foundgoal = true; break; } if (newdist < dist) { dist = newdist; bestmotion = motion; } } else { // Extension failed validity check break; } prevDistToTarget = distToTarget; distToTarget = si_->distance(cmotion->state, gstate); } return bestmotion; } //============================================================================= ::ompl::base::PlannerStatus CRRT::solve(double solveTime) { return solve(::ompl::base::timedPlannerTerminationCondition( solveTime)); //, std::min(solveTime/100., 0.1))); } //============================================================================= double CRRT::distanceFunction(const Motion *a, const Motion *b) const { return si_->distance(a->state, b->state); } } } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2004 by Stanislav Karchebny * * Stanislav.Karchebny@kdemail.net * * * * Licensed under GPL. * ***************************************************************************/ #include "akregator_part.h" #include "akregator_view.h" #include "akregatorconfig.h" #include <kparts/genericfactory.h> #include <kinstance.h> #include <kaction.h> #include <kactionclasses.h> #include <kstdaction.h> #include <kfiledialog.h> #include <qfile.h> using namespace Akregator; typedef KParts::GenericFactory< aKregatorPart > aKregatorFactory; K_EXPORT_COMPONENT_FACTORY( libakregatorpart, aKregatorFactory ) aKregatorPart::aKregatorPart( QWidget *parentWidget, const char * /*widgetName*/, QObject *parent, const char *name, const QStringList& ) : KParts::ReadWritePart(parent, name) { // we need an instance setInstance( aKregatorFactory::instance() ); m_view=new aKregatorView(this, parentWidget, "Akregator View"); // notify the part that this is our internal widget setWidget(m_view); // create our actions KStdAction::open(this, SLOT(fileOpen()), actionCollection()); KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection()); KStdAction::save(this, SLOT(save()), actionCollection()); new KAction(i18n("&Import Feeds"), "", "", this, SLOT(fileImport()), actionCollection(), "file_import"); /* -- ACTIONS */ /* --- Feed popup menu */ new KAction(i18n("&Add..."), "add", "Alt+Insert", m_view, SLOT(slotFeedAdd()), actionCollection(), "feed_add"); new KAction(i18n("Add &Folder..."), "add", "Alt+Shift+Insert", m_view, SLOT(slotFeedAddGroup()), actionCollection(), "feed_add_group"); new KAction(i18n("&Delete"), "delete", "Shift+Delete", m_view, SLOT(slotFeedRemove()), actionCollection(), "feed_remove"); new KAction(i18n("&Modify"), "edit", "F2", m_view, SLOT(slotFeedModify()), actionCollection(), "feed_modify"); new KAction(i18n("&Fetch"), "down", "Alt+Ctrl+F", m_view, SLOT(slotFetchCurrentFeed()), actionCollection(), "feed_fetch"); new KAction(i18n("Fe&tch All"), "bottom", "Alt+Ctrl+A", m_view, SLOT(slotFetchAllFeeds()), actionCollection(), "feed_fetch_all"); new KAction(i18n("Mark All As Read"), "", "Ctrl+R", m_view, SLOT(slotMarkAllRead()), actionCollection(), "feed_mark_all_as_read"); KRadioAction *ra=new KRadioAction(i18n("&Normal View"), "view_top_bottom", "Alt+Ctrl+1", m_view, SLOT(slotNormalView()), actionCollection(), "normal_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Widescreen View"), "view_left_right", "Alt+Ctrl+2", m_view, SLOT(slotWidescreenView()), actionCollection(), "widescreen_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Combined View"), "view_text", "Alt+Ctrl+3", m_view, SLOT(slotCombinedView()), actionCollection(), "combined_view"); ra->setExclusiveGroup( "ViewMode" ); // set our XML-UI resource file setXMLFile("akregator_part.rc"); // we are read-write by default setReadWrite(true); // we are not modified since we haven't done anything yet setModified(false); } aKregatorPart::~aKregatorPart() { Settings::writeConfig(); } void aKregatorPart::setReadWrite(bool rw) { ReadWritePart::setReadWrite(rw); } void aKregatorPart::setModified(bool modified) { // get a handle on our Save action and make sure it is valid KAction *save = actionCollection()->action(KStdAction::stdName(KStdAction::Save)); if (!save) return; // if so, we either enable or disable it based on the current // state if (modified) save->setEnabled(true); else save->setEnabled(false); // in any event, we want our parent to do it's thing ReadWritePart::setModified(modified); } void aKregatorPart::changePart(KParts::Part *p) { emit partChanged(p); } void aKregatorPart::setStatusBar(const QString &text) { emit setStatusBarText(text); } /*************************************************************************************************/ /* LOAD */ /*************************************************************************************************/ bool aKregatorPart::openFile() { // m_file is always local so we can use QFile on it QFile file(m_file); if (file.open(IO_ReadOnly) == false) return false; // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return false; if (!m_view->loadFeeds(doc)) // will take care of building feeds tree and loading archive return false; // just for fun, set the status bar setStatusBar( m_url.prettyURL() ); return true; } /*************************************************************************************************/ /* SAVE */ /*************************************************************************************************/ bool aKregatorPart::saveFile() { // if we aren't read-write, return immediately if (isReadWrite() == false) return false; // m_file is always local, so we use QFile QFile file(m_file); if (file.open(IO_WriteOnly) == false) return false; // use QTextStream to dump the text to the file QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // Write OPML data file. // Archive data files are saved elsewhere. QDomDocument newdoc; QDomElement root = newdoc.createElement( "opml" ); root.setAttribute( "version", "1.0" ); newdoc.appendChild( root ); QDomElement head = newdoc.createElement( "head" ); root.appendChild( head ); QDomElement title = newdoc.createElement( "text" ); head.appendChild( title ); QDomText t = newdoc.createTextNode( "aKregator Feeds" ); title.appendChild( t ); QDomElement body = newdoc.createElement( "body" ); root.appendChild( body ); m_view->writeChildNodes( 0, body, newdoc); stream << newdoc.toString(); file.close(); return true; } void aKregatorPart::importFile(QString file_name) { QFile file(file_name); if (file.open(IO_ReadOnly) == false) return; // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return; m_view->importFeeds(doc); } /*************************************************************************************************/ /* SLOTS */ /*************************************************************************************************/ void aKregatorPart::fileOpen() { // this slot is called whenever the File->Open menu is selected, // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar // button is clicked QString file_name = KFileDialog::getOpenFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) openURL(file_name); } void aKregatorPart::fileSaveAs() { // this slot is called whenever the File->Save As menu is selected, QString file_name = KFileDialog::getSaveFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) saveAs(file_name); } void aKregatorPart::fileImport() { QString file_name = KFileDialog::getOpenFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) importFile(file_name); } /*************************************************************************************************/ /* STATIC METHODS */ /*************************************************************************************************/ KAboutData* aKregatorPart::s_about = 0L; KAboutData *aKregatorPart::createAboutData() { if ( !s_about ) { s_about = new KAboutData("akregatorpart", I18N_NOOP("aKregatorPart"), "0.9", I18N_NOOP("This is a KPart for RSS aggregator"), KAboutData::License_GPL, "(C) 2004 Stanislav Karchebny", 0, "http://berk.upnet.ru/projects/kde/akregator", "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Stanislav Karchebny", I18N_NOOP("Author, Developer, Maintainer"), "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Sashmit Bhaduri", I18N_NOOP("Developer"), "smt@vfemail.net"); } return s_about; } #include "akregator_part.moc" <commit_msg>- When importing feeds, let the file dialog start in the directory into which kde.opml was installed.<commit_after>/*************************************************************************** * Copyright (C) 2004 by Stanislav Karchebny * * Stanislav.Karchebny@kdemail.net * * * * Licensed under GPL. * ***************************************************************************/ #include "akregator_part.h" #include "akregator_view.h" #include "akregatorconfig.h" #include <kparts/genericfactory.h> #include <kinstance.h> #include <kaction.h> #include <kactionclasses.h> #include <kstandarddirs.h> #include <kstdaction.h> #include <kfiledialog.h> #include <qfile.h> using namespace Akregator; typedef KParts::GenericFactory< aKregatorPart > aKregatorFactory; K_EXPORT_COMPONENT_FACTORY( libakregatorpart, aKregatorFactory ) aKregatorPart::aKregatorPart( QWidget *parentWidget, const char * /*widgetName*/, QObject *parent, const char *name, const QStringList& ) : KParts::ReadWritePart(parent, name) { // we need an instance setInstance( aKregatorFactory::instance() ); m_view=new aKregatorView(this, parentWidget, "Akregator View"); // notify the part that this is our internal widget setWidget(m_view); // create our actions KStdAction::open(this, SLOT(fileOpen()), actionCollection()); KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection()); KStdAction::save(this, SLOT(save()), actionCollection()); new KAction(i18n("&Import Feeds"), "", "", this, SLOT(fileImport()), actionCollection(), "file_import"); /* -- ACTIONS */ /* --- Feed popup menu */ new KAction(i18n("&Add..."), "add", "Alt+Insert", m_view, SLOT(slotFeedAdd()), actionCollection(), "feed_add"); new KAction(i18n("Add &Folder..."), "add", "Alt+Shift+Insert", m_view, SLOT(slotFeedAddGroup()), actionCollection(), "feed_add_group"); new KAction(i18n("&Delete"), "delete", "Shift+Delete", m_view, SLOT(slotFeedRemove()), actionCollection(), "feed_remove"); new KAction(i18n("&Modify"), "edit", "F2", m_view, SLOT(slotFeedModify()), actionCollection(), "feed_modify"); new KAction(i18n("&Fetch"), "down", "Alt+Ctrl+F", m_view, SLOT(slotFetchCurrentFeed()), actionCollection(), "feed_fetch"); new KAction(i18n("Fe&tch All"), "bottom", "Alt+Ctrl+A", m_view, SLOT(slotFetchAllFeeds()), actionCollection(), "feed_fetch_all"); new KAction(i18n("Mark All As Read"), "", "Ctrl+R", m_view, SLOT(slotMarkAllRead()), actionCollection(), "feed_mark_all_as_read"); KRadioAction *ra=new KRadioAction(i18n("&Normal View"), "view_top_bottom", "Alt+Ctrl+1", m_view, SLOT(slotNormalView()), actionCollection(), "normal_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Widescreen View"), "view_left_right", "Alt+Ctrl+2", m_view, SLOT(slotWidescreenView()), actionCollection(), "widescreen_view"); ra->setExclusiveGroup( "ViewMode" ); ra=new KRadioAction(i18n("&Combined View"), "view_text", "Alt+Ctrl+3", m_view, SLOT(slotCombinedView()), actionCollection(), "combined_view"); ra->setExclusiveGroup( "ViewMode" ); // set our XML-UI resource file setXMLFile("akregator_part.rc"); // we are read-write by default setReadWrite(true); // we are not modified since we haven't done anything yet setModified(false); } aKregatorPart::~aKregatorPart() { Settings::writeConfig(); } void aKregatorPart::setReadWrite(bool rw) { ReadWritePart::setReadWrite(rw); } void aKregatorPart::setModified(bool modified) { // get a handle on our Save action and make sure it is valid KAction *save = actionCollection()->action(KStdAction::stdName(KStdAction::Save)); if (!save) return; // if so, we either enable or disable it based on the current // state if (modified) save->setEnabled(true); else save->setEnabled(false); // in any event, we want our parent to do it's thing ReadWritePart::setModified(modified); } void aKregatorPart::changePart(KParts::Part *p) { emit partChanged(p); } void aKregatorPart::setStatusBar(const QString &text) { emit setStatusBarText(text); } /*************************************************************************************************/ /* LOAD */ /*************************************************************************************************/ bool aKregatorPart::openFile() { // m_file is always local so we can use QFile on it QFile file(m_file); if (file.open(IO_ReadOnly) == false) return false; // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return false; if (!m_view->loadFeeds(doc)) // will take care of building feeds tree and loading archive return false; // just for fun, set the status bar setStatusBar( m_url.prettyURL() ); return true; } /*************************************************************************************************/ /* SAVE */ /*************************************************************************************************/ bool aKregatorPart::saveFile() { // if we aren't read-write, return immediately if (isReadWrite() == false) return false; // m_file is always local, so we use QFile QFile file(m_file); if (file.open(IO_WriteOnly) == false) return false; // use QTextStream to dump the text to the file QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // Write OPML data file. // Archive data files are saved elsewhere. QDomDocument newdoc; QDomElement root = newdoc.createElement( "opml" ); root.setAttribute( "version", "1.0" ); newdoc.appendChild( root ); QDomElement head = newdoc.createElement( "head" ); root.appendChild( head ); QDomElement title = newdoc.createElement( "text" ); head.appendChild( title ); QDomText t = newdoc.createTextNode( "aKregator Feeds" ); title.appendChild( t ); QDomElement body = newdoc.createElement( "body" ); root.appendChild( body ); m_view->writeChildNodes( 0, body, newdoc); stream << newdoc.toString(); file.close(); return true; } void aKregatorPart::importFile(QString file_name) { QFile file(file_name); if (file.open(IO_ReadOnly) == false) return; // Read OPML feeds list and build QDom tree. QTextStream stream(&file); stream.setEncoding(QTextStream::UnicodeUTF8); // FIXME not all opmls are in utf8 QDomDocument doc; QString str; str = stream.read(); file.close(); if (!doc.setContent(str)) return; m_view->importFeeds(doc); } /*************************************************************************************************/ /* SLOTS */ /*************************************************************************************************/ void aKregatorPart::fileOpen() { // this slot is called whenever the File->Open menu is selected, // the Open shortcut is pressed (usually CTRL+O) or the Open toolbar // button is clicked QString file_name = KFileDialog::getOpenFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) openURL(file_name); } void aKregatorPart::fileSaveAs() { // this slot is called whenever the File->Save As menu is selected, QString file_name = KFileDialog::getSaveFileName( QString::null, "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) saveAs(file_name); } void aKregatorPart::fileImport() { QString file_name = KFileDialog::getOpenFileName( locate( "appdata", "kde.opml" ), "*.opml *.xml|" + i18n("OPML Outlines (*.opml, *.xml)") +"\n*|" + i18n("All Files") ); if (file_name.isEmpty() == false) importFile(file_name); } /*************************************************************************************************/ /* STATIC METHODS */ /*************************************************************************************************/ KAboutData* aKregatorPart::s_about = 0L; KAboutData *aKregatorPart::createAboutData() { if ( !s_about ) { s_about = new KAboutData("akregatorpart", I18N_NOOP("aKregatorPart"), "0.9", I18N_NOOP("This is a KPart for RSS aggregator"), KAboutData::License_GPL, "(C) 2004 Stanislav Karchebny", 0, "http://berk.upnet.ru/projects/kde/akregator", "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Stanislav Karchebny", I18N_NOOP("Author, Developer, Maintainer"), "Stanislav.Karchebny@kdemail.net"); s_about->addAuthor("Sashmit Bhaduri", I18N_NOOP("Developer"), "smt@vfemail.net"); } return s_about; } #include "akregator_part.moc" <|endoftext|>
<commit_before>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cstdlib> #include <iostream> #include <fstream> #include <algorithm> #include "hal.h" using namespace std; using namespace hal; /** This is a tool that counts the number of other genomes each base in * a query region is aligned to. * * Coordinates are always genome-relative by default (as opposed to * sequence-relative). The one exception is all methods within the * Sequence interface. * * By default, all bases in the referecen genome are scanned. And all * other genomes are considered. The --refSequence, --start, and * --length options can limit the query to a subrange. Note that unless * --refSequence is specified, --start is genome-relative (based on * all sequences being concatenated together). * * Other genomes to query (default all) are controlled by --rootGenome * (name of highest ancestor to consider) and/or --targetGenomes * (a list of genomes to consider). * * So if a base in the reference genome is aligned to a base in a genome * that is not under root or in the target list, it will not count to the * alignability. */ /** Print the alignability wiggle for a subrange of a given sequence to * the output stream. */ static void printSequence(ostream& outStream, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes); /** If given genome-relative coordinates, map them to a series of * sequence subranges */ static void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes); static const hal_size_t StringBufferSize = 1024; static CLParserPtr initParser() { /** It is convenient to use the HAL command line parser for the command * line because it automatically adds some comman options. Using the * parser is by no means required however */ CLParserPtr optionsParser = hdf5CLParserInstance(false); optionsParser->addArgument("halPath", "input hal file"); optionsParser->addArgument("refGenome", "reference genome to scan"); optionsParser->addOption("outWiggle", "output wig file (stdout if none)", "stdout"); optionsParser->addOption("refSequence", "sequence name to export (" "all sequences by default)", "\"\""); optionsParser->addOption("start", "coordinate within reference genome (or sequence" " if specified) to start at", 0); optionsParser->addOption("length", "length of the reference genome (or sequence" " if specified) to convert. If set to 0," " the entire thing is converted", 0); optionsParser->addOption("rootGenome", "name of root genome (none if empty)", "\"\""); optionsParser->addOption("targetGenomes", "comma-separated (no spaces) list of target genomes " "(others are excluded) (vist all if empty)", "\"\""); optionsParser->addOptionFlag("countDupes", "count each other *position* each base aligns " "to, rather than the number of unique genomes, " "including paralogies so a genome can be " "counted multiple times. This will give the " "height of the MAF column created with hal2maf.", false); optionsParser->addOption("step", "step size", 1); optionsParser->setDescription("Make alignability wiggle plot for a genome. By default, this is a count of the number of other unique genomes each base aligns to."); return optionsParser; } int main(int argc, char** argv) { CLParserPtr optionsParser = initParser(); string halPath; string wigPath; string refGenomeName; string rootGenomeName; string targetGenomes; string refSequenceName; hal_size_t start; hal_size_t length; hal_size_t step; bool countDupes; try { optionsParser->parseOptions(argc, argv); halPath = optionsParser->getArgument<string>("halPath"); refGenomeName = optionsParser->getArgument<string>("refGenome"); wigPath = optionsParser->getOption<string>("outWiggle"); refSequenceName = optionsParser->getOption<string>("refSequence"); start = optionsParser->getOption<hal_size_t>("start"); length = optionsParser->getOption<hal_size_t>("length"); rootGenomeName = optionsParser->getOption<string>("rootGenome"); targetGenomes = optionsParser->getOption<string>("targetGenomes"); step = optionsParser->getOption<hal_size_t>("step"); countDupes = optionsParser->getFlag("countDupes"); if (rootGenomeName != "\"\"" && targetGenomes != "\"\"") { throw hal_exception("--rootGenome and --targetGenomes options are " " mutually exclusive"); } } catch(exception& e) { cerr << e.what() << endl; optionsParser->printUsage(cerr); exit(1); } try { /** Everything begins with the alignment object, which is created * via a path to a .hal file. Options don't necessarily need to * come from the optionsParser -- see other interfaces in * hal/api/inc/halAlignmentInstance.h */ AlignmentConstPtr alignment = openHalAlignmentReadOnly(halPath, optionsParser); if (alignment->getNumGenomes() == 0) { throw hal_exception("input hal alignmenet is empty"); } /** Alignments are composed of sets of Genomes. Each genome is a set * of Sequences (chromosomes). They are accessed by their names. * here we map the root and targetSet parameters (if specifeid) to * a sset of readonly Genome pointers */ set<const Genome*> targetSet; const Genome* rootGenome = NULL; if (rootGenomeName != "\"\"") { rootGenome = alignment->openGenome(rootGenomeName); if (rootGenome == NULL) { throw hal_exception(string("Root genome, ") + rootGenomeName + ", not found in alignment"); } if (rootGenomeName != alignment->getRootName()) { getGenomesInSubTree(rootGenome, targetSet); } } if (targetGenomes != "\"\"") { vector<string> targetNames = chopString(targetGenomes, ","); for (size_t i = 0; i < targetNames.size(); ++i) { const Genome* tgtGenome = alignment->openGenome(targetNames[i]); if (tgtGenome == NULL) { throw hal_exception(string("Target genome, ") + targetNames[i] + ", not found in alignment"); } targetSet.insert(tgtGenome); } } /** Open the reference genome */ const Genome* refGenome = NULL; if (refGenomeName != "\"\"") { refGenome = alignment->openGenome(refGenomeName); if (refGenome == NULL) { throw hal_exception(string("Reference genome, ") + refGenomeName + ", not found in alignment"); } } else { refGenome = alignment->openGenome(alignment->getRootName()); } const SegmentedSequence* ref = refGenome; /** If a sequence was spefied we look for it in the reference genome */ const Sequence* refSequence = NULL; if (refSequenceName != "\"\"") { refSequence = refGenome->getSequence(refSequenceName); ref = refSequence; if (refSequence == NULL) { throw hal_exception(string("Reference sequence, ") + refSequenceName + ", not found in reference genome, " + refGenome->getName()); } } ofstream ofile; ostream& outStream = wigPath == "stdout" ? cout : ofile; if (wigPath != "stdout") { ofile.open(wigPath.c_str()); if (!ofile) { throw hal_exception(string("Error opening output file ") + wigPath); } } printGenome(outStream, refGenome, refSequence, targetSet, start, length, step, countDupes); } catch(hal_exception& e) { cerr << "hal exception caught: " << e.what() << endl; return 1; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return 1; } return 0; } /** Given a Sequence (chromosome) and a (sequence-relative) coordinate * range, print the alignmability wiggle with respect to the genomes * in the target set */ void printSequence(ostream& outStream, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes) { hal_size_t seqLen = sequence->getSequenceLength(); if (seqLen == 0) { return; } /** If the length is 0, we do from the start position until the end * of the sequence */ if (length == 0) { length = seqLen - start; } hal_size_t last = start + length; if (last > seqLen) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for sequence " << sequence->getName() << ", which has length " << seqLen; throw (hal_exception(ss.str())); } const Genome* genome = sequence->getGenome(); string sequenceName = sequence->getName(); string genomeName = genome->getName(); /** The ColumnIterator is fundamental structure used in this example to * traverse the alignment. It essientially generates the multiple alignment * on the fly according to the given reference (in this case the target * sequence). Since this is the sequence interface, the positions * are sequence relative. Note that we must specify the last position * in advance when we get the iterator. This will limit it following * duplications out of the desired range while we are iterating. */ hal_size_t pos = start; ColumnIteratorConstPtr colIt = sequence->getColumnIterator(&targetSet, 0, pos, last - 1, false); // note wig coordinates are 1-based for some reason so we shift to right outStream << "fixedStep chrom=" << sequenceName << " start=" << start + 1 << " step=" << step << "\n"; /** Since the column iterator stores coordinates in Genome coordinates * internally, we have to switch back to genome coordinates. */ // convert to genome coordinates pos += sequence->getStartPosition(); last += sequence->getStartPosition(); // keep track of unique genomes set<const Genome*> genomeSet; while (pos <= last) { genomeSet.clear(); hal_size_t count = 0; /** ColumnIterator::ColumnMap maps a Sequence to a list of bases * the bases in the map form the alignment column. Some sequences * in the map can have no bases (for efficiency reasons) */ const ColumnIterator::ColumnMap* cmap = colIt->getColumnMap(); /** For every sequence in the map */ for (ColumnIterator::ColumnMap::const_iterator i = cmap->begin(); i != cmap->end(); ++i) { if (countDupes == true) { // countDupes enabled: we just count everything count += i->second->size(); } else if (!i->second->empty()) { // just counting unique genomes: add it if there's at least one base genomeSet.insert(i->first->getGenome()); } } if (countDupes == false) { count = genomeSet.size(); } // don't want to include reference base in output --count; outStream << count << '\n'; /** lastColumn checks if we are at the last column (inclusive) * in range. So we need to check at end of iteration instead * of beginning (which would be more convenient). Need to * merge global fix from other branch */ if (colIt->lastColumn() == true) { break; } pos += step; if (step == 1) { /** Move the iterator one position to the right */ colIt->toRight(); /** This is some tuning code that will probably be hidden from * the interface at some point. It is a good idea to use for now * though */ // erase empty entries from the column. helps when there are // millions of sequences (ie from fastas with lots of scaffolds) if (pos % 1000 == 0) { colIt->defragment(); } } else { /** Reset the iterator to a non-contiguous position */ colIt->toSite(pos, last); } } } /** Map a range of genome-level coordinates to potentially multiple sequence * ranges. For example, if a genome contains two chromosomes ChrA and ChrB, * both of which are of length 500, then the genome-coordinates would be * [0,499] for ChrA and [500,999] for ChrB. All aspects of the HAL API * use these global coordinates (chromosomes concatenated together) except * for the hal::Sequence interface. We can convert between the two by * adding or subtracting the sequence start position (in the example it woudl * be 0 for ChrA and 500 for ChrB) */ void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes) { if (sequence != NULL) { printSequence(outStream, sequence, targetSet, start, length, step, countDupes); } else { if (start + length > genome->getSequenceLength()) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for genome " << genome->getName() << ", which has length " << genome->getSequenceLength(); throw (hal_exception(ss.str())); } if (length == 0) { length = genome->getSequenceLength() - start; } SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEndIt = genome->getSequenceEndIterator(); hal_size_t runningLength = 0; for (; seqIt != seqEndIt; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); hal_size_t seqLen = sequence->getSequenceLength(); hal_size_t seqStart = (hal_size_t)sequence->getStartPosition(); if (start + length >= seqStart && start < seqStart + seqLen && runningLength < length) { hal_size_t readStart = seqStart >= start ? 0 : start - seqStart; hal_size_t readLen = min(seqLen - readStart, length); readLen = min(readLen, length - runningLength); printSequence(outStream, sequence, targetSet, readStart, readLen, step, countDupes); runningLength += readLen; } } } } <commit_msg>add noAncestors option to halAlignability<commit_after>/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <cstdlib> #include <iostream> #include <fstream> #include <algorithm> #include "hal.h" using namespace std; using namespace hal; /** This is a tool that counts the number of other genomes each base in * a query region is aligned to. * * Coordinates are always genome-relative by default (as opposed to * sequence-relative). The one exception is all methods within the * Sequence interface. * * By default, all bases in the referecen genome are scanned. And all * other genomes are considered. The --refSequence, --start, and * --length options can limit the query to a subrange. Note that unless * --refSequence is specified, --start is genome-relative (based on * all sequences being concatenated together). * * Other genomes to query (default all) are controlled by --rootGenome * (name of highest ancestor to consider) and/or --targetGenomes * (a list of genomes to consider). * * So if a base in the reference genome is aligned to a base in a genome * that is not under root or in the target list, it will not count to the * alignability. */ /** Print the alignability wiggle for a subrange of a given sequence to * the output stream. */ static void printSequence(ostream& outStream, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes, bool noAncestors); /** If given genome-relative coordinates, map them to a series of * sequence subranges */ static void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes, bool noAncestors); static const hal_size_t StringBufferSize = 1024; static CLParserPtr initParser() { /** It is convenient to use the HAL command line parser for the command * line because it automatically adds some comman options. Using the * parser is by no means required however */ CLParserPtr optionsParser = hdf5CLParserInstance(false); optionsParser->addArgument("halPath", "input hal file"); optionsParser->addArgument("refGenome", "reference genome to scan"); optionsParser->addOption("outWiggle", "output wig file (stdout if none)", "stdout"); optionsParser->addOption("refSequence", "sequence name to export (" "all sequences by default)", "\"\""); optionsParser->addOption("start", "coordinate within reference genome (or sequence" " if specified) to start at", 0); optionsParser->addOption("length", "length of the reference genome (or sequence" " if specified) to convert. If set to 0," " the entire thing is converted", 0); optionsParser->addOption("rootGenome", "name of root genome (none if empty)", "\"\""); optionsParser->addOption("targetGenomes", "comma-separated (no spaces) list of target genomes " "(others are excluded) (vist all if empty)", "\"\""); optionsParser->addOption("step", "step size", 1); optionsParser->addOptionFlag("countDupes", "count each other *position* each base aligns " "to, rather than the number of unique genomes, " "including paralogies so a genome can be " "counted multiple times. This will give the " "height of the MAF column created with hal2maf.", false); optionsParser->addOptionFlag("noAncestors", "do not count ancestral genomes.", false); optionsParser->setDescription("Make alignability wiggle plot for a genome. " "By default, this is a count of the number of " "other unique genomes each base aligns to, " "including ancestral genomes."); return optionsParser; } int main(int argc, char** argv) { CLParserPtr optionsParser = initParser(); string halPath; string wigPath; string refGenomeName; string rootGenomeName; string targetGenomes; string refSequenceName; hal_size_t start; hal_size_t length; hal_size_t step; bool countDupes; bool noAncestors; try { optionsParser->parseOptions(argc, argv); halPath = optionsParser->getArgument<string>("halPath"); refGenomeName = optionsParser->getArgument<string>("refGenome"); wigPath = optionsParser->getOption<string>("outWiggle"); refSequenceName = optionsParser->getOption<string>("refSequence"); start = optionsParser->getOption<hal_size_t>("start"); length = optionsParser->getOption<hal_size_t>("length"); rootGenomeName = optionsParser->getOption<string>("rootGenome"); targetGenomes = optionsParser->getOption<string>("targetGenomes"); step = optionsParser->getOption<hal_size_t>("step"); countDupes = optionsParser->getFlag("countDupes"); noAncestors = optionsParser->getFlag("noAncestors"); if (rootGenomeName != "\"\"" && targetGenomes != "\"\"") { throw hal_exception("--rootGenome and --targetGenomes options are " " mutually exclusive"); } } catch(exception& e) { cerr << e.what() << endl; optionsParser->printUsage(cerr); exit(1); } try { /** Everything begins with the alignment object, which is created * via a path to a .hal file. Options don't necessarily need to * come from the optionsParser -- see other interfaces in * hal/api/inc/halAlignmentInstance.h */ AlignmentConstPtr alignment = openHalAlignmentReadOnly(halPath, optionsParser); if (alignment->getNumGenomes() == 0) { throw hal_exception("input hal alignmenet is empty"); } /** Alignments are composed of sets of Genomes. Each genome is a set * of Sequences (chromosomes). They are accessed by their names. * here we map the root and targetSet parameters (if specifeid) to * a sset of readonly Genome pointers */ set<const Genome*> targetSet; const Genome* rootGenome = NULL; if (rootGenomeName != "\"\"") { rootGenome = alignment->openGenome(rootGenomeName); if (rootGenome == NULL) { throw hal_exception(string("Root genome, ") + rootGenomeName + ", not found in alignment"); } if (rootGenomeName != alignment->getRootName()) { getGenomesInSubTree(rootGenome, targetSet); } } if (targetGenomes != "\"\"") { vector<string> targetNames = chopString(targetGenomes, ","); for (size_t i = 0; i < targetNames.size(); ++i) { const Genome* tgtGenome = alignment->openGenome(targetNames[i]); if (tgtGenome == NULL) { throw hal_exception(string("Target genome, ") + targetNames[i] + ", not found in alignment"); } targetSet.insert(tgtGenome); } } /** Open the reference genome */ const Genome* refGenome = NULL; if (refGenomeName != "\"\"") { refGenome = alignment->openGenome(refGenomeName); if (refGenome == NULL) { throw hal_exception(string("Reference genome, ") + refGenomeName + ", not found in alignment"); } } else { refGenome = alignment->openGenome(alignment->getRootName()); } const SegmentedSequence* ref = refGenome; /** If a sequence was spefied we look for it in the reference genome */ const Sequence* refSequence = NULL; if (refSequenceName != "\"\"") { refSequence = refGenome->getSequence(refSequenceName); ref = refSequence; if (refSequence == NULL) { throw hal_exception(string("Reference sequence, ") + refSequenceName + ", not found in reference genome, " + refGenome->getName()); } } if (refGenome->getNumChildren() != 0 && noAncestors == true) { throw hal_exception(string("--noAncestors cannot be used when reference " "genome (") + refGenome->getName() + string(") is ancetral")); } ofstream ofile; ostream& outStream = wigPath == "stdout" ? cout : ofile; if (wigPath != "stdout") { ofile.open(wigPath.c_str()); if (!ofile) { throw hal_exception(string("Error opening output file ") + wigPath); } } printGenome(outStream, refGenome, refSequence, targetSet, start, length, step, countDupes, noAncestors); } catch(hal_exception& e) { cerr << "hal exception caught: " << e.what() << endl; return 1; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return 1; } return 0; } /** Given a Sequence (chromosome) and a (sequence-relative) coordinate * range, print the alignmability wiggle with respect to the genomes * in the target set */ void printSequence(ostream& outStream, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes, bool noAncestors) { hal_size_t seqLen = sequence->getSequenceLength(); if (seqLen == 0) { return; } /** If the length is 0, we do from the start position until the end * of the sequence */ if (length == 0) { length = seqLen - start; } hal_size_t last = start + length; if (last > seqLen) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for sequence " << sequence->getName() << ", which has length " << seqLen; throw (hal_exception(ss.str())); } const Genome* genome = sequence->getGenome(); string sequenceName = sequence->getName(); string genomeName = genome->getName(); /** The ColumnIterator is fundamental structure used in this example to * traverse the alignment. It essientially generates the multiple alignment * on the fly according to the given reference (in this case the target * sequence). Since this is the sequence interface, the positions * are sequence relative. Note that we must specify the last position * in advance when we get the iterator. This will limit it following * duplications out of the desired range while we are iterating. */ hal_size_t pos = start; ColumnIteratorConstPtr colIt = sequence->getColumnIterator(&targetSet, 0, pos, last - 1, false, noAncestors); // note wig coordinates are 1-based for some reason so we shift to right outStream << "fixedStep chrom=" << sequenceName << " start=" << start + 1 << " step=" << step << "\n"; /** Since the column iterator stores coordinates in Genome coordinates * internally, we have to switch back to genome coordinates. */ // convert to genome coordinates pos += sequence->getStartPosition(); last += sequence->getStartPosition(); // keep track of unique genomes set<const Genome*> genomeSet; while (pos <= last) { genomeSet.clear(); hal_size_t count = 0; /** ColumnIterator::ColumnMap maps a Sequence to a list of bases * the bases in the map form the alignment column. Some sequences * in the map can have no bases (for efficiency reasons) */ const ColumnIterator::ColumnMap* cmap = colIt->getColumnMap(); /** For every sequence in the map */ for (ColumnIterator::ColumnMap::const_iterator i = cmap->begin(); i != cmap->end(); ++i) { if (countDupes == true) { // countDupes enabled: we just count everything count += i->second->size(); } else if (!i->second->empty()) { // just counting unique genomes: add it if there's at least one base genomeSet.insert(i->first->getGenome()); } } if (countDupes == false) { count = genomeSet.size(); } // don't want to include reference base in output --count; outStream << count << '\n'; /** lastColumn checks if we are at the last column (inclusive) * in range. So we need to check at end of iteration instead * of beginning (which would be more convenient). Need to * merge global fix from other branch */ if (colIt->lastColumn() == true) { break; } pos += step; if (step == 1) { /** Move the iterator one position to the right */ colIt->toRight(); /** This is some tuning code that will probably be hidden from * the interface at some point. It is a good idea to use for now * though */ // erase empty entries from the column. helps when there are // millions of sequences (ie from fastas with lots of scaffolds) if (pos % 1000 == 0) { colIt->defragment(); } } else { /** Reset the iterator to a non-contiguous position */ colIt->toSite(pos, last); } } } /** Map a range of genome-level coordinates to potentially multiple sequence * ranges. For example, if a genome contains two chromosomes ChrA and ChrB, * both of which are of length 500, then the genome-coordinates would be * [0,499] for ChrA and [500,999] for ChrB. All aspects of the HAL API * use these global coordinates (chromosomes concatenated together) except * for the hal::Sequence interface. We can convert between the two by * adding or subtracting the sequence start position (in the example it woudl * be 0 for ChrA and 500 for ChrB) */ void printGenome(ostream& outStream, const Genome* genome, const Sequence* sequence, const set<const Genome*>& targetSet, hal_size_t start, hal_size_t length, hal_size_t step, bool countDupes, bool noAncestors) { if (sequence != NULL) { printSequence(outStream, sequence, targetSet, start, length, step, countDupes, noAncestors); } else { if (start + length > genome->getSequenceLength()) { stringstream ss; ss << "Specified range [" << start << "," << length << "] is" << "out of range for genome " << genome->getName() << ", which has length " << genome->getSequenceLength(); throw (hal_exception(ss.str())); } if (length == 0) { length = genome->getSequenceLength() - start; } SequenceIteratorConstPtr seqIt = genome->getSequenceIterator(); SequenceIteratorConstPtr seqEndIt = genome->getSequenceEndIterator(); hal_size_t runningLength = 0; for (; seqIt != seqEndIt; seqIt->toNext()) { const Sequence* sequence = seqIt->getSequence(); hal_size_t seqLen = sequence->getSequenceLength(); hal_size_t seqStart = (hal_size_t)sequence->getStartPosition(); if (start + length >= seqStart && start < seqStart + seqLen && runningLength < length) { hal_size_t readStart = seqStart >= start ? 0 : start - seqStart; hal_size_t readLen = min(seqLen - readStart, length); readLen = min(readLen, length - runningLength); printSequence(outStream, sequence, targetSet, readStart, readLen, step, countDupes, noAncestors); runningLength += readLen; } } } } <|endoftext|>
<commit_before>/* * * * * * * * * * * * *\ |* ╔═╗ v0.3 *| |* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *| |* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *| |* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *| |* * * * * * * * * ╚═╝ * *| |* Manipulation tool for *| |* ESRI Shapefiles *| |* * * * * * * * * * * * *| |* http://www.npolar.no/ *| \* * * * * * * * * * * * */ #include "handler.hpp" namespace reshp { void handler::list(const std::string& shapefile, const bool full) { reshp::shp shp; if(!shp.load(shapefile)) return; printf("Filename: %s\n", shapefile.c_str()); printf("Version: %i\n", shp.header.version); printf("Type: %s\n", shp::typestr(shp.header.type)); printf("Bounding: [%.4f, %.4f] [%.4f, %.4f]\n", shp.header.box[0], shp.header.box[1], shp.header.box[2], shp.header.box[3]); printf("Records: %lu\n\n", shp.records.size()); for(unsigned i = 0; i < shp.records.size(); ++i) { const char* type = shp::typestr(shp.records[i].type); printf(" record %05i (%s)", shp.records[i].number, type); int32_t points = 0, rings = 0; if(shp.records[i].polygon) { rings = shp.records[i].polygon->num_parts; points = shp.records[i].polygon->num_points; } if(points) printf(":%*s%5i point%c", int(13 - strlen(type)), " ", points, (points == 1 ? ' ' : 's')); if(rings) printf(", %5i ring%c", rings, (rings == 1 ? ' ' : 's')); printf("\n"); if(full) { int32_t rpoints[rings]; for(int32_t r = 0; r < rings; ++r) rpoints[r] = shp.records[i].polygon->parts[r]; for(int32_t p = 0; p < points; ++p) { for(int32_t r = 0; r < rings; ++r) if(rpoints[r] == p) printf(" ring %i:\n", r); printf(" [%.4f, %.4f]\n", shp.records[i].polygon->points[p].x, shp.records[i].polygon->points[p].y); } } } } } <commit_msg>Added polygon ring-type output to list-full method<commit_after>/* * * * * * * * * * * * *\ |* ╔═╗ v0.3 *| |* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *| |* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *| |* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *| |* * * * * * * * * ╚═╝ * *| |* Manipulation tool for *| |* ESRI Shapefiles *| |* * * * * * * * * * * * *| |* http://www.npolar.no/ *| \* * * * * * * * * * * * */ #include "handler.hpp" #include "polygon.hpp" #include <vector> namespace reshp { void handler::list(const std::string& shapefile, const bool full) { reshp::shp shp; if(!shp.load(shapefile)) return; printf("Filename: %s\n", shapefile.c_str()); printf("Version: %i\n", shp.header.version); printf("Type: %s\n", shp::typestr(shp.header.type)); printf("Bounding: [%.4f, %.4f] [%.4f, %.4f]\n", shp.header.box[0], shp.header.box[1], shp.header.box[2], shp.header.box[3]); printf("Records: %lu\n\n", shp.records.size()); for(unsigned i = 0; i < shp.records.size(); ++i) { const char* type = shp::typestr(shp.records[i].type); printf(" record %05i (%s)", shp.records[i].number, type); int32_t points = 0, rings = 0; if(shp.records[i].polygon) { rings = shp.records[i].polygon->num_parts; points = shp.records[i].polygon->num_points; } if(points) printf(":%*s%5i point%c", int(13 - strlen(type)), " ", points, (points == 1 ? ' ' : 's')); if(rings) printf(", %5i ring%c", rings, (rings == 1 ? ' ' : 's')); printf("\n"); if(full) { if(shp.records[i].polygon) { reshp::polygon poly(*shp.records[i].polygon); for(unsigned r = 0; r < poly.rings.size(); ++r) { printf(" ring %i (%s):\n", r, (poly.rings[r].type == reshp::polygon::ring::inner ? "inner" : "outer")); for(unsigned p = 0; p < poly.rings[r].points.size(); ++p) { printf(" [%.4f, %.4f]\n", poly.rings[r].points[p].x, poly.rings[r].points[p].y); } } } } } // records } // handler::list() } // namespace reshp <|endoftext|>
<commit_before>#ifndef __LUA_RAPIDJSION_LUACOMPAT_H__ #define __LUA_RAPIDJSION_LUACOMPAT_H__ #include <cmath> #include <lua.hpp> namespace luax { inline void setfuncs(lua_State* L, const luaL_Reg* funcs) { #if LUA_VERSION_NUM >= 502 // LUA 5.2 or above luaL_setfuncs(L, funcs, 0); #else luaL_register(L, NULL, funcs); #endif } inline size_t rawlen(lua_State* L, int idx) { #if LUA_VERSION_NUM >= 502 return lua_rawlen(L, idx); #else return lua_objlen(L, idx); #endif } inline bool isinteger(lua_State* L, int idx, int64_t* out = NULL) { #if LUA_VERSION_NUM >= 503 if (lua_isinteger(L, idx)) // but it maybe not detect all integers. { if (out) *out = lua_tointeger(L, idx); return true; } #endif double intpart; if (std::modf(lua_tonumber(L, idx), &intpart) == 0.0) { if (std::numeric_limits<lua_Integer>::min() <= intpart && intpart <= std::numeric_limits<lua_Integer>::max()) { if (out) *out = static_cast<int64_t>(intpart); return true; } } return false; } inline int typerror(lua_State* L, int narg, const char* tname) { #if LUA_VERSION_NUM < 502 return luaL_typerror(L, narg, tname); #else const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, luaL_typename(L, narg)); return luaL_argerror(L, narg, msg); #endif } static bool optboolfield(lua_State* L, int idx, const char* name, bool def) { auto v = def; auto t = lua_type(L, idx); if (t != LUA_TTABLE && t != LUA_TNONE) luax::typerror(L, idx, "table"); if (t != LUA_TNONE) { lua_getfield(L, idx, name); // [field] if (!lua_isnoneornil(L, -1)) v = lua_toboolean(L, -1) != 0;; lua_pop(L, 1); } return v; } static int optintfield(lua_State* L, int idx, const char* name, int def) { auto v = def; lua_getfield(L, idx, name); // [field] if (lua_isnumber(L, -1)) v = static_cast<int>(lua_tointeger(L, -1)); lua_pop(L, 1); return v; } } #endif // __LUA_RAPIDJSION_LUACOMPAT_H__ <commit_msg>should be inline in header.<commit_after>#ifndef __LUA_RAPIDJSION_LUACOMPAT_H__ #define __LUA_RAPIDJSION_LUACOMPAT_H__ #include <cmath> #include <lua.hpp> namespace luax { inline void setfuncs(lua_State* L, const luaL_Reg* funcs) { #if LUA_VERSION_NUM >= 502 // LUA 5.2 or above luaL_setfuncs(L, funcs, 0); #else luaL_register(L, NULL, funcs); #endif } inline size_t rawlen(lua_State* L, int idx) { #if LUA_VERSION_NUM >= 502 return lua_rawlen(L, idx); #else return lua_objlen(L, idx); #endif } inline bool isinteger(lua_State* L, int idx, int64_t* out = NULL) { #if LUA_VERSION_NUM >= 503 if (lua_isinteger(L, idx)) // but it maybe not detect all integers. { if (out) *out = lua_tointeger(L, idx); return true; } #endif double intpart; if (std::modf(lua_tonumber(L, idx), &intpart) == 0.0) { if (std::numeric_limits<lua_Integer>::min() <= intpart && intpart <= std::numeric_limits<lua_Integer>::max()) { if (out) *out = static_cast<int64_t>(intpart); return true; } } return false; } inline int typerror(lua_State* L, int narg, const char* tname) { #if LUA_VERSION_NUM < 502 return luaL_typerror(L, narg, tname); #else const char *msg = lua_pushfstring(L, "%s expected, got %s", tname, luaL_typename(L, narg)); return luaL_argerror(L, narg, msg); #endif } inline bool optboolfield(lua_State* L, int idx, const char* name, bool def) { auto v = def; auto t = lua_type(L, idx); if (t != LUA_TTABLE && t != LUA_TNONE) luax::typerror(L, idx, "table"); if (t != LUA_TNONE) { lua_getfield(L, idx, name); // [field] if (!lua_isnoneornil(L, -1)) v = lua_toboolean(L, -1) != 0;; lua_pop(L, 1); } return v; } inline int optintfield(lua_State* L, int idx, const char* name, int def) { auto v = def; lua_getfield(L, idx, name); // [field] if (lua_isnumber(L, -1)) v = static_cast<int>(lua_tointeger(L, -1)); lua_pop(L, 1); return v; } } #endif // __LUA_RAPIDJSION_LUACOMPAT_H__ <|endoftext|>
<commit_before>#include <iostream> #include <SDL.h> #include <SDL_net.h> #include <SDL_image.h> #include <string> #include <vector> #include <MsgStruct.h> #include "Player.h" #include "GameObject.h" #include "Enemy.h" #include "Cursor.h" #include "Tower.h" #include "Cannon.h" #include "Rocket.h" #include "Path.h" #include "Soldier.h" #include <unordered_map> using namespace std; int send(string); int send(MsgStruct*, int); int send(string, int); MsgStruct* createMsgStruct(int, bool); void setupMessages(); MsgStruct* newPacket(int); bool canHandleMsg(bool); MsgStruct* readPacket(bool); const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; SDLNet_SocketSet socketSet; TCPsocket sock; char buffer[512]; int bufferSize; map<int, MsgStruct*> outMsgStructs; map<int, MsgStruct*> inMsgStructs; string roomCode; vector<Tower*> listTower; vector<Enemy*> listEnemy; unordered_map<int, Player*> listPlayers; Level lvl1(640, 480); // User IO functions to be called from networking code? Player* getPlayerbyID(int id); void addPlayerbyID(int id, SDL_Renderer* r); void addTower(int id, int type, SDL_Renderer* r); int init(); int main() { if (SDL_Init(SDL_INIT_VIDEO) == -1) { std::cout << "ERROR, SDL_Init\n"; return -1; } cout << "SDL2 loaded.\n"; // The window we'll be rendering to SDL_Window* window = NULL; // The surface contained by the window SDL_Surface* screenSurface = NULL; window = SDL_CreateWindow("Party Towers", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if(init() == -1) { std::cout << "Quitting\n"; return -1; } std::cout << "SDL_net loaded.\n"; IPaddress ip; if (SDLNet_ResolveHost(&ip, "localhost", atoi("8886")) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if (!(sock = SDLNet_TCP_Open(&ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); } socketSet = SDLNet_AllocSocketSet(1); SDLNet_TCP_AddSocket(socketSet, sock); setupMessages(); send("TCP"); bool waiting = true; while (waiting) { if (SDLNet_TCP_Recv(sock, buffer, 512) > 0) { waiting = false; if (string(buffer) == "1") { cout << "Handshake to server made.\n"; } } } send("9990000"); // Create Renderer SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); printf("This is what happens when Marcus writes a renderer %s\n", SDL_GetError()); if (renderer) { cout << "It works!\n"; } // Testing Images Player p1(0, 0, 0, &lvl1); p1.loadImg(renderer); listPlayers.emplace(0, &p1); GameObject go1; go1.loadImg("./res/BaseTower.png", renderer); SDL_Event e; bool running = true; int k = 0; Uint32 ctime = SDL_GetTicks(); int wave = 1; bool confirmed = false; Soldier* soldier = new Soldier(1, 0, 0); soldier->loadImg(renderer); listEnemy.push_back(soldier); Path* path = new Path(); path->addDest(0,0); path->addDest(128,0); path->addDest(128,128); soldier->setPath(path); while (running) { SDL_UpdateWindowSurface(window); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } } int ready = SDLNet_CheckSockets(socketSet, 15); if (ready > 0 && SDLNet_SocketReady(sock)) { int s = SDLNet_TCP_Recv(sock, buffer + bufferSize, 512); if (s > 0) { bufferSize += s; } } if (canHandleMsg(confirmed)) { MsgStruct* packet = readPacket(confirmed); int pID = packet->getPID(); int msgID = packet->getMsgID(); if (msgID == 999) { confirmed = true; roomCode = packet->read(); cout << "Room code: " + roomCode + "\n"; } else if (msgID == 998) { cout << "New player!\n"; addPlayerbyID(pID, renderer); } else if (msgID == 2) { string dir = packet->read(); // We have pID and dir Player* p = getPlayerbyID(pID); if (dir == "l") { p->moveLeft(); } else if (dir == "r") { p->moveRight(); } else if (dir == "u") { p->moveUp(); } else if (dir == "d") { p->moveDown(); } else { cout << "error, direction: " << dir << "\n"; } } else if (msgID == 3) { MsgStruct* p = newPacket(3); // Can I place a tower here? 1 yes, 0 no Player* player = getPlayerbyID(pID); auto player_pos = player->getPos(); if(lvl1.spotOpen(player_pos.first, player_pos.second)) { std::cout << "Spot" << player_pos.first <<" " <<player_pos.second << "open\n"; p->write("1"); } else { std::cout << "Spot" << player_pos.first <<" " <<player_pos.second << "closed\n"; p->write("0"); } send(p, pID); } else if (msgID == 4) { int towerType = packet->readInt(); cout << "Placing a tower.\n"; // Attempt to place towerType // here addTower(pID, towerType, renderer); MsgStruct* p = newPacket(4); // Write success p->write("1"); send(p, pID); } } k += 1; if (SDL_GetTicks() - ctime > 1000) { // cout << k; k = 0; ctime = SDL_GetTicks(); // cout << "\n"; } /*************** * Aiming Code **************/ Enemy* attacked = nullptr; int r, radius; int radiusAttacked = 10000; for (auto t : listTower) { for (auto e : listEnemy) { r = t->getRange(); auto tpair = t->getPosition(); auto epair = e->getPosition(); radius = sqrt((epair.first - tpair.first) * (epair.first - tpair.first) + (epair.second - tpair.second) * (epair.second - tpair.second)); if(radius < r && radius < radiusAttacked) { radiusAttacked = radius; attacked = e; } } // end of enemy loop if (attacked) { cout << "Hit the enemy!\n"; attacked->setHealth(attacked->getHealth() - t->getPower()); } } // end of tower loop // Drawing code SDL_RenderClear(renderer); SDL_Rect txr; // img size txr.w = 32; txr.h = 32; // For each path item, draw // For each base tower, draw for (auto it : listTower) { Tower* t = it; pair<int, int> tower_pos = t->getPosition(); txr.x = tower_pos.first; txr.y = tower_pos.second; SDL_Texture* tx = t->draw(); if(!tx) { std::cout << "ERROR, tx is NULL!!!"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } // For each player, get cursor, draw for (auto it : listPlayers) { Player* p = it.second; pair<int, int> player_pos = p->getPos(); txr.x = player_pos.first; txr.y = player_pos.second; SDL_Texture* t = p->getTexture(); SDL_RenderCopy(renderer, t, NULL, &txr); } for (auto e : listEnemy) { e->move(); pair<int, int> e_pos = e->getPosition(); txr.x = e_pos.first; txr.y = e_pos.second; SDL_Texture* tx = e->draw(); if (!tx) { cout << "Error, tx is NULL!"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } // SDL_RenderCopy(renderer, t, NULL, &txr); SDL_RenderPresent(renderer); } SDL_FreeSurface(screenSurface); SDL_DestroyWindow(window); SDLNet_TCP_Close(sock); SDLNet_Quit(); SDL_Quit(); return 0; } void setupMessages() { MsgStruct* m1 = createMsgStruct(999, false); m1->addChars(4); MsgStruct* m998 = createMsgStruct(998, false); MsgStruct* m2 = createMsgStruct(2, false); m2->addChars(1); MsgStruct* m3 = createMsgStruct(3, false); MsgStruct* o3 = createMsgStruct(3, true); o3->addChars(1); MsgStruct* m4 = createMsgStruct(4, false); m4->addChars(2); MsgStruct* o4 = createMsgStruct(4, true); o4->addChars(1); MsgStruct* o5 = createMsgStruct(5, true); o5->addString(); } bool canHandleMsg(bool confirmed) { if (bufferSize < 5) { return false; } string data = string(buffer); if (data.size() < 5) { return false; } // cout << "Handling message...\n"; int offset = 2; if (confirmed) { offset += 2; } // cout << data + "\n"; data = data.substr(offset); // cout << data + "\n"; string rawMsgID = data.substr(0, 3); // cout << rawMsgID + "\n"; int msgID = atoi(rawMsgID.c_str()); if (inMsgStructs.find(msgID) != inMsgStructs.end()) { return inMsgStructs[msgID]->canHandle(data); } cout << "Message ID does not exist " + rawMsgID + "\n"; return false; } MsgStruct* readPacket(bool confirmed) { string data = string(buffer).substr(0, bufferSize); int offset = 2; if (confirmed) { offset += 2; } int msgID = atoi(data.substr(offset, 3).c_str()); return inMsgStructs[msgID]->fillFromData(confirmed); } MsgStruct* createMsgStruct(int msgID, bool outgoing) { MsgStruct* packet = new MsgStruct(msgID); if (outgoing) { outMsgStructs[msgID] = packet; } else { inMsgStructs[msgID] = packet; } return packet; } MsgStruct* newPacket(int msgID) { return outMsgStructs[msgID]->reset(); } int send(string data) { send(data, 0); } int send(string data, int pID) { if (pID > 0) { data = extend(pID, 2) + data + "*"; } int len = data.size() + 1; int out = SDLNet_TCP_Send(sock, (void*)data.c_str(), len); if (out < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } return 0; } int send(MsgStruct* packet, int pID) { send(packet->getData(), pID); } Player* getPlayerbyID(int id) { auto it = listPlayers.find(id); if (it != listPlayers.end()) { return it->second; } return nullptr; } void addPlayerbyID(int id, SDL_Renderer* r) { auto it = listPlayers.find(id); if (it == listPlayers.end()) { Player* p = new Player(id, 0, 0, &lvl1); p->loadImg(r); listPlayers.emplace(id, p); } } void addTower(int id, int type, SDL_Renderer* r) { Player* p = getPlayerbyID(id); if(p == nullptr) { return; } auto pos = p->getPos(); int x = pos.first; int y = pos.second; std::cout << "x,y " << x << "," << y << "\n"; Tower* t; std::cout << type << "\n"; if(type == 1) { std::cout << "MAKING A CANNON!!\n"; Cannon* cannon = new Cannon(x,y,1); cannon->loadImg(r); t = cannon; } else { std::cout << "MAKING A ROCKET!!\n"; Rocket* rocket = new Rocket(x,y,1); rocket->loadImg(r); t = rocket; } if(!lvl1.spotOpen(x, y)) { std::cout << "Position wasn't open!\n"; delete t; return; } t->setPlayer(p); listTower.push_back(t); lvl1.addGameObject(t); } int init() { int flag = IMG_INIT_PNG; if ((IMG_Init(flag) & flag) != flag) { std::cout << "Error, SDL_image!\n"; return -1; } if (SDLNet_Init() == -1) { std::cout << "ERROR, SDLNet_Init\n"; return -1; } return 0; } <commit_msg>Some more code cleanup.<commit_after>#include <iostream> #include <SDL.h> #include <SDL_net.h> #include <SDL_image.h> #include <string> #include <vector> #include <MsgStruct.h> #include "Player.h" #include "GameObject.h" #include "Enemy.h" #include "Cursor.h" #include "Tower.h" #include "Cannon.h" #include "Rocket.h" #include "Path.h" #include "Soldier.h" #include <unordered_map> using namespace std; int send(string); int send(MsgStruct*, int); int send(string, int); MsgStruct* createMsgStruct(int, bool); void setupMessages(); MsgStruct* newPacket(int); bool canHandleMsg(bool); MsgStruct* readPacket(bool); const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; SDLNet_SocketSet socketSet; TCPsocket sock; char buffer[512]; int bufferSize; map<int, MsgStruct*> outMsgStructs; map<int, MsgStruct*> inMsgStructs; string roomCode; vector<Tower*> listTower; vector<Enemy*> listEnemy; unordered_map<int, Player*> listPlayers; Level lvl1(640, 480); // User IO functions to be called from networking code? Player* getPlayerbyID(int id); void addPlayerbyID(int id, SDL_Renderer* r); void addTower(int id, int type, SDL_Renderer* r); int init(); int main() { if (SDL_Init(SDL_INIT_VIDEO) == -1) { std::cout << "ERROR, SDL_Init\n"; return -1; } cout << "SDL2 loaded.\n"; // The window we'll be rendering to SDL_Window* window = NULL; // The surface contained by the window SDL_Surface* screenSurface = NULL; window = SDL_CreateWindow("Party Towers", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if(init() == -1) { std::cout << "Quitting\n"; return -1; } std::cout << "SDL_net loaded.\n"; IPaddress ip; if (SDLNet_ResolveHost(&ip, "localhost", atoi("8886")) < 0) { fprintf(stderr, "SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } if (!(sock = SDLNet_TCP_Open(&ip))) { fprintf(stderr, "SDLNet_TCP_Open: %s\n", SDLNet_GetError()); } socketSet = SDLNet_AllocSocketSet(1); SDLNet_TCP_AddSocket(socketSet, sock); setupMessages(); send("TCP"); bool waiting = true; while (waiting) { if (SDLNet_TCP_Recv(sock, buffer, 512) > 0) { waiting = false; if (string(buffer) == "1") { cout << "Handshake to server made.\n"; } } } send("9990000"); // Create Renderer SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); printf("This is what happens when Marcus writes a renderer %s\n", SDL_GetError()); if (renderer) { cout << "It works!\n"; } SDL_Event e; bool running = true; int k = 0; Uint32 ctime = SDL_GetTicks(); int wave = 1; bool confirmed = false; Soldier* soldier = new Soldier(1, 0, 0); soldier->loadImg(renderer); listEnemy.push_back(soldier); Path* path = new Path(); path->addDest(0,0); path->addDest(128,0); path->addDest(128,128); soldier->setPath(path); while (running) { SDL_UpdateWindowSurface(window); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { running = false; } } int ready = SDLNet_CheckSockets(socketSet, 15); if (ready > 0 && SDLNet_SocketReady(sock)) { int s = SDLNet_TCP_Recv(sock, buffer + bufferSize, 512); if (s > 0) { bufferSize += s; } } if (canHandleMsg(confirmed)) { MsgStruct* packet = readPacket(confirmed); int pID = packet->getPID(); int msgID = packet->getMsgID(); if (msgID == 999) { confirmed = true; roomCode = packet->read(); cout << "Room code: " + roomCode + "\n"; } else if (msgID == 998) { cout << "New player!\n"; addPlayerbyID(pID, renderer); } else if (msgID == 2) { string dir = packet->read(); // We have pID and dir Player* p = getPlayerbyID(pID); if (dir == "l") { p->moveLeft(); } else if (dir == "r") { p->moveRight(); } else if (dir == "u") { p->moveUp(); } else if (dir == "d") { p->moveDown(); } else { cout << "error, direction: " << dir << "\n"; } } else if (msgID == 3) { MsgStruct* p = newPacket(3); // Can I place a tower here? 1 yes, 0 no Player* player = getPlayerbyID(pID); auto player_pos = player->getPos(); if(lvl1.spotOpen(player_pos.first, player_pos.second)) { std::cout << "Spot" << player_pos.first <<" " <<player_pos.second << "open\n"; p->write("1"); } else { std::cout << "Spot" << player_pos.first <<" " <<player_pos.second << "closed\n"; p->write("0"); } send(p, pID); } else if (msgID == 4) { int towerType = packet->readInt(); cout << "Placing a tower.\n"; // Attempt to place towerType // here addTower(pID, towerType, renderer); MsgStruct* p = newPacket(4); // Write success p->write("1"); send(p, pID); } } k += 1; if (SDL_GetTicks() - ctime > 1000) { // cout << k; k = 0; ctime = SDL_GetTicks(); // cout << "\n"; } /*************** * Aiming Code **************/ Enemy* attacked = nullptr; int r, radius; int radiusAttacked = 10000; for (auto t : listTower) { for (auto e : listEnemy) { r = t->getRange(); auto tpair = t->getPosition(); auto epair = e->getPosition(); radius = sqrt((epair.first - tpair.first) * (epair.first - tpair.first) + (epair.second - tpair.second) * (epair.second - tpair.second)); if(radius < r && radius < radiusAttacked) { radiusAttacked = radius; attacked = e; } } // end of enemy loop if (attacked) { cout << "Hit the enemy!\n"; attacked->setHealth(attacked->getHealth() - t->getPower()); } } // end of tower loop // Drawing code SDL_RenderClear(renderer); SDL_Rect txr; // img size txr.w = 32; txr.h = 32; // For each path item, draw // For each base tower, draw for (auto it : listTower) { Tower* t = it; pair<int, int> tower_pos = t->getPosition(); txr.x = tower_pos.first; txr.y = tower_pos.second; SDL_Texture* tx = t->draw(); if(!tx) { std::cout << "ERROR, tx is NULL!!!"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } // For each player, get cursor, draw for (auto it : listPlayers) { Player* p = it.second; pair<int, int> player_pos = p->getPos(); txr.x = player_pos.first; txr.y = player_pos.second; SDL_Texture* t = p->getTexture(); SDL_RenderCopy(renderer, t, NULL, &txr); } for (auto e : listEnemy) { e->move(); pair<int, int> e_pos = e->getPosition(); txr.x = e_pos.first; txr.y = e_pos.second; SDL_Texture* tx = e->draw(); if (!tx) { cout << "Error, tx is NULL!"; } SDL_RenderCopy(renderer, tx, NULL, &txr); } // SDL_RenderCopy(renderer, t, NULL, &txr); SDL_RenderPresent(renderer); } SDL_FreeSurface(screenSurface); SDL_DestroyWindow(window); SDLNet_TCP_Close(sock); SDLNet_Quit(); SDL_Quit(); return 0; } void setupMessages() { MsgStruct* m1 = createMsgStruct(999, false); m1->addChars(4); MsgStruct* m998 = createMsgStruct(998, false); MsgStruct* m2 = createMsgStruct(2, false); m2->addChars(1); MsgStruct* m3 = createMsgStruct(3, false); MsgStruct* o3 = createMsgStruct(3, true); o3->addChars(1); MsgStruct* m4 = createMsgStruct(4, false); m4->addChars(2); MsgStruct* o4 = createMsgStruct(4, true); o4->addChars(1); MsgStruct* o5 = createMsgStruct(5, true); o5->addString(); } bool canHandleMsg(bool confirmed) { if (bufferSize < 5) { return false; } string data = string(buffer); if (data.size() < 5) { return false; } // cout << "Handling message...\n"; int offset = 2; if (confirmed) { offset += 2; } // cout << data + "\n"; data = data.substr(offset); // cout << data + "\n"; string rawMsgID = data.substr(0, 3); // cout << rawMsgID + "\n"; int msgID = atoi(rawMsgID.c_str()); if (inMsgStructs.find(msgID) != inMsgStructs.end()) { return inMsgStructs[msgID]->canHandle(data); } cout << "Message ID does not exist " + rawMsgID + "\n"; return false; } MsgStruct* readPacket(bool confirmed) { string data = string(buffer).substr(0, bufferSize); int offset = 2; if (confirmed) { offset += 2; } int msgID = atoi(data.substr(offset, 3).c_str()); return inMsgStructs[msgID]->fillFromData(confirmed); } MsgStruct* createMsgStruct(int msgID, bool outgoing) { MsgStruct* packet = new MsgStruct(msgID); if (outgoing) { outMsgStructs[msgID] = packet; } else { inMsgStructs[msgID] = packet; } return packet; } MsgStruct* newPacket(int msgID) { return outMsgStructs[msgID]->reset(); } int send(string data) { send(data, 0); } int send(string data, int pID) { if (pID > 0) { data = extend(pID, 2) + data + "*"; } int len = data.size() + 1; int out = SDLNet_TCP_Send(sock, (void*)data.c_str(), len); if (out < len) { fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError()); exit(EXIT_FAILURE); } return 0; } int send(MsgStruct* packet, int pID) { send(packet->getData(), pID); } Player* getPlayerbyID(int id) { auto it = listPlayers.find(id); if (it != listPlayers.end()) { return it->second; } return nullptr; } void addPlayerbyID(int id, SDL_Renderer* r) { auto it = listPlayers.find(id); if (it == listPlayers.end()) { Player* p = new Player(id, 0, 0, &lvl1); p->loadImg(r); listPlayers.emplace(id, p); } } void addTower(int id, int type, SDL_Renderer* r) { Player* p = getPlayerbyID(id); if(p == nullptr) { return; } auto pos = p->getPos(); int x = pos.first; int y = pos.second; std::cout << "x,y " << x << "," << y << "\n"; Tower* t; std::cout << type << "\n"; if(type == 1) { std::cout << "MAKING A CANNON!!\n"; Cannon* cannon = new Cannon(x,y,1); cannon->loadImg(r); t = cannon; } else { std::cout << "MAKING A ROCKET!!\n"; Rocket* rocket = new Rocket(x,y,1); rocket->loadImg(r); t = rocket; } if(!lvl1.spotOpen(x, y)) { std::cout << "Position wasn't open!\n"; delete t; return; } t->setPlayer(p); listTower.push_back(t); lvl1.addGameObject(t); } int init() { int flag = IMG_INIT_PNG; if ((IMG_Init(flag) & flag) != flag) { std::cout << "Error, SDL_image!\n"; return -1; } if (SDLNet_Init() == -1) { std::cout << "ERROR, SDLNet_Init\n"; return -1; } return 0; } <|endoftext|>
<commit_before>#include "math/vec.hpp" #include "math/mat.hpp" #include "math/MatrixTransform.hpp" #include "math/Sphere.hpp" #include "math/misc.hpp" #include "math/Ray.hpp" #include "math/TransformPair.hpp" #include "noncopyable.hpp" #include "output.hpp" #include "Optional.hpp" #include <vector> #include <memory> #include <algorithm> #include <limits> using namespace yks; struct Material { vec3 diffuse; Material(vec3 diffuse) : diffuse(diffuse) {} }; struct SceneObject; struct SceneShape; struct Intersection { float t; vec3 position; vec3 normal; vec2 uv; const SceneObject* object; const SceneShape* shape; }; struct SceneShape { TransformPair transform; SceneShape(TransformPair transform) : transform(std::move(transform)) {} virtual Optional<float> hasIntersection(const Ray& r) const = 0; Optional<float> hasIntersection(const Ray& r, float max_t) const { const Optional<float> t = hasIntersection(r); if (t && *t > max_t) { return Optional<float>(); } return t; } virtual Optional<Intersection> intersect(const Ray& r) const = 0; Optional<Intersection> intersect(const Ray& r, float max_t) const { const Optional<Intersection> intersection = intersect(r); if (intersection && intersection->t > max_t) { return Optional<Intersection>(); } return intersection; } }; struct ShapeSphere : SceneShape { ShapeSphere(TransformPair transform) : SceneShape(transform) {} virtual Optional<float> hasIntersection(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const vec3 o = local_ray.origin; const vec3 v = local_ray.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - 1.0f, t1, t2); if (solutions > 0) { return make_optional<float>(t1); } else { return Optional<float>(); } } virtual Optional<Intersection> intersect(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const vec3 o = local_ray.origin; const vec3 v = local_ray.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - 1.0f, t1, t2); if (solutions == 0) { return Optional<Intersection>(); } Intersection i; i.t = t1; i.position = r(t1); vec3 local_pos = local_ray(t1); i.uv = mvec2(std::atan2(local_pos[2], local_pos[0]) / (2*pi) + 0.5f, std::acos(local_pos[1]) / pi); i.normal = mvec3(transpose(transform.localFromParent) * mvec4(normalized(local_ray(t1)), 0.0f)); return make_optional<Intersection>(i); } }; struct ShapePlane : SceneShape { ShapePlane(TransformPair transform) : SceneShape(std::move(transform)) {} virtual Optional<float> hasIntersection(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const float t = -local_ray.origin[1] / local_ray.direction[1]; return make_optional<float>(t); } virtual Optional<Intersection> intersect(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const float t = -local_ray.origin[1] / local_ray.direction[1]; if (t < 0.0f) { return Optional<Intersection>(); } Intersection i; i.t = t; i.position = r(t); i.uv = mvec2(0.0f, 0.0f); i.normal = mvec3(transpose(transform.localFromParent) * mvec4(vec3_y, 0.0f)); return make_optional<Intersection>(i); } }; struct SceneObject { Material material; std::unique_ptr<SceneShape> shape; SceneObject(Material material, std::unique_ptr<SceneShape>&& shape) : material(material), shape(std::move(shape)) {} SceneObject(SceneObject&& o) : material(std::move(o.material)), shape(std::move(o.shape)) {} private: NONCOPYABLE(SceneObject); }; struct SceneLight { vec3 origin; vec3 intensity; }; struct Camera { vec3 origin; mat3 orientation; float focal_distance; // distance from image plane Camera(vec3 origin, mat3 orientation, float focal_distance) : origin(origin), orientation(orientation), focal_distance(focal_distance) {} Ray createRay(const vec2 film_pos) const { const vec3 cameraspace_ray = mvec3(film_pos[0], film_pos[1], focal_distance); return Ray{origin, orientation * cameraspace_ray}; } }; struct Scene { Camera camera; std::vector<SceneObject> objects; Scene(Camera camera) : camera(camera) {} Scene(Scene&& o) : camera(std::move(o.camera)), objects(std::move(o.objects)) {} private: NONCOPYABLE(Scene); }; Scene setup_scene() { Scene s(Camera(vec3_0, orient(vec3_y, vec3_z), 0.5f)); s.objects.push_back(SceneObject( Material(vec3_1), std::make_unique<ShapeSphere>(TransformPair().translate(vec3_z * 2)) )); s.objects.push_back(SceneObject( Material(mvec3(0.5f, 0.0f, 0.0f)), std::make_unique<ShapePlane>(TransformPair().translate(vec3_y * -1.5f)) )); return std::move(s); } static vec2 filmspace_from_screenspace(const vec2 screen_pos, const vec2 screen_size) { return (screen_pos - (screen_size * 0.5f)) * 2.0f * (1.0f / screen_size[1]); } Optional<Intersection> find_nearest_intersection(const Scene& scene, const Ray ray) { Optional<Intersection> nearest_intersection; for (const SceneObject& object : scene.objects) { const Optional<Intersection> intersection = object.shape->intersect(ray); if (intersection && (!nearest_intersection || intersection->t < nearest_intersection->t)) { nearest_intersection = intersection; nearest_intersection->object = &object; nearest_intersection->shape = object.shape.get(); } } return nearest_intersection; } int main(int, char* []) { static const int IMAGE_WIDTH = 1280; static const int IMAGE_HEIGHT = 720; std::vector<vec3> image_data(IMAGE_WIDTH * IMAGE_HEIGHT); const Scene scene = setup_scene(); for (int y = 0; y < IMAGE_HEIGHT; ++y) { for (int x = 0; x < IMAGE_WIDTH; x++) { const vec2 film_coord = filmspace_from_screenspace(mvec2(float(x), float(y)), mvec2(float(IMAGE_WIDTH), float(IMAGE_HEIGHT))) * mvec2(1.0f, -1.0f); const Ray camera_ray = scene.camera.createRay(film_coord); const Optional<Intersection> hit = find_nearest_intersection(scene, camera_ray); const vec3 color = hit ? hit->normal * 0.5f + vec3_1 * 0.5f : vec3_1*0.1f; //const vec3 color = hit ? hit->object->material.diffuse : vec3_1*0.1f; image_data[y*IMAGE_WIDTH + x] = color; } } save_srgb_image(image_data, IMAGE_WIDTH, IMAGE_HEIGHT); }<commit_msg>Specify camera FOV in angles. Correct misnamed variable.<commit_after>#include "math/vec.hpp" #include "math/mat.hpp" #include "math/MatrixTransform.hpp" #include "math/Sphere.hpp" #include "math/misc.hpp" #include "math/Ray.hpp" #include "math/TransformPair.hpp" #include "noncopyable.hpp" #include "output.hpp" #include "Optional.hpp" #include <vector> #include <memory> #include <algorithm> #include <limits> using namespace yks; struct Material { vec3 diffuse; Material(vec3 diffuse) : diffuse(diffuse) {} }; struct SceneObject; struct SceneShape; struct Intersection { float t; vec3 position; vec3 normal; vec2 uv; const SceneObject* object; const SceneShape* shape; }; struct SceneShape { TransformPair transform; SceneShape(TransformPair transform) : transform(std::move(transform)) {} virtual Optional<float> hasIntersection(const Ray& r) const = 0; Optional<float> hasIntersection(const Ray& r, float max_t) const { const Optional<float> t = hasIntersection(r); if (t && *t > max_t) { return Optional<float>(); } return t; } virtual Optional<Intersection> intersect(const Ray& r) const = 0; Optional<Intersection> intersect(const Ray& r, float max_t) const { const Optional<Intersection> intersection = intersect(r); if (intersection && intersection->t > max_t) { return Optional<Intersection>(); } return intersection; } }; struct ShapeSphere : SceneShape { ShapeSphere(TransformPair transform) : SceneShape(transform) {} virtual Optional<float> hasIntersection(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const vec3 o = local_ray.origin; const vec3 v = local_ray.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - 1.0f, t1, t2); if (solutions > 0) { return make_optional<float>(t1); } else { return Optional<float>(); } } virtual Optional<Intersection> intersect(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const vec3 o = local_ray.origin; const vec3 v = local_ray.direction; float t1, t2; const int solutions = solve_quadratic(dot(v, v), 2*dot(o, v), dot(o, o) - 1.0f, t1, t2); if (solutions == 0) { return Optional<Intersection>(); } Intersection i; i.t = t1; i.position = r(t1); vec3 local_pos = local_ray(t1); i.uv = mvec2(std::atan2(local_pos[2], local_pos[0]) / (2*pi) + 0.5f, std::acos(local_pos[1]) / pi); i.normal = mvec3(transpose(transform.localFromParent) * mvec4(normalized(local_ray(t1)), 0.0f)); return make_optional<Intersection>(i); } }; struct ShapePlane : SceneShape { ShapePlane(TransformPair transform) : SceneShape(std::move(transform)) {} virtual Optional<float> hasIntersection(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const float t = -local_ray.origin[1] / local_ray.direction[1]; return make_optional<float>(t); } virtual Optional<Intersection> intersect(const Ray& r) const override { const Ray local_ray = transform.localFromParent * r; const float t = -local_ray.origin[1] / local_ray.direction[1]; if (t < 0.0f) { return Optional<Intersection>(); } Intersection i; i.t = t; i.position = r(t); i.uv = mvec2(0.0f, 0.0f); i.normal = mvec3(transpose(transform.localFromParent) * mvec4(vec3_y, 0.0f)); return make_optional<Intersection>(i); } }; struct SceneObject { Material material; std::unique_ptr<SceneShape> shape; SceneObject(Material material, std::unique_ptr<SceneShape>&& shape) : material(material), shape(std::move(shape)) {} SceneObject(SceneObject&& o) : material(std::move(o.material)), shape(std::move(o.shape)) {} private: NONCOPYABLE(SceneObject); }; struct SceneLight { vec3 origin; vec3 intensity; }; float focal_distance_from_fov(const float fov_degrees) { const float half_fov = fov_degrees / 360.0f * pi; return std::tan(0.5f*pi - half_fov); } struct Camera { vec3 origin; mat3 orientation; float focal_length; // distance from image plane Camera(vec3 origin, mat3 orientation, float vertical_fov) : origin(origin), orientation(orientation), focal_length(focal_distance_from_fov(vertical_fov)) {} Ray createRay(const vec2 film_pos) const { const vec3 cameraspace_ray = mvec3(film_pos[0], film_pos[1], focal_length); return Ray{origin, orientation * cameraspace_ray}; } }; struct Scene { Camera camera; std::vector<SceneObject> objects; Scene(Camera camera) : camera(camera) {} Scene(Scene&& o) : camera(std::move(o.camera)), objects(std::move(o.objects)) {} private: NONCOPYABLE(Scene); }; Scene setup_scene() { Scene s(Camera(vec3_0, orient(vec3_y, vec3_z), 75.0f)); s.objects.push_back(SceneObject( Material(vec3_1), std::make_unique<ShapeSphere>(TransformPair().translate(vec3_z * 2)) )); s.objects.push_back(SceneObject( Material(mvec3(0.5f, 0.0f, 0.0f)), std::make_unique<ShapePlane>(TransformPair().translate(vec3_y * -1.5f)) )); return std::move(s); } static vec2 filmspace_from_screenspace(const vec2 screen_pos, const vec2 screen_size) { return (screen_pos - (screen_size * 0.5f)) * 2.0f * (1.0f / screen_size[1]); } Optional<Intersection> find_nearest_intersection(const Scene& scene, const Ray ray) { Optional<Intersection> nearest_intersection; for (const SceneObject& object : scene.objects) { const Optional<Intersection> intersection = object.shape->intersect(ray); if (intersection && (!nearest_intersection || intersection->t < nearest_intersection->t)) { nearest_intersection = intersection; nearest_intersection->object = &object; nearest_intersection->shape = object.shape.get(); } } return nearest_intersection; } int main(int, char* []) { static const int IMAGE_WIDTH = 1280; static const int IMAGE_HEIGHT = 720; std::vector<vec3> image_data(IMAGE_WIDTH * IMAGE_HEIGHT); const Scene scene = setup_scene(); for (int y = 0; y < IMAGE_HEIGHT; ++y) { for (int x = 0; x < IMAGE_WIDTH; x++) { const vec2 film_coord = filmspace_from_screenspace(mvec2(float(x), float(y)), mvec2(float(IMAGE_WIDTH), float(IMAGE_HEIGHT))) * mvec2(1.0f, -1.0f); const Ray camera_ray = scene.camera.createRay(film_coord); const Optional<Intersection> hit = find_nearest_intersection(scene, camera_ray); const vec3 color = hit ? hit->normal * 0.5f + vec3_1 * 0.5f : vec3_1*0.1f; //const vec3 color = hit ? hit->object->material.diffuse : vec3_1*0.1f; image_data[y*IMAGE_WIDTH + x] = color; } } save_srgb_image(image_data, IMAGE_WIDTH, IMAGE_HEIGHT); }<|endoftext|>
<commit_before> #include "fetch.h" #include "decode.h" #include "execute.h" #include "stdarg.h" #include "breg.h" #include "memoria.h" int sc_main(int argc, char* argv[]){ fetch Fetch("Fetch"); decode Decode("Decode"); execute Execute("Execute"); mem Memoria("Memoria"); breg Breg("Breg"); sc_fifo < contexto* > e_f( 1); sc_fifo < contexto* > f_d( 1); sc_fifo < contexto* > d_e( 1); Fetch.p_mem(Memoria); Fetch.p_breg(Breg); Fetch.execute_fetch(e_f); Fetch.fetch_decode(f_d); Execute.p_breg(Breg); Execute.p_mem(Memoria); Execute.decode_execute(d_e); Execute.execute_fetch(e_f); Decode.p_breg(Breg); Decode.decode_execute(d_e); Decode.fetch_decode(f_d); contexto *dado_entrada = new contexto(); // zera pc; Breg.write(31, 0); e_f.write(dado_entrada); sc_start(); return 0; } <commit_msg>geraINSTRUÇÕES<commit_after> #include "fetch.h" #include "decode.h" #include "execute.h" #include "stdarg.h" #include "breg.h" #include "memoria.h" short gerainst(int n, ...); int sc_main(int argc, char* argv[]){ fetch Fetch("Fetch"); decode Decode("Decode"); execute Execute("Execute"); mem Memoria("Memoria"); breg Breg("Breg"); sc_fifo < contexto* > e_f( 1); sc_fifo < contexto* > f_d( 1); sc_fifo < contexto* > d_e( 1); Fetch.p_mem(Memoria); Fetch.p_breg(Breg); Fetch.execute_fetch(e_f); Fetch.fetch_decode(f_d); Execute.p_breg(Breg); Execute.p_mem(Memoria); Execute.decode_execute(d_e); Execute.execute_fetch(e_f); Decode.p_breg(Breg); Decode.decode_execute(d_e); Decode.fetch_decode(f_d); contexto *dado_entrada = new contexto(); // zera pc; Breg.write(31, 0); e_f.write(dado_entrada); sc_start(); return 0; } short gerainst(int n, ...){ short inst = 0; va_list ap; va_start(ap, n); switch (n) { case TIPO_R: inst |= (va_arg(ap, int ) & 0xF) << 12; inst |= (va_arg(ap, int ) & 0xF) << 8; inst |= (va_arg(ap, int ) & 0xF) << 4; inst |= (va_arg(ap, int ) & 0xF); break; case TIPO_J: inst |= (va_arg(ap, int ) & 0xF) << 12; inst |= (va_arg(ap, int ) & 0xF) << 8; inst |= (va_arg(ap, int ) & 0xFF); break; default: break; } return inst; } <|endoftext|>
<commit_before>/** * libcec-daemon * A simple daemon to connect libcec to uinput. * by Andrew Brampton * * TODO * */ #include "uinput.h" #include "libcec.h" #include <cstdio> #include <iostream> #include <stdint.h> #include <cstddef> #include <csignal> #include <vector> using namespace CEC; using std::cerr; using std::endl; using std::vector; class Main : public CecCallback { private: Cec cec; UInput uinput; bool running; // TODO Change this to be threadsafe!. Voiatile or better Main(); virtual ~Main(); // Not implemented to avoid copying the singleton Main(Main const&); void operator=(Main const&); static void signalHandler(int sigNum); static const std::vector<__u16> & setupUinputMap(); public: static const std::vector<__u16> uinputCecMap; int onCecLogMessage(const cec_log_message &message); int onCecKeyPress(const cec_keypress &key); int onCecCommand(const cec_command &command); int onCecConfigurationChanged(const libcec_configuration & configuration); static Main & instance(); void loop(); void stop(); void listDevices(); }; const vector<__u16> Main::uinputCecMap = Main::setupUinputMap(); Main & Main::instance() { static Main main; return main; } Main::Main() : cec("Linux PC", this), uinput("libcec-daemon", uinputCecMap), running(true) { std::cerr << "Main::Main()" << std::endl; signal (SIGINT, &Main::signalHandler); signal (SIGTERM, &Main::signalHandler); } Main::~Main() { stop(); } void Main::loop() { cec.open(); while (running) { cerr << "Loop" << endl; sleep(1); } cec.close(); } void Main::stop() { running = false; } void Main::listDevices() { cec.listDevices(); } void Main::signalHandler(int sigNum) { cerr << "SignalHanlder(" << sigNum << ")" << endl; Main::instance().stop(); } const std::vector<__u16> & Main::setupUinputMap() { static std::vector<__u16> uinputCecMap; if (uinputCecMap.empty()) { uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX, KEY_RESERVED); uinputCecMap[CEC_USER_CONTROL_CODE_SELECT ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_UP ] = KEY_UP; uinputCecMap[CEC_USER_CONTROL_CODE_DOWN ] = KEY_DOWN; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT ] = KEY_LEFT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT ] = KEY_RIGHT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU ] = KEY_SETUP; uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU ] = KEY_MENU; uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU ] = KEY_FAVORITES; uinputCecMap[CEC_USER_CONTROL_CODE_EXIT ] = KEY_BACKSPACE; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0 ] = KEY_0; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1 ] = KEY_1; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2 ] = KEY_2; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3 ] = KEY_3; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4 ] = KEY_4; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5 ] = KEY_5; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6 ] = KEY_6; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7 ] = KEY_7; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8 ] = KEY_8; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9 ] = KEY_9; uinputCecMap[CEC_USER_CONTROL_CODE_DOT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ENTER ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP ] = KEY_CHANNELUP; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN ] = KEY_CHANNELDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_HELP ] = KEY_HELP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP ] = KEY_PAGEUP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN ] = KEY_PAGEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_POWER ] = KEY_POWER; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP ] = KEY_VOLUMEUP; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN ] = KEY_VOLUMEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE ] = KEY_MUTE; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY ] = KEY_PLAY; uinputCecMap[CEC_USER_CONTROL_CODE_STOP ] = KEY_STOP; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE ] = KEY_PAUSE; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD ] = KEY_RECORD; uinputCecMap[CEC_USER_CONTROL_CODE_REWIND ] = KEY_REWIND; uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD ] = KEY_FASTFORWARD; uinputCecMap[CEC_USER_CONTROL_CODE_EJECT ] = KEY_EJECTCD; uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD ] = KEY_NEXTSONG; uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD ] = KEY_PREVIOUSSONG; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE ] = KEY_BLUE; uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED ] = KEY_RED; uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN ] = KEY_GREEN; uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW ] = KEY_YELLOW; uinputCecMap[CEC_USER_CONTROL_CODE_F5 ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DATA ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_MAX ] = 0; } return uinputCecMap; } int Main::onCecLogMessage(const cec_log_message &message) { cerr << message; return 1; } int Main::onCecKeyPress(const cec_keypress &key) { cerr << key; int uinputKey = 0; // Check bounds and find uinput code for this cec keypress if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX) uinputKey = uinputCecMap[key.keycode]; if (uinputKey != 0) { cerr << " sent " << uinputKey; uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0); uinput.sync(); } cerr << endl; return 1; } int Main::onCecCommand(const cec_command & command) { //cerr << command; return 1; } int Main::onCecConfigurationChanged(const libcec_configuration & configuration) { //cerr << configuration; return 1; } int main (int argc, char *argv[]) { // TODO Parse the config //int daemon(int nochdir, int noclose); // Create the main Main & main = Main::instance(); main.loop(); /* cec_keypress test = {CEC_USER_CONTROL_CODE_NUMBER0, 1}; main.onCecKeyPress(test); main.onCecKeyPress(test); main.onCecKeyPress(test); main.onCecKeyPress(test); main.onCecKeyPress(test); */ //main.listDevices(); return 0; } <commit_msg>Fixed a array out of bounds error, due to a off by one mistake.<commit_after>/** * libcec-daemon * A simple daemon to connect libcec to uinput. * by Andrew Brampton * * TODO * */ #include "uinput.h" #include "libcec.h" #include <cstdio> #include <iostream> #include <stdint.h> #include <cstddef> #include <csignal> #include <vector> using namespace CEC; using std::cerr; using std::endl; using std::vector; class Main : public CecCallback { private: Cec cec; UInput uinput; bool running; // TODO Change this to be threadsafe!. Voiatile or better Main(); virtual ~Main(); // Not implemented to avoid copying the singleton Main(Main const&); void operator=(Main const&); static void signalHandler(int sigNum); static const std::vector<__u16> & setupUinputMap(); public: static const std::vector<__u16> uinputCecMap; int onCecLogMessage(const cec_log_message &message); int onCecKeyPress(const cec_keypress &key); int onCecCommand(const cec_command &command); int onCecConfigurationChanged(const libcec_configuration & configuration); static Main & instance(); void loop(); void stop(); void listDevices(); }; const vector<__u16> Main::uinputCecMap = Main::setupUinputMap(); Main & Main::instance() { static Main main; return main; } Main::Main() : cec("Linux PC", this), uinput("libcec-daemon", uinputCecMap), running(true) { std::cerr << "Main::Main()" << std::endl; signal (SIGINT, &Main::signalHandler); signal (SIGTERM, &Main::signalHandler); } Main::~Main() { stop(); } void Main::loop() { cec.open(); while (running) { cerr << "Loop" << endl; sleep(1); } cec.close(); } void Main::stop() { running = false; } void Main::listDevices() { cec.listDevices(); } void Main::signalHandler(int sigNum) { cerr << "SignalHanlder(" << sigNum << ")" << endl; Main::instance().stop(); } const std::vector<__u16> & Main::setupUinputMap() { static std::vector<__u16> uinputCecMap; if (uinputCecMap.empty()) { uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0); uinputCecMap[CEC_USER_CONTROL_CODE_SELECT ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_UP ] = KEY_UP; uinputCecMap[CEC_USER_CONTROL_CODE_DOWN ] = KEY_DOWN; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT ] = KEY_LEFT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT ] = KEY_RIGHT; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU ] = KEY_SETUP; uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU ] = KEY_MENU; uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU ] = KEY_FAVORITES; uinputCecMap[CEC_USER_CONTROL_CODE_EXIT ] = KEY_BACKSPACE; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0 ] = KEY_0; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1 ] = KEY_1; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2 ] = KEY_2; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3 ] = KEY_3; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4 ] = KEY_4; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5 ] = KEY_5; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6 ] = KEY_6; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7 ] = KEY_7; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8 ] = KEY_8; uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9 ] = KEY_9; uinputCecMap[CEC_USER_CONTROL_CODE_DOT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ENTER ] = KEY_ENTER; uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP ] = KEY_CHANNELUP; uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN ] = KEY_CHANNELDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_HELP ] = KEY_HELP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP ] = KEY_PAGEUP; uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN ] = KEY_PAGEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_POWER ] = KEY_POWER; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP ] = KEY_VOLUMEUP; uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN ] = KEY_VOLUMEDOWN; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE ] = KEY_MUTE; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY ] = KEY_PLAY; uinputCecMap[CEC_USER_CONTROL_CODE_STOP ] = KEY_STOP; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE ] = KEY_PAUSE; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD ] = KEY_RECORD; uinputCecMap[CEC_USER_CONTROL_CODE_REWIND ] = KEY_REWIND; uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD ] = KEY_FASTFORWARD; uinputCecMap[CEC_USER_CONTROL_CODE_EJECT ] = KEY_EJECTCD; uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD ] = KEY_NEXTSONG; uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD ] = KEY_PREVIOUSSONG; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE ] = KEY_BLUE; uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED ] = KEY_RED; uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN ] = KEY_GREEN; uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW ] = KEY_YELLOW; uinputCecMap[CEC_USER_CONTROL_CODE_F5 ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_DATA ] = 0; uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN ] = 0; } return uinputCecMap; } int Main::onCecLogMessage(const cec_log_message &message) { cerr << message; return 1; } int Main::onCecKeyPress(const cec_keypress &key) { cerr << key; int uinputKey = 0; // Check bounds and find uinput code for this cec keypress if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX) uinputKey = uinputCecMap[key.keycode]; if (uinputKey != 0) { cerr << " sent " << uinputKey; uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0); uinput.sync(); } cerr << endl; return 1; } int Main::onCecCommand(const cec_command & command) { //cerr << command; return 1; } int Main::onCecConfigurationChanged(const libcec_configuration & configuration) { //cerr << configuration; return 1; } int main (int argc, char *argv[]) { // TODO Parse the config //int daemon(int nochdir, int noclose); // Create the main Main & main = Main::instance(); main.loop(); /* cec_keypress test = {CEC_USER_CONTROL_CODE_NUMBER0, 1}; main.onCecKeyPress(test); main.onCecKeyPress(test); main.onCecKeyPress(test); main.onCecKeyPress(test); main.onCecKeyPress(test); */ //main.listDevices(); return 0; } <|endoftext|>
<commit_before> #include <string> #include <fstream> #include <iostream> #include "thermalPrinter.h" static inline bool loadFromPath(const std::string& path, std::string* into) { std::ifstream file; std::string buffer; file.open(path.c_str()); if(!file.is_open()) return false; while(!file.eof()) { getline(file, buffer); (*into) += buffer + "\n"; } file.close(); return true; } static inline bool haveExt(const std::string& file, const std::string& ext){ return file.find("."+ext) != std::string::npos; } ThermalPrinter printer; // Main program //============================================================================ int main(int argc, char **argv){ // Get a list of ports #ifdef PLATFORM_RPI std::string port = "/dev/ttyAMA0"; #else std::string port = "NONE"; #endif std::vector<serial::PortInfo> ports = serial::list_ports(); for (uint i = 0; i < ports.size(); i++){ // std::cout << ports[i].port << " - " << ports[i].description << " - " << ports[i].hardware_id << std::endl; std::string::size_type found = ports[i].description.find("Prolific Technology Inc. USB-Serial Controller"); if (found != std::string::npos){ port = ports[i].port; break; } } // Contect the printer to the port std::cout << "Connecting to port [" << port << "] "; if (printer.open(port)){ printer.setControlParameter(7, 100, 2); // printer.setPrintDensity(100,40); std::cout << "successfully."<< std::endl; } else { std::cout << "error."<< std::endl; return 0; } // Load files to watch for (int i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ // Load Image and print it printer.printImg(argument); } else if ( haveExt(argument,"txt") || haveExt(argument,"TXT") || haveExt(argument,"md") || haveExt(argument,"MD") ){ // Load Text to print std::string text = ""; loadFromPath(argument,&text); printer.print(text+"\n"); } else if (argument == "-s") { std::string text = ""; for (int j = i+1; j < argc ; j++){ text += std::string(argv[j]) + " "; } printer.print(text+"\n"); break; } } if (argc == 0){ printer.printTestPage(); } // printer.close(); return 0; }<commit_msg>use CIN<commit_after> #include <string> #include <fstream> #include <iostream> #include "thermalPrinter.h" static inline bool loadFromPath(const std::string& path, std::string* into) { std::ifstream file; std::string buffer; file.open(path.c_str()); if(!file.is_open()) return false; while(!file.eof()) { getline(file, buffer); (*into) += buffer + "\n"; } file.close(); return true; } static inline bool haveExt(const std::string& file, const std::string& ext){ return file.find("."+ext) != std::string::npos; } ThermalPrinter printer; // Main program //============================================================================ int main(int argc, char **argv){ // Get a list of ports #ifdef PLATFORM_RPI std::string port = "/dev/ttyAMA0"; #else std::string port = "NONE"; #endif std::vector<serial::PortInfo> ports = serial::list_ports(); for (uint i = 0; i < ports.size(); i++){ // std::cout << ports[i].port << " - " << ports[i].description << " - " << ports[i].hardware_id << std::endl; std::string::size_type found = ports[i].description.find("Prolific Technology Inc. USB-Serial Controller"); if (found != std::string::npos){ port = ports[i].port; break; } } // Contect the printer to the port std::cout << "Connecting to port [" << port << "] "; if (printer.open(port)){ printer.setControlParameter(7, 100, 2); // printer.setPrintDensity(100,40); std::cout << "successfully."<< std::endl; } else { std::cout << "error."<< std::endl; return 0; } // Load files to watch if (argc == 1) { std::string line; while (std::getline(std::cin, line)){ printer.print(line+"\n"); } } else { for (int i = 1; i < argc ; i++){ std::string argument = std::string(argv[i]); if ( haveExt(argument,"png") || haveExt(argument,"PNG") || haveExt(argument,"jpg") || haveExt(argument,"JPG") || haveExt(argument,"jpeg") || haveExt(argument,"JPEG") ){ // Load Image and print it printer.printImg(argument); } else if ( haveExt(argument,"txt") || haveExt(argument,"TXT") || haveExt(argument,"md") || haveExt(argument,"MD") ){ // Load Text to print std::string text = ""; loadFromPath(argument,&text); printer.print(text+"\n"); } else if (argument == "-s") { std::string text = ""; for (int j = i+1; j < argc ; j++){ text += std::string(argv[j]) + " "; } printer.print(text+"\n"); break; } } } // printer.close(); return 0; }<|endoftext|>
<commit_before>/* SNEeSe, an Open Source Super NES emulator. Copyright (c) 1998-2004 Charles Bilyue'. Portions Copyright (c) 2003-2004 Daniel Horchner. This is free software. See 'LICENSE' for details. You must read and accept the license prior to use. */ //#define NO_GUI #include "wrapaleg.h" #include <iostream> using namespace std; #include <stdio.h> #include "platform.h" #include "romload.h" #include "helper.h" #include "guicore.h" #include "emugui.h" #include "debug.h" #include "snes.h" #include "timers.h" #include "scrmode.h" #include "types.h" #include "version.h" void no_adjust(void){} SCREEN screenmodes[]={ #if defined(ALLEGRO_DOS) { 8,320,200,320,200,GFX_VGA ,no_adjust }, // 320x200x256 VGA { 8,320,240,320,240,GFX_VESA2L,no_adjust }, // 320x240x256 VESA2L { 8,320,240,320,240,GFX_MODEX ,no_adjust }, // 320x240x256 MODE-X { 8,256,256,256,239,GFX_VGA ,Set256x239 }, // 256x239x256 VGA {16,320,200,320,200,GFX_VESA2L,no_adjust }, // 320x200x16b SVGA {16,320,240,320,240,GFX_VESA2L,no_adjust }, // 320x240x16b SVGA {16,640,480,640,480,GFX_VESA2L,no_adjust } // 640x480x16b SVGA #elif defined(ALLEGRO_WINDOWS) || defined(ALLEGRO_UNIX) || defined(ALLEGRO_BEOS) { 8,320,200,320,200,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x200x256 WIN { 8,320,240,320,240,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x240x256 WIN { 8,320,240,320,240,GFX_AUTODETECT_FULLSCREEN,no_adjust }, // 320x240x256 FS { 8,256,256,256,239,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 256x239x256 WIN {16,320,200,320,200,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x200x16b WIN {16,320,240,320,240,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x240x16b WIN {16,640,480,640,480,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 640x480x16b WIN {16,640,480,640,480,GFX_AUTODETECT_FULLSCREEN,no_adjust } // 640x480x16b FS #else #error No screen modes defined. #endif }; int main(int argc, char **argv) { cout << "SNEeSe, version " << SNEESE_VERSION_STR << " (" << RELEASE_DATE << ")" << endl << allegro_id << endl << endl; cout.flush(); // Perform platform-specific initialization if (platform_init(argc, argv)) return 1; atexit(platform_exit); // Load saved configuration, using defaults for missing settings if (LoadConfig()) return 1; char *name = NULL; if (parse_args(argc, argv, &name, 1)) return 1; snes_init(); if (name != NULL) { char filename[MAXPATH]; cout << "Attempting to load " << name << endl; fix_filename_path(filename, name, MAXPATH); if (!open_rom(filename)) { cout << "Failed to load cartridge ROM: " << name << endl; return 1; } #if defined(ALLEGRO_DOS) || defined(ALLEGRO_UNIX) || defined(ALLEGRO_BEOS) cout << endl << "Press any key to continue..."; cout.flush(); // We have to create a window or else the keyboard functions won't work // (i.e., the two just below) #if defined(ALLEGRO_UNIX) if (set_gfx_mode(GFX_XWINDOWS, 300, 80, 0, 0) == 0) textout_ex(screen, font, "Press any key to continue...", 38, 36, makecol(220, 220, 220), -1); #elif defined(ALLEGRO_BEOS) if (set_gfx_mode(GFX_BWINDOW, 300, 80, 0, 0) == 0) textout_ex(screen, font, "Press any key to continue...", 38, 36, makecol(220, 220, 220), -1); #endif while (!keypressed()); readkey(); cout << " continueing" << endl; #endif } #ifndef NO_GUI const char *errormsg = (const char *)0; if (GUI_ENABLED) { errormsg = GUI_init(); if (errormsg) { cout << errormsg; return 1; } } #endif if (!SetGUIScreen(SCREEN_MODE)) return 1; #ifndef NO_GUI GUI_ERROR GUI_error = GUI_EXIT; #endif for (;;) { if (snes_rom_loaded) { snes_exec(); } #ifndef NO_GUI if (!GUI_ENABLED) break; GUI_error = GUI(); if (GUI_error != GUI_CONTINUE) break; #else break; #endif } if (snes_rom_loaded) SaveSRAM(SRAM_filename); // Save the Save RAM to file SaveConfig(); set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); remove_keyboard(); #ifdef DEBUG if (snes_rom_loaded) { DisplayStatus(); } // cout << "\nThanks for testing SNEeSe - look out for future releases.\n"; cout << "\nThanks for using SNEeSe - look out for future releases.\n"; #else cout << "\nThanks for using SNEeSe - look out for future releases.\n"; #endif cout << "Displayed frames: " << Frames << endl; #ifndef NO_GUI if (GUI_ENABLED) { if (GUI_error != GUI_EXIT) { cout << "GUI: " << GUI_error_table[GUI_error] << endl; } } #endif save_debug_dumps(); cout.flush(); return 0; } END_OF_MAIN() <commit_msg>Fixed a misspelled word in init.<commit_after>/* SNEeSe, an Open Source Super NES emulator. Copyright (c) 1998-2004 Charles Bilyue'. Portions Copyright (c) 2003-2004 Daniel Horchner. This is free software. See 'LICENSE' for details. You must read and accept the license prior to use. */ //#define NO_GUI #include "wrapaleg.h" #include <iostream> using namespace std; #include <stdio.h> #include "platform.h" #include "romload.h" #include "helper.h" #include "guicore.h" #include "emugui.h" #include "debug.h" #include "snes.h" #include "timers.h" #include "scrmode.h" #include "types.h" #include "version.h" void no_adjust(void){} SCREEN screenmodes[]={ #if defined(ALLEGRO_DOS) { 8,320,200,320,200,GFX_VGA ,no_adjust }, // 320x200x256 VGA { 8,320,240,320,240,GFX_VESA2L,no_adjust }, // 320x240x256 VESA2L { 8,320,240,320,240,GFX_MODEX ,no_adjust }, // 320x240x256 MODE-X { 8,256,256,256,239,GFX_VGA ,Set256x239 }, // 256x239x256 VGA {16,320,200,320,200,GFX_VESA2L,no_adjust }, // 320x200x16b SVGA {16,320,240,320,240,GFX_VESA2L,no_adjust }, // 320x240x16b SVGA {16,640,480,640,480,GFX_VESA2L,no_adjust } // 640x480x16b SVGA #elif defined(ALLEGRO_WINDOWS) || defined(ALLEGRO_UNIX) || defined(ALLEGRO_BEOS) { 8,320,200,320,200,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x200x256 WIN { 8,320,240,320,240,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x240x256 WIN { 8,320,240,320,240,GFX_AUTODETECT_FULLSCREEN,no_adjust }, // 320x240x256 FS { 8,256,256,256,239,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 256x239x256 WIN {16,320,200,320,200,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x200x16b WIN {16,320,240,320,240,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 320x240x16b WIN {16,640,480,640,480,GFX_AUTODETECT_WINDOWED ,no_adjust }, // 640x480x16b WIN {16,640,480,640,480,GFX_AUTODETECT_FULLSCREEN,no_adjust } // 640x480x16b FS #else #error No screen modes defined. #endif }; int main(int argc, char **argv) { cout << "SNEeSe, version " << SNEESE_VERSION_STR << " (" << RELEASE_DATE << ")" << endl << allegro_id << endl << endl; cout.flush(); // Perform platform-specific initialization if (platform_init(argc, argv)) return 1; atexit(platform_exit); // Load saved configuration, using defaults for missing settings if (LoadConfig()) return 1; char *name = NULL; if (parse_args(argc, argv, &name, 1)) return 1; snes_init(); if (name != NULL) { char filename[MAXPATH]; cout << "Attempting to load " << name << endl; fix_filename_path(filename, name, MAXPATH); if (!open_rom(filename)) { cout << "Failed to load cartridge ROM: " << name << endl; return 1; } #if defined(ALLEGRO_DOS) || defined(ALLEGRO_UNIX) || defined(ALLEGRO_BEOS) cout << endl << "Press any key to continue..."; cout.flush(); // We have to create a window or else the keyboard functions won't work // (i.e., the two just below) #if defined(ALLEGRO_UNIX) if (set_gfx_mode(GFX_XWINDOWS, 300, 80, 0, 0) == 0) textout_ex(screen, font, "Press any key to continue...", 38, 36, makecol(220, 220, 220), -1); #elif defined(ALLEGRO_BEOS) if (set_gfx_mode(GFX_BWINDOW, 300, 80, 0, 0) == 0) textout_ex(screen, font, "Press any key to continue...", 38, 36, makecol(220, 220, 220), -1); #endif while (!keypressed()); readkey(); cout << " continuing..." << endl; #endif } #ifndef NO_GUI const char *errormsg = (const char *)0; if (GUI_ENABLED) { errormsg = GUI_init(); if (errormsg) { cout << errormsg; return 1; } } #endif if (!SetGUIScreen(SCREEN_MODE)) return 1; #ifndef NO_GUI GUI_ERROR GUI_error = GUI_EXIT; #endif for (;;) { if (snes_rom_loaded) { snes_exec(); } #ifndef NO_GUI if (!GUI_ENABLED) break; GUI_error = GUI(); if (GUI_error != GUI_CONTINUE) break; #else break; #endif } if (snes_rom_loaded) SaveSRAM(SRAM_filename); // Save the Save RAM to file SaveConfig(); set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); remove_keyboard(); #ifdef DEBUG if (snes_rom_loaded) { DisplayStatus(); } // cout << "\nThanks for testing SNEeSe - look out for future releases.\n"; cout << "\nThanks for using SNEeSe - look out for future releases.\n"; #else cout << "\nThanks for using SNEeSe - look out for future releases.\n"; #endif cout << "Displayed frames: " << Frames << endl; #ifndef NO_GUI if (GUI_ENABLED) { if (GUI_error != GUI_EXIT) { cout << "GUI: " << GUI_error_table[GUI_error] << endl; } } #endif save_debug_dumps(); cout.flush(); return 0; } END_OF_MAIN() <|endoftext|>
<commit_before>#include "main.h" /* if you add a module please register it * here by adding it to the mapping */ void register_modules(map<string,Module*> &m) { // registering a dummy module, do not copy this // m.insert(make_pair("module", new Module())); // registration, copy this for new modules m.insert(make_pair("attacks/example", new Example())); m.insert(make_pair("attacks/histogram", new Histogram())); m.insert(make_pair("attacks/caesar", new CaesarAttack())); m.insert(make_pair("ciphers/caesar", new Caesar())); m.insert(make_pair("ciphers/vigenere", new Vigenere())); } /* helper function to split strings */ void split(string &s, char delim, vector<string> &e) { stringstream ss; ss.str(s); string item; while (getline(ss, item, delim)) e.push_back(item); } /* main loop prompt */ void prompt(int &alive, map<string,Module*> &m, string &curr_m) { string buff; vector<string> tokens; // print prompt cout << "[" << curr_m << "] > "; // get input getline(cin, buff); split(buff, ' ', tokens); // parse tokens if (tokens.size() < 1) { return; } else if (tokens[0] == "use" || tokens[0] == "u") { if (tokens.size() < 2) cout << "[-] Please specify a module" << endl; else { if (m.find(tokens[1]) == m.end()) cout << "[-] Invalid module name" << endl; else curr_m = tokens[1]; } } else if(tokens[0] == "show" || tokens[0] == "s") { if (tokens.size() < 2) cout << "[-] Please specify what information to show:\n\tmodules\n\tdescription\n\toptions" << endl; else if (tokens[1] == "description" || tokens[1] == "desc" || tokens[1] == "d") { if (curr_m.empty()) cout << "[-] Please select a module first" << endl; else m[curr_m]->disp_desc(); } else if (tokens[1] == "options" || tokens[1] == "o") { if (curr_m.empty()) cout << "[-] Please select a module first" << endl; else m[curr_m]->disp_opts(); } else if (tokens[1] == "modules" || tokens[1] == "m") { cout << "Available Modules:" << endl; map<string,Module*>::iterator it = m.begin(); while (it != m.end()) cout << "\t" << (it++)->first << endl; } } else if (tokens[0] == "set") { if (tokens.size() < 3) cout << "[-] Please specify option and value\n[-] Options can be listed with: show options" << endl; else if (curr_m.empty()) cout << "[-] Please select a module first" << endl; else m[curr_m]->set_opt_value(tokens[1], tokens[2]); } else if (tokens[0] == "run" || tokens[0] == "r") { if (curr_m == "") cout << "[-] Please select a module first" << endl; else { try { int r = m[curr_m]->run(); if (r != 0) cout << "[-] Module returned with non-zero error value: " << r << endl; } catch (const exception &e) { cout << "[-] Caught fatal error from module: " << e.what() << endl; } } } else if (tokens[0] == "clear" || tokens[0] == "c") { curr_m.clear(); } else if (tokens[0] == "help" || tokens[0] == "h") { cout << HELPTEXT << endl; } else if (tokens[0] == "exit" || tokens[0] == "e" || tokens[0] == "quit" || tokens[0] == "q") { alive = 0; } else { cout << "[-] Invalid command" << endl; } } /* parse command line args */ int parse_args(int argc, char **argv, string &cm, map<string,Module*> &m) { bool run = false; vector<string> tokens; for (int i = 1; i < argc; i++) { if (strlen(argv[i]) > 2 && memcmp(argv[i], "-m", 2) == 0) { if (m.find(&argv[i][2]) == m.end()) { cout << "[-] Invalid module name" << endl; return 1; } else { cm = &argv[i][2]; } } else if (strlen(argv[i]) > 2 && memcmp(argv[i], "-o", 2) == 0) { string temp = &argv[i][2]; split(temp, ',', tokens); } else if (strcmp(argv[i], "-r") == 0) run = true; } for (int i = 0; i < tokens.size(); i++) { vector<string> pair; split(tokens[i], ':', pair); if (pair.size() != 2) { cout << "[-] Invalid option pair" << endl; return 1; } else if (cm.empty()) { cout << "[-] Cannot use -o without -m, dropping option: " << pair[0] << endl; } else { m[cm]->set_opt_value(pair[0], pair[1]); } } if (run) { if (!cm.empty()) m[cm]->run(); else cout << "[-] No module specified" << endl; return 1; } else return 0; } int main(int argc, char **argv) { int alive = 1; map<string,Module*> mods; string current_module = ""; // load modules register_modules(mods); if (parse_args(argc, argv, current_module, mods)) return 0; // welcome information and version cout << WELCOME << endl; cout << "[*] Version " << VERSION << endl; // number of loaded modules // modules loaded earlier so parse_args can use it cout << "[*] Loaded " << mods.size() << " modules" << endl; // help cout << "[*] Type 'help' to see available commands" << endl; // main loop while (alive) prompt(alive, mods, current_module); return 0; } <commit_msg>minor change<commit_after>#include "main.h" /* if you add a module please register it * here by adding it to the mapping */ void register_modules(map<string,Module*> &m) { // registering a dummy module, do not copy this // m.insert(make_pair("module", new Module())); // registration, copy this for new modules m.insert(make_pair("attacks/example", new Example())); m.insert(make_pair("attacks/histogram", new Histogram())); m.insert(make_pair("attacks/caesar", new CaesarAttack())); m.insert(make_pair("ciphers/caesar", new Caesar())); m.insert(make_pair("ciphers/vigenere", new Vigenere())); } /* helper function to split strings */ void split(string &s, char delim, vector<string> &e) { stringstream ss; ss.str(s); string item; while (getline(ss, item, delim)) e.push_back(item); } /* main loop prompt */ void prompt(int &alive, map<string,Module*> &m, string &curr_m) { string buff; vector<string> tokens; // print prompt cout << "[" << curr_m << "] > "; // get input getline(cin, buff); split(buff, ' ', tokens); // parse tokens if (tokens.size() < 1) { return; } else if (tokens[0] == "use" || tokens[0] == "u") { if (tokens.size() < 2) cout << "[-] Please specify a module" << endl; else { if (m.find(tokens[1]) == m.end()) cout << "[-] Invalid module name" << endl; else curr_m = tokens[1]; } } else if(tokens[0] == "show" || tokens[0] == "s") { if (tokens.size() < 2) cout << "[-] Please specify what information to show:\n\tmodules\n\tdescription\n\toptions" << endl; else if (tokens[1] == "description" || tokens[1] == "desc" || tokens[1] == "d") { if (curr_m.empty()) cout << "[-] Please select a module first" << endl; else m[curr_m]->disp_desc(); } else if (tokens[1] == "options" || tokens[1] == "o") { if (curr_m.empty()) cout << "[-] Please select a module first" << endl; else m[curr_m]->disp_opts(); } else if (tokens[1] == "modules" || tokens[1] == "m") { cout << "Available Modules:" << endl; map<string,Module*>::iterator it = m.begin(); while (it != m.end()) cout << "\t" << (it++)->first << endl; } } else if (tokens[0] == "set") { if (tokens.size() < 3) cout << "[-] Please specify option and value\n[-] Options can be listed with: show options" << endl; else if (curr_m.empty()) cout << "[-] Please select a module first" << endl; else m[curr_m]->set_opt_value(tokens[1], tokens[2]); } else if (tokens[0] == "run" || tokens[0] == "r") { if (curr_m == "") cout << "[-] Please select a module first" << endl; else { try { int r = m[curr_m]->run(); if (r != 0) cout << "[-] Module returned with non-zero error value: " << r << endl; } catch (const exception &e) { cout << "[-] Caught fatal error from module: " << e.what() << endl; } } } else if (tokens[0] == "clear" || tokens[0] == "c") { curr_m.clear(); } else if (tokens[0] == "help" || tokens[0] == "h") { cout << HELPTEXT << endl; } else if (tokens[0] == "exit" || tokens[0] == "e" || tokens[0] == "quit" || tokens[0] == "q") { alive = 0; } else { cout << "[-] Invalid command" << endl; } } /* parse command line args */ int parse_args(int argc, char **argv, string &cm, map<string,Module*> &m) { bool run = false; vector<string> tokens; for (int i = 1; i < argc; i++) { if (strlen(argv[i]) > 2 && memcmp(argv[i], "-m", 2) == 0) { if (m.find(&argv[i][2]) == m.end()) { cout << "[-] Invalid module name" << endl; return 1; } else { cm = &argv[i][2]; } } else if (strlen(argv[i]) > 2 && memcmp(argv[i], "-o", 2) == 0) { string temp = &argv[i][2]; split(temp, ',', tokens); } else if (strcmp(argv[i], "-r") == 0) run = true; } for (int i = 0; i < tokens.size(); i++) { vector<string> pair; split(tokens[i], ':', pair); if (pair.size() != 2) { cout << "[-] Invalid option pair" << endl; return 1; } else if (cm.empty()) { cout << "[-] Cannot use -o without -m, dropping option: " << pair[0] << endl; } else { m[cm]->set_opt_value(pair[0], pair[1]); } } if (run && !cm.empty()) { m[cm]->run(); return 1; } else return 0; } int main(int argc, char **argv) { int alive = 1; map<string,Module*> mods; string current_module = ""; // load modules register_modules(mods); if (parse_args(argc, argv, current_module, mods)) return 0; // welcome information and version cout << WELCOME << endl; cout << "[*] Version " << VERSION << endl; // number of loaded modules // modules loaded earlier so parse_args can use it cout << "[*] Loaded " << mods.size() << " modules" << endl; // help cout << "[*] Type 'help' to see available commands" << endl; // main loop while (alive) prompt(alive, mods, current_module); return 0; } <|endoftext|>
<commit_before>// Standard includes #include <stdlib.h> // OpenGL includes #include <GL/glew.h> #include <GLFW/glfw3.h> #include "fluidDynamics.h" void simulate() { // We ping-pong back and forth between two buffers on the GPU // u = advect(u); // u = diffuse(u); // u = addForces(u); // // p = computePressure(u); // u = subtractPressureGradient(u, p); } int main(int argc, char** argv) { GLFWmonitor* monitor = glfwGetPrimaryMonitor(); GLFWwindow* window; if (!glfwInit()) { return -1; } window = glfwCreateWindow(640, 480, "FlickFlow", monitor, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); while (!glfwWindowShouldClose(window)) { /* Render here */ glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return EXIT_SUCCESS; } <commit_msg>Call glewInit before trying to load shaders<commit_after>// Standard includes #include <stdlib.h> // OpenGL includes #include <GL/glew.h> #include <GLFW/glfw3.h> #include "fluidDynamics.h" #define DEFAULT_WIDTH 640 #define DEFAULT_HEIGHT 480 void simulate() { // We ping-pong back and forth between two buffers on the GPU // u = advect(u); // u = diffuse(u); // u = addForces(u); // // p = computePressure(u); // u = subtractPressureGradient(u, p); } int main(int argc, char** argv) { GLFWmonitor* monitor = glfwGetPrimaryMonitor(); GLFWwindow* window; if (!glfwInit()) { return -1; } window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "FlickFlow", monitor, NULL); if (!window) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { return -1; } printf("%s", glGetString(GL_VERSION)); loadShaders(); while (!glfwWindowShouldClose(window)) { /* Render here */ glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>//Using SDL, SDL_image, standard IO, and strings #include <SDL2/SDL.h> #include <stdio.h> #include <string> //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; //The window we'll be rendering to static SDL_Window* gWindow = NULL; //The window renderer static SDL_Renderer* gRenderer = NULL; int main(int argc, char* argv[]) { static_cast<void>(argc); static_cast<void>(argv); //Initialize SDL if (0 > SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "SDL could not initialize! SDL Error: %s\n", SDL_GetError()); return -1; } SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); SDL_EventState(SDL_FINGERMOTION, SDL_IGNORE); //Set texture filtering to linear if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { printf( "Warning: Linear texture filtering not enabled!"); } //Create window gWindow = SDL_CreateWindow("goon", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (gWindow == NULL) { fprintf(stderr, "Window could not be created! SDL Error: %s\n", SDL_GetError()); return -1; } //Create vsynced renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (gRenderer == NULL) { printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); return -1; } //Initialize renderer color SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0); bool keep_running = true; while (keep_running) { SDL_Event e; while (0 != SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: keep_running = false; break; case SDL_WINDOWEVENT: switch (e.window.event) { case SDL_WINDOWEVENT_SHOWN: printf("Window has been shown\n"); break; case SDL_WINDOWEVENT_HIDDEN: printf("Window has been hidden\n"); break; case SDL_WINDOWEVENT_EXPOSED: printf("Window has been exposed and should be redrawn\n"); break; case SDL_WINDOWEVENT_MOVED: printf("Window has been moved to (%d, %d)\n", e.window.data1, e.window.data2); break; case SDL_WINDOWEVENT_RESIZED: printf("Window has been resized to %d x %d\n", e.window.data1, e.window.data2); break; case SDL_WINDOWEVENT_SIZE_CHANGED: printf("Window size changed to %d x %d\n", e.window.data1, e.window.data2); break; case SDL_WINDOWEVENT_MINIMIZED: printf("Window minimized\n"); break; case SDL_WINDOWEVENT_MAXIMIZED: printf("Window maximized\n"); break; case SDL_WINDOWEVENT_RESTORED: printf("Window restored\n"); break; case SDL_WINDOWEVENT_ENTER: printf("Mouse entered window\n"); break; case SDL_WINDOWEVENT_LEAVE: printf("Mouse left window\n"); break; case SDL_WINDOWEVENT_FOCUS_GAINED: printf("Window gained keyboard focus\n"); break; case SDL_WINDOWEVENT_FOCUS_LOST: printf("Window lost keyboard focus\n"); break; case SDL_WINDOWEVENT_CLOSE: printf("Window manager requests that the window be closed\n"); break; default: printf("Some window event happened!\n"); break; } break; case SDL_SYSWMEVENT: printf("Event %d\n", __LINE__); break; case SDL_APP_TERMINATING: printf("Event %d\n", __LINE__); break; case SDL_APP_LOWMEMORY: printf("Event %d\n", __LINE__); break; case SDL_APP_WILLENTERBACKGROUND: printf("Event %d\n", __LINE__); break; case SDL_APP_DIDENTERBACKGROUND: printf("Event %d\n", __LINE__); break; case SDL_APP_WILLENTERFOREGROUND: printf("Event %d\n", __LINE__); break; case SDL_APP_DIDENTERFOREGROUND: printf("Event %d\n", __LINE__); break; case SDL_KEYDOWN: printf("Event %d\n", __LINE__); break; case SDL_KEYUP: printf("Event %d\n", __LINE__); break; case SDL_TEXTEDITING: printf("Event %d\n", __LINE__); break; case SDL_TEXTINPUT: printf("Event %d\n", __LINE__); break; case SDL_KEYMAPCHANGED: printf("Event %d\n", __LINE__); break; case SDL_MOUSEBUTTONDOWN: printf("Event %d\n", __LINE__); break; case SDL_MOUSEBUTTONUP: printf("Event %d\n", __LINE__); break; case SDL_MOUSEWHEEL: printf("Event %d\n", __LINE__); break; case SDL_JOYAXISMOTION: printf("Event %d\n", __LINE__); break; case SDL_JOYBALLMOTION: printf("Event %d\n", __LINE__); break; case SDL_JOYHATMOTION: printf("Event %d\n", __LINE__); break; case SDL_JOYBUTTONDOWN: printf("Event %d\n", __LINE__); break; case SDL_JOYBUTTONUP: printf("Event %d\n", __LINE__); break; case SDL_JOYDEVICEADDED: printf("Event %d\n", __LINE__); break; case SDL_JOYDEVICEREMOVED: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERAXISMOTION: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERBUTTONDOWN: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERBUTTONUP: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERDEVICEADDED: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERDEVICEREMOVED: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERDEVICEREMAPPED: printf("Event %d\n", __LINE__); break; case SDL_FINGERDOWN: printf("Event %d\n", __LINE__); break; case SDL_FINGERUP: printf("Event %d\n", __LINE__); break; case SDL_DOLLARGESTURE: printf("Event %d\n", __LINE__); break; case SDL_DOLLARRECORD: printf("Event %d\n", __LINE__); break; case SDL_MULTIGESTURE: printf("Event %d\n", __LINE__); break; case SDL_CLIPBOARDUPDATE: printf("Event %d\n", __LINE__); break; case SDL_DROPFILE: printf("Event %d\n", __LINE__); break; case SDL_AUDIODEVICEADDED: printf("Event %d\n", __LINE__); break; case SDL_AUDIODEVICEREMOVED: printf("Event %d\n", __LINE__); break; case SDL_RENDER_TARGETS_RESET: printf("Event %d\n", __LINE__); break; case SDL_RENDER_DEVICE_RESET: printf("Event %d\n", __LINE__); break; case SDL_USEREVENT: printf("Event %d\n", __LINE__); break; case SDL_LASTEVENT: printf("Event %d\n", __LINE__); break; #if 0 case SDL_MOUSEMOTION: printf("Mouse motion!\n"); break; case SDL_FINGERMOTION: printf("Finger motion\n"); break; #endif default: printf("Something happened!\n"); break; } // switch } // while //Clear screen SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0); SDL_RenderClear(gRenderer); //Update screen SDL_RenderPresent(gRenderer); } // while (keep_running) //Destroy window SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gWindow = NULL; gRenderer = NULL; //Quit SDL subsystems SDL_Quit(); return 0; } <commit_msg>Made the window resizable<commit_after>//Using SDL, SDL_image, standard IO, and strings #include <SDL2/SDL.h> #include <stdio.h> #include <string> //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; //The window we'll be rendering to static SDL_Window* gWindow = NULL; //The window renderer static SDL_Renderer* gRenderer = NULL; int main(int argc, char* argv[]) { static_cast<void>(argc); static_cast<void>(argv); //Initialize SDL if (0 > SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "SDL could not initialize! SDL Error: %s\n", SDL_GetError()); return -1; } SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); SDL_EventState(SDL_FINGERMOTION, SDL_IGNORE); //Set texture filtering to linear if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) { printf( "Warning: Linear texture filtering not enabled!"); } //Create window gWindow = SDL_CreateWindow("goon", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); if (gWindow == NULL) { fprintf(stderr, "Window could not be created! SDL Error: %s\n", SDL_GetError()); return -1; } //Create vsynced renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (gRenderer == NULL) { printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); return -1; } //Initialize renderer color SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0); bool keep_running = true; while (keep_running) { SDL_Event e; while (0 != SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: keep_running = false; break; case SDL_WINDOWEVENT: switch (e.window.event) { case SDL_WINDOWEVENT_SHOWN: printf("Window has been shown\n"); break; case SDL_WINDOWEVENT_HIDDEN: printf("Window has been hidden\n"); break; case SDL_WINDOWEVENT_EXPOSED: printf("Window has been exposed and should be redrawn\n"); break; case SDL_WINDOWEVENT_MOVED: printf("Window has been moved to (%d, %d)\n", e.window.data1, e.window.data2); break; case SDL_WINDOWEVENT_RESIZED: printf("Window has been resized to %d x %d\n", e.window.data1, e.window.data2); break; case SDL_WINDOWEVENT_SIZE_CHANGED: printf("Window size changed to %d x %d\n", e.window.data1, e.window.data2); break; case SDL_WINDOWEVENT_MINIMIZED: printf("Window minimized\n"); break; case SDL_WINDOWEVENT_MAXIMIZED: printf("Window maximized\n"); break; case SDL_WINDOWEVENT_RESTORED: printf("Window restored\n"); break; case SDL_WINDOWEVENT_ENTER: printf("Mouse entered window\n"); break; case SDL_WINDOWEVENT_LEAVE: printf("Mouse left window\n"); break; case SDL_WINDOWEVENT_FOCUS_GAINED: printf("Window gained keyboard focus\n"); break; case SDL_WINDOWEVENT_FOCUS_LOST: printf("Window lost keyboard focus\n"); break; case SDL_WINDOWEVENT_CLOSE: printf("Window manager requests that the window be closed\n"); break; default: printf("Some window event happened!\n"); break; } break; case SDL_SYSWMEVENT: printf("Event %d\n", __LINE__); break; case SDL_APP_TERMINATING: printf("Event %d\n", __LINE__); break; case SDL_APP_LOWMEMORY: printf("Event %d\n", __LINE__); break; case SDL_APP_WILLENTERBACKGROUND: printf("Event %d\n", __LINE__); break; case SDL_APP_DIDENTERBACKGROUND: printf("Event %d\n", __LINE__); break; case SDL_APP_WILLENTERFOREGROUND: printf("Event %d\n", __LINE__); break; case SDL_APP_DIDENTERFOREGROUND: printf("Event %d\n", __LINE__); break; case SDL_KEYDOWN: printf("Event %d\n", __LINE__); break; case SDL_KEYUP: printf("Event %d\n", __LINE__); break; case SDL_TEXTEDITING: printf("Event %d\n", __LINE__); break; case SDL_TEXTINPUT: printf("Event %d\n", __LINE__); break; case SDL_KEYMAPCHANGED: printf("Event %d\n", __LINE__); break; case SDL_MOUSEBUTTONDOWN: printf("Event %d\n", __LINE__); break; case SDL_MOUSEBUTTONUP: printf("Event %d\n", __LINE__); break; case SDL_MOUSEWHEEL: printf("Event %d\n", __LINE__); break; case SDL_JOYAXISMOTION: printf("Event %d\n", __LINE__); break; case SDL_JOYBALLMOTION: printf("Event %d\n", __LINE__); break; case SDL_JOYHATMOTION: printf("Event %d\n", __LINE__); break; case SDL_JOYBUTTONDOWN: printf("Event %d\n", __LINE__); break; case SDL_JOYBUTTONUP: printf("Event %d\n", __LINE__); break; case SDL_JOYDEVICEADDED: printf("Event %d\n", __LINE__); break; case SDL_JOYDEVICEREMOVED: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERAXISMOTION: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERBUTTONDOWN: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERBUTTONUP: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERDEVICEADDED: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERDEVICEREMOVED: printf("Event %d\n", __LINE__); break; case SDL_CONTROLLERDEVICEREMAPPED: printf("Event %d\n", __LINE__); break; case SDL_FINGERDOWN: printf("Event %d\n", __LINE__); break; case SDL_FINGERUP: printf("Event %d\n", __LINE__); break; case SDL_DOLLARGESTURE: printf("Event %d\n", __LINE__); break; case SDL_DOLLARRECORD: printf("Event %d\n", __LINE__); break; case SDL_MULTIGESTURE: printf("Event %d\n", __LINE__); break; case SDL_CLIPBOARDUPDATE: printf("Event %d\n", __LINE__); break; case SDL_DROPFILE: printf("Event %d\n", __LINE__); break; case SDL_AUDIODEVICEADDED: printf("Event %d\n", __LINE__); break; case SDL_AUDIODEVICEREMOVED: printf("Event %d\n", __LINE__); break; case SDL_RENDER_TARGETS_RESET: printf("Event %d\n", __LINE__); break; case SDL_RENDER_DEVICE_RESET: printf("Event %d\n", __LINE__); break; case SDL_USEREVENT: printf("Event %d\n", __LINE__); break; case SDL_LASTEVENT: printf("Event %d\n", __LINE__); break; #if 0 case SDL_MOUSEMOTION: printf("Mouse motion!\n"); break; case SDL_FINGERMOTION: printf("Finger motion\n"); break; #endif default: printf("Something happened!\n"); break; } // switch } // while //Clear screen SDL_SetRenderDrawColor(gRenderer, 0, 0, 0, 0); SDL_RenderClear(gRenderer); //Update screen SDL_RenderPresent(gRenderer); } // while (keep_running) //Destroy window SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gWindow = NULL; gRenderer = NULL; //Quit SDL subsystems SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/* * main.cpp - Demo in C++ of a simple shell * * Copyright 2010-2011 Jesús Torres <jmtorres@ull.es> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <string> #include <cli/callbacks.hpp> #include <cli/cli.hpp> #include <cli/parsers.hpp> const char INTRO_TEXT[] = "\x1b[2J\x1b[H" "Simple Shell - C++ Demo\n" "Copyright 2010-2011 Jesús Torres <jmtorres@ull.es>\n"; const char PROMPT_TEXT[] = "$ "; // // Function to be invoked by the interpreter when the user inputs the // 'exit' command. // // See include/cli/shell_parser.hpp for // cli::parser::shellparser::CommandArguments definition. // bool exitCommandCallback(const std::string& command, cli::parser::shellparser::CommandArguments const& arguments) { return true; } // // Function to be invoked by the interpreter when the user inputs any // other command. // // See include/cli/shell_parser.hpp for // cli::parser::shellparser::CommandArguments definition. // bool defaultCommandCallback(const std::string& command, cli::parser::shellparser::CommandArguments const& arguments) { std::cout << command << ": "; std::cout << arguments << std::endl; return false; } // // Main function // int main(int argc, char** argv) { // Create the interpreter object with the ShellParser parser cli::CommandLineInterpreter<cli::parser::ShellParser> interpreter; // Set the intro and prompt texts interpreter.setIntroText(INTRO_TEXT); interpreter.setPromptText(PROMPT_TEXT); // Set the callback function that will be invoked when the user inputs // the 'exit' command interpreter.setCallback<cli::callback::DoCommandCallback>( &exitCommandCallback, "exit"); // Set the callback function that will be invoked when the user inputs // any other command interpreter.setCallback<cli::callback::DoCommandCallback>( &defaultCommandCallback); // Run the interpreter interpreter.loop(); return 0; } <commit_msg>some additional comments about how the interpreter works<commit_after>/* * main.cpp - Demo in C++ of a simple shell * * Copyright 2010-2011 Jesús Torres <jmtorres@ull.es> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <string> #include <cli/callbacks.hpp> #include <cli/cli.hpp> #include <cli/parsers.hpp> const char INTRO_TEXT[] = "\x1b[2J\x1b[H" "Simple Shell - C++ Demo\n" "Copyright 2010-2011 Jesús Torres <jmtorres@ull.es>\n"; const char PROMPT_TEXT[] = "$ "; // // Function to be invoked by the interpreter when the user inputs the // 'exit' command. // // If this function returns true, the interpreter ends. // // See include/cli/shell_parser.hpp for // cli::parser::shellparser::CommandArguments definition. // bool exitCommandCallback(const std::string& command, cli::parser::shellparser::CommandArguments const& arguments) { return true; } // // Function to be invoked by the interpreter when the user inputs any // other command. // // If this function returns true, the interpreter ends. // // See include/cli/shell_parser.hpp for // cli::parser::shellparser::CommandArguments definition. // bool defaultCommandCallback(const std::string& command, cli::parser::shellparser::CommandArguments const& arguments) { std::cout << command << ": "; std::cout << arguments << std::endl; return false; } // // Main function // int main(int argc, char** argv) { // Create the interpreter object with the ShellParser parser cli::CommandLineInterpreter<cli::parser::ShellParser> interpreter; // Set the intro and prompt texts interpreter.setIntroText(INTRO_TEXT); interpreter.setPromptText(PROMPT_TEXT); // Set the callback function that will be invoked when the user inputs // the 'exit' command interpreter.setCallback<cli::callback::DoCommandCallback>( &exitCommandCallback, "exit"); // Set the callback function that will be invoked when the user inputs // any other command interpreter.setCallback<cli::callback::DoCommandCallback>( &defaultCommandCallback); // Run the interpreter interpreter.loop(); return 0; } <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2015 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <openspace/engine/openspaceengine.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logging> #include <openspace/rendering/renderengine.h> #include <sgct.h> sgct::Engine* _sgctEngine; // function pointer declarations void mainInitFunc(); void mainPreSyncFunc(); void mainPostSyncPreDrawFunc(); void mainRenderFunc(); void mainPostDrawFunc(); void mainKeyboardCallback(int key, int action); void mainCharCallback(unsigned int codepoint); void mainMouseButtonCallback(int key, int action); void mainMousePosCallback(double x, double y); void mainMouseScrollCallback(double posX, double posY); void mainEncodeFun(); void mainDecodeFun(); void mainExternalControlCallback(const char * receivedChars, int size); void mainLogCallback(const char* msg); //temporary post-FX functions, TODO make a more permanent solution to this @JK void postFXPass(); void setupPostFX(); GLint _postFXTexLoc; GLint _postFXOpacityLoc; namespace { const std::string _loggerCat = "main"; } int main(int argc, char** argv) { // create the OpenSpace engine and get arguments for the sgct engine std::vector<std::string> sgctArguments; const bool success = openspace::OpenSpaceEngine::create(argc, argv, sgctArguments); if (!success) return EXIT_FAILURE; // create sgct engine c arguments int newArgc = static_cast<int>(sgctArguments.size()); char** newArgv = new char*[newArgc]; for (int i = 0; i < newArgc; ++i) newArgv[i] = const_cast<char*>(sgctArguments.at(i).c_str()); sgct::MessageHandler::instance()->setLogToConsole(false); sgct::MessageHandler::instance()->setShowTime(false); sgct::MessageHandler::instance()->setLogToCallback(true); sgct::MessageHandler::instance()->setLogCallback(mainLogCallback); LDEBUG("Creating SGCT Engine"); _sgctEngine = new sgct::Engine(newArgc, newArgv); // deallocate sgct c arguments delete[] newArgv; // Bind functions _sgctEngine->setInitOGLFunction(mainInitFunc); _sgctEngine->setPreSyncFunction(mainPreSyncFunc); _sgctEngine->setPostSyncPreDrawFunction(mainPostSyncPreDrawFunc); _sgctEngine->setDrawFunction(mainRenderFunc); _sgctEngine->setPostDrawFunction(mainPostDrawFunc); _sgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback); _sgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback); _sgctEngine->setMousePosCallbackFunction(mainMousePosCallback); _sgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback); _sgctEngine->setExternalControlCallback(mainExternalControlCallback); _sgctEngine->setCharCallbackFunction(mainCharCallback); // set encode and decode functions // NOTE: starts synchronizing before init functions sgct::SharedData::instance()->setEncodeFunction(mainEncodeFun); sgct::SharedData::instance()->setDecodeFunction(mainDecodeFun); // try to open a window LDEBUG("Initialize SGCT Engine"); #ifdef __APPLE__ sgct::Engine::RunMode rm = sgct::Engine::RunMode::OpenGL_4_1_Core_Profile; #else sgct::Engine::RunMode rm = sgct::Engine::RunMode::OpenGL_4_3_Core_Profile; #endif const bool initSuccess = _sgctEngine->init(rm); if (!initSuccess) { LFATAL("Initializing failed"); // could not open a window, deallocates and exits delete _sgctEngine; openspace::OpenSpaceEngine::destroy(); return EXIT_FAILURE; } //is this node the master? (must be set after call to _sgctEngine->init()) OsEng.ref().setMaster(_sgctEngine->isMaster()); // Main loop LDEBUG("Starting rendering loop"); _sgctEngine->render(); LDEBUG("Destroying OpenSpaceEngine"); openspace::OpenSpaceEngine::destroy(); // Clean up (de-allocate) LDEBUG("Destroying SGCT Engine"); delete _sgctEngine; // Exit program exit(EXIT_SUCCESS); } void mainInitFunc() { bool success = OsEng.initialize(); if (success) success = OsEng.initializeGL(); if (!success) { LFATAL("Initializing OpenSpaceEngine failed"); std::cout << "Press any key to continue..."; std::cin.ignore(100); exit(EXIT_FAILURE); } //temporary post-FX solution, TODO add a more permanent solution @JK setupPostFX(); } void mainPreSyncFunc() { OsEng.preSynchronization(); } void mainPostSyncPreDrawFunc() { OsEng.postSynchronizationPreDraw(); } void mainRenderFunc() { //not the most efficient, but for clarity @JK glm::mat4 userMatrix = glm::translate(glm::mat4(1.f), _sgctEngine->getDefaultUserPtr()->getPos()); glm::mat4 sceneMatrix = _sgctEngine->getModelMatrix(); glm::mat4 viewMatrix = _sgctEngine->getActiveViewMatrix() * userMatrix; //dont shift nav-direction on master, makes it very tricky to navigate @JK if (!OsEng.ref().isMaster()){ viewMatrix = viewMatrix * sceneMatrix; } glm::mat4 projectionMatrix = _sgctEngine->getActiveProjectionMatrix(); OsEng.render(projectionMatrix, viewMatrix); } void mainPostDrawFunc() { OsEng.postDraw(); } void mainExternalControlCallback(const char* receivedChars, int size) { if (OsEng.ref().isMaster()) OsEng.externalControlCallback(receivedChars, size, 0); } void mainKeyboardCallback(int key, int action) { if (OsEng.ref().isMaster()) OsEng.keyboardCallback(key, action); } void mainMouseButtonCallback(int key, int action) { if (OsEng.ref().isMaster()) OsEng.mouseButtonCallback(key, action); } void mainMousePosCallback(double x, double y) { // TODO use float instead if (OsEng.ref().isMaster()) OsEng.mousePositionCallback(static_cast<int>(x), static_cast<int>(y)); } void mainMouseScrollCallback(double posX, double posY) { // TODO use float instead if (OsEng.ref().isMaster()) OsEng.mouseScrollWheelCallback(static_cast<int>(posY)); } void mainCharCallback(unsigned int codepoint) { if (OsEng.ref().isMaster()) OsEng.charCallback(codepoint); } void mainEncodeFun() { OsEng.encode(); } void mainDecodeFun() { OsEng.decode(); } void mainLogCallback(const char* msg){ std::string message = msg; // Remove the trailing \n that is passed along LINFOC("SGCT", message.substr(0, std::max<size_t>(message.size() - 1, 0))); } void postFXPass(){ glUniform1i(_postFXTexLoc, 0); if (OsEng.isMaster()){ glUniform1f(_postFXOpacityLoc, 1.f); } else{ glUniform1f(_postFXOpacityLoc, OsEng.ref().renderEngine()->globalOpacity()); } } void setupPostFX(){ sgct::PostFX fx[1]; sgct::ShaderProgram *shader; fx[0].init("OpacityControl", absPath("${SHADERS}/postFX_vs.glsl"), absPath("${SHADERS}/postFX_fs.glsl")); fx[0].setUpdateUniformsFunction(postFXPass); shader = fx[0].getShaderProgram(); shader->bind(); _postFXTexLoc = shader->getUniformLocation("Tex"); _postFXOpacityLoc = shader->getUniformLocation("Opacity"); shader->unbind(); _sgctEngine->addPostFX(fx[0]); }<commit_msg>OpenGL 4.3 -> OpenGL 4.2<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2015 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <openspace/engine/openspaceengine.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logging> #include <openspace/rendering/renderengine.h> #include <sgct.h> sgct::Engine* _sgctEngine; // function pointer declarations void mainInitFunc(); void mainPreSyncFunc(); void mainPostSyncPreDrawFunc(); void mainRenderFunc(); void mainPostDrawFunc(); void mainKeyboardCallback(int key, int action); void mainCharCallback(unsigned int codepoint); void mainMouseButtonCallback(int key, int action); void mainMousePosCallback(double x, double y); void mainMouseScrollCallback(double posX, double posY); void mainEncodeFun(); void mainDecodeFun(); void mainExternalControlCallback(const char * receivedChars, int size); void mainLogCallback(const char* msg); //temporary post-FX functions, TODO make a more permanent solution to this @JK void postFXPass(); void setupPostFX(); GLint _postFXTexLoc; GLint _postFXOpacityLoc; namespace { const std::string _loggerCat = "main"; } int main(int argc, char** argv) { // create the OpenSpace engine and get arguments for the sgct engine std::vector<std::string> sgctArguments; const bool success = openspace::OpenSpaceEngine::create(argc, argv, sgctArguments); if (!success) return EXIT_FAILURE; // create sgct engine c arguments int newArgc = static_cast<int>(sgctArguments.size()); char** newArgv = new char*[newArgc]; for (int i = 0; i < newArgc; ++i) newArgv[i] = const_cast<char*>(sgctArguments.at(i).c_str()); sgct::MessageHandler::instance()->setLogToConsole(false); sgct::MessageHandler::instance()->setShowTime(false); sgct::MessageHandler::instance()->setLogToCallback(true); sgct::MessageHandler::instance()->setLogCallback(mainLogCallback); LDEBUG("Creating SGCT Engine"); _sgctEngine = new sgct::Engine(newArgc, newArgv); // deallocate sgct c arguments delete[] newArgv; // Bind functions _sgctEngine->setInitOGLFunction(mainInitFunc); _sgctEngine->setPreSyncFunction(mainPreSyncFunc); _sgctEngine->setPostSyncPreDrawFunction(mainPostSyncPreDrawFunc); _sgctEngine->setDrawFunction(mainRenderFunc); _sgctEngine->setPostDrawFunction(mainPostDrawFunc); _sgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback); _sgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback); _sgctEngine->setMousePosCallbackFunction(mainMousePosCallback); _sgctEngine->setMouseScrollCallbackFunction(mainMouseScrollCallback); _sgctEngine->setExternalControlCallback(mainExternalControlCallback); _sgctEngine->setCharCallbackFunction(mainCharCallback); // set encode and decode functions // NOTE: starts synchronizing before init functions sgct::SharedData::instance()->setEncodeFunction(mainEncodeFun); sgct::SharedData::instance()->setDecodeFunction(mainDecodeFun); // try to open a window LDEBUG("Initialize SGCT Engine"); #ifdef __APPLE__ sgct::Engine::RunMode rm = sgct::Engine::RunMode::OpenGL_4_1_Core_Profile; #else sgct::Engine::RunMode rm = sgct::Engine::RunMode::OpenGL_4_2_Core_Profile; #endif const bool initSuccess = _sgctEngine->init(rm); if (!initSuccess) { LFATAL("Initializing failed"); // could not open a window, deallocates and exits delete _sgctEngine; openspace::OpenSpaceEngine::destroy(); return EXIT_FAILURE; } //is this node the master? (must be set after call to _sgctEngine->init()) OsEng.ref().setMaster(_sgctEngine->isMaster()); // Main loop LDEBUG("Starting rendering loop"); _sgctEngine->render(); LDEBUG("Destroying OpenSpaceEngine"); openspace::OpenSpaceEngine::destroy(); // Clean up (de-allocate) LDEBUG("Destroying SGCT Engine"); delete _sgctEngine; // Exit program exit(EXIT_SUCCESS); } void mainInitFunc() { bool success = OsEng.initialize(); if (success) success = OsEng.initializeGL(); if (!success) { LFATAL("Initializing OpenSpaceEngine failed"); std::cout << "Press any key to continue..."; std::cin.ignore(100); exit(EXIT_FAILURE); } //temporary post-FX solution, TODO add a more permanent solution @JK setupPostFX(); } void mainPreSyncFunc() { OsEng.preSynchronization(); } void mainPostSyncPreDrawFunc() { OsEng.postSynchronizationPreDraw(); } void mainRenderFunc() { //not the most efficient, but for clarity @JK glm::mat4 userMatrix = glm::translate(glm::mat4(1.f), _sgctEngine->getDefaultUserPtr()->getPos()); glm::mat4 sceneMatrix = _sgctEngine->getModelMatrix(); glm::mat4 viewMatrix = _sgctEngine->getActiveViewMatrix() * userMatrix; //dont shift nav-direction on master, makes it very tricky to navigate @JK if (!OsEng.ref().isMaster()){ viewMatrix = viewMatrix * sceneMatrix; } glm::mat4 projectionMatrix = _sgctEngine->getActiveProjectionMatrix(); OsEng.render(projectionMatrix, viewMatrix); } void mainPostDrawFunc() { OsEng.postDraw(); } void mainExternalControlCallback(const char* receivedChars, int size) { if (OsEng.ref().isMaster()) OsEng.externalControlCallback(receivedChars, size, 0); } void mainKeyboardCallback(int key, int action) { if (OsEng.ref().isMaster()) OsEng.keyboardCallback(key, action); } void mainMouseButtonCallback(int key, int action) { if (OsEng.ref().isMaster()) OsEng.mouseButtonCallback(key, action); } void mainMousePosCallback(double x, double y) { // TODO use float instead if (OsEng.ref().isMaster()) OsEng.mousePositionCallback(static_cast<int>(x), static_cast<int>(y)); } void mainMouseScrollCallback(double posX, double posY) { // TODO use float instead if (OsEng.ref().isMaster()) OsEng.mouseScrollWheelCallback(static_cast<int>(posY)); } void mainCharCallback(unsigned int codepoint) { if (OsEng.ref().isMaster()) OsEng.charCallback(codepoint); } void mainEncodeFun() { OsEng.encode(); } void mainDecodeFun() { OsEng.decode(); } void mainLogCallback(const char* msg){ std::string message = msg; // Remove the trailing \n that is passed along LINFOC("SGCT", message.substr(0, std::max<size_t>(message.size() - 1, 0))); } void postFXPass(){ glUniform1i(_postFXTexLoc, 0); if (OsEng.isMaster()){ glUniform1f(_postFXOpacityLoc, 1.f); } else{ glUniform1f(_postFXOpacityLoc, OsEng.ref().renderEngine()->globalOpacity()); } } void setupPostFX(){ sgct::PostFX fx[1]; sgct::ShaderProgram *shader; fx[0].init("OpacityControl", absPath("${SHADERS}/postFX_vs.glsl"), absPath("${SHADERS}/postFX_fs.glsl")); fx[0].setUpdateUniformsFunction(postFXPass); shader = fx[0].getShaderProgram(); shader->bind(); _postFXTexLoc = shader->getUniformLocation("Tex"); _postFXOpacityLoc = shader->getUniformLocation("Opacity"); shader->unbind(); _sgctEngine->addPostFX(fx[0]); }<|endoftext|>
<commit_before>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); // Display formatting std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; size_t n = 12; // 12 qubits size_t N = std::pow(n, 2); std::cout << "n=" << n << " qubits, matrix size " << N << " x " << N << " ." << endl; // TIMING Timer t, total; // start the timer, automatic tic() in the constructor cmat randcmat = cmat::Random(N, N); t.toc(); // read the time cout << "Took " << t.seconds() << " seconds."; t.tic(); // reset the chronometer cmat prodmat; prodmat = randcmat * randcmat; t.toc(); // read the time cout << "Took " << t.seconds() << " seconds."; total.toc(); // read the total running time cout << "Total time: " << total.seconds() << " seconds." << endl; // END TIMING cout << endl << "Exiting qpp..." << endl; } <commit_msg>commit<commit_after>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; //int main(int argc, char **argv) int main() { _init(); // Display formatting std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; size_t n = 12; // 12 qubits size_t N = std::pow(2, n); std::cout << "n=" << n << " qubits, matrix size " << N << " x " << N << " ." << endl; // TIMING Timer t, total; // start the timer, automatic tic() in the constructor cmat randcmat = cmat::Random(N, N); t.toc(); // read the time cout << "Took " << t.seconds() << " seconds." << endl; t.tic(); // reset the chronometer cmat prodmat; prodmat = randcmat * randcmat; t.toc(); // read the time cout << "Took " << t.seconds() << " seconds." << endl; total.toc(); // read the total running time cout << "Total time: " << total.seconds() << " seconds." << endl; // END TIMING cout << endl << "Exiting qpp..." << endl; } <|endoftext|>
<commit_before>#include "coloshell.hpp" #include "platform.h" #include "program.hpp" #include "beadisassembler.hpp" #include "toolbox.hpp" #include "argtable2.h" #include <iostream> #include <exception> #include <cstdlib> #define NUM_V "0.1" #ifdef ARCH_X64 #define VERSION_TMP NUM_V " x64 built the " __DATE__ " " __TIME__ #else #define VERSION_TMP NUM_V " x86 built the " __DATE__ " " __TIME__ #endif #ifdef WINDOWS #define VERSION_TM VERSION_TMP " for Windows" #else #define VERSION_TM VERSION_TMP " for Unix" #endif #ifdef _DEBUG #define VERSION VERSION_TM " (Debug)" #else #define VERSION VERSION_TM " (Release)" #endif int main(int argc, char* argv[]) { struct arg_file *file = arg_file0("f", "file", "<binary path>", "give binary path"); struct arg_int *display = arg_int0("i", "info", "<0-2>", "display information concerning the elf/pe"); struct arg_int *rop = arg_int0("r", "rop", "<positive int>", "find a bunch of gadgets usable in your future exploits (the maximum number of instruction in arg)"); struct arg_str *shexa = arg_str0(NULL, "search-hexa", "<\\x90A\\x90>", "try to find hex values"); struct arg_str *sint = arg_str0(NULL, "search-int", "<int in hex>", "try to find a pointer on a specific integer value"); struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_lit *version = arg_lit0("v", "version", "print version information and exit"); struct arg_end *end = arg_end(20); void* argtable[] = {file, display, rop, shexa, sint, help, version, end}; if(arg_nullcheck(argtable) != 0) RAISE_EXCEPTION("Cannot allocate long option structures"); int nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { arg_print_errors(stdout, end, "rp++"); std::cout << "Try './rp++ --help' for more information." << std::endl; return -1; } try { if(help->count > 0) { w_yel_lf("DESCRIPTION:"); w_red("rp++"); std::cout << " is a very simple tool with a very simple purpose:" << std::endl << " -> helping you to find interesting gadget in pe/elf x86/x64 binaries." << std::endl; std::cout << "NB: The original idea goes to Jonathan Salwan and its 'ROPGadget' tool." << std::endl << std::endl; w_yel_lf("USAGE:"); std::cout << "./rp++"; arg_print_syntax(stdout, argtable, "\n"); std::cout << std::endl; w_yel_lf("OPTIONS:"); arg_print_glossary(stdout, argtable, " %-25s %s\n"); } if(version->count > 0) std::cout << "You are currently using the version " << VERSION << " of rp++." << std::endl; /* If we've asked the help or version option, we assume the program is terminated */ if(version->count > 0 || help->count > 0) return 0; if(file->count > 0) { std::string program_path(file->filename[0]); Program p(program_path); if(display->count > 0) { if(display->ival[0] < 0 || display->ival[0] > 2) display->ival[0] = 0; p.display_information((VerbosityLevel)display->ival[0]); } if(rop->count > 0) { if(rop->ival[0] < 0) rop->ival[0] = 0; p.find_and_display_gadgets(rop->ival[0]); } if(shexa->count > 0) p.search_and_display(shexa->sval[0]); if(sint->count > 0) { unsigned int val = std::strtoul(sint->sval[0], NULL, 16); p.search_int_and_display(val); } } } catch(const std::exception &e) { enable_color(COLO_RED); std::cout << e.what() << std::endl; disable_color(); } return 0; }<commit_msg>main: display help if no argument is passed<commit_after>#include "coloshell.hpp" #include "platform.h" #include "program.hpp" #include "beadisassembler.hpp" #include "toolbox.hpp" #include "argtable2.h" #include <iostream> #include <exception> #include <cstdlib> #define NUM_V "0.1" #ifdef ARCH_X64 #define VERSION_TMP NUM_V " x64 built the " __DATE__ " " __TIME__ #else #define VERSION_TMP NUM_V " x86 built the " __DATE__ " " __TIME__ #endif #ifdef WINDOWS #define VERSION_TM VERSION_TMP " for Windows" #else #define VERSION_TM VERSION_TMP " for Unix" #endif #ifdef _DEBUG #define VERSION VERSION_TM " (Debug)" #else #define VERSION VERSION_TM " (Release)" #endif int main(int argc, char* argv[]) { struct arg_file *file = arg_file0("f", "file", "<binary path>", "give binary path"); struct arg_int *display = arg_int0("i", "info", "<0-2>", "display information concerning the elf/pe"); struct arg_int *rop = arg_int0("r", "rop", "<positive int>", "find a bunch of gadgets usable in your future exploits (the maximum number of instruction in arg)"); struct arg_str *shexa = arg_str0(NULL, "search-hexa", "<\\x90A\\x90>", "try to find hex values"); struct arg_str *sint = arg_str0(NULL, "search-int", "<int in hex>", "try to find a pointer on a specific integer value"); struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_lit *version = arg_lit0("v", "version", "print version information and exit"); struct arg_end *end = arg_end(20); void* argtable[] = {file, display, rop, shexa, sint, help, version, end}; if(arg_nullcheck(argtable) != 0) RAISE_EXCEPTION("Cannot allocate long option structures"); int nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { arg_print_errors(stdout, end, "rp++"); std::cout << "Try './rp++ --help' for more information." << std::endl; return -1; } try { if(help->count > 0 || argc == 1) { w_yel_lf("DESCRIPTION:"); w_red("rp++"); std::cout << " is a very simple tool with a very simple purpose:" << std::endl << " -> helping you to find interesting gadget in pe/elf x86/x64 binaries." << std::endl; std::cout << "NB: The original idea goes to Jonathan Salwan and its 'ROPGadget' tool." << std::endl << std::endl; w_yel_lf("USAGE:"); std::cout << "./rp++"; arg_print_syntax(stdout, argtable, "\n"); std::cout << std::endl; w_yel_lf("OPTIONS:"); arg_print_glossary(stdout, argtable, " %-25s %s\n"); } if(version->count > 0) std::cout << "You are currently using the version " << VERSION << " of rp++." << std::endl; /* If we've asked the help or version option, we assume the program is terminated */ if(version->count > 0 || help->count > 0) return 0; if(file->count > 0) { std::string program_path(file->filename[0]); Program p(program_path); if(display->count > 0) { if(display->ival[0] < 0 || display->ival[0] > 2) display->ival[0] = 0; p.display_information((VerbosityLevel)display->ival[0]); } if(rop->count > 0) { if(rop->ival[0] < 0) rop->ival[0] = 0; p.find_and_display_gadgets(rop->ival[0]); } if(shexa->count > 0) p.search_and_display(shexa->sval[0]); if(sint->count > 0) { unsigned int val = std::strtoul(sint->sval[0], NULL, 16); p.search_int_and_display(val); } } } catch(const std::exception &e) { enable_color(COLO_RED); std::cout << e.what() << std::endl; disable_color(); } return 0; }<|endoftext|>
<commit_before>#include "stdinc.h" #include "parser.hpp" #include "error.hpp" #include "symtable.hpp" #include "commands.hpp" #include "compiler.hpp" #include "disassembler.hpp" #include "decompiler.hpp" #include "codegen.hpp" #include "program.hpp" #include "system.hpp" #include "cpp/argv.hpp" int compile(fs::path input, fs::path output, const Options& options, const Commands& commands); int decompile(fs::path input, fs::path output, const Options& options, const Commands& commands); const char* help_message = R"(Usage: gta3sc [compile|decompile] file --config=<name> [options] Options: --help Display this information -o <file> Place the output into <file> --config=<name> Which compilation configurations to use (gta3,gtavc, gtasa). This effectively reads the data files at '/config/<name>/' and sets some appropriate flags. -pedantic Forbid the usage of extensions not in R* compiler. -f[no-]half-float Whether codegen uses GTA III half-float format. -f[no-]text-label-prefix Whether codegen uses GTA SA text label data type. )"; enum class Action { None, Compile, Decompile, }; int main(int argc, char** argv) { // use fprintf(stderr, ...) for error reporting since we don't have a ProgramContext on main. Action action = Action::None; Options options; fs::path input, output; std::string config_name; optional<Commands> commands; // can't construct Commands with no arguments ++argv; if(*argv && **argv != '-') { if(!strcmp(*argv, "compile")) { ++argv; action = Action::Compile; } if(!strcmp(*argv, "decompile")) { ++argv; action = Action::Decompile; } } try { bool flag; while(*argv) { if(**argv != '-') { if(!input.empty()) throw invalid_opt("input file appears twice"); input = *argv; ++argv; } else if(optget(argv, "-h", "--help", 0)) { fprintf(stdout, "%s", help_message); return EXIT_SUCCESS; } else if(const char* o = optget(argv, "-o", nullptr, 1)) { output = o; } else if(optget(argv, nullptr, "-pedantic", 0)) { options.pedantic = true; } else if(const char* name = optget(argv, nullptr, "--config", 1)) { config_name = name; // TODO instead of hard-coding the flags, use a XML? if(config_name == "gta3") { options.use_half_float = true; options.has_text_label_prefix = false; } else if(config_name == "gtavc") { options.use_half_float = false; options.has_text_label_prefix = false; } else if(config_name == "gtasa") { options.use_half_float = false; options.has_text_label_prefix = true; } else { throw invalid_opt("arbitrary config names not supported yet"); } } else if(optflag(argv, "half-float", &flag)) { options.use_half_float = flag; } else if(optflag(argv, "text-label-prefix", &flag)) { options.has_text_label_prefix = flag; } else { throw invalid_opt(fmt::format("unregonized argument '{}'", *argv)); } } } catch(const invalid_opt& e) { fprintf(stderr, "gta3sc: error: %s\n", e.what()); return EXIT_FAILURE; } if(input.empty()) { fprintf(stderr, "gta3sc: error: no input file\n"); return EXIT_FAILURE; } if(config_name.empty()) { fprintf(stderr, "gta3sc: error: no game config specified [--config=<name>]\n"); return EXIT_FAILURE; } if(action == Action::None) { std::string extension = input.extension().string(); if(iequal_to()(extension, ".sc")) action = Action::Compile; else if(iequal_to()(extension, ".scm")) action = Action::Decompile; else if(iequal_to()(extension, ".scc")) action = Action::Decompile; else if(iequal_to()(extension, ".cs")) action = Action::Decompile; else if(iequal_to()(extension, ".cm")) action = Action::Decompile; else { fprintf(stderr, "gta3sc: error: could not infer action from input extension (compile/decompile)\n"); return EXIT_FAILURE; } } fs::path conf_path = config_path(); fprintf(stdout, "Using '%s' as configuration path\n", conf_path.string().c_str()); try { commands = Commands::from_xml({ config_name + "/constants.xml", config_name + "/commands.xml" }); } catch(const ConfigError& e) { fprintf(stderr, "gta3sc: error: %s\n", e.what()); } switch(action) { case Action::Compile: return compile(input, output, options, *commands); case Action::Decompile: return decompile(input, output, options, *commands); default: Unreachable(); } } int compile(fs::path input, fs::path output, const Options& options, const Commands& commands) { if(output.empty()) { // TODO .cs .scc output = input; output.replace_extension(".scm"); } try { std::vector<shared_ptr<Script>> scripts; ProgramContext program(options); //const char* input = "intro.sc"; //const char* input = "test.sc"; //const char* input = "gta3_src/main.sc"; auto main = Script::create(input, ScriptType::Main); auto symbols = SymTable::from_script(*main, commands, program); symbols.apply_offset_to_vars(2); scripts.emplace_back(main); auto subdir = main->scan_subdir(); auto ext_scripts = read_and_scan_symbols(subdir, symbols.extfiles.begin(), symbols.extfiles.end(), ScriptType::MainExtension, commands, program); auto sub_scripts = read_and_scan_symbols(subdir, symbols.subscript.begin(), symbols.subscript.end(), ScriptType::Subscript, commands, program); auto mission_scripts = read_and_scan_symbols(subdir, symbols.mission.begin(), symbols.mission.end(), ScriptType::Mission, commands, program); // TODO handle lex/parser errors for(auto& x : ext_scripts) { symbols.merge(std::move(x.second), program); scripts.emplace_back(x.first); // maybe move } for(auto& x : sub_scripts) { symbols.merge(std::move(x.second), program); scripts.emplace_back(x.first); // maybe move } for(size_t i = 0; i < mission_scripts.size(); ++i) { auto& x = mission_scripts[i]; symbols.merge(std::move(x.second), program); scripts.emplace_back(x.first); // maybe move scripts.back()->mission_id = i; } symbols.check_command_count(program); symbols.build_script_table(scripts); for(auto& script : scripts) { script->annotate_tree(symbols, commands, program); } // not thread-safe std::vector<std::string> models = Script::compute_unknown_models(scripts); // CompilerContext wants an annotated ASTs, if we have any error, it's possible that // the AST is not correctly annotated. if(program.has_error()) throw HaltJobException(); std::vector<CodeGenerator> gens; gens.reserve(scripts.size()); for(auto& script : scripts) { CompilerContext cc(script, symbols, commands, program); cc.compile(); gens.emplace_back(std::move(cc), program); } // Codegen expects a successful compilation. if(program.has_error()) throw HaltJobException(); size_t global_vars_size = 0; if(auto highest_var = symbols.highest_global_var()) { global_vars_size = (*highest_var)->end_offset(); } CompiledScmHeader header(CompiledScmHeader::Version::Liberty, symbols.size_global_vars(), models, scripts); // not thread-safe Expects(gens.size() == scripts.size()); for(size_t i = 0; i < gens.size(); ++i) // zip { scripts[i]->size = gens[i].compute_labels(); // <- maybe???! this is actually thread safe } // Script::compute_script_offsets(scripts, header.compiled_size()); // <- but this isn't for(auto& gen : gens) gen.generate(); if(FILE* f = u8fopen(output, "wb")) { auto guard = make_scope_guard([&] { fclose(f); }); if(true) { CodeGeneratorData hgen(header, program); hgen.generate(); write_file(f, hgen.buffer(), hgen.buffer_size()); } for(auto& gen : gens) { write_file(f, gen.buffer(), gen.buffer_size()); } } else { program.error(nocontext, "XXX"); } if(program.has_error()) throw HaltJobException(); } catch(const HaltJobException&) { // TODO put a error message of compilation failed instead of zeroing output!??!!! FILE* f = u8fopen(output, "wb"); if(f) fclose(f); } return 0; } int decompile(fs::path input, fs::path output, const Options& options, const Commands& commands) { ProgramContext program(options); FILE* outstream; if(output.empty()) { outstream = stdout; } else { outstream = u8fopen(output, "wb"); if(!outstream) program.fatal_error(nocontext, "Could not open file {} for writing", output.generic_u8string()); } auto guard = make_scope_guard([&] { if(outstream != stdout) fclose(outstream); }); auto opt_decomp = Disassembler::from_file(options, commands, input); if(!opt_decomp) program.fatal_error(nocontext, "File {} does not exist", input.generic_u8string()); Disassembler decomp(std::move(*opt_decomp)); auto scm_header = decomp.read_header(DecompiledScmHeader::Version::Liberty).value(); decomp.analyze_header(scm_header); decomp.run_analyzer(); auto data = decomp.get_data(); fprintf(outstream, "%s\n", DecompilerContext(commands, std::move(data)).decompile().c_str()); return 0; } <commit_msg>Mention possible options for config names in error case<commit_after>#include "stdinc.h" #include "parser.hpp" #include "error.hpp" #include "symtable.hpp" #include "commands.hpp" #include "compiler.hpp" #include "disassembler.hpp" #include "decompiler.hpp" #include "codegen.hpp" #include "program.hpp" #include "system.hpp" #include "cpp/argv.hpp" int compile(fs::path input, fs::path output, const Options& options, const Commands& commands); int decompile(fs::path input, fs::path output, const Options& options, const Commands& commands); const char* help_message = R"(Usage: gta3sc [compile|decompile] file --config=<name> [options] Options: --help Display this information -o <file> Place the output into <file> --config=<name> Which compilation configurations to use (gta3,gtavc, gtasa). This effectively reads the data files at '/config/<name>/' and sets some appropriate flags. -pedantic Forbid the usage of extensions not in R* compiler. -f[no-]half-float Whether codegen uses GTA III half-float format. -f[no-]text-label-prefix Whether codegen uses GTA SA text label data type. )"; enum class Action { None, Compile, Decompile, }; int main(int argc, char** argv) { // use fprintf(stderr, ...) for error reporting since we don't have a ProgramContext on main. Action action = Action::None; Options options; fs::path input, output; std::string config_name; optional<Commands> commands; // can't construct Commands with no arguments ++argv; if(*argv && **argv != '-') { if(!strcmp(*argv, "compile")) { ++argv; action = Action::Compile; } if(!strcmp(*argv, "decompile")) { ++argv; action = Action::Decompile; } } try { bool flag; while(*argv) { if(**argv != '-') { if(!input.empty()) throw invalid_opt("input file appears twice"); input = *argv; ++argv; } else if(optget(argv, "-h", "--help", 0)) { fprintf(stdout, "%s", help_message); return EXIT_SUCCESS; } else if(const char* o = optget(argv, "-o", nullptr, 1)) { output = o; } else if(optget(argv, nullptr, "-pedantic", 0)) { options.pedantic = true; } else if(const char* name = optget(argv, nullptr, "--config", 1)) { config_name = name; // TODO instead of hard-coding the flags, use a XML? if(config_name == "gta3") { options.use_half_float = true; options.has_text_label_prefix = false; } else if(config_name == "gtavc") { options.use_half_float = false; options.has_text_label_prefix = false; } else if(config_name == "gtasa") { options.use_half_float = false; options.has_text_label_prefix = true; } else { throw invalid_opt("arbitrary config names not supported yet. Must be 'gta3', 'gtavc' or 'gtasa'"); } } else if(optflag(argv, "half-float", &flag)) { options.use_half_float = flag; } else if(optflag(argv, "text-label-prefix", &flag)) { options.has_text_label_prefix = flag; } else { throw invalid_opt(fmt::format("unregonized argument '{}'", *argv)); } } } catch(const invalid_opt& e) { fprintf(stderr, "gta3sc: error: %s\n", e.what()); return EXIT_FAILURE; } if(input.empty()) { fprintf(stderr, "gta3sc: error: no input file\n"); return EXIT_FAILURE; } if(config_name.empty()) { fprintf(stderr, "gta3sc: error: no game config specified [--config=<name>]\n"); return EXIT_FAILURE; } if(action == Action::None) { std::string extension = input.extension().string(); if(iequal_to()(extension, ".sc")) action = Action::Compile; else if(iequal_to()(extension, ".scm")) action = Action::Decompile; else if(iequal_to()(extension, ".scc")) action = Action::Decompile; else if(iequal_to()(extension, ".cs")) action = Action::Decompile; else if(iequal_to()(extension, ".cm")) action = Action::Decompile; else { fprintf(stderr, "gta3sc: error: could not infer action from input extension (compile/decompile)\n"); return EXIT_FAILURE; } } fs::path conf_path = config_path(); fprintf(stdout, "Using '%s' as configuration path\n", conf_path.string().c_str()); try { commands = Commands::from_xml({ config_name + "/constants.xml", config_name + "/commands.xml" }); } catch(const ConfigError& e) { fprintf(stderr, "gta3sc: error: %s\n", e.what()); } switch(action) { case Action::Compile: return compile(input, output, options, *commands); case Action::Decompile: return decompile(input, output, options, *commands); default: Unreachable(); } } int compile(fs::path input, fs::path output, const Options& options, const Commands& commands) { if(output.empty()) { // TODO .cs .scc output = input; output.replace_extension(".scm"); } try { std::vector<shared_ptr<Script>> scripts; ProgramContext program(options); //const char* input = "intro.sc"; //const char* input = "test.sc"; //const char* input = "gta3_src/main.sc"; auto main = Script::create(input, ScriptType::Main); auto symbols = SymTable::from_script(*main, commands, program); symbols.apply_offset_to_vars(2); scripts.emplace_back(main); auto subdir = main->scan_subdir(); auto ext_scripts = read_and_scan_symbols(subdir, symbols.extfiles.begin(), symbols.extfiles.end(), ScriptType::MainExtension, commands, program); auto sub_scripts = read_and_scan_symbols(subdir, symbols.subscript.begin(), symbols.subscript.end(), ScriptType::Subscript, commands, program); auto mission_scripts = read_and_scan_symbols(subdir, symbols.mission.begin(), symbols.mission.end(), ScriptType::Mission, commands, program); // TODO handle lex/parser errors for(auto& x : ext_scripts) { symbols.merge(std::move(x.second), program); scripts.emplace_back(x.first); // maybe move } for(auto& x : sub_scripts) { symbols.merge(std::move(x.second), program); scripts.emplace_back(x.first); // maybe move } for(size_t i = 0; i < mission_scripts.size(); ++i) { auto& x = mission_scripts[i]; symbols.merge(std::move(x.second), program); scripts.emplace_back(x.first); // maybe move scripts.back()->mission_id = i; } symbols.check_command_count(program); symbols.build_script_table(scripts); for(auto& script : scripts) { script->annotate_tree(symbols, commands, program); } // not thread-safe std::vector<std::string> models = Script::compute_unknown_models(scripts); // CompilerContext wants an annotated ASTs, if we have any error, it's possible that // the AST is not correctly annotated. if(program.has_error()) throw HaltJobException(); std::vector<CodeGenerator> gens; gens.reserve(scripts.size()); for(auto& script : scripts) { CompilerContext cc(script, symbols, commands, program); cc.compile(); gens.emplace_back(std::move(cc), program); } // Codegen expects a successful compilation. if(program.has_error()) throw HaltJobException(); size_t global_vars_size = 0; if(auto highest_var = symbols.highest_global_var()) { global_vars_size = (*highest_var)->end_offset(); } CompiledScmHeader header(CompiledScmHeader::Version::Liberty, symbols.size_global_vars(), models, scripts); // not thread-safe Expects(gens.size() == scripts.size()); for(size_t i = 0; i < gens.size(); ++i) // zip { scripts[i]->size = gens[i].compute_labels(); // <- maybe???! this is actually thread safe } // Script::compute_script_offsets(scripts, header.compiled_size()); // <- but this isn't for(auto& gen : gens) gen.generate(); if(FILE* f = u8fopen(output, "wb")) { auto guard = make_scope_guard([&] { fclose(f); }); if(true) { CodeGeneratorData hgen(header, program); hgen.generate(); write_file(f, hgen.buffer(), hgen.buffer_size()); } for(auto& gen : gens) { write_file(f, gen.buffer(), gen.buffer_size()); } } else { program.error(nocontext, "XXX"); } if(program.has_error()) throw HaltJobException(); } catch(const HaltJobException&) { // TODO put a error message of compilation failed instead of zeroing output!??!!! FILE* f = u8fopen(output, "wb"); if(f) fclose(f); } return 0; } int decompile(fs::path input, fs::path output, const Options& options, const Commands& commands) { ProgramContext program(options); FILE* outstream; if(output.empty()) { outstream = stdout; } else { outstream = u8fopen(output, "wb"); if(!outstream) program.fatal_error(nocontext, "Could not open file {} for writing", output.generic_u8string()); } auto guard = make_scope_guard([&] { if(outstream != stdout) fclose(outstream); }); auto opt_decomp = Disassembler::from_file(options, commands, input); if(!opt_decomp) program.fatal_error(nocontext, "File {} does not exist", input.generic_u8string()); Disassembler decomp(std::move(*opt_decomp)); auto scm_header = decomp.read_header(DecompiledScmHeader::Version::Liberty).value(); decomp.analyze_header(scm_header); decomp.run_analyzer(); auto data = decomp.get_data(); fprintf(outstream, "%s\n", DecompilerContext(commands, std::move(data)).decompile().c_str()); return 0; } <|endoftext|>
<commit_before>// // Turbo Linecount // Copyright 2015, Christien Rioux // // MIT Licensed, see file 'LICENSE' for details // /////////////////////////////////////////////// #include"turbo_linecount.h" #include<cstring> #include<cstdio> #ifdef _WIN32 #include<tchar.h> #elif defined(TLC_COMPATIBLE_UNIX) #include<stdlib.h> #define _tprintf printf #define _ftprintf fprintf #define _tcscmp strcmp #define _tcslen strlen #define _ttoi atoi #define _tcstoui64 strtoull #define _T(x) x #define TCHAR char #endif using namespace TURBOLINECOUNT; ////////////////////////////////////////////////////// void help(const TCHAR *argv0) { _ftprintf(stderr, _T("usage: %s [options] <file>\n"), argv0); _ftprintf(stderr, _T(" -h --help print this usage and exit\n")); _ftprintf(stderr, _T(" -b --buffersize <BUFFERSIZE> size of buffer per-thread to use when reading (default is 1MB)\n")); _ftprintf(stderr, _T(" -t --threadcount <THREADCOUNT> number of threads to use (defaults to number of cpu cores)\n")); _ftprintf(stderr, _T(" -v --version print version information and exit\n")); } void version(void) { _tprintf(_T("lc (linecount) %d.%2.2d\nCopyright (c) 2015 Christien Rioux\n"), LINECOUNT_VERSION_MAJOR, LINECOUNT_VERSION_MINOR); } ////////////////////////////////////////////////////// #if defined(WIN32) && defined(_UNICODE) int wmain(int argc, TCHAR **argv) #else int main(int argc, char **argv) #endif { // Parse parameters int arg = 1; int posparam = 0; CLineCount::PARAMETERS params; params.buffersize = -1; params.threadcount = -1; TCHAR *filename = NULL; if(argc==1) { help(argv[0]); exit(0); } while (arg < argc) { if (_tcscmp(argv[arg], _T("-h")) == 0 || _tcscmp(argv[arg], _T("--help")) == 0) { help(argv[0]); exit(0); } else if (_tcscmp(argv[arg], _T("-v")) == 0 || _tcscmp(argv[arg], _T("--version")) == 0) { version(); exit(0); } else if (_tcscmp(argv[arg], _T("-b")) == 0 || _tcscmp(argv[arg], _T("--buffersize")) == 0) { arg++; if (arg == argc) { _ftprintf(stderr, _T("%s: missing argument to %s\n"), argv[0], argv[arg-1]); return 1; } TCHAR *wsstr = argv[arg]; // Check for size multipliers size_t multiplier = 1; TCHAR *lastchar = wsstr + (_tcslen(wsstr) - 1); if (*lastchar == _T('k') || *lastchar == _T('K')) { multiplier = 1024; lastchar = 0; } else if (*lastchar == _T('m') || *lastchar == _T('M')) { multiplier = 1024 * 1024; lastchar = 0; } else if (*lastchar == _T('g') || *lastchar == _T('G')) { multiplier = 1024 * 1024 * 1024; lastchar = 0; } TCHAR *endptr; params.buffersize = ((size_t)_tcstoui64(argv[arg], &endptr, 10)) * multiplier; } else if (_tcscmp(argv[arg], _T("-t")) == 0 || _tcscmp(argv[arg], _T("--threadcount")) == 0) { arg++; if (arg == argc) { _ftprintf(stderr, _T("%s: Missing argument to %s\n"), argv[0], argv[arg-1]); return 1; } params.threadcount = _ttoi(argv[arg]); if(params.threadcount<=0) { _ftprintf(stderr, _T("%s: Invalid thread count\n"), argv[0]); return 1; } } else { if (posparam == 0) { filename = argv[arg]; } else { _ftprintf(stderr, _T("%s: Too many arguments\n"), argv[0]); return 1; } posparam++; } arg++; } if (posparam != 1) { _ftprintf(stderr, _T("%s: Missing required argument\n"), argv[0]); return 1; } // Create line count class CLineCount lc(&params); if (!lc.open(filename)) { tlc_error_t err = lc.lastError(); tlc_string_t errstr = lc.lastErrorString(); _ftprintf(stderr, _T("%s: Error %d (%s)\n"), argv[0], err, errstr.c_str()); return err; } // Count lines tlc_linecount_t count; if (!lc.countLines(count)) { tlc_error_t err = lc.lastError(); tlc_string_t errstr = lc.lastErrorString(); _ftprintf(stderr, _T("%s: Error %d: (%s)\n"), argv[0], err, errstr.c_str()); return err; } // Display output _tprintf(_T(TLC_LINECOUNT_FMT _T("\n")), count); return 0; }<commit_msg>macro<commit_after>// // Turbo Linecount // Copyright 2015, Christien Rioux // // MIT Licensed, see file 'LICENSE' for details // /////////////////////////////////////////////// #include"turbo_linecount.h" #include<cstring> #include<cstdio> #ifdef _WIN32 #include<tchar.h> #elif defined(TLC_COMPATIBLE_UNIX) #include<stdlib.h> #define _tprintf printf #define _ftprintf fprintf #define _tcscmp strcmp #define _tcslen strlen #define _ttoi atoi #define _tcstoui64 strtoull #define _T(x) x #define TCHAR char #endif using namespace TURBOLINECOUNT; ////////////////////////////////////////////////////// void help(const TCHAR *argv0) { _ftprintf(stderr, _T("usage: %s [options] <file>\n"), argv0); _ftprintf(stderr, _T(" -h --help print this usage and exit\n")); _ftprintf(stderr, _T(" -b --buffersize <BUFFERSIZE> size of buffer per-thread to use when reading (default is 1MB)\n")); _ftprintf(stderr, _T(" -t --threadcount <THREADCOUNT> number of threads to use (defaults to number of cpu cores)\n")); _ftprintf(stderr, _T(" -v --version print version information and exit\n")); } void version(void) { _tprintf(_T("lc (linecount) %d.%2.2d\nCopyright (c) 2015 Christien Rioux\n"), LINECOUNT_VERSION_MAJOR, LINECOUNT_VERSION_MINOR); } ////////////////////////////////////////////////////// #if defined(WIN32) && defined(_UNICODE) int wmain(int argc, TCHAR **argv) #else int main(int argc, char **argv) #endif { // Parse parameters int arg = 1; int posparam = 0; CLineCount::PARAMETERS params; params.buffersize = -1; params.threadcount = -1; TCHAR *filename = NULL; if(argc==1) { help(argv[0]); exit(0); } while (arg < argc) { if (_tcscmp(argv[arg], _T("-h")) == 0 || _tcscmp(argv[arg], _T("--help")) == 0) { help(argv[0]); exit(0); } else if (_tcscmp(argv[arg], _T("-v")) == 0 || _tcscmp(argv[arg], _T("--version")) == 0) { version(); exit(0); } else if (_tcscmp(argv[arg], _T("-b")) == 0 || _tcscmp(argv[arg], _T("--buffersize")) == 0) { arg++; if (arg == argc) { _ftprintf(stderr, _T("%s: missing argument to %s\n"), argv[0], argv[arg-1]); return 1; } TCHAR *wsstr = argv[arg]; // Check for size multipliers size_t multiplier = 1; TCHAR *lastchar = wsstr + (_tcslen(wsstr) - 1); if (*lastchar == _T('k') || *lastchar == _T('K')) { multiplier = 1024; lastchar = 0; } else if (*lastchar == _T('m') || *lastchar == _T('M')) { multiplier = 1024 * 1024; lastchar = 0; } else if (*lastchar == _T('g') || *lastchar == _T('G')) { multiplier = 1024 * 1024 * 1024; lastchar = 0; } TCHAR *endptr; params.buffersize = ((size_t)_tcstoui64(argv[arg], &endptr, 10)) * multiplier; } else if (_tcscmp(argv[arg], _T("-t")) == 0 || _tcscmp(argv[arg], _T("--threadcount")) == 0) { arg++; if (arg == argc) { _ftprintf(stderr, _T("%s: Missing argument to %s\n"), argv[0], argv[arg-1]); return 1; } params.threadcount = _ttoi(argv[arg]); if(params.threadcount<=0) { _ftprintf(stderr, _T("%s: Invalid thread count\n"), argv[0]); return 1; } } else { if (posparam == 0) { filename = argv[arg]; } else { _ftprintf(stderr, _T("%s: Too many arguments\n"), argv[0]); return 1; } posparam++; } arg++; } if (posparam != 1) { _ftprintf(stderr, _T("%s: Missing required argument\n"), argv[0]); return 1; } // Create line count class CLineCount lc(&params); if (!lc.open(filename)) { tlc_error_t err = lc.lastError(); tlc_string_t errstr = lc.lastErrorString(); _ftprintf(stderr, _T("%s: Error %d (%s)\n"), argv[0], err, errstr.c_str()); return err; } // Count lines tlc_linecount_t count; if (!lc.countLines(count)) { tlc_error_t err = lc.lastError(); tlc_string_t errstr = lc.lastErrorString(); _ftprintf(stderr, _T("%s: Error %d: (%s)\n"), argv[0], err, errstr.c_str()); return err; } // Display output _tprintf(_T(TLC_LINECOUNT_FMT "\n"), count); return 0; }<|endoftext|>
<commit_before>#include <errno.h> #include <iostream> #include <string> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <vector> #include <pwd.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; string shell_prompt(); //prototype for prompt function int main (int argc, char** argv) { while(true) { string input; vector<string> inVector; input = shell_prompt(); if (input != "exit") { char_separator<char> sep(";|&"); tokenizer< char_separator<char> > tokens(input, sep); string t; BOOST_FOREACH(t, tokens); { inVector.push_back(t); //cout << t << endl; } //tokenizer<> tokens(shell_prompt()); } else { cout << "Goodbye." << endl; exit(0); } } /* int pid = fork(); if (pid == 0) { int error = execvp(argv[0], argv); if (error == -1) { perror("execvp"); //throw an error exit(1); } else { if (argv[0] != "exit") { //execute } exit(0); } } else { wait(NULL); } */ return 0; } string shell_prompt() { string in; //TODO - error checking for getlogin and gethostname //implement later /* char name[256]; int maxlen = 64; if (!gethostname(name, maxlen)) { string strname(name); cout << getlogin() << "@" << name << "$ "; //custom prompt with hostname and login name cin >> in; } else { perror("gethostname"); //throw error if not found } */ cout << "rshell$ "; cin >> in; return in; } <commit_msg>main can now recieve input and tokenize into a string vector<commit_after>#include <errno.h> #include <iostream> #include <string> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <vector> #include <pwd.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace std; using namespace boost; string shell_prompt(); //prototype for prompt function void cmd_interpreter(vector<string>); //prototype for command interpreter int main (int argc, char** argv) { vector<string> inVector; string input; input = shell_prompt(); while(input != "exit") { //string input; //vector<string> inVector; // input = shell_prompt(); // if (input != "exit") // { char_separator<char> sep(";|&"); string t; tokenizer< char_separator<char> > tokens(input, sep); BOOST_FOREACH(t, tokens); { inVector.push_back(t); // cout << t << endl; } //cmd_interpreter(inVector); // } // else // { // cout << "Goodbye." << endl; // exit(0); // } cmd_interpreter(inVector); input = shell_prompt(); } cout << "Exiting." << endl; exit(0); return 0; } void cmd_interpreter(vector<string> input) { //int size = input.size(); for (unsigned i = 0; true ; i++) cout << i << ": " << input.at(i) << endl; /* int pid = fork(); if (pid == 0) { int error = execvp(argv[0], argv); if (error == -1) { perror("execvp"); //throw an error exit(1); } else { if (argv[0] != "exit") { //execute } exit(0); } } else { wait(NULL); } */ } string shell_prompt() { string in; //TODO - error checking for getlogin and gethostname //implement later /* char name[256]; int maxlen = 64; if (!gethostname(name, maxlen)) { string strname(name); cout << getlogin() << "@" << name << "$ "; //custom prompt with hostname and login name cin >> in; } else { perror("gethostname"); //throw error if not found } */ cout << "rshell$ "; cin >> in; cin.clear(); return in; } <|endoftext|>
<commit_before>// // Projectname: amos-ss16-proj5 // // Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5 // // This file is part of the AMOS Project 2016 @ FAU // (Friedrich-Alexander University Erlangen-Nürnberg) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // /** * This is the global main of amos-ss16-proj5. * * It takes a video (hdf5 or mp4), extracts it, executes object detection and scenario analysation. * Every time a specific scenario is detected, the communication is performed. */ //std #include <iostream> #include <sstream> #include <vector> //local #include "StreamDecoder/hdf5_frame_selector.h" #include "StreamDecoder/frame_selector_factory.h" #include "StreamDecoder/image_view.h" #include "ProcessControl/controller.h" //#include "ProcessControl/multithreadedcontroller.h" #include "CarCommunication/protoagent.h" using namespace std; static bool str_to_uint16(const char *str, uint16_t *res) { char *end; errno = 0; intmax_t val = strtoimax(str, &end, 10); if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0') return false; *res = (uint16_t) val; return true; } int main(int argc, const char* argv[]) { if (argc > 4 || argc == 1){ cerr << "Usage1: " << " FULL_PATH_TO_VIDEO_FILE (IMAGE_INDEX)\n"; cerr << "Usage2: " << " PORT (SERVERIP FULL_PATH_TO_VIDEO_FILE)" << endl; return -1; } if(argc == 2){ uint16_t port; if(str_to_uint16(argv[1],&port)) { cout << "Server port: " << port << endl; ProtoAgent protoagent(port); } else { cerr << "Analysing video in file " << argv[1] << endl; Controller controller; controller.AnalyseVideo(argv[1]); } } if(argc == 3){ /*FrameSelectorFactory frame_selector_factory(argv[1]); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); // read one image unsigned int index = 0; stringstream string_index(argv[2]); string_index >> index; Image * result_image = pipeline->ReadImage(index); ImageView image_viewer; image_viewer.ShowImage(result_image, 0);*/ } if(argc == 4){ uint16_t port; if(str_to_uint16(argv[1],&port)) { //MultithreadedController controller(argv[3],port,argv[2]); Controller controller; controller.InitilalizeCarConnection(port,argv[2]); controller.AnalyseVideo(argv[3]); } else { cerr << "Could not read port" << endl; } } return 0; } <commit_msg>added into image and basic team-info in main.cpp<commit_after>// // Projectname: amos-ss16-proj5 // // Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5 // // This file is part of the AMOS Project 2016 @ FAU // (Friedrich-Alexander University Erlangen-Nürnberg) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // /** * This is the global main of amos-ss16-proj5. * * It takes a video (hdf5 or mp4), extracts it, executes object detection and scenario analysation. * Every time a specific scenario is detected, the communication is performed. */ //std #include <iostream> #include <sstream> #include <vector> //local #include "StreamDecoder/hdf5_frame_selector.h" #include "StreamDecoder/frame_selector_factory.h" #include "StreamDecoder/image_view.h" #include "ProcessControl/controller.h" //#include "ProcessControl/multithreadedcontroller.h" #include "CarCommunication/protoagent.h" using namespace std; static bool str_to_uint16(const char *str, uint16_t *res) { char *end; errno = 0; intmax_t val = strtoimax(str, &end, 10); if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0') return false; *res = (uint16_t) val; return true; } int main(int argc, const char* argv[]) { std::cout << "AMOS Project 2016 - Group 5 @ University of Erlangen-Nuremberg \n" " \n" " _____ \n" " | ____| \n" " __ _ _ __ ___ | |__ ___ ___ \n" " / _` | '_ ` _ \\|___ \\ / _ \\/ __| \n" "| (_| | | | | | |___) | (_) \\__ \\ \n" " \\__,_|_| |_| |_|____/ \\___/|___/ \n" " \n" << std::endl; if (argc > 4 || argc == 1){ cerr << "Usage1: " << " FULL_PATH_TO_VIDEO_FILE (IMAGE_INDEX)\n"; cerr << "Usage2: " << " PORT (SERVERIP FULL_PATH_TO_VIDEO_FILE)" << endl; return -1; } if(argc == 2){ uint16_t port; if(str_to_uint16(argv[1],&port)) { cout << "Server port: " << port << endl; ProtoAgent protoagent(port); } else { cerr << "Analysing video in file " << argv[1] << endl; Controller controller; controller.AnalyseVideo(argv[1]); } } if(argc == 3){ /*FrameSelectorFactory frame_selector_factory(argv[1]); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); // read one image unsigned int index = 0; stringstream string_index(argv[2]); string_index >> index; Image * result_image = pipeline->ReadImage(index); ImageView image_viewer; image_viewer.ShowImage(result_image, 0);*/ } if(argc == 4){ uint16_t port; if(str_to_uint16(argv[1],&port)) { //MultithreadedController controller(argv[3],port,argv[2]); Controller controller; controller.InitilalizeCarConnection(port,argv[2]); controller.AnalyseVideo(argv[3]); } else { cerr << "Could not read port" << endl; } } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <list> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <netdb.h> #include <pwd.h> #include <sys/socket.h> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost::algorithm; //Virtual Base Class class Base{ public: Base(){}; //Function Inherited by each class virtual bool evaluate() = 0; }; // Command Class that each command will inherit from class Command: public Base{ private: //Vector of commands vector<string> commandVec; public: //Contructor to take in vector and set it to commands vectors Command(vector<string>s){ commandVec = s; } }; int main () { //take user input string initialCommand = ""; while (true) { string login = getlogin(); char hostname[100]; gethostname(hostname, 100); cout << "[" << login << "@" << hostname << "] $ "; getline(cin, initialCommand); trim(initialCommand); } return 0; } <commit_msg>Update main.cpp<commit_after>#include <iostream> #include <vector> #include <list> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <netdb.h> #include <pwd.h> #include <sys/socket.h> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost::algorithm; //Virtual Base Class class Base{ public: Base(){}; //Function Inherited by each class virtual bool evaluate() = 0; }; // Command Class that each command will inherit from class Command: public Base{ private: //Vector of commands vector<string> commandVec; public: //Contructor to take in vector and set it to commands vectors Command(vector<string>s){ commandVec = s; } }; class Connectors:public Base{ private: Connectors(){}; protected: bool leftCommand; Base* rightCommand; }; int main () { //take user input string initialCommand = ""; while (true) { string login = getlogin(); char hostname[100]; gethostname(hostname, 100); cout << "[" << login << "@" << hostname << "] $ "; getline(cin, initialCommand); trim(initialCommand); } return 0; } <|endoftext|>
<commit_before> #include <iostream> #include <memory> #include "Game.h" using namespace Yoba; int main(int argc, char* args[]) { auto game = Game::Instance(); if (!game->init(100, 100, 640, 480)) { std::cerr << "game init failure - " << SDL_GetError() << std::endl; return EXIT_FAILURE; } while(game->running()) { game->handleEvents(); game->update(); game->render(); SDL_Delay(10); } return EXIT_SUCCESS; } <commit_msg>[main loop] Set the fixed FPS.<commit_after> #include <iostream> #include <memory> #include "Game.h" using namespace Yoba; const int FPS = 60; const int DELAY_TIME = 1000.0f / FPS; int main(int argc, char* args[]) { Uint32 frameStart, frameTime; auto game = Game::Instance(); if (!game->init(100, 100, 640, 480)) { std::cerr << "game init failure - " << SDL_GetError() << std::endl; return EXIT_FAILURE; } while(game->running()) { frameStart = SDL_GetTicks(); game->handleEvents(); game->update(); game->render(); frameTime = SDL_GetTicks() - frameStart; if(frameTime < DELAY_TIME) { SDL_Delay((int)(DELAY_TIME - frameTime)); } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <chrono> #include "latexImprover.h" int main(int argc, char* argv[]){ // argv[0] is not interesting, since it's just your program's path. for (int i = 1; i < argc; ++i){ std::string filePath = argv[i]; std::ifstream file(filePath); if(file){ auto started = std::chrono::high_resolution_clock::now(); std::stringstream buffer; std::stringstream out; buffer << file.rdbuf(); file.close(); latexImprover(buffer, out); std::ofstream file("newFile.tex"); if (file){ file << out.rdbuf(); file.close(); } auto done = std::chrono::high_resolution_clock::now(); std::cout << "Executed: " << filePath << " In: " << std::chrono::duration_cast<std::chrono::milliseconds>(done-started).count() << "ms"; } } std::string input; std::cin >> input; return 0; } <commit_msg>Cleaning<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <chrono> #include "latexImprover.h" int main(int argc, char* argv[]){ // argv[0] is not interesting, since it's just your program's path. for (int i = 1; i < argc; ++i){ std::string filePath = argv[i]; std::ifstream file(filePath); if(file){ auto started = std::chrono::high_resolution_clock::now(); std::stringstream buffer; std::stringstream out; buffer << file.rdbuf(); file.close(); latexImprover(buffer, out); std::ofstream file("newFile.tex"); if (file){ file << out.rdbuf(); file.close(); } auto done = std::chrono::high_resolution_clock::now(); std::cout << "Executed: " << filePath << " In: " << std::chrono::duration_cast<std::chrono::milliseconds>(done-started).count() << "ms" << std::endl; } } std::string input; std::cin >> input; return 0; } <|endoftext|>
<commit_before>/* volat_minimal.cpp * This file is a part of tasks library * Copyright (c) tasks authors (see file `COPYRIGHT` for the license) */ #include <iostream> #include <boost/array.hpp> #include <boost/thread.hpp> #include <boost/thread/barrier.hpp> #include <boost/bind.hpp> static const int NUM_IT=1024 * 1024; void IncThreadFunc(boost::barrier * barrier, volatile int * volatile int_ptr) { barrier->wait(); for(int i = 0; i < NUM_IT; ++i) { ++*int_ptr; } } int main() { static const int NUM_THREADS = 64; typedef boost::array<boost::thread, NUM_THREADS> Threads; volatile int i = 0; boost::barrier barrier(NUM_THREADS); Threads threads; for(Threads::iterator it = threads.begin(); it != threads.end(); ++it) { *it = boost::thread(boost::bind(&IncThreadFunc, &barrier, &i)); } for(Threads::iterator it = threads.begin(); it != threads.end(); ++it) { (*it).join(); } std::cout<<"result "<<i<<" expected "<<(NUM_THREADS*NUM_IT) <<" ("<<(NUM_THREADS*NUM_IT-i)<<")"<<std::endl; return 0; } <commit_msg>task example replaces main code<commit_after>/* main.cpp * This file is a part of tasks library * Copyright (c) tasks authors (see file `COPYRIGHT` for the license) */ #include <iostream> #include <boost/array.hpp> #include <boost/thread.hpp> #include <boost/thread/barrier.hpp> #include <boost/bind.hpp> #include <boost/task.hpp> long fibonacci( long n) { if ( n == 0) return 0; if ( n == 1) return 1; long k1( 1), k2( 0); for ( int i( 2); i <= n; ++i) { long tmp( k1); k1 = k1 + k2; k2 = tmp; } return k1; } int main() { // create a thread-pool boost::tasks::static_pool< boost::tasks::unbounded_fifo > pool( boost::tasks::poolsize( 5) ); // execute tasks in thread-pool // move tasks ownership to executor boost::tasks::handle< long > h1( boost::tasks::async( boost::tasks::make_task( fibonacci, 10), pool)); boost::tasks::handle< long > h2( boost::tasks::async( boost::tasks::make_task( fibonacci, 5), pool)); std::cout << "h1: is ready == " << std::boolalpha << h1.is_ready() << "\n"; std::cout << "h2: is ready == " << std::boolalpha << h2.is_ready() << "\n"; // wait for completion of both tasks boost::tasks::waitfor_all( h1, h2); std::cout << "h1: is ready == " << std::boolalpha << h1.is_ready() << "\n"; std::cout << "h2: is ready == " << std::boolalpha << h2.is_ready() << "\n"; std::cout << "h1: has value == " << std::boolalpha << h1.has_value() << "\n"; std::cout << "h2: has value == " << std::boolalpha << h2.has_value() << "\n"; std::cout << "h1: has exception == " << std::boolalpha << h1.has_exception() << "\n"; std::cout << "h2: has exception == " << std::boolalpha << h2.has_exception() << "\n"; // get results std::cout << "fibonacci(10) == " << h1.get() << std::endl; std::cout << "fibonacci(5) == " << h2.get() << std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Mike Tzou All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of foo_xspf_1 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdafx.h" #include "main.h" #include "helper.h" #define PLUGIN_NAME "XSPF Playlist" #define PLUGIN_VERSION "2.0" DECLARE_COMPONENT_VERSION ( PLUGIN_NAME , PLUGIN_VERSION , PLUGIN_NAME"\n" "Compiled on: "__DATE__"\n" "https://github.com/Chocobo1/foo_xspf_1\n" "This plugin is released under BSD 3-Clause license\n" "\n" "Mike Tzou (Chocobo1)\n" "\n" "This plugin links statically with the following open source library:\n" "TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n" ); const char *xspf::get_extension() { return "xspf"; } bool xspf::is_our_content_type( const char *p_content_type ) { const char mime[] = "application/xspf+xml"; if( strcmp( p_content_type , mime ) == 0 ) return true; return false; } bool xspf::is_associatable() { return true; } bool xspf::can_write() { return true; } void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort ) { // avoid file open loop static lruCache<bool> open_list( FILE_OPEN_MAX ); if( open_list.get( p_path ) != nullptr ) return; open_list.set( p_path , true ); pfc::hires_timer t; t.start(); p_callback->on_progress( p_path ); open_helper( p_path , p_file , p_callback , p_abort ); console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path ); open_list.remove( p_path ); return; } void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort ) { pfc::hires_timer t; t.start(); write_helper( p_path , p_file , p_data , p_abort ); console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path ); return; } <commit_msg>fix bug: if file throws exception, it cannot be read again<commit_after>/* Copyright (c) 2015, Mike Tzou All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of foo_xspf_1 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "stdafx.h" #include "main.h" #include "helper.h" #define PLUGIN_NAME "XSPF Playlist" #define PLUGIN_VERSION "2.0" DECLARE_COMPONENT_VERSION ( PLUGIN_NAME , PLUGIN_VERSION , PLUGIN_NAME"\n" "Compiled on: "__DATE__"\n" "https://github.com/Chocobo1/foo_xspf_1\n" "This plugin is released under BSD 3-Clause license\n" "\n" "Mike Tzou (Chocobo1)\n" "\n" "This plugin links statically with the following open source library:\n" "TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n" ); const char *xspf::get_extension() { return "xspf"; } bool xspf::is_our_content_type( const char *p_content_type ) { const char mime[] = "application/xspf+xml"; if( strcmp( p_content_type , mime ) == 0 ) return true; return false; } bool xspf::is_associatable() { return true; } bool xspf::can_write() { return true; } void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort ) { // avoid file open loop static lruCache<bool> open_list( FILE_OPEN_MAX ); if( open_list.get( p_path ) != nullptr ) return; open_list.set( p_path , true ); pfc::hires_timer t; t.start(); try { p_callback->on_progress( p_path ); open_helper( p_path , p_file , p_callback , p_abort ); } catch( ... ) { open_list.remove( p_path ); throw; } console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path ); open_list.remove( p_path ); return; } void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort ) { pfc::hires_timer t; t.start(); write_helper( p_path , p_file , p_data , p_abort ); console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path ); return; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtGui> #include <QGLWidget> #include "mcompositescene.h" #include "mcompositemanager.h" int main(int argc, char *argv[]) { // Don't load any Qt plugins QCoreApplication::setLibraryPaths(QStringList()); MCompositeManager app(argc, argv); QGraphicsScene *scene = app.scene(); QGraphicsView view(scene); // TODO: Which property is valid now? view.setProperty("NoDuiStyle", true); view.setProperty("NoMStyle", true); view.setUpdatesEnabled(false); view.setAutoFillBackground(false); view.setBackgroundBrush(Qt::NoBrush); view.setForegroundBrush(Qt::NoBrush); view.setFrameShadow(QFrame::Plain); view.setWindowFlags(Qt::X11BypassWindowManagerHint); view.setAttribute(Qt::WA_NoSystemBackground); #if QT_VERSION >= 0x040600 view.move(-2, -2); view.setViewportUpdateMode(QGraphicsView::NoViewportUpdate); view.setOptimizationFlags(QGraphicsView::IndirectPainting); #endif app.setSurfaceWindow(view.winId()); view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); view.setMinimumSize(QApplication::desktop()->width() + 2, QApplication::desktop()->height() + 2); view.setMaximumSize(QApplication::desktop()->width() + 2, QApplication::desktop()->height() + 2); QGLFormat fmt; fmt.setSamples(0); fmt.setSampleBuffers(false); QGLWidget *w = new QGLWidget(fmt); w->setAutoFillBackground(false); w->setMinimumSize(QApplication::desktop()->width(), QApplication::desktop()->height()); w->setMaximumSize(QApplication::desktop()->width(), QApplication::desktop()->height()); app.setGLWidget(w); view.setViewport(w); w->makeCurrent(); view.show(); app.prepareEvents(); app.redirectWindows(); return app.exec(); } <commit_msg>Paint a black background at startup<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mcompositor. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtGui> #include <QGLWidget> #include "mcompositescene.h" #include "mcompositemanager.h" int main(int argc, char *argv[]) { // Don't load any Qt plugins QCoreApplication::setLibraryPaths(QStringList()); MCompositeManager app(argc, argv); QGraphicsScene *scene = app.scene(); QGraphicsView view(scene); // TODO: Which property is valid now? view.setProperty("NoDuiStyle", true); view.setProperty("NoMStyle", true); view.setUpdatesEnabled(false); view.setAutoFillBackground(false); view.setBackgroundBrush(Qt::NoBrush); view.setForegroundBrush(Qt::NoBrush); view.setFrameShadow(QFrame::Plain); view.setWindowFlags(Qt::X11BypassWindowManagerHint); view.setAttribute(Qt::WA_NoSystemBackground); #if QT_VERSION >= 0x040600 view.move(-2, -2); view.setViewportUpdateMode(QGraphicsView::NoViewportUpdate); view.setOptimizationFlags(QGraphicsView::IndirectPainting); #endif app.setSurfaceWindow(view.winId()); view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view.setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); view.setMinimumSize(QApplication::desktop()->width() + 2, QApplication::desktop()->height() + 2); view.setMaximumSize(QApplication::desktop()->width() + 2, QApplication::desktop()->height() + 2); QGLFormat fmt; fmt.setSamples(0); fmt.setSampleBuffers(false); QGLWidget *w = new QGLWidget(fmt); QPalette p = w->palette(); p.setColor(QPalette::Background, QColor(Qt::black)); w->setPalette(p); w->setAutoFillBackground(true); w->setMinimumSize(QApplication::desktop()->width(), QApplication::desktop()->height()); w->setMaximumSize(QApplication::desktop()->width(), QApplication::desktop()->height()); app.setGLWidget(w); view.setViewport(w); w->makeCurrent(); view.show(); app.prepareEvents(); app.redirectWindows(); return app.exec(); } <|endoftext|>
<commit_before>// // main.cpp // expressionline2 // // Created by Adam Roberts on 3/23/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #define PACKAGE_VERSION "INTERNAL" #include <boost/filesystem.hpp> #include <getopt.h> #include <boost/thread.hpp> #include <cassert> #include <iostream> #include <fstream> #include <cmath> #include "transcripts.h" #include "fld.h" #include "fragments.h" #include "biascorrection.h" #include "mismatchmodel.h" using namespace std; double ff_param = 0; string output_dir = "."; double expr_alpha = .001; double fld_alpha = 1; double bias_alpha = 1; double mm_alpha = 1; int def_fl_max = 800; int def_fl_mean = 200; int def_fl_stddev = 80; bool user_provided_fld = false; bool bias_correct = true; bool upper_quart_norm = false; void print_usage() { fprintf(stderr, "cuffexpress v%s\n", PACKAGE_VERSION); // fprintf(stderr, "linked against Boost version %d\n", BOOST_VERSION); fprintf(stderr, "-----------------------------\n"); fprintf(stderr, "File Usage: cuffexpress [options] <transcripts.fasta> <hits.sam>\n"); fprintf(stderr, "Piped Usage: bowtie [options] -S <reads.fastq> | cuffexpress [options] <transcripts.fasta>\n"); fprintf(stderr, "General Options:\n"); fprintf(stderr, " -o/--output-dir write all output files to this directory [ default: ./ ]\n"); fprintf(stderr, " -f/--forget-param forgetting factor exponent parameter [ default: 0 ]\n"); fprintf(stderr, " -m/--frag-len-mean average fragment length (unpaired reads only) [ default: 200 ]\n"); fprintf(stderr, " -s/--frag-len-std-dev fragment length std deviation (unpaired reads only) [ default: 80 ]\n"); fprintf(stderr, " --upper-quartile-norm use upper-quartile normalization [ default: FALSE ]\n"); fprintf(stderr, " --no-bias-correct do not correct for fragment bias [ default: FALSE ]\n"); } #define OPT_UPPER_QUARTILE_NORM 200 #define OPT_NO_BIAS_CORRECT 201 const char *short_options = "o:f:m:s"; static struct option long_options[] = { // general options {"output-dir", required_argument, 0, 'o'}, {"forget-param", required_argument, 0, 'f'}, {"frag-len-mean", required_argument, 0, 'm'}, {"frag-len-std-dev", required_argument, 0, 's'}, {"upper-quartile-norm", no_argument, 0, OPT_UPPER_QUARTILE_NORM}, {"no-bias-correct", no_argument, 0, OPT_NO_BIAS_CORRECT}, {0, 0, 0, 0} // terminator }; /** * Parse an int out of optarg and enforce that it be at least 'lower'; * if it is less than 'lower', than output the given error message and * exit with an error and a usage message. */ int parseInt(int lower, const char *errmsg, void (*print_usage)()) { long l; char *endPtr= NULL; l = strtol(optarg, &endPtr, 10); if (endPtr != NULL) { if (l < lower) { cerr << errmsg << endl; print_usage(); exit(1); } return (int32_t)l; } cerr << errmsg << endl; print_usage(); exit(1); return -1; } /** * Parse an float out of optarg and enforce that is between 'lower' and 'upper'; * if it is not, output the given error message and * exit with an error and a usage message. */ float parseFloat(float lower, float upper, const char *errmsg, void (*print_usage)()) { float l; l = (float)atof(optarg); if (l < lower) { cerr << errmsg << endl; print_usage(); exit(1); } if (l > upper) { cerr << errmsg << endl; print_usage(); exit(1); } return l; cerr << errmsg << endl; print_usage(); exit(1); return -1; } int parse_options(int argc, char** argv) { int option_index = 0; int next_option; do { next_option = getopt_long(argc, argv, short_options, long_options, &option_index); switch (next_option) { case -1: /* Done with options. */ break; case 'f': ff_param = parseFloat(0, 5, "-f/--forget-param arg must be between 0 and 1", print_usage); break; case 'm': user_provided_fld = true; def_fl_mean = (uint32_t)parseInt(0, "-m/--frag-len-mean arg must be at least 0", print_usage); break; case 's': user_provided_fld = true; def_fl_stddev = (uint32_t)parseInt(0, "-s/--frag-len-std-dev arg must be at least 0", print_usage); break; case 'o': output_dir = optarg; break; case OPT_UPPER_QUARTILE_NORM: upper_quart_norm = true; break; case OPT_NO_BIAS_CORRECT: bias_correct = false; break; default: print_usage(); return 1; } } while(next_option != -1); return 0; } double log_sum(double x, double y) { return x+log(1+exp(y-x)); } void process_fragment(size_t n, Fragment* frag_p, TranscriptTable* trans_table, FLD* fld, BiasBoss* bias_table, MismatchTable* mismatch_table) { Fragment& frag = *frag_p; if (frag.num_maps()==0 || frag.num_maps()== trans_table->size()) { delete frag_p; return; } double forget_fact = pow(n, ff_param); if (frag.num_maps()==1) { const FragMap& m = *frag.maps()[0]; Transcript* t = trans_table->get_trans(m.trans_id); if (!t) { cerr << "ERROR: Transcript " << m.name << " not found in reference fasta."; exit(1); } double mass = forget_fact; t->add_mass(mass); fld->add_val(m.length(), mass); if (bias_table) bias_table->update_observed(m, *t, mass); mismatch_table->update(m, *t, mass); delete frag_p; return; } vector<double> likelihoods(frag.num_maps()); vector<Transcript*> transcripts(frag.num_maps()); double total_likelihood = 0.0; for(size_t i = 0; i < frag.num_maps(); ++i) { const FragMap& m = *frag.maps()[i]; Transcript* t = trans_table->get_trans(m.trans_id); transcripts[i] = t; assert(t->id() == m.trans_id); likelihoods[i] = t->log_likelihood(m); if (!likelihoods[i]) continue; total_likelihood = (i) ? log_sum(total_likelihood, likelihoods[i]):likelihoods[i]; } if (total_likelihood == 0) { delete frag_p; return; } double total_mass = 0.0; for(size_t i = 0; i < frag.num_maps(); ++i) { if (!likelihoods[i]) continue; const FragMap& m = *frag.maps()[i]; Transcript* t = transcripts[i]; double mass = forget_fact*exp(likelihoods[i]-total_likelihood); assert(!isnan(mass)); if (frag.num_maps() == trans_table->size()) { t->set_counts( (t->frag_count() + mass) / (fld->num_obs() + forget_fact) * fld->num_obs() ); } else { t->add_mass(mass); fld->add_val(m.length(), mass); } if (bias_table) bias_table->update_observed(m, *t, mass); mismatch_table->update(m, *t, mass); total_mass += mass; } assert(abs(total_mass-forget_fact) < .0001); delete frag_p; } void threaded_calc_abundances(MapParser& map_parser, TranscriptTable* trans_table, FLD* fld, BiasBoss* bias_table, MismatchTable* mismatch_table) { ParseThreadSafety ts; ts.proc_lk.lock(); ts.parse_lk.lock(); boost::thread parse(&MapParser::threaded_parse, &map_parser, &ts); size_t count = 0; ofstream running_expr_file((output_dir + "/running.expr").c_str()); trans_table->output_header(running_expr_file); int m = 0; int n = 1; while(true) { ts.proc_lk.lock(); Fragment* frag = ts.next_frag; ts.parse_lk.unlock(); if (!frag) { ts.proc_lk.unlock(); return; } // count += frag->num_maps(); // if (count % 100000 < frag->num_maps() ) // cout<< count << "\n"; count += 1; if (count == n * pow(10.,m)) { running_expr_file << count << '\t'; trans_table->output_current(running_expr_file); if (n==9) { n = 1; m += 1; } else { n += 1; } } process_fragment(count, frag, trans_table, fld, bias_table, mismatch_table); } running_expr_file.close(); } void calc_abundances(MapParser& map_parser, TranscriptTable* trans_table, FLD* fld, BiasBoss* bias_table, MismatchTable* mismatch_table) { bool fragments_remain = true; size_t count = 0; while(fragments_remain) { Fragment* frag = new Fragment(); fragments_remain = map_parser.next_fragment(*frag); count += frag->num_maps(); if (count % 100000 < frag->num_maps() ) cout<< count << "\n"; process_fragment(count, frag, trans_table, fld, bias_table, mismatch_table); } } int main (int argc, char ** argv) { int parse_ret = parse_options(argc,argv); if (parse_ret) return parse_ret; if(optind >= argc) { print_usage(); return 1; } if (output_dir != ".") { boost::filesystem::create_directories(output_dir); } if (!boost::filesystem::exists(output_dir)) { cerr << "Error: cannot create directory " << output_dir << ".\n"; exit(1); } string trans_fasta_file_name = argv[optind++]; string sam_hits_file_name = (optind >= argc) ? "" : argv[optind++]; FLD fld(fld_alpha, def_fl_max); BiasBoss* bias_table = (bias_correct) ? new BiasBoss(bias_alpha):NULL; MismatchTable mismatch_table(mm_alpha); MapParser map_parser(sam_hits_file_name); TranscriptTable trans_table(trans_fasta_file_name, expr_alpha, &fld, bias_table, &mismatch_table); if (bias_table) boost::thread bias_update(&TranscriptTable::threaded_bias_update, &trans_table); threaded_calc_abundances(map_parser, &trans_table, &fld, bias_table, &mismatch_table); fld.output(output_dir); mismatch_table.output(output_dir); trans_table.output_expression(output_dir); return 0; } <commit_msg>Forgetting factor now matches the paper<commit_after>// // main.cpp // expressionline2 // // Created by Adam Roberts on 3/23/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #define PACKAGE_VERSION "INTERNAL" #include <boost/filesystem.hpp> #include <getopt.h> #include <boost/thread.hpp> #include <cassert> #include <iostream> #include <fstream> #include <cmath> #include "transcripts.h" #include "fld.h" #include "fragments.h" #include "biascorrection.h" #include "mismatchmodel.h" using namespace std; double ff_param = 0; string output_dir = "."; double expr_alpha = .001; double fld_alpha = 1; double bias_alpha = 1; double mm_alpha = 1; int def_fl_max = 800; int def_fl_mean = 200; int def_fl_stddev = 80; bool user_provided_fld = false; bool bias_correct = true; bool upper_quart_norm = false; void print_usage() { fprintf(stderr, "cuffexpress v%s\n", PACKAGE_VERSION); // fprintf(stderr, "linked against Boost version %d\n", BOOST_VERSION); fprintf(stderr, "-----------------------------\n"); fprintf(stderr, "File Usage: cuffexpress [options] <transcripts.fasta> <hits.sam>\n"); fprintf(stderr, "Piped Usage: bowtie [options] -S <reads.fastq> | cuffexpress [options] <transcripts.fasta>\n"); fprintf(stderr, "General Options:\n"); fprintf(stderr, " -o/--output-dir write all output files to this directory [ default: ./ ]\n"); fprintf(stderr, " -f/--forget-param forgetting factor exponent parameter [ default: 0 ]\n"); fprintf(stderr, " -m/--frag-len-mean average fragment length (unpaired reads only) [ default: 200 ]\n"); fprintf(stderr, " -s/--frag-len-std-dev fragment length std deviation (unpaired reads only) [ default: 80 ]\n"); fprintf(stderr, " --upper-quartile-norm use upper-quartile normalization [ default: FALSE ]\n"); fprintf(stderr, " --no-bias-correct do not correct for fragment bias [ default: FALSE ]\n"); } #define OPT_UPPER_QUARTILE_NORM 200 #define OPT_NO_BIAS_CORRECT 201 const char *short_options = "o:f:m:s"; static struct option long_options[] = { // general options {"output-dir", required_argument, 0, 'o'}, {"forget-param", required_argument, 0, 'f'}, {"frag-len-mean", required_argument, 0, 'm'}, {"frag-len-std-dev", required_argument, 0, 's'}, {"upper-quartile-norm", no_argument, 0, OPT_UPPER_QUARTILE_NORM}, {"no-bias-correct", no_argument, 0, OPT_NO_BIAS_CORRECT}, {0, 0, 0, 0} // terminator }; /** * Parse an int out of optarg and enforce that it be at least 'lower'; * if it is less than 'lower', than output the given error message and * exit with an error and a usage message. */ int parseInt(int lower, const char *errmsg, void (*print_usage)()) { long l; char *endPtr= NULL; l = strtol(optarg, &endPtr, 10); if (endPtr != NULL) { if (l < lower) { cerr << errmsg << endl; print_usage(); exit(1); } return (int32_t)l; } cerr << errmsg << endl; print_usage(); exit(1); return -1; } /** * Parse an float out of optarg and enforce that is between 'lower' and 'upper'; * if it is not, output the given error message and * exit with an error and a usage message. */ float parseFloat(float lower, float upper, const char *errmsg, void (*print_usage)()) { float l; l = (float)atof(optarg); if (l < lower) { cerr << errmsg << endl; print_usage(); exit(1); } if (l > upper) { cerr << errmsg << endl; print_usage(); exit(1); } return l; cerr << errmsg << endl; print_usage(); exit(1); return -1; } int parse_options(int argc, char** argv) { int option_index = 0; int next_option; do { next_option = getopt_long(argc, argv, short_options, long_options, &option_index); switch (next_option) { case -1: /* Done with options. */ break; case 'f': ff_param = parseFloat(0, 5, "-f/--forget-param arg must be between 0 and 1", print_usage); break; case 'm': user_provided_fld = true; def_fl_mean = (uint32_t)parseInt(0, "-m/--frag-len-mean arg must be at least 0", print_usage); break; case 's': user_provided_fld = true; def_fl_stddev = (uint32_t)parseInt(0, "-s/--frag-len-std-dev arg must be at least 0", print_usage); break; case 'o': output_dir = optarg; break; case OPT_UPPER_QUARTILE_NORM: upper_quart_norm = true; break; case OPT_NO_BIAS_CORRECT: bias_correct = false; break; default: print_usage(); return 1; } } while(next_option != -1); return 0; } double log_sum(double x, double y) { return x+log(1+exp(y-x)); } void process_fragment(double gamma_n, Fragment* frag_p, TranscriptTable* trans_table, FLD* fld, BiasBoss* bias_table, MismatchTable* mismatch_table) { Fragment& frag = *frag_p; if (frag.num_maps()==0) { delete frag_p; return; } if (frag.num_maps()==1) { const FragMap& m = *frag.maps()[0]; Transcript* t = trans_table->get_trans(m.trans_id); if (!t) { cerr << "ERROR: Transcript " << m.name << " not found in reference fasta."; exit(1); } double mass = gamma_n; t->add_mass(mass); fld->add_val(m.length(), mass); if (bias_table) bias_table->update_observed(m, *t, mass); mismatch_table->update(m, *t, mass); delete frag_p; return; } vector<double> likelihoods(frag.num_maps()); vector<Transcript*> transcripts(frag.num_maps()); double total_likelihood = 0.0; for(size_t i = 0; i < frag.num_maps(); ++i) { const FragMap& m = *frag.maps()[i]; Transcript* t = trans_table->get_trans(m.trans_id); transcripts[i] = t; assert(t->id() == m.trans_id); likelihoods[i] = t->log_likelihood(m); if (!likelihoods[i]) continue; total_likelihood = (i) ? log_sum(total_likelihood, likelihoods[i]):likelihoods[i]; } if (total_likelihood == 0) { delete frag_p; return; } double total_mass = 0.0; for(size_t i = 0; i < frag.num_maps(); ++i) { if (!likelihoods[i]) continue; const FragMap& m = *frag.maps()[i]; Transcript* t = transcripts[i]; double mass = gamma_n*exp(likelihoods[i]-total_likelihood); assert(!isnan(mass)); t->add_mass(mass); fld->add_val(m.length(), mass); if (bias_table) bias_table->update_observed(m, *t, mass); mismatch_table->update(m, *t, mass); total_mass += mass; } assert(abs(total_mass-forget_fact) < .0001); delete frag_p; } void threaded_calc_abundances(MapParser& map_parser, TranscriptTable* trans_table, FLD* fld, BiasBoss* bias_table, MismatchTable* mismatch_table) { ParseThreadSafety ts; ts.proc_lk.lock(); ts.parse_lk.lock(); boost::thread parse(&MapParser::threaded_parse, &map_parser, &ts); size_t count = 0; double mass = 1; ofstream running_expr_file((output_dir + "/running.expr").c_str()); trans_table->output_header(running_expr_file); int m = 0; int n = 1; while(true) { ts.proc_lk.lock(); Fragment* frag = ts.next_frag; ts.parse_lk.unlock(); if (!frag) { ts.proc_lk.unlock(); return; } // count += frag->num_maps(); // if (count % 100000 < frag->num_maps() ) // cout<< count << "\n"; count += 1; if (count == n * pow(10.,m)) { running_expr_file << count << '\t'; trans_table->output_current(running_expr_file); if (n==9) { n = 1; m += 1; } else { n += 1; } } if (count > 1) mass = mass * pow(count-1,ff_param) / (pow(count, ff_param) -1); process_fragment(mass, frag, trans_table, fld, bias_table, mismatch_table); } running_expr_file.close(); } void calc_abundances(MapParser& map_parser, TranscriptTable* trans_table, FLD* fld, BiasBoss* bias_table, MismatchTable* mismatch_table) { bool fragments_remain = true; size_t count = 0; while(fragments_remain) { Fragment* frag = new Fragment(); fragments_remain = map_parser.next_fragment(*frag); count += frag->num_maps(); if (count % 100000 < frag->num_maps() ) cout<< count << "\n"; process_fragment(count, frag, trans_table, fld, bias_table, mismatch_table); } } int main (int argc, char ** argv) { int parse_ret = parse_options(argc,argv); if (parse_ret) return parse_ret; if(optind >= argc) { print_usage(); return 1; } if (output_dir != ".") { boost::filesystem::create_directories(output_dir); } if (!boost::filesystem::exists(output_dir)) { cerr << "Error: cannot create directory " << output_dir << ".\n"; exit(1); } string trans_fasta_file_name = argv[optind++]; string sam_hits_file_name = (optind >= argc) ? "" : argv[optind++]; FLD fld(fld_alpha, def_fl_max); BiasBoss* bias_table = (bias_correct) ? new BiasBoss(bias_alpha):NULL; MismatchTable mismatch_table(mm_alpha); MapParser map_parser(sam_hits_file_name); TranscriptTable trans_table(trans_fasta_file_name, expr_alpha, &fld, bias_table, &mismatch_table); if (bias_table) boost::thread bias_update(&TranscriptTable::threaded_bias_update, &trans_table); threaded_calc_abundances(map_parser, &trans_table, &fld, bias_table, &mismatch_table); fld.output(output_dir); mismatch_table.output(output_dir); trans_table.output_expression(output_dir); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/idriver_ui_adapter.h" #include "common/software_texture.h" #include "common/texture_load.h" #include "common/software_mesh.h" #include "common/mesh_load.h" #include "common/mesh_write.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/json_structure.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Make an isometric camera. auto cam = gfx::make_isometric_camera(); auto terrain_obj = gfx::Object{}; *terrain_obj.material = gfx::load_material("mat/terrain.json"); // Build our terrain from a heightmap. { Software_Texture terrain_heightmap; load_png("map/default.png", terrain_heightmap); auto terrain = make_heightmap_from_image(terrain_heightmap); auto terrain_chunks = make_terrain_mesh(*terrain_obj.mesh, terrain, .01f, .01); write_obj("../terrain.obj", terrain_obj.mesh->mesh_data()); } prepare_object(driver, terrain_obj); // Load our house structure auto house_struct = Json_Structure{"structure/house.json"}; // This is code smell, right here. The fact that before, we were preparing // a temporary but it still worked because of the implementation of // Json_Structure and the object sharing mechanism. auto house_obj = house_struct.make_obj(); prepare_object(driver, house_obj); std::vector<Structure_Instance> house_instances; Structure_Instance moveable_instance{house_struct, Orient::N}; int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_button")->add_click_listener([](auto const& pt) { log_i("BUILD!"); }); hud->layout(driver.window_extents()); controller.add_click_listener([&](auto const&) { // Commit the current position of our moveable instance. house_instances.push_back(moveable_instance); }); controller.add_hover_listener([&](auto const& pt) { if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0) { moveable_instance.obj.model_matrix = glm::mat4(1.0); } else { // Find our depth. GLfloat z; glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); // Unproject our depth. auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z), camera_view_matrix(cam), camera_proj_matrix(cam), glm::vec4(0.0, 0.0, 1000.0, 1000.0)); // We have our position, render a single house there. moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val); } // Move the house by however much the structure *type* requires. moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix * house_struct.make_obj().model_matrix; }); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); render_object(driver, terrain_obj); // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); // Render our movable instance of a house. render_object(driver, moveable_instance.obj); // Render all of our other house instances. for(auto const& instance : house_instances) { render_object(driver, instance.obj); } { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <commit_msg>We are now rendering the terrain in chunks!<commit_after>/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include <fstream> #include <sstream> #include <cstdlib> #include <vector> #include <thread> #include "common/log.h" #include "gfx/gl/driver.h" #include "gfx/camera.h" #include "gfx/object.h" #include "gfx/scene_node.h" #include "gfx/idriver_ui_adapter.h" #include "common/software_texture.h" #include "common/texture_load.h" #include "common/software_mesh.h" #include "common/mesh_load.h" #include "common/mesh_write.h" #include "ui/load.h" #include "ui/freetype_renderer.h" #include "ui/mouse_logic.h" #include "ui/simple_controller.h" #include "map/map.h" #include "map/json_structure.h" #include "glad/glad.h" #include "glfw3.h" #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "uv.h" #define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" void scroll_callback(GLFWwindow* window, double, double deltay) { auto cam_ptr = glfwGetWindowUserPointer(window); auto& camera = *((game::gfx::Camera*) cam_ptr); camera.fp.pos += -deltay; } game::ui::Mouse_State gen_mouse_state(GLFWwindow* w) { game::ui::Mouse_State ret; ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; game::Vec<double> pos; glfwGetCursorPos(w, &pos.x, &pos.y); ret.position = game::vec_cast<int>(pos); return ret; } void log_gl_limits(game::Log_Severity s) noexcept { GLint i = 0; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i); log(s, "GL_MAX_ELEMENTS_VERTICES: %", i); } struct Command_Options { }; Command_Options parse_command_line(int argc, char**) { Command_Options opt; for(int i = 0; i < argc; ++i) { //auto option = argv[i]; } return opt; } int main(int argc, char** argv) { using namespace game; set_log_level(Log_Severity::Debug); uv_chdir("assets/"); // Initialize logger. Scoped_Log_Init log_init_raii_lock{}; // Parse command line arguments. auto options = parse_command_line(argc - 1, argv+1); // Init glfw. if(!glfwInit()) return EXIT_FAILURE; auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return EXIT_FAILURE; } // Init context + load gl functions. glfwMakeContextCurrent(window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); // Log glfw version. log_i("Initialized GLFW %", glfwGetVersionString()); int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR); int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR); int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION); // Log GL profile. log_i("OpenGL core profile %.%.%", maj, min, rev); { // Make an OpenGL driver. gfx::gl::Driver driver{Vec<int>{1000, 1000}}; // Make an isometric camera. auto cam = gfx::make_isometric_camera(); auto terrain_obj = gfx::Object{}; *terrain_obj.material = gfx::load_material("mat/terrain.json"); // Load the image Software_Texture terrain_image; load_png("map/default.png", terrain_image); // Convert it into a heightmap auto terrain_heightmap = make_heightmap_from_image(terrain_image); auto terrain = make_terrain_mesh(*terrain_obj.mesh, terrain_heightmap,{20,20}, .01f, .01); write_obj("../terrain.obj", terrain_obj.mesh->mesh_data()); prepare_object(driver, terrain_obj); // Load our house structure auto house_struct = Json_Structure{"structure/house.json"}; // This is code smell, right here. The fact that before, we were preparing // a temporary but it still worked because of the implementation of // Json_Structure and the object sharing mechanism. auto house_obj = house_struct.make_obj(); prepare_object(driver, house_obj); std::vector<Structure_Instance> house_instances; Structure_Instance moveable_instance{house_struct, Orient::N}; int fps = 0; int time = glfwGetTime(); // Set up some pre-rendering state. driver.clear_color_value(Color{0x55, 0x66, 0x77}); driver.clear_depth_value(1.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); // Our quick hack to avoid splitting into multiple functions and dealing // either with global variables or like a bound struct or something. bool has_clicked_down = false; // Load our ui gfx::IDriver_UI_Adapter ui_adapter{driver}; ui::Freetype_Renderer freetype_font; auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter}; auto hud = ui::load("ui/hud.json", ui_load_params); auto controller = ui::Simple_Controller{}; hud->find_child_r("build_button")->add_click_listener([](auto const& pt) { log_i("BUILD!"); }); hud->layout(driver.window_extents()); controller.add_click_listener([&](auto const&) { // Commit the current position of our moveable instance. house_instances.push_back(moveable_instance); }); controller.add_hover_listener([&](auto const& pt) { if(pt.x < 0 || pt.x > 1000.0 || pt.y < 0 || pt.y > 1000.0) { moveable_instance.obj.model_matrix = glm::mat4(1.0); } else { // Find our depth. GLfloat z; glReadPixels((float) pt.x, (float) 1000.0 - pt.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); // Unproject our depth. auto val = glm::unProject(glm::vec3(pt.x, 1000.0 - pt.y, z), camera_view_matrix(cam), camera_proj_matrix(cam), glm::vec4(0.0, 0.0, 1000.0, 1000.0)); // We have our position, render a single house there. moveable_instance.obj.model_matrix = glm::translate(glm::mat4(1.0), val); } // Move the house by however much the structure *type* requires. moveable_instance.obj.model_matrix = moveable_instance.obj.model_matrix * house_struct.make_obj().model_matrix; }); controller.add_drag_listener([&](auto const& np, auto const& op) { // pan auto movement = vec_cast<float>(np - op); movement /= -75; glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f); move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec; cam.fp.pos.x += move_vec.x; cam.fp.pos.z += move_vec.z; }); glfwSetWindowUserPointer(window, &cam); glfwSetScrollCallback(window, scroll_callback); while(!glfwWindowShouldClose(window)) { ++fps; glfwPollEvents(); // Clear the screen and render the terrain. driver.clear(); use_camera(driver, cam); for(auto const& chunk : terrain.chunks) { render_object(driver, terrain_obj, chunk.mesh.offset, chunk.mesh.count); } // Render the terrain before we calculate the depth of the mouse position. auto mouse_state = gen_mouse_state(window); controller.step(hud, mouse_state); // Render our movable instance of a house. render_object(driver, moveable_instance.obj); // Render all of our other house instances. for(auto const& instance : house_instances) { render_object(driver, instance.obj); } { ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter}; hud->render(ui_adapter); } glfwSwapBuffers(window); if(int(glfwGetTime()) != time) { time = glfwGetTime(); log_d("fps: %", fps); fps = 0; } flush_log(); } } glfwTerminate(); return 0; } <|endoftext|>
<commit_before> #include <Urho3D/Engine/Application.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Engine/Console.h> #include <Urho3D/UI/Cursor.h> #include <Urho3D/Engine/DebugHud.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/UI/Sprite.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/Core/Timer.h> #include <Urho3D/UI/UI.h> #include <iostream> #include <entityx/entityx.h> #include <glm/glm.hpp> #include <glm/vec2.hpp> #include <glm/gtx/string_cast.hpp> namespace Urho3D { class Node; class Scene; class Sprite; } using namespace Urho3D; class testclass : public Application { URHO3D_OBJECT(testclass, Application); testclass(Context *context) : Application(context) { } void Setup() { engineParameters_["WindowTitle"] = "YTBA"; engineParameters_["FullScreen"] = false; engineParameters_["Sound"] = false; } void Start() { } void Stop() { engine->DumpResources(true); } }; class ytba : public testclass { URHO3D_DEFINE_APPLICATION_MAIN(ytba) ytba(Context *context) : testclass(context) { } }; int main() { glm::vec2 lol(1.f, 2.f); glm::vec2 rofl(2.f, 3.f); std::cout << glm::to_string(lol + rofl) << std::endl; std::cout << "hello world" << std::endl; return 1; } <commit_msg>small change for testing stuff<commit_after> #include <Urho3D/Engine/Application.h> #include <Urho3D/Graphics/Camera.h> #include <Urho3D/Engine/Console.h> #include <Urho3D/UI/Cursor.h> #include <Urho3D/Engine/DebugHud.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Scene/Scene.h> #include <Urho3D/UI/Sprite.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/Core/Timer.h> #include <Urho3D/UI/UI.h> #include <iostream> #include <entityx/entityx.h> #include <glm/glm.hpp> #include <glm/vec2.hpp> #include <glm/gtx/string_cast.hpp> namespace Urho3D { class Node; class Scene; class Sprite; } using namespace Urho3D; class testclass : public Application { URHO3D_OBJECT(testclass, Application); testclass(Context *context) : Application(context) { } void Setup() { engineParameters_["WindowTitle"] = "YTBA"; engineParameters_["FullScreen"] = false; engineParameters_["Sound"] = false; std::cout << "small change " << std::endl; } void Start() { } void Stop() { engine->DumpResources(true); } }; class ytba : public testclass { URHO3D_DEFINE_APPLICATION_MAIN(ytba) ytba(Context *context) : testclass(context) { } }; int main() { glm::vec2 lol(1.f, 2.f); glm::vec2 rofl(2.f, 3.f); std::cout << glm::to_string(lol + rofl) << std::endl; std::cout << "hello world" << std::endl; return 1; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015-2016 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <unistd.h> #include <ydsh/ydsh.h> #include "misc/argv.hpp" using namespace ydsh; int exec_interactive(DSContext *ctx); static void loadRC(DSContext *ctx, const char *rcfile) { std::string path; if(rcfile != nullptr) { path += rcfile; } else { path += getenv("HOME"); path += "/.ydshrc"; } FILE *fp = fopen(path.c_str(), "rb"); if(fp == NULL) { return; // not read } int ret = DSContext_loadAndEval(ctx, path.c_str(), fp); int status = DSContext_status(ctx); fclose(fp); if(status != DS_STATUS_SUCCESS) { DSContext_delete(&ctx); exit(ret); } // reset line num DSContext_setLineNum(ctx, 1); } static const char *statusLogPath = nullptr; template <typename Functor, typename ... T> static int invoke(Functor func, DSContext **ctx, T && ... arg) { int ret = func(*ctx, std::forward<T>(arg)...); if(statusLogPath != nullptr) { FILE *fp = fopen(statusLogPath, "w"); if(fp != nullptr) { fprintf(fp, "type=%d lineNum=%d kind=%s\n", DSContext_status(*ctx), DSContext_errorLineNum(*ctx), DSContext_errorKind(*ctx)); fclose(fp); } } DSContext_delete(ctx); return ret; } static void showFeature(std::ostream &stream) { static const char *featureNames[] = { "USE_LOGGING", "USE_DBUS", "USE_SAFE_CAST", "USE_FIXED_TIME" }; const unsigned int featureBit = DSContext_featureBit(); for(unsigned int i = 0; i < (sizeof(featureNames) / sizeof(featureNames[0])); i++) { if(ydsh::misc::hasFlag(featureBit, static_cast<unsigned int>(1 << i))) { stream << featureNames[i] << std::endl; } } } #define EACH_OPT(OP) \ OP(DUMP_UAST, "--dump-untyped-ast", 0, "dump abstract syntax tree (before type checking)") \ OP(DUMP_AST, "--dump-ast", 0, "dump abstract syntax tree (after type checking)") \ OP(PARSE_ONLY, "--parse-only", 0, "not evaluate, parse only") \ OP(DISABLE_ASSERT, "--disable-assertion", 0, "disable assert statement") \ OP(PRINT_TOPLEVEL, "--print-toplevel", 0, "print toplevel evaluated value") \ OP(TRACE_EXIT, "--trace-exit", 0, "trace execution process to exit command") \ OP(VERSION, "--version", 0, "show version and copyright") \ OP(HELP, "--help", 0, "show this help message") \ OP(COMMAND, "-c", argv::HAS_ARG | argv::IGNORE_REST, "evaluate argument") \ OP(NORC, "--norc", 0, "not load rc file (only available interactive mode)") \ OP(EXEC, "-e", argv::HAS_ARG | argv::IGNORE_REST, "execute builtin command (ignore some option)") \ OP(STATUS_LOG, "--status-log", argv::HAS_ARG, "write execution status to specified file (ignored in interactive mode)") \ OP(FEATURE, "--feature", 0, "show available features") \ OP(RC_FILE, "--rcfile", argv::HAS_ARG, "load specified rc file (only available interactive mode)") \ OP(QUIET, "--quiet", 0, "suppress startup message (only available interactive mode)") \ OP(SET_ARGS, "-s", argv::IGNORE_REST, "set arguments and read command from standard input") \ OP(INTERACTIVE, "-i", 0, "run interactive mode") enum OptionKind { #define GEN_ENUM(E, S, F, D) E, EACH_OPT(GEN_ENUM) #undef GEN_ENUM }; static const argv::Option<OptionKind> options[] = { #define GEN_OPT(E, S, F, D) {E, S, F, D}, EACH_OPT(GEN_OPT) #undef GEN_OPT }; #undef EACH_OPT enum class InvocationKind { FROM_FILE, FROM_STDIN, FROM_STRING, BUILTIN, }; int main(int argc, char **argv) { argv::CmdLines<OptionKind> cmdLines; int restIndex = argc; try { restIndex = argv::parseArgv(argc, argv, options, cmdLines); } catch(const argv::ParseError &e) { std::cerr << e.getMessage() << std::endl; std::cerr << DSContext_version() << std::endl; std::cerr << options << std::endl; return 1; } DSContext *ctx = DSContext_create(); InvocationKind invocationKind = InvocationKind::FROM_FILE; const char *evalText = nullptr; bool userc = true; const char *rcfile = nullptr; bool quiet = false; bool forceInteractive = false; for(auto &cmdLine : cmdLines) { switch(cmdLine.first) { case DUMP_UAST: DSContext_setOption(ctx, DS_OPTION_DUMP_UAST); break; case DUMP_AST: DSContext_setOption(ctx, DS_OPTION_DUMP_AST); break; case PARSE_ONLY: DSContext_setOption(ctx, DS_OPTION_PARSE_ONLY); break; case DISABLE_ASSERT: DSContext_unsetOption(ctx, DS_OPTION_ASSERT); break; case PRINT_TOPLEVEL: DSContext_setOption(ctx, DS_OPTION_TOPLEVEL); break; case TRACE_EXIT: DSContext_setOption(ctx, DS_OPTION_TRACE_EXIT); break; case VERSION: std::cout << DSContext_version() << std::endl; std::cout << DSContext_copyright() << std::endl; return 0; case HELP: std::cout << DSContext_version() << std::endl; std::cout << options << std::endl; return 0; case COMMAND: invocationKind = InvocationKind::FROM_STRING; evalText = cmdLine.second; break; case NORC: userc = false; break; case EXEC: invocationKind = InvocationKind::BUILTIN; restIndex--; break; case STATUS_LOG: statusLogPath = cmdLine.second; break; case FEATURE: showFeature(std::cout); return 0; case RC_FILE: rcfile = cmdLine.second; break; case QUIET: quiet = true; break; case SET_ARGS: invocationKind = InvocationKind::FROM_STDIN; break; case INTERACTIVE: forceInteractive = true; break; } } // set rest argument const int size = argc - restIndex; char *shellArgs[size + 1]; memcpy(shellArgs, argv + restIndex, sizeof(char *) * size); shellArgs[size] = nullptr; if(invocationKind == InvocationKind::FROM_FILE && size == 0) { invocationKind = InvocationKind::FROM_STDIN; } // execute switch(invocationKind) { case InvocationKind::FROM_FILE: { const char *scriptName = shellArgs[0]; FILE *fp = fopen(scriptName, "rb"); if(fp == NULL) { fprintf(stderr, "ydsh: %s: %s\n", scriptName, strerror(errno)); return 1; } DSContext_setShellName(ctx, scriptName); DSContext_setArguments(ctx, shellArgs + 1); return invoke([](DSContext *ctx, const char *sourceName, FILE *fp) { return DSContext_loadAndEval(ctx, sourceName, fp); }, &ctx, scriptName, fp); } case InvocationKind::FROM_STDIN: { DSContext_setArguments(ctx, shellArgs); if(isatty(STDIN_FILENO) == 0 && !forceInteractive) { // pipe line mode return invoke([](DSContext *ctx, const char *sourceName, FILE *fp) { return DSContext_loadAndEval(ctx, sourceName, fp); }, &ctx, nullptr, stdin); } else { // interactive mode if(!quiet) { std::cout << DSContext_version() << std::endl; std::cout << DSContext_copyright() << std::endl; } if(userc) { loadRC(ctx, rcfile); } return exec_interactive(ctx); } } case InvocationKind::FROM_STRING: { DSContext_setShellName(ctx, shellArgs[0]); DSContext_setArguments(ctx, size == 0 ? nullptr : shellArgs + 1); return invoke([](DSContext *ctx, const char *sourceName, const char *source) { return DSContext_eval(ctx, sourceName, source); }, &ctx, "(string)", evalText); } case InvocationKind::BUILTIN: { return invoke([](DSContext *ctx, char *const argv[]) { return DSContext_exec(ctx, argv); }, &ctx, (char **)shellArgs); } } } <commit_msg>Revert "fix build error in gcc5"<commit_after>/* * Copyright (C) 2015-2016 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <unistd.h> #include <ydsh/ydsh.h> #include "misc/argv.hpp" using namespace ydsh; int exec_interactive(DSContext *ctx); static void loadRC(DSContext *ctx, const char *rcfile) { std::string path; if(rcfile != nullptr) { path += rcfile; } else { path += getenv("HOME"); path += "/.ydshrc"; } FILE *fp = fopen(path.c_str(), "rb"); if(fp == NULL) { return; // not read } int ret = DSContext_loadAndEval(ctx, path.c_str(), fp); int status = DSContext_status(ctx); fclose(fp); if(status != DS_STATUS_SUCCESS) { DSContext_delete(&ctx); exit(ret); } // reset line num DSContext_setLineNum(ctx, 1); } static const char *statusLogPath = nullptr; template <typename F, F func, typename ...T> static int invoke(DSContext **ctx, T&& ... args) { int ret = func(*ctx, std::forward<T>(args)...); if(statusLogPath != nullptr) { FILE *fp = fopen(statusLogPath, "w"); if(fp != nullptr) { fprintf(fp, "type=%d lineNum=%d kind=%s\n", DSContext_status(*ctx), DSContext_errorLineNum(*ctx), DSContext_errorKind(*ctx)); fclose(fp); } } DSContext_delete(ctx); return ret; } #define INVOKE(F) invoke<decltype(DSContext_ ## F), DSContext_ ## F> static void showFeature(std::ostream &stream) { static const char *featureNames[] = { "USE_LOGGING", "USE_DBUS", "USE_SAFE_CAST", "USE_FIXED_TIME" }; const unsigned int featureBit = DSContext_featureBit(); for(unsigned int i = 0; i < (sizeof(featureNames) / sizeof(featureNames[0])); i++) { if(ydsh::misc::hasFlag(featureBit, static_cast<unsigned int>(1 << i))) { stream << featureNames[i] << std::endl; } } } #define EACH_OPT(OP) \ OP(DUMP_UAST, "--dump-untyped-ast", 0, "dump abstract syntax tree (before type checking)") \ OP(DUMP_AST, "--dump-ast", 0, "dump abstract syntax tree (after type checking)") \ OP(PARSE_ONLY, "--parse-only", 0, "not evaluate, parse only") \ OP(DISABLE_ASSERT, "--disable-assertion", 0, "disable assert statement") \ OP(PRINT_TOPLEVEL, "--print-toplevel", 0, "print toplevel evaluated value") \ OP(TRACE_EXIT, "--trace-exit", 0, "trace execution process to exit command") \ OP(VERSION, "--version", 0, "show version and copyright") \ OP(HELP, "--help", 0, "show this help message") \ OP(COMMAND, "-c", argv::HAS_ARG | argv::IGNORE_REST, "evaluate argument") \ OP(NORC, "--norc", 0, "not load rc file (only available interactive mode)") \ OP(EXEC, "-e", argv::HAS_ARG | argv::IGNORE_REST, "execute builtin command (ignore some option)") \ OP(STATUS_LOG, "--status-log", argv::HAS_ARG, "write execution status to specified file (ignored in interactive mode)") \ OP(FEATURE, "--feature", 0, "show available features") \ OP(RC_FILE, "--rcfile", argv::HAS_ARG, "load specified rc file (only available interactive mode)") \ OP(QUIET, "--quiet", 0, "suppress startup message (only available interactive mode)") \ OP(SET_ARGS, "-s", argv::IGNORE_REST, "set arguments and read command from standard input") \ OP(INTERACTIVE, "-i", 0, "run interactive mode") enum OptionKind { #define GEN_ENUM(E, S, F, D) E, EACH_OPT(GEN_ENUM) #undef GEN_ENUM }; static const argv::Option<OptionKind> options[] = { #define GEN_OPT(E, S, F, D) {E, S, F, D}, EACH_OPT(GEN_OPT) #undef GEN_OPT }; #undef EACH_OPT enum class InvocationKind { FROM_FILE, FROM_STDIN, FROM_STRING, BUILTIN, }; int main(int argc, char **argv) { argv::CmdLines<OptionKind> cmdLines; int restIndex = argc; try { restIndex = argv::parseArgv(argc, argv, options, cmdLines); } catch(const argv::ParseError &e) { std::cerr << e.getMessage() << std::endl; std::cerr << DSContext_version() << std::endl; std::cerr << options << std::endl; return 1; } DSContext *ctx = DSContext_create(); InvocationKind invocationKind = InvocationKind::FROM_FILE; const char *evalText = nullptr; bool userc = true; const char *rcfile = nullptr; bool quiet = false; bool forceInteractive = false; for(auto &cmdLine : cmdLines) { switch(cmdLine.first) { case DUMP_UAST: DSContext_setOption(ctx, DS_OPTION_DUMP_UAST); break; case DUMP_AST: DSContext_setOption(ctx, DS_OPTION_DUMP_AST); break; case PARSE_ONLY: DSContext_setOption(ctx, DS_OPTION_PARSE_ONLY); break; case DISABLE_ASSERT: DSContext_unsetOption(ctx, DS_OPTION_ASSERT); break; case PRINT_TOPLEVEL: DSContext_setOption(ctx, DS_OPTION_TOPLEVEL); break; case TRACE_EXIT: DSContext_setOption(ctx, DS_OPTION_TRACE_EXIT); break; case VERSION: std::cout << DSContext_version() << std::endl; std::cout << DSContext_copyright() << std::endl; return 0; case HELP: std::cout << DSContext_version() << std::endl; std::cout << options << std::endl; return 0; case COMMAND: invocationKind = InvocationKind::FROM_STRING; evalText = cmdLine.second; break; case NORC: userc = false; break; case EXEC: invocationKind = InvocationKind::BUILTIN; restIndex--; break; case STATUS_LOG: statusLogPath = cmdLine.second; break; case FEATURE: showFeature(std::cout); return 0; case RC_FILE: rcfile = cmdLine.second; break; case QUIET: quiet = true; break; case SET_ARGS: invocationKind = InvocationKind::FROM_STDIN; break; case INTERACTIVE: forceInteractive = true; break; } } // set rest argument const int size = argc - restIndex; char *shellArgs[size + 1]; memcpy(shellArgs, argv + restIndex, sizeof(char *) * size); shellArgs[size] = nullptr; if(invocationKind == InvocationKind::FROM_FILE && size == 0) { invocationKind = InvocationKind::FROM_STDIN; } // execute switch(invocationKind) { case InvocationKind::FROM_FILE: { const char *scriptName = shellArgs[0]; FILE *fp = fopen(scriptName, "rb"); if(fp == NULL) { fprintf(stderr, "ydsh: %s: %s\n", scriptName, strerror(errno)); return 1; } DSContext_setShellName(ctx, scriptName); DSContext_setArguments(ctx, shellArgs + 1); return INVOKE(loadAndEval)(&ctx, scriptName, fp); } case InvocationKind::FROM_STDIN: { DSContext_setArguments(ctx, shellArgs); if(isatty(STDIN_FILENO) == 0 && !forceInteractive) { // pipe line mode return INVOKE(loadAndEval)(&ctx, nullptr, stdin); } else { // interactive mode if(!quiet) { std::cout << DSContext_version() << std::endl; std::cout << DSContext_copyright() << std::endl; } if(userc) { loadRC(ctx, rcfile); } return exec_interactive(ctx); } } case InvocationKind::FROM_STRING: { DSContext_setShellName(ctx, shellArgs[0]); DSContext_setArguments(ctx, size == 0 ? nullptr : shellArgs + 1); return INVOKE(eval)(&ctx, "(string)", evalText); } case InvocationKind::BUILTIN: { return INVOKE(exec)(&ctx, (char **)shellArgs); } } } <|endoftext|>
<commit_before>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #include "curleasy.h" const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.perform(); std::ofstream ofs(name()); if (ofs.good()) { ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = tolower(c); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); curl.perform(); std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; for (auto &t : new_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG for (auto &t : new_targets) { t.fetch(); } for (auto &t : old_targets) { t.fetch(); } #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int argc, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } l.stat_targets(); return 0; } <commit_msg>Do not fetch target unless destination is writeable.<commit_after>#include <stdexcept> #include <limits> #include <algorithm> #include <array> #include <memory> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #include "curleasy.h" const std::string version("0.1.0"); const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string file_checksum(const std::string &path); std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } void make_dir(const std::string &path) { auto elems = split(path, '/'); std::string descend; for (size_t i = 0, k = elems.size() - 1; i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { descend.append((i > 0 ? "/" : "") + s); auto status = mkdir(descend.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << descend << ": " << err.message() << std::endl; } } } } } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; make_dir(name()); fs.open(name(), std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << name() << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::ofstream ofs(name()); if (ofs.good()) { std::string s; std::string url(patch_dir + name()); CurlEasy curl(url); curl.write_to(s); curl.perform(); ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ return calcsum.str(); } namespace Options { bool version(const std::string &val) { return val == "version"; } bool update_path(const std::string &val) { return val == "update path"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = tolower(c); } while (c != 'y' && c != 'n'); return c == 'y'; } class EfuLauncher { public: explicit EfuLauncher(const std::string path, const std::string update_check): m_path(path), m_update_check(update_check), m_has_update(false) {} bool has_update() { if (m_has_update) { return m_has_update; } std::string fetch; CurlEasy curl(m_update_check.c_str()); curl.write_to(fetch); curl.perform(); std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (keyvals.size() != 2) { std::cerr << "Malformed option: " + *beg + ", aborting launcher update check." << std::endl; return m_has_update = false; } if (Options::version(keyvals[0])) { const std::string version_test(keyvals[1]); m_has_update = version_test != version; } else if (Options::update_path(keyvals[0])) { m_update_path = keyvals[1]; } } return m_has_update; } bool get_update() { if (!m_has_update || m_update_path.empty()) { return m_has_update = false; } return !(m_has_update = false); } void stat_targets() { std::string fetch; CurlEasy curl(listing); curl.write_to(fetch); curl.perform(); auto lines(split(fetch, '\n')); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; for (auto &t : new_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG for (auto &t : new_targets) { t.fetch(); } for (auto &t : old_targets) { t.fetch(); } #endif } private: const std::string path() const { return m_path; } const std::string m_path; const std::string m_update_check; std::string m_update_path; bool m_has_update; }; int main(int argc, char *argv[]) { CurlGlobalInit curl_global; EfuLauncher l(argv[0], "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } l.stat_targets(); return 0; } <|endoftext|>
<commit_before>/** * This file is part of Slideshow. * Copyright (C) 2008 David Sveningsson <ext@sidvind.com> * * Slideshow is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Slideshow 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #include "Kernel.h" #include "ForegroundApp.h" #include "DaemonApp.h" #include "Log.h" #include "Exceptions.h" #include "module_loader.h" #include "path.h" #include <cstring> #include <portable/Time.h> int main( int argc, const char* argv[] ){ try { // Default arguments Kernel::argument_set_t arguments = { Kernel::ForegroundMode, // mode Log::Info, // loglevel false, // fullscreen false, // have_password 0, // collection_id 800, // width 600, // height 3.0f, // transition_time; 5.0f, // switch_time; NULL, // connection_string NULL // transition_string }; // Parse the cli arguments, overriding the defaults if ( !Kernel::parse_arguments(arguments, argc, argv) ){ throw ArgumentException(""); } initTime(); moduleloader_init(pluginpath()); Log::initialize("slideshow.log"); Log::set_level( (Log::Severity)arguments.loglevel ); Kernel* application = NULL; switch ( arguments.mode ){ case Kernel::ForegroundMode: application = new ForegroundApp(arguments); break; case Kernel::DaemonMode: application = new DaemonApp(arguments); break; case Kernel::ListTransitionMode: Kernel::print_transitions(); throw ExitException(); default: throw KernelException("No valid mode. This should not happen, please report this to the maintainer. Modeid: %d\n", arguments.mode); } application->init(); application->run(); application->cleanup(); delete application; moduleloader_cleanup(); Log::deinitialize(); } catch ( ExitException &e ){ return 0; } catch ( FatalException &e ){ // Only display message if there is one available. // Some exceptions like ArgumentException usually // print the error messages before throwing the // exception. if ( e.what() && strlen(e.what()) > 0 ){ fprintf(stderr, "\nError 0x%02x:\n%s\n", e.code(), e.what()); } return e.code(); } catch ( BaseException &e ){ fprintf(stderr, "Uhh, unhandled exception, recovery not possible. The message was: %s\n", e.what()); return UNHANDLED_ERROR; } return 0; } <commit_msg>Conditional compilation of daemon mode (will not be supported on win32)<commit_after>/** * This file is part of Slideshow. * Copyright (C) 2008 David Sveningsson <ext@sidvind.com> * * Slideshow is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Slideshow 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Slideshow. If not, see <http://www.gnu.org/licenses/>. */ #include "Kernel.h" #include "ForegroundApp.h" #ifdef BUILD_DAEMON # include "DaemonApp.h" #endif /* BUILD_DAEMON */ #include "Log.h" #include "Exceptions.h" #include "module_loader.h" #include "path.h" #include <cstring> #include <portable/Time.h> int main( int argc, const char* argv[] ){ try { // Default arguments Kernel::argument_set_t arguments = { Kernel::ForegroundMode, // mode Log::Info, // loglevel false, // fullscreen false, // have_password 0, // collection_id 800, // width 600, // height 3.0f, // transition_time; 5.0f, // switch_time; NULL, // connection_string NULL // transition_string }; // Parse the cli arguments, overriding the defaults if ( !Kernel::parse_arguments(arguments, argc, argv) ){ throw ArgumentException(""); } initTime(); moduleloader_init(pluginpath()); Log::initialize("slideshow.log"); Log::set_level( (Log::Severity)arguments.loglevel ); Kernel* application = NULL; switch ( arguments.mode ){ case Kernel::ForegroundMode: application = new ForegroundApp(arguments); break; case Kernel::DaemonMode: #ifdef BUILD_DAEMON application = new DaemonApp(arguments); break; #else /* BUILD_DAEMON */ throw KernelException("DaemonMode is not supported."); #endif /* BUILD_DAEMON */ case Kernel::ListTransitionMode: Kernel::print_transitions(); throw ExitException(); default: throw KernelException("No valid mode. This should not happen, please report this to the maintainer. Modeid: %d\n", arguments.mode); } application->init(); application->run(); application->cleanup(); delete application; moduleloader_cleanup(); Log::deinitialize(); } catch ( ExitException &e ){ return 0; } catch ( FatalException &e ){ // Only display message if there is one available. // Some exceptions like ArgumentException usually // print the error messages before throwing the // exception. if ( e.what() && strlen(e.what()) > 0 ){ fprintf(stderr, "\nError 0x%02x:\n%s\n", e.code(), e.what()); } return e.code(); } catch ( BaseException &e ){ fprintf(stderr, "Uhh, unhandled exception, recovery not possible. The message was: %s\n", e.what()); return UNHANDLED_ERROR; } return 0; } <|endoftext|>
<commit_before>#include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // XML save data std::string filename("thresholds.xml"); cv::FileStorage fs(filename, cv::FileStorage::READ); // If there is a save file then read it if (fs.isOpened()) { maxH = fs["H_MAX"]; minH = fs["H_MIN"]; maxS = fs["S_MAX"]; minS = fs["S_MIN"]; maxV = fs["V_MAX"]; minV = fs["V_MIN"]; fs.release(); } // Create a window cv::namedWindow("binalized"); cv::createTrackbar("H max", "binalized", &maxH, 255); cv::createTrackbar("H min", "binalized", &minH, 255); cv::createTrackbar("S max", "binalized", &maxS, 255); cv::createTrackbar("S min", "binalized", &minS, 255); cv::createTrackbar("V max", "binalized", &maxV, 255); cv::createTrackbar("V min", "binalized", &minV, 255); cv::resizeWindow("binalized", 0, 0); // Kalman filter cv::KalmanFilter kalman(4, 2, 0); // Sampling time [s] const double dt = 1.0; // Transition matrix (x, y, vx, vy) cv::Mat1f A(4, 4); A << 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0; kalman.transitionMatrix = A; // Measurement matrix (x, y) cv::Mat1f H(2, 4); H << 1, 0, 0, 0, 0, 1, 0, 0; kalman.measurementMatrix = H; // Process noise covairance (x, y, vx, vy) cv::Mat1f Q(4, 4); Q << 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5; kalman.processNoiseCov = Q; // Measurement noise covariance (x, y) cv::Mat1f R(2, 2); R << 1e-1, 0.0, 0.0, 1e-1; kalman.measurementNoiseCov = R; char textBuffer[80]; cv::Scalar green = CV_RGB(0,255,0); float speed = 0.0; bool learnMode = false; // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // HSV image cv::Mat hsv; cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV_FULL); // Binalize cv::Mat binalized; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, binalized); // Show result cv::imshow("binalized", binalized); // De-noising cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel); //cv::imshow("morphologyEx", binalized); // Detect contours std::vector<std::vector<cv::Point>> contours; cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // Find largest contour int contour_index = -1; double max_area = 0.0; for (size_t i = 0; i < contours.size(); i++) { double area = fabs(cv::contourArea(contours[i])); if (area > max_area) { contour_index = i; max_area = area; } } // Object detected if (contour_index >= 0) { // Moments cv::Moments moments = cv::moments(contours[contour_index], true); double marker_y = (int)(moments.m01 / moments.m00); double marker_x = (int)(moments.m10 / moments.m00); // Measurements cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y); // Correction cv::Mat estimated = kalman.correct(measurement); // Show result cv::Rect rect = cv::boundingRect(contours[contour_index]); cv::rectangle(image, rect, cv::Scalar(0, 255, 0)); } // Prediction cv::Mat1f prediction = kalman.predict(); int radius = 1e+3 * kalman.errorCovPre.at<float>(0, 0); // Calculate object heading fraction float heading = -((image.cols/2)-prediction(0, 0))/(image.cols/2); sprintf(textBuffer, "heading = %+3.2f", heading); putText(image, textBuffer, cvPoint(30,30), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); // Sample the object color if(learnMode) { // Crosshairs cv::line(image, cvPoint(image.cols/2, 0), cvPoint(image.cols/2, image.rows/2 - 2), green); //top vertical crosshair cv::line(image, cvPoint(image.cols/2, image.rows/2 + 2), cvPoint(image.cols/2, image.rows), green); //bottom vertical crosshair cv::line(image, cvPoint(0, image.rows/2), cvPoint(image.cols/2 - 2, image.rows/2), green); //left horizontal crosshair cv::line(image, cvPoint(image.cols/2 + 2, image.rows/2), cvPoint(image.cols, image.rows/2), green); //right horizontal crosshair //cv::Vec3b bgrSample = image.at<cv::Vec3b>(cvPoint(image.cols/2, image.rows/2)); //sprintf(textBuffer, "bgrSample = %3d, %3d, %3d", bgrSample[0], bgrSample[1], bgrSample[2]); //putText(image, textBuffer, cvPoint(30,90), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); cv::Vec3b hsvSample = hsv.at<cv::Vec3b>(cvPoint(image.cols/2, image.rows/2)); sprintf(textBuffer, "hsvSample = %3d, %3d, %3d", hsvSample[0], hsvSample[1], hsvSample[2]); putText(image, textBuffer, cvPoint(30,120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); } // Show predicted position cv::circle(image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, green, 2); // Control drone double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 0x260000) vx = 1.0; if (key == 0x280000) vx = -1.0; if (key == 0x250000) vr = 1.0; if (key == 0x270000) vr = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; if (key == 'l') learnMode = !learnMode; if ((key >= '0') && (key <= '9')) { speed = (key-'0')*0.1; //printf("speed = %3.2f\n", speed); } sprintf(textBuffer, "speed = %3.2f", speed); putText(image, textBuffer, cvPoint(30,60), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); if (key == -1) {//No key hit - chase the object vx=speed; vr = -heading*2; } ardrone.move3D(vx, vy, vz, vr); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) { ardrone.takeoff(); } else { ardrone.landing(); } } // Display the image cv::imshow("camera", image); } // Save thresholds fs.open(filename, cv::FileStorage::WRITE); if (fs.isOpened()) { cv::write(fs, "H_MAX", maxH); cv::write(fs, "H_MIN", minH); cv::write(fs, "S_MAX", maxS); cv::write(fs, "S_MIN", minS); cv::write(fs, "V_MAX", maxV); cv::write(fs, "V_MIN", minV); fs.release(); } // See you ardrone.close(); return 0; }<commit_msg>Learn mode basically works (not for border cases though).<commit_after>#include "ardrone/ardrone.h" // -------------------------------------------------------------------------- // main(Number of arguments, Argument values) // Description : This is the entry point of the program. // Return value : SUCCESS:0 ERROR:-1 // -------------------------------------------------------------------------- int main(int argc, char *argv[]) { // AR.Drone class ARDrone ardrone; // Initialize if (!ardrone.open()) { std::cout << "Failed to initialize." << std::endl; return -1; } // Thresholds int minH = 0, maxH = 255; int minS = 0, maxS = 255; int minV = 0, maxV = 255; // XML save data std::string filename("thresholds.xml"); cv::FileStorage fs(filename, cv::FileStorage::READ); // If there is a save file then read it if (fs.isOpened()) { maxH = fs["H_MAX"]; minH = fs["H_MIN"]; maxS = fs["S_MAX"]; minS = fs["S_MIN"]; maxV = fs["V_MAX"]; minV = fs["V_MIN"]; fs.release(); } // Create a window cv::namedWindow("binalized"); cv::createTrackbar("H max", "binalized", &maxH, 255); cv::createTrackbar("H min", "binalized", &minH, 255); cv::createTrackbar("S max", "binalized", &maxS, 255); cv::createTrackbar("S min", "binalized", &minS, 255); cv::createTrackbar("V max", "binalized", &maxV, 255); cv::createTrackbar("V min", "binalized", &minV, 255); cv::resizeWindow("binalized", 0, 0); // Kalman filter cv::KalmanFilter kalman(4, 2, 0); // Sampling time [s] const double dt = 1.0; // Transition matrix (x, y, vx, vy) cv::Mat1f A(4, 4); A << 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, dt, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0; kalman.transitionMatrix = A; // Measurement matrix (x, y) cv::Mat1f H(2, 4); H << 1, 0, 0, 0, 0, 1, 0, 0; kalman.measurementMatrix = H; // Process noise covairance (x, y, vx, vy) cv::Mat1f Q(4, 4); Q << 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5, 0.0, 0.0, 0.0, 0.0, 1e-5; kalman.processNoiseCov = Q; // Measurement noise covariance (x, y) cv::Mat1f R(2, 2); R << 1e-1, 0.0, 0.0, 1e-1; kalman.measurementNoiseCov = R; char textBuffer[80]; cv::Scalar green = CV_RGB(0,255,0); float speed = 0.0; bool learnMode = false; // Main loop while (1) { // Key input int key = cv::waitKey(33); if (key == 0x1b) break; // Get an image cv::Mat image = ardrone.getImage(); // HSV image cv::Mat hsv; cv::cvtColor(image, hsv, cv::COLOR_BGR2HSV_FULL); // Binalize cv::Mat binalized; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, binalized); // Show result cv::imshow("binalized", binalized); // De-noising cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel); //cv::imshow("morphologyEx", binalized); // Detect contours std::vector<std::vector<cv::Point>> contours; cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE); // Find largest contour int contour_index = -1; double max_area = 0.0; for (size_t i = 0; i < contours.size(); i++) { double area = fabs(cv::contourArea(contours[i])); if (area > max_area) { contour_index = i; max_area = area; } } // Object detected if (contour_index >= 0) { // Moments cv::Moments moments = cv::moments(contours[contour_index], true); double marker_y = (int)(moments.m01 / moments.m00); double marker_x = (int)(moments.m10 / moments.m00); // Measurements cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y); // Correction cv::Mat estimated = kalman.correct(measurement); // Show result cv::Rect rect = cv::boundingRect(contours[contour_index]); cv::rectangle(image, rect, cv::Scalar(0, 255, 0)); } // Prediction cv::Mat1f prediction = kalman.predict(); int radius = 1e+3 * kalman.errorCovPre.at<float>(0, 0); // Calculate object heading fraction float heading = -((image.cols/2)-prediction(0, 0))/(image.cols/2); sprintf(textBuffer, "heading = %+3.2f", heading); putText(image, textBuffer, cvPoint(30,30), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); // Sample the object color if(learnMode) { // Crosshairs cv::line(image, cvPoint(image.cols/2, 0), cvPoint(image.cols/2, image.rows/2 - 2), green); //top vertical crosshair cv::line(image, cvPoint(image.cols/2, image.rows/2 + 2), cvPoint(image.cols/2, image.rows), green); //bottom vertical crosshair cv::line(image, cvPoint(0, image.rows/2), cvPoint(image.cols/2 - 2, image.rows/2), green); //left horizontal crosshair cv::line(image, cvPoint(image.cols/2 + 2, image.rows/2), cvPoint(image.cols, image.rows/2), green); //right horizontal crosshair //cv::Vec3b bgrSample = image.at<cv::Vec3b>(cvPoint(image.cols/2, image.rows/2)); //sprintf(textBuffer, "bgrSample = %3d, %3d, %3d", bgrSample[0], bgrSample[1], bgrSample[2]); //putText(image, textBuffer, cvPoint(30,90), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); cv::Vec3b hsvSample = hsv.at<cv::Vec3b>(cvPoint(image.cols/2, image.rows/2)); sprintf(textBuffer, "hsvSample = %3d, %3d, %3d", hsvSample[0], hsvSample[1], hsvSample[2]); putText(image, textBuffer, cvPoint(30,120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); cv::setTrackbarPos("H max", "binalized", hsvSample[0]+20); cv::setTrackbarPos("H min", "binalized", hsvSample[0]-20); cv::setTrackbarPos("S max", "binalized", hsvSample[1]+20); cv::setTrackbarPos("S min", "binalized", hsvSample[1]-20); cv::setTrackbarPos("V max", "binalized", hsvSample[2]+20); cv::setTrackbarPos("V min", "binalized", hsvSample[2]-20); } // Show predicted position cv::circle(image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, green, 2); // Control drone double vx = 0.0, vy = 0.0, vz = 0.0, vr = 0.0; if (key == 0x260000) vx = 1.0; if (key == 0x280000) vx = -1.0; if (key == 0x250000) vr = 1.0; if (key == 0x270000) vr = -1.0; if (key == 'q') vz = 1.0; if (key == 'a') vz = -1.0; if (key == 'l') learnMode = !learnMode; if ((key >= '0') && (key <= '9')) { speed = (key-'0')*0.1; //printf("speed = %3.2f\n", speed); } sprintf(textBuffer, "speed = %3.2f", speed); putText(image, textBuffer, cvPoint(30,60), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA); if (key == -1) {//No key hit - chase the object vx=speed; vr = -heading*2; } ardrone.move3D(vx, vy, vz, vr); // Take off / Landing if (key == ' ') { if (ardrone.onGround()) { ardrone.takeoff(); } else { ardrone.landing(); } } // Display the image cv::imshow("camera", image); } // Save thresholds fs.open(filename, cv::FileStorage::WRITE); if (fs.isOpened()) { cv::write(fs, "H_MAX", maxH); cv::write(fs, "H_MIN", minH); cv::write(fs, "S_MAX", maxS); cv::write(fs, "S_MIN", minS); cv::write(fs, "V_MAX", maxV); cv::write(fs, "V_MIN", minV); fs.release(); } // See you ardrone.close(); return 0; }<|endoftext|>
<commit_before>/* * boostMPI template, boost+boostMPI, include boost include/lib MS-MPI include, and MS-MPI library, which is msmpi.lib * Author: Shirong Bai * Email: bunnysirah@hotmail.com or shirong.bai@colorado.edu * Date: 10/08/2015 */ #include <cstdlib> #include "../include/drivers/drivers.h" #include "../include/tools/my_debug/my_debug.h" int main(int argc, char **argv) { /*************************************************************************************************/ /* * 0. Parse parameters * Default, has to run */ /*************************************************************************************************/ po::variables_map vm; // current working directory std::string main_cwd; // boost property tree boost::property_tree::ptree pt; driver::parse_parameters(argc, argv, vm, main_cwd, pt); #if defined(__NO_USE_MPI_) if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_over_time")) driver::evaluate_path_AT_over_time(main_cwd, pt); #endif // __NO_USE_MPI_ #if defined(__USE_MPI_) boost::mpi::environment env(argc, argv); boost::mpi::communicator world; MyClock_us timer; if (world.rank() == 0) timer.begin(); /*************************************************************************************************/ /* * 1. Solve for concentration of Lokta-Voltera system or Dimerization or Michaelis Menten, using LSODE */ /*************************************************************************************************/ if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_LSODE")) driver::solve_ODEs_for_concentration_using_LSODE(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_SSA")) driver::solve_ODEs_for_concentration_using_SSA(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("write_concentration_at_time_to_file")) driver::write_concentration_at_time_to_file(world, main_cwd, pt); /*************************************************************************************************/ /* * 2. Generate pathway first, it might take some time, depends on what kinds of pathway you want */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); //2.1. else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); /*************************************************************************************************/ /* * 3. Evaluate pathway integral using Importance based Monte Carlo simulation */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_over_time")) driver::evaluate_path_AT_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_with_SP_over_time")) driver::evaluate_path_AT_with_SP_over_time(world, main_cwd, pt); /*************************************************************************************************/ /* * 4. For speciation, print out concentration at for different sets of rate constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("speciation_evaluate_concentrations_for_different_sets_rate_coefficients")) driver::speciation_evaluate_concentrations_for_different_sets_rate_coefficients(world, main_cwd, pt); /*************************************************************************************************/ /* * 5. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 2 * Monte Carlo simulation * not parallel code */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_single_core")) driver::ODE_solver_MC_trajectory_single_core(world, main_cwd, pt); /*************************************************************************************************/ /* * 6. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 4 * constant temperature, surface reactions, independent of pressure * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_s_ct_np_parallel")) driver::ODE_solver_MC_trajectory_s_ct_np_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 7. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 5 * varing temperature, varing pressure, constant volume, H2-O2 system, not working because the initiation * is actually a rare event, stochastic trajectory converge too slow * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_cv_parallel")) driver::ODE_solver_MC_trajectory_cv_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 8. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v2")) driver::ODE_solver_path_integral_parallel_s_ct_np_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v3")) driver::ODE_solver_path_integral_parallel_s_ct_np_v3(world, main_cwd, pt); /*************************************************************************************************/ /* * 9. Pathway based equation solver, solve differential equations derived from chemical mechanisms * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability * hold concentration of some species to be constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_cc1_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_cc1_v1(world, main_cwd, pt); /*************************************************************************************************/ /* * 10. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * constant volume, varying temperature, varying pressure * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v9")) driver::ODE_solver_path_integral_parallel_cv_v9(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v10")) driver::ODE_solver_path_integral_parallel_cv_v10(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v11")) driver::ODE_solver_path_integral_parallel_cv_v11(world, main_cwd, pt); /* * 11. constant volume, constant temperature */ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v1")) driver::ODE_solver_path_integral_parallel_cv_ct_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v2")) driver::ODE_solver_path_integral_parallel_cv_ct_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v3")) driver::ODE_solver_path_integral_parallel_cv_ct_v3(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v4")) driver::ODE_solver_path_integral_parallel_cv_ct_v4(world, main_cwd, pt); /*************************************************************************************************/ /* * 13. M-matrix test */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("M_matrix_R_matrix")) driver::M_matrix_R_matrix(world, main_cwd); /*************************************************************************************************/ /* * MISC */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("MISC")) driver::MISC(world, main_cwd); #endif // __USE_MPI_ return EXIT_SUCCESS; } <commit_msg>minor<commit_after>/* * boostMPI template, boost+boostMPI, include boost include/lib MS-MPI include, and MS-MPI library, which is msmpi.lib * Author: Shirong Bai * Email: bunnysirah@hotmail.com or shirong.bai@colorado.edu * Date: 10/08/2015 */ #include <cstdlib> #include "../include/drivers/drivers.h" #include "../include/tools/my_debug/my_debug.h" int main(int argc, char **argv) { /*************************************************************************************************/ /* * 0. Parse parameters * Default, has to run */ /*************************************************************************************************/ po::variables_map vm; // current working directory std::string main_cwd; // boost property tree boost::property_tree::ptree pt; driver::parse_parameters(argc, argv, vm, main_cwd, pt); #if defined(__NO_USE_MPI_) if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_over_time")) driver::evaluate_path_AT_over_time(main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_with_SP_over_time")) driver::evaluate_path_AT_with_SP_over_time(main_cwd, pt); #endif // __NO_USE_MPI_ #if defined(__USE_MPI_) boost::mpi::environment env(argc, argv); boost::mpi::communicator world; MyClock_us timer; if (world.rank() == 0) timer.begin(); /*************************************************************************************************/ /* * 1. Solve for concentration of Lokta-Voltera system or Dimerization or Michaelis Menten, using LSODE */ /*************************************************************************************************/ if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_LSODE")) driver::solve_ODEs_for_concentration_using_LSODE(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("solve_ODEs_for_concentration_using_SSA")) driver::solve_ODEs_for_concentration_using_SSA(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("write_concentration_at_time_to_file")) driver::write_concentration_at_time_to_file(world, main_cwd, pt); /*************************************************************************************************/ /* * 2. Generate pathway first, it might take some time, depends on what kinds of pathway you want */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("generate_pathway_running_Monte_carlo_trajectory")) driver::generate_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); //2.1. else if (pt.get<std::string>("job.job_type") == std::string("generate_species_pathway_running_Monte_carlo_trajectory")) driver::generate_species_pathway_running_Monte_carlo_trajectory(world, main_cwd, pt); /*************************************************************************************************/ /* * 3. Evaluate pathway integral using Importance based Monte Carlo simulation */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_integral_over_time")) driver::evaluate_path_integral_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_species_path_integral_over_time")) driver::evaluate_species_path_integral_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_over_time")) driver::evaluate_path_AT_over_time(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("evaluate_path_AT_with_SP_over_time")) driver::evaluate_path_AT_with_SP_over_time(world, main_cwd, pt); /*************************************************************************************************/ /* * 4. For speciation, print out concentration at for different sets of rate constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("speciation_evaluate_concentrations_for_different_sets_rate_coefficients")) driver::speciation_evaluate_concentrations_for_different_sets_rate_coefficients(world, main_cwd, pt); /*************************************************************************************************/ /* * 5. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 2 * Monte Carlo simulation * not parallel code */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_single_core")) driver::ODE_solver_MC_trajectory_single_core(world, main_cwd, pt); /*************************************************************************************************/ /* * 6. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 4 * constant temperature, surface reactions, independent of pressure * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_s_ct_np_parallel")) driver::ODE_solver_MC_trajectory_s_ct_np_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 7. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 5 * varing temperature, varing pressure, constant volume, H2-O2 system, not working because the initiation * is actually a rare event, stochastic trajectory converge too slow * Monte Carlo Simulation * Parallel version */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_MC_trajectory_cv_parallel")) driver::ODE_solver_MC_trajectory_cv_parallel(world, main_cwd, pt); /*************************************************************************************************/ /* * 8. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v2")) driver::ODE_solver_path_integral_parallel_s_ct_np_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_v3")) driver::ODE_solver_path_integral_parallel_s_ct_np_v3(world, main_cwd, pt); /*************************************************************************************************/ /* * 9. Pathway based equation solver, solve differential equations derived from chemical mechanisms * surface reaction, independent of pressure, constant temperature, or independent or temperature * directly evaluate the pathway probability * hold concentration of some species to be constant */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_s_ct_np_cc1_v1")) driver::ODE_solver_path_integral_parallel_s_ct_np_cc1_v1(world, main_cwd, pt); /*************************************************************************************************/ /* * 10. Pathway based equation solver, solve differential equations derived from chemical mechanisms * version 3 * constant volume, varying temperature, varying pressure * directly evaluate the pathway probability */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v9")) driver::ODE_solver_path_integral_parallel_cv_v9(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v10")) driver::ODE_solver_path_integral_parallel_cv_v10(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_v11")) driver::ODE_solver_path_integral_parallel_cv_v11(world, main_cwd, pt); /* * 11. constant volume, constant temperature */ else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v1")) driver::ODE_solver_path_integral_parallel_cv_ct_v1(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v2")) driver::ODE_solver_path_integral_parallel_cv_ct_v2(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v3")) driver::ODE_solver_path_integral_parallel_cv_ct_v3(world, main_cwd, pt); else if (pt.get<std::string>("job.job_type") == std::string("ODE_solver_path_integral_parallel_cv_ct_v4")) driver::ODE_solver_path_integral_parallel_cv_ct_v4(world, main_cwd, pt); /*************************************************************************************************/ /* * 13. M-matrix test */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("M_matrix_R_matrix")) driver::M_matrix_R_matrix(world, main_cwd); /*************************************************************************************************/ /* * MISC */ /*************************************************************************************************/ else if (pt.get<std::string>("job.job_type") == std::string("MISC")) driver::MISC(world, main_cwd); #endif // __USE_MPI_ return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * LynxBot: a Twitch.tv IRC bot for Old School Runescape * Copyright (C) 2016 Alexei Frolov */ #include <cpr/cpr.h> #include <iostream> #include <string> #include <string.h> #include <utils.h> #include "config.h" #include "lynxbot.h" #include "option.h" #include "TwitchBot.h" #ifdef __linux__ # include <sys/types.h> # include <sys/wait.h> # include <unistd.h> #endif /* LynxBot authorization URL */ static const char *AUTH_URL = "https://api.twitch.tv/kraken/oauth2/" "authorize?response_type=token&client_id=kkjhmekkzbepq0pgn34g671y5nexap8&" "redirect_uri=https://frolv.github.io/lynxbot/twitchauthconfirm.html&" "scope=channel_editor+channel_subscriptions+channel_check_subscription"; /* github api for latest release */ static const char *RELEASE_API = "https://api.github.com/repos/frolv/lynxbot/releases/latest"; struct botset { std::string name; /* twitch username of bot */ std::string channel; /* channel to join */ std::string pass; /* oauth token for account */ std::string access_token; /* access token for user's twitch */ }; void checkupdates(); void launchBot(struct botset *b, ConfigReader *cfgr); void twitchAuth(struct botset *b); bool authtest(const std::string &token, std::string &user); #ifdef __linux__ static int open_linux(const char *url); #endif #ifdef _WIN32 static int open_win(const char *url); #endif /* LynxBot: a Twitch.tv IRC bot for Old School Runescape */ int main(int argc, char **argv) { struct botset b; std::string path; int update; int c; static struct l_option long_opts[] = { { "help", NO_ARG, 'h' }, { "no-check-update", NO_ARG, 'n' }, { "version", NO_ARG, 'v' }, { 0, 0, 0 } }; opt_init(); update = 1; while ((c = l_getopt_long(argc, argv, "hv", long_opts)) != EOF) { switch (c) { case 'h': printf("usage: lynxbot [CHANNEL]\n%s - A Twitch.tv IRC " "bot for Old School Runescape\n" "Documentation can be found at %s\n", BOT_NAME, BOT_WEBSITE); return 0; case 'n': update = 0; break; case 'v': printf("%s %s\nCopyright (C) 2016 Alexei Frolov\n" "This program is distributed as free " "software\nunder the terms of the MIT " "License.\n", BOT_NAME, BOT_VERSION); return 0; case '?': fprintf(stderr, "%s\n", l_opterr()); fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; default: fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } } if (argc - l_optind > 1) { fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } /* check if a new version is available */ if (update) checkupdates(); /* read the config file */ path = utils::configdir() + utils::config("config"); ConfigReader cfgr(path); if (!cfgr.read()) { WAIT_INPUT(); return 1; } b.name = cfgr.get("name"); b.channel = cfgr.get("channel"); b.pass = cfgr.get("password"); b.access_token = cfgr.get("twitchtok"); /* authenticate with twitch */ if (b.access_token == "UNSET") { twitchAuth(&b); cfgr.set("twitchtok", b.access_token); cfgr.write(); } /* overwrite channel with arg */ if (l_optind != argc) b.channel = argv[l_optind]; if (b.channel[0] != '#') b.channel = '#' + b.channel; launchBot(&b, &cfgr); return 0; } /* launchBot: start a TwitchBot instance */ void launchBot(struct botset *b, ConfigReader *cfgr) { TwitchBot bot(b->name.c_str(), b->channel.c_str(), b->pass.c_str(), b->access_token.c_str(), cfgr); if (bot.connect()) bot.server_loop(); } /* twitchAuth: interactively authorize LynxBot with a Twitch account */ void twitchAuth(struct botset *b) { int c, status; std::string token, user; printf("In order for the $status command to work, %s must be authorized" " to update your Twitch channel settings.\nWould you " "like to authorize %s now? (y/n) ", BOT_NAME, BOT_NAME); while ((c = getchar()) != EOF && c != 'n' && c != 'y') ; if (c == EOF) { putchar('\n'); exit(0); } else if (c == 'n') { b->access_token = "NULL"; return; } #ifdef __linux__ status = open_linux(AUTH_URL); #endif #ifdef _WIN32 status = open_win(AUTH_URL); #endif if (status != 0) { fprintf(stderr, "Could not open web browser\nPlease navigate " "to the following URL manually:\n%s\n,", AUTH_URL); WAIT_INPUT(); } printf("The authorization URL has been opened in your browser. Sign in " "with your Twitch account and click \"Authorize\" to " "proceed.\n"); printf("After you have clicked \"Authorize\" you will be redirected to " "a webpage with an access token.\nEnter the access " "token here:\n"); while (token.empty()) std::getline(std::cin, token); if (authtest(token, user)) { b->access_token = token; printf("Welcome, %s!\n %s has successfully been authorized " "with your Twitch account.", user.c_str(), BOT_NAME); } else { printf("Invalid token. Authorization failed.\n"); } WAIT_INPUT(); } /* authtest: test access token validity */ bool authtest(const std::string &token, std::string &user) { Json::Value json; cpr::Response resp = cpr::Get(cpr::Url("https://api.twitch.tv/kraken"), cpr::Header{{ "Authorization", "OAuth " + token }}); Json::Reader reader; if (!reader.parse(resp.text, json)) return false; if (json["token"]["valid"].asBool()) { user = json["token"]["user_name"].asString(); return true; } return false; } /* check for new lynxbot version and prompt user to install */ void checkupdates() { static const char *accept = "application/vnd.github.v3+json"; cpr::Response resp; Json::Value js; Json::Reader reader; int c; if (strchr(BOT_VERSION, '-')) return; resp = cpr::Get(cpr::Url(RELEASE_API), cpr::Header{{ "Accept", accept }}); if (!reader.parse(resp.text, js)) return; if (strcmp(js["tag_name"].asCString(), BOT_VERSION) != 0) { printf("A new version of %s (%s) is available.\nWould you like " "to open the download page? (y/n)\n", BOT_NAME, js["tag_name"].asCString()); while ((c = getchar()) != EOF && c != 'y' && c != 'n') ; if (c == EOF) exit(0); if (c == 'n') return; #ifdef __linux__ open_linux(js["html_url"].asCString()); #endif #ifdef _WIN32 open_win(js["html_url"].asCString()); #endif exit(0); } } #ifdef __linux__ /* open_linux: launch browser on linux systems */ static int open_linux(const char *url) { switch (fork()) { case -1: perror("fork"); exit(1); case 0: execl("/usr/bin/xdg-open", "xdg-open", url, (char *)NULL); perror("/usr/bin/xdg-open"); exit(1); default: int status; wait(&status); return status >> 8; } } #endif #ifdef _WIN32 /* open_win: launch browser on windows systems */ static int open_win(const char *url) { HINSTANCE ret; ret = ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); return *(int *)&ret <= 32; } #endif <commit_msg>$status command -> certain commands<commit_after>/* * LynxBot: a Twitch.tv IRC bot for Old School Runescape * Copyright (C) 2016 Alexei Frolov */ #include <cpr/cpr.h> #include <iostream> #include <string> #include <string.h> #include <utils.h> #include "config.h" #include "lynxbot.h" #include "option.h" #include "TwitchBot.h" #ifdef __linux__ # include <sys/types.h> # include <sys/wait.h> # include <unistd.h> #endif /* LynxBot authorization URL */ static const char *AUTH_URL = "https://api.twitch.tv/kraken/oauth2/" "authorize?response_type=token&client_id=kkjhmekkzbepq0pgn34g671y5nexap8&" "redirect_uri=https://frolv.github.io/lynxbot/twitchauthconfirm.html&" "scope=channel_editor+channel_subscriptions+channel_check_subscription"; /* github api for latest release */ static const char *RELEASE_API = "https://api.github.com/repos/frolv/lynxbot/releases/latest"; struct botset { std::string name; /* twitch username of bot */ std::string channel; /* channel to join */ std::string pass; /* oauth token for account */ std::string access_token; /* access token for user's twitch */ }; void checkupdates(); void launchBot(struct botset *b, ConfigReader *cfgr); void twitchAuth(struct botset *b); bool authtest(const std::string &token, std::string &user); #ifdef __linux__ static int open_linux(const char *url); #endif #ifdef _WIN32 static int open_win(const char *url); #endif /* LynxBot: a Twitch.tv IRC bot for Old School Runescape */ int main(int argc, char **argv) { struct botset b; std::string path; int update; int c; static struct l_option long_opts[] = { { "help", NO_ARG, 'h' }, { "no-check-update", NO_ARG, 'n' }, { "version", NO_ARG, 'v' }, { 0, 0, 0 } }; opt_init(); update = 1; while ((c = l_getopt_long(argc, argv, "hv", long_opts)) != EOF) { switch (c) { case 'h': printf("usage: lynxbot [CHANNEL]\n%s - A Twitch.tv IRC " "bot for Old School Runescape\n" "Documentation can be found at %s\n", BOT_NAME, BOT_WEBSITE); return 0; case 'n': update = 0; break; case 'v': printf("%s %s\nCopyright (C) 2016 Alexei Frolov\n" "This program is distributed as free " "software\nunder the terms of the MIT " "License.\n", BOT_NAME, BOT_VERSION); return 0; case '?': fprintf(stderr, "%s\n", l_opterr()); fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; default: fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } } if (argc - l_optind > 1) { fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } /* check if a new version is available */ if (update) checkupdates(); /* read the config file */ path = utils::configdir() + utils::config("config"); ConfigReader cfgr(path); if (!cfgr.read()) { WAIT_INPUT(); return 1; } b.name = cfgr.get("name"); b.channel = cfgr.get("channel"); b.pass = cfgr.get("password"); b.access_token = cfgr.get("twitchtok"); /* authenticate with twitch */ if (b.access_token == "UNSET") { twitchAuth(&b); cfgr.set("twitchtok", b.access_token); cfgr.write(); } /* overwrite channel with arg */ if (l_optind != argc) b.channel = argv[l_optind]; if (b.channel[0] != '#') b.channel = '#' + b.channel; launchBot(&b, &cfgr); return 0; } /* launchBot: start a TwitchBot instance */ void launchBot(struct botset *b, ConfigReader *cfgr) { TwitchBot bot(b->name.c_str(), b->channel.c_str(), b->pass.c_str(), b->access_token.c_str(), cfgr); if (bot.connect()) bot.server_loop(); } /* twitchAuth: interactively authorize LynxBot with a Twitch account */ void twitchAuth(struct botset *b) { int c, status; std::string token, user; printf("In order for the certain bot commands to work, %s must be " "authorized to update your Twitch channel settings.\n" "Would you like to authorize %s now? (y/n) ", BOT_NAME, BOT_NAME); while ((c = getchar()) != EOF && c != 'n' && c != 'y') ; if (c == EOF) { putchar('\n'); exit(0); } else if (c == 'n') { b->access_token = "NULL"; return; } #ifdef __linux__ status = open_linux(AUTH_URL); #endif #ifdef _WIN32 status = open_win(AUTH_URL); #endif if (status != 0) { fprintf(stderr, "Could not open web browser\nPlease navigate " "to the following URL manually:\n%s\n,", AUTH_URL); WAIT_INPUT(); } printf("The authorization URL has been opened in your browser. Sign in " "with your Twitch account and click \"Authorize\" to " "proceed.\n"); printf("After you have clicked \"Authorize\" you will be redirected to " "a webpage with an access token.\nEnter the access " "token here:\n"); while (token.empty()) std::getline(std::cin, token); if (authtest(token, user)) { b->access_token = token; printf("Welcome, %s!\n %s has successfully been authorized " "with your Twitch account.", user.c_str(), BOT_NAME); } else { printf("Invalid token. Authorization failed.\n"); } WAIT_INPUT(); } /* authtest: test access token validity */ bool authtest(const std::string &token, std::string &user) { Json::Value json; cpr::Response resp = cpr::Get(cpr::Url("https://api.twitch.tv/kraken"), cpr::Header{{ "Authorization", "OAuth " + token }}); Json::Reader reader; if (!reader.parse(resp.text, json)) return false; if (json["token"]["valid"].asBool()) { user = json["token"]["user_name"].asString(); return true; } return false; } /* check for new lynxbot version and prompt user to install */ void checkupdates() { static const char *accept = "application/vnd.github.v3+json"; cpr::Response resp; Json::Value js; Json::Reader reader; int c; if (strchr(BOT_VERSION, '-')) return; resp = cpr::Get(cpr::Url(RELEASE_API), cpr::Header{{ "Accept", accept }}); if (!reader.parse(resp.text, js)) return; if (strcmp(js["tag_name"].asCString(), BOT_VERSION) != 0) { printf("A new version of %s (%s) is available.\nWould you like " "to open the download page? (y/n)\n", BOT_NAME, js["tag_name"].asCString()); while ((c = getchar()) != EOF && c != 'y' && c != 'n') ; if (c == EOF) exit(0); if (c == 'n') return; #ifdef __linux__ open_linux(js["html_url"].asCString()); #endif #ifdef _WIN32 open_win(js["html_url"].asCString()); #endif exit(0); } } #ifdef __linux__ /* open_linux: launch browser on linux systems */ static int open_linux(const char *url) { switch (fork()) { case -1: perror("fork"); exit(1); case 0: execl("/usr/bin/xdg-open", "xdg-open", url, (char *)NULL); perror("/usr/bin/xdg-open"); exit(1); default: int status; wait(&status); return status >> 8; } } #endif #ifdef _WIN32 /* open_win: launch browser on windows systems */ static int open_win(const char *url) { HINSTANCE ret; ret = ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); return *(int *)&ret <= 32; } #endif <|endoftext|>
<commit_before>#include <iostream> #include <irrlicht.h> #include "driverChoice.h" #include "eventReceiver.h" using namespace irr; enum { ID_IsNotPickable = 0, IDFlag_IsPickable = 1 << 0, IDFlag_IsHighlightable = 1 << 1 }; int main() { // Choose driver video::E_DRIVER_TYPE driverType = driverChoiceConsole(); if(driverType == video::EDT_COUNT) return 1; EventReceiver eventReceiver; IrrlichtDevice *device = createDevice(driverType, core::dimension2d<u32>(1280, 720), 32, true, false, false, &eventReceiver); if(device == 0) return 1; video::IVideoDriver *driver = device->getVideoDriver(); scene::ISceneManager *smgr = device->getSceneManager(); gui::IGUIEnvironment *guienv = device->getGUIEnvironment(); guienv->addStaticText(L"Use WASD to move\nUse SPACE to jump\nUse ESC to exit", core::rect<s32>(30, 30, 120, 65), false, false, 0, -1, true); device->getFileSystem()->addFileArchive("../res/map-20kdm2.pk3"); scene::IAnimatedMesh *mapmesh = smgr->getMesh("20kdm2.bsp"); scene::IMeshSceneNode *mapnode = 0; if(mapmesh) { mapnode = smgr->addOctreeSceneNode(mapmesh->getMesh(0), 0, IDFlag_IsPickable); } scene::ITriangleSelector *tselector = 0; if(mapnode) { mapnode->setPosition(core::vector3df(-1350, -130, -1400)); tselector = smgr->createOctreeTriangleSelector(mapnode->getMesh(), mapnode, 128); mapnode->setTriangleSelector(tselector); } // Setup new keys SKeyMap keyMap[6]; keyMap[0].Action = EKA_MOVE_FORWARD; keyMap[0].KeyCode = KEY_KEY_W; keyMap[1].Action = EKA_MOVE_BACKWARD; keyMap[1].KeyCode = KEY_KEY_S; keyMap[2].Action = EKA_STRAFE_LEFT; keyMap[2].KeyCode = KEY_KEY_A; keyMap[3].Action = EKA_STRAFE_RIGHT; keyMap[3].KeyCode = KEY_KEY_D; keyMap[4].Action = EKA_JUMP_UP; keyMap[4].KeyCode = KEY_SPACE; scene::ICameraSceneNode *cam = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, ID_IsNotPickable, keyMap, sizeof(keyMap) / sizeof(*keyMap), true, 3.0f); cam->setPosition(core::vector3df(50, 50, -60)); cam->setTarget(core::vector3df(-70, 30, -60)); if(tselector) { scene::ISceneNodeAnimator *sanim = smgr->createCollisionResponseAnimator(tselector, cam, core::vector3df(30, 50, 30), core::vector3df(0, -10, 0), core::vector3df(0, 30, 0)); tselector->drop(); cam->addAnimator(sanim); sanim->drop(); } device->getCursorControl()->setVisible(false); int lastFPS = -1; while(device->run()) { driver->beginScene(true, true, video::SColor(0, 255, 101, 255)); smgr->drawAll(); guienv->drawAll(); driver->endScene(); if(eventReceiver.IsKeyDown(KEY_ESCAPE)) { device->closeDevice(); } int fps = driver->getFPS(); if(lastFPS != fps) { std::cout << "FPS: " << fps << std::endl; lastFPS = fps; } } device->drop(); return 0; } <commit_msg>Removed enum (no need).<commit_after>#include <iostream> #include <irrlicht.h> #include "driverChoice.h" #include "eventReceiver.h" using namespace irr; int main() { // Choose driver video::E_DRIVER_TYPE driverType = driverChoiceConsole(); if(driverType == video::EDT_COUNT) return 1; EventReceiver eventReceiver; IrrlichtDevice *device = createDevice(driverType, core::dimension2d<u32>(1280, 720), 32, true, false, false, &eventReceiver); if(device == 0) return 1; video::IVideoDriver *driver = device->getVideoDriver(); scene::ISceneManager *smgr = device->getSceneManager(); gui::IGUIEnvironment *guienv = device->getGUIEnvironment(); guienv->addStaticText(L"Use WASD to move\nUse SPACE to jump\nUse ESC to exit", core::rect<s32>(30, 30, 120, 65), false, false, 0, -1, true); device->getFileSystem()->addFileArchive("../res/map-20kdm2.pk3"); scene::IAnimatedMesh *mapmesh = smgr->getMesh("20kdm2.bsp"); scene::IMeshSceneNode *mapnode = 0; if(mapmesh) { mapnode = smgr->addOctreeSceneNode(mapmesh->getMesh(0)); } scene::ITriangleSelector *tselector = 0; if(mapnode) { mapnode->setPosition(core::vector3df(-1350, -130, -1400)); tselector = smgr->createOctreeTriangleSelector(mapnode->getMesh(), mapnode, 128); mapnode->setTriangleSelector(tselector); } // Setup new keys SKeyMap keyMap[6]; keyMap[0].Action = EKA_MOVE_FORWARD; keyMap[0].KeyCode = KEY_KEY_W; keyMap[1].Action = EKA_MOVE_BACKWARD; keyMap[1].KeyCode = KEY_KEY_S; keyMap[2].Action = EKA_STRAFE_LEFT; keyMap[2].KeyCode = KEY_KEY_A; keyMap[3].Action = EKA_STRAFE_RIGHT; keyMap[3].KeyCode = KEY_KEY_D; keyMap[4].Action = EKA_JUMP_UP; keyMap[4].KeyCode = KEY_SPACE; scene::ICameraSceneNode *cam = smgr->addCameraSceneNodeFPS(0, 100.0f, .3f, -1, keyMap, sizeof(keyMap) / sizeof(*keyMap), true, 3.0f); cam->setPosition(core::vector3df(50, 50, -60)); cam->setTarget(core::vector3df(-70, 30, -60)); if(tselector) { scene::ISceneNodeAnimator *sanim = smgr->createCollisionResponseAnimator(tselector, cam, core::vector3df(30, 50, 30), core::vector3df(0, -10, 0), core::vector3df(0, 30, 0)); tselector->drop(); cam->addAnimator(sanim); sanim->drop(); } device->getCursorControl()->setVisible(false); int lastFPS = -1; while(device->run()) { driver->beginScene(true, true, video::SColor(0, 255, 101, 255)); smgr->drawAll(); guienv->drawAll(); driver->endScene(); if(eventReceiver.IsKeyDown(KEY_ESCAPE)) { device->closeDevice(); } int fps = driver->getFPS(); if(lastFPS != fps) { std::cout << "FPS: " << fps << std::endl; lastFPS = fps; } } device->drop(); return 0; } <|endoftext|>
<commit_before>#include "serialutil.h" #include "usbutil.h" #include "listener.h" #include "signals.h" #include "log.h" #define VERSION_CONTROL_COMMAND 0x80 #define RESET_CONTROL_COMMAND 0x81 // USB #define DATA_ENDPOINT 1 extern void reset(); void setup(); void loop(); const char* VERSION = "2.0-pre"; #ifdef __CHIPKIT__ SerialDevice serialDevice = {&Serial1}; #else SerialDevice serialDevice; #endif // __CHIPKIT__ UsbDevice USB_DEVICE = { #ifdef CHIPKIT USBDevice(usbCallback), #endif // CHIPKIT DATA_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES}; Listener listener = {&USB_DEVICE, &serialDevice}; int main(void) { #ifdef CHIPKIT init(); #endif setup(); for (;;) loop(); return 0; } bool handleControlRequest(uint8_t request) { switch(request) { case VERSION_CONTROL_COMMAND: char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4]; sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet()); debug("Version: %s", combinedVersion); sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion)); return true; case RESET_CONTROL_COMMAND: debug("Resetting..."); reset(); return true; default: return false; } } <commit_msg>Add newlines to control commands.<commit_after>#include "serialutil.h" #include "usbutil.h" #include "listener.h" #include "signals.h" #include "log.h" #define VERSION_CONTROL_COMMAND 0x80 #define RESET_CONTROL_COMMAND 0x81 // USB #define DATA_ENDPOINT 1 extern void reset(); void setup(); void loop(); const char* VERSION = "2.0-pre"; #ifdef __CHIPKIT__ SerialDevice serialDevice = {&Serial1}; #else SerialDevice serialDevice; #endif // __CHIPKIT__ UsbDevice USB_DEVICE = { #ifdef CHIPKIT USBDevice(usbCallback), #endif // CHIPKIT DATA_ENDPOINT, MAX_USB_PACKET_SIZE_BYTES}; Listener listener = {&USB_DEVICE, &serialDevice}; int main(void) { #ifdef CHIPKIT init(); #endif setup(); for (;;) loop(); return 0; } bool handleControlRequest(uint8_t request) { switch(request) { case VERSION_CONTROL_COMMAND: char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4]; sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet()); debug("Version: %s\r\n", combinedVersion); sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion)); return true; case RESET_CONTROL_COMMAND: debug("Resetting...\r\n"); reset(); return true; default: return false; } } <|endoftext|>
<commit_before>/** * Name: Rebecca Hom * This is the main file that will be used to run the rshell. * Tests the system calls * * */ #include "rshell.h" #include <iostream> #include <string> using namespace std; int main(int arc, char* argv[]) { Rshell rshell = Rshell(); // Initial variables for taking in commands string input = ""; vector<string> inputs; // Gets the command(s) from user input until exit while(input != "exit") { cout << "$ "; getline(cin, input); rshell.removeSpace(input); // Removes whitespace from input string rshell.convertCommands(input, inputs); // Gets all commands // Shows all of the inputs for(unsigned i = 0; i < inputs.size(); ++i) { cout << "Command " << i + 1 << ": " << inputs.at(i) << endl; } inputs.clear(); // Clears the commands in the vector } return 0; } <commit_msg>modified main.cpp to accomdate for new parsing format<commit_after>/** * Name: Rebecca Hom * This is the main file that will be used to run the rshell. * Tests the system calls * * */ #include "rshell.h" #include <iostream> #include <string> using namespace std; int main() { Rshell rshell = Rshell(); // Initial variables for taking in commands string input = ""; // vector<string> inputs; char line[100][256]; char *argv[64]; // Gets the command(s) from user input until exit while(input != "exit") { cout << "$ "; getline(cin, input); rshell.parseCommand(input, line, argv); } return 0; } <|endoftext|>
<commit_before>#include "Image.h" #include "Ray.h" #include "Sphere.h" #include "HitableList.h" #include "Camera.h" #include "Lambertian.h" #include <chrono> #include <iostream> const auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); auto realRand = std::bind(std::uniform_real_distribution<double>(0, 1), std::mt19937(seed)); static Eigen::Vector3f randomInUnitSphere() { Eigen::Vector3f p; do { p = 2.0 * Eigen::Vector3f(realRand(), realRand(), realRand()) - Eigen::Vector3f(1, 1, 1); } while (p.dot(p) > 1.0); return p; } Eigen::Vector3f color(const sol::Ray &ray, sol::Hitable &hitable, unsigned int curDepth, unsigned int maxDepth) { if (curDepth == maxDepth) { return Eigen::Vector3f(0, 0, 0); } sol::HitRecord hitRecord; if (hitable.hit(ray, 0.0, std::numeric_limits<float>::max(), hitRecord)) { const auto target = hitRecord.point + hitRecord.normal + randomInUnitSphere(); return 0.5 * color(sol::Ray(hitRecord.point, target - hitRecord.point), hitable, curDepth + 1, maxDepth); } else { const auto unitDirection = ray.getDirection().normalized(); const auto t = 0.5 * (unitDirection.y() + 1.0); return (1.0 - t) * Eigen::Vector3f(1.0, 1.0, 1.0) + t * Eigen::Vector3f(0.5, 0.7, 1.0); } } Eigen::Vector3f color(const sol::Ray &ray, sol::Hitable &hitable) { return color(ray, hitable, 0, 10); } int main(int, char**) { const int nx = 400; const int ny = 200; const int ns = 100; //const auto aspectRatio = float(nx) / float(ny); sol::Image image(nx, ny); sol::Camera camera; sol::HitableList hitableList; hitableList.add(std::make_shared<sol::Sphere>(Eigen::Vector3f(0, 0, -1), 0.5, std::make_shared<sol::Lambertian>(Eigen::Vector3f(0.8, 0.3, 0.3)))); hitableList.add(std::make_shared<sol::Sphere>(Eigen::Vector3f(0, -100.5, -1), 100, std::make_shared<sol::Lambertian>(Eigen::Vector3f(0.8, 0.8, 0.0)))); for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { Eigen::Vector3f col(0, 0, 0); for (int s = 0; s < ns; s++) { const auto u = float(i + realRand()) / float(nx); const auto v = float(j + realRand()) / float(ny); const auto ray = camera.getRay(u, v); col += color(ray, hitableList); } col /= ns; col = Eigen::Vector3f(sqrt(col[0]), sqrt(col[1]), sqrt(col[2])); const auto r = int(255.99 * col[0]); const auto g = int(255.99 * col[1]); const auto b = int(255.99 * col[2]); image.setPixel(i, (ny - 1) - j, r, g, b); } } image.write("test.png"); return 0; } <commit_msg>use material in shading method<commit_after>#include "Image.h" #include "Ray.h" #include "Sphere.h" #include "HitableList.h" #include "Camera.h" #include "Lambertian.h" #include <chrono> #include <iostream> const auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); auto realRand = std::bind(std::uniform_real_distribution<double>(0, 1), std::mt19937(seed)); Eigen::Vector3f operator *(const Eigen::Vector3f &a, const Eigen::Vector3f &b) { return Eigen::Vector3f(a.x() * b.x(), a.y() * b.y(), a.z() * b.z()); } Eigen::Vector3f color(const sol::Ray &ray, sol::Hitable &hitable, unsigned int curDepth, unsigned int maxDepth) { sol::HitRecord hitRecord; if (hitable.hit(ray, 0.001, std::numeric_limits<float>::max(), hitRecord)) { sol::Ray scattered; Eigen::Vector3f attenuation; if (curDepth < maxDepth && hitRecord.material->scatter(ray, hitRecord, attenuation, scattered)) { return attenuation * color(scattered, hitable, curDepth + 1, maxDepth); } else { return Eigen::Vector3f(0, 0, 0); } } else { const auto unitDirection = ray.getDirection().normalized(); const auto t = 0.5 * (unitDirection.y() + 1.0); return (1.0 - t) * Eigen::Vector3f(1.0, 1.0, 1.0) + t * Eigen::Vector3f(0.5, 0.7, 1.0); } } Eigen::Vector3f color(const sol::Ray &ray, sol::Hitable &hitable) { return color(ray, hitable, 0, 50); } int main(int, char**) { const int nx = 400; const int ny = 200; const int ns = 100; //const auto aspectRatio = float(nx) / float(ny); sol::Image image(nx, ny); sol::Camera camera; sol::HitableList hitableList; hitableList.add(std::make_shared<sol::Sphere>(Eigen::Vector3f(0, 0, -1), 0.5, std::make_shared<sol::Lambertian>(Eigen::Vector3f(0.8, 0.3, 0.3)))); hitableList.add(std::make_shared<sol::Sphere>(Eigen::Vector3f(0, -100.5, -1), 100, std::make_shared<sol::Lambertian>(Eigen::Vector3f(0.8, 0.8, 0.0)))); for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { Eigen::Vector3f col(0, 0, 0); for (int s = 0; s < ns; s++) { const auto u = float(i + realRand()) / float(nx); const auto v = float(j + realRand()) / float(ny); const auto ray = camera.getRay(u, v); col += color(ray, hitableList); } col /= ns; col = Eigen::Vector3f(sqrt(col[0]), sqrt(col[1]), sqrt(col[2])); const auto r = int(255.99 * col[0]); const auto g = int(255.99 * col[1]); const auto b = int(255.99 * col[2]); image.setPixel(i, (ny - 1) - j, r, g, b); } } image.write("test.png"); return 0; } <|endoftext|>
<commit_before>#include <Core/openGL.hpp> #include <iostream> int main(int argc, char **args) { if(argc != 2) { std::cout << "Arguments are invalid, use:\n\t" << args[0] << " [scene_name]" << std::endl; exit(-1); } std::string scene = args[1]; const char* title = "OpenGL Project"; int width = 1024; int height = 576; // Create GLUT window glutInit(&argc, args); glutInitContextVersion(3,3); glutInitContextProfile(GLUT_CORE_PROFILE);aaa glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); glutInitWindowSize(width, height); glutInitWindowPosition(100, 100); glutCreateWindow(title); // Create GLUT callbacks glutDisplayFunc([]() -> void { OpenGL::GetInstance()->DisplayFunc(); }); glutIdleFunc([]() -> void { OpenGL::GetInstance()->DisplayFunc(); }); glutKeyboardFunc([](unsigned char key, int x, int y) -> void { OpenGL::GetInstance()->KeyboardFunc(key, true, x, y); }); glutKeyboardUpFunc([](unsigned char key, int x, int y) -> void { OpenGL::GetInstance()->KeyboardFunc(key, false, x, y); }); // Create singleton instance of OpenGL if(!OpenGL::CreateInstance(width, height, scene)) { std::cout << "Couldn't Create Instance of OpenGL" << std::endl; return -1; } // Enter GLUT main loop glutMainLoop(); // Destroy singletons OpenGL::DeleteInstance(); return 0; } <commit_msg>fixed error<commit_after>#include <Core/openGL.hpp> #include <iostream> int main(int argc, char **args) { if(argc != 2) { std::cout << "Arguments are invalid, use:\n\t" << args[0] << " [scene_name]" << std::endl; exit(-1); } std::string scene = args[1]; const char* title = "OpenGL Project"; int width = 1024; int height = 576; // Create GLUT window glutInit(&argc, args); glutInitContextVersion(3,3); glutInitContextProfile(GLUT_CORE_PROFILE); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); glutInitWindowSize(width, height); glutInitWindowPosition(100, 100); glutCreateWindow(title); // Create GLUT callbacks glutDisplayFunc([]() -> void { OpenGL::GetInstance()->DisplayFunc(); }); glutIdleFunc([]() -> void { OpenGL::GetInstance()->DisplayFunc(); }); glutKeyboardFunc([](unsigned char key, int x, int y) -> void { OpenGL::GetInstance()->KeyboardFunc(key, true, x, y); }); glutKeyboardUpFunc([](unsigned char key, int x, int y) -> void { OpenGL::GetInstance()->KeyboardFunc(key, false, x, y); }); // Create singleton instance of OpenGL if(!OpenGL::CreateInstance(width, height, scene)) { std::cout << "Couldn't Create Instance of OpenGL" << std::endl; return -1; } // Enter GLUT main loop glutMainLoop(); // Destroy singletons OpenGL::DeleteInstance(); return 0; } <|endoftext|>
<commit_before>#include <time.h> #include "../include/PSATsolver.hpp" #include "../include/TestGenerator.hpp" using namespace std; using namespace arma; void test(int N, int k, int n, double step, int begin, int end, string prefix); int main(int argc, char** argv) { bool v; if(argc < 20) v = true; else v = false; if (argc < 2) { std::cout << "I need a input file " << "\n"; return -1; } if((string) argv[1] == "--test") { TestGenerator t(atoi(argv[2])); t.createAll(atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atof(argv[6]), atoi(argv[7]), atoi(argv[8]), argv[9]); return 1; } if (argc < 2) { std::cout << "I need a input file " << "\n"; return -1; } //if (argc == 3 && argv[2][1] == 'v' && argv[2][0] == '-') // v = true; test(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atof(argv[4]), atoi(argv[5]), atoi(argv[6]), argv[7]); return 1; } void test(int N, int k, int n, double step, int begin, int end, string prefix) { int** matrix; int**& M = matrix; vector<double> pi; ofstream output; output.open("./data/data.txt"); for(double i = begin; i <= end; i+=step) { double y = 0; for(int j = 0; j < N; j++) { double time = 0; int m = round(n*i); string file = prefix; file += "_K" + to_string(k) + "_N" + to_string(n) + "_M" + to_string(m) + "_" + to_string(j) + ".pcnf"; cout << "opening: " << file << "\n"; PSATsolver::solve(M, pi, &time, (char*) file.c_str(), false); cout << j << " " << time << "\n"; y += time/N; } output << i << " " << y << "\n"; cout <<"media: "<< y << "\n"; } output.close(); } <commit_msg>Tests are ok<commit_after>#include <time.h> #include "../include/PSATsolver.hpp" #include "../include/TestGenerator.hpp" using namespace std; using namespace arma; void test(int N, int k, int n, double step, int begin, int end, string prefix); int main(int argc, char** argv) { bool v; if(argc < 20) v = true; else v = false; if (argc < 2) { std::cout << "I need a input file " << "\n"; return -1; } if((string) argv[1] == "--maketest") { TestGenerator t(atoi(argv[2])); t.createAll(atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atof(argv[6]), atoi(argv[7]), atoi(argv[8]), argv[9]); return 1; } if((string) argv[1] == "--test") { test(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atof(argv[4]), atoi(argv[5]), atoi(argv[6]), argv[7]); } int** matrix; int**& M = matrix; vector<double> pi; double time; PSATsolver::solve(M, pi, &time, argv[1], true); return 1; } void test(int N, int k, int n, double step, int begin, int end, string prefix) { int** matrix; int**& M = matrix; vector<double> pi; ofstream output; output.open("./data/data.txt"); for(double i = begin; i <= end; i+=step) { double y = 0; for(int j = 0; j < N; j++) { double time = 0; int m = round(n*i); string file = prefix; file += "_K" + to_string(k) + "_N" + to_string(n) + "_M" + to_string(m) + "_" + to_string(j) + ".pcnf"; cout << "opening: " << file << "\n"; PSATsolver::solve(M, pi, &time, (char*) file.c_str(), false); cout << j << " " << time << "\n"; y += time/N; } output << i << " " << y << "\n"; cout <<"media: "<< y << "\n"; } output.close(); } <|endoftext|>
<commit_before>#include <errno.h> #include <iostream> #include <string> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <vector> #include <pwd.h> #include <algorithm> #include <functional> #include <dirent.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/utsname.h> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; string shell_prompt(); //prototype for prompt function int cmd_interpreter(string); //prototype for command interpreter void input_redir(vector<string>); //prototype for input redirection function int input_helper(string, string); void output_redir(vector<string>); //prototype for output redirection function int output_helper(string, string); const char* convert(const string); bool read_dir(const char*, const char*); void change_dir(string); int main (int argc, char** argv) { while(true) { vector<string> inVector; string input; input = shell_prompt(); //while (inVector.back() != "") if (input == "exit") { //exits cout << "Exiting rshell." << endl; exit(0); } else { //take in input char_separator<char> sep(";", "|&#<>"); string t; tokenizer< char_separator<char> > tokens(input, sep); BOOST_FOREACH(t, tokens) { //TODO do different things depending on delimiters in vector inVector.push_back(t); } //end BOOST_FOREACH bool comment_sentinel = true; bool pipe_sentinel = false; bool cd_sentinel = false; for (unsigned i = 0; i < inVector.size(); i++) //go through vector of commands - looking for comments { if((comment_sentinel)&&(!cd_sentinel)) //if a comment sign is not found, execute { string in = inVector.at(i); // cerr << "[ " << in << " ]" << endl; if (in.at(0) == '#') { comment_sentinel = false; } else { // if((in == "cd")||!cd_sentinel) string cd = "cd"; // cerr << "compare: " << in.compare(0,2, cd) << endl; if(in.compare(0, 2, cd) == 0 ) { //change directory change_dir(in); cd_sentinel = true; break; } else if (cd_sentinel) { break; } else { for (unsigned k = 0; k < inVector.size(); k++) { if (inVector.at(k).at(0) == '&') { //TODO: remove later and fix } else if (inVector.at(k).at(0) == '|') { if (inVector.at(k + 1).at(0) == '|') //likely to go out of range if at end of command { pipe_sentinel = true; } if (pipe_sentinel) { //TODO: remove later and fix } } else if (inVector.at(k).at(0) == '<') { //input redirection // cerr << "we indir i hope" << endl; input_redir(inVector); //input_redir handles comment_sentinel = false; //force a skip break; } else if (inVector.at(k).at(0) == '>') { //output redirection // cerr << "we outdir i hope" << endl; output_redir(inVector); //output_redir function handles this comment_sentinel = false; //force a skip break; } else { //nothing continue; } } cmd_interpreter(in); } } } //TODO: this is for connectors // check if the current in.at(0) character equals a connector // if it does, check if the next one equals a connector // if it does, run both commands // check return values of both commands // ???? // profit }//endfor }//endif }//endwhile return 0; } void change_dir(string in) { vector<string> input; string t; char_separator<char> sep(" "); tokenizer< char_separator<char> > tokens(in, sep); BOOST_FOREACH(t, tokens) //tokenize input string with flags to seperate items { input.push_back(t); cerr << input.at(0) << " to " << input.at(1) << endl; //need chdir if (chdir(input.at(1).c_str()) == -1) { perror("chdir"); } } void input_redir(vector<string> input) { //handles all of input redirection for (unsigned i = 0; i < input.size(); i++) { if (input.at(i).at(0) == '<') { // cerr << "we input now" << endl; input_helper(input.at(i-1), input.at(i+1)); } } } int input_helper(string one, string two) { int pid = fork(); if (pid == 0) { //child //open close dup if (open(two.c_str(), O_RDONLY) != -1) { if(close(0) != -1) //stdin { if(dup(0) != -1) { //cerr << one << endl; cmd_interpreter(one); return 1; } else { perror("dup"); exit(1); } } else { perror("close"); exit(1); } } else { perror("open"); exit(1); } if (close(0) == -1) { perror("close"); exit(1); } } else { //parent // close(0); if (waitpid(-1, NULL, 0) == -1) { perror("waitpid"); exit(1); } if(close(0) == -1) { perror("close"); exit(1); } return 1; } return 0; } void output_redir(vector<string> input) { //handles all output redirectionThen pass it to your function via the .data() member of vector: for (unsigned i = 0; i < input.size(); i++) { //iterate through vector and finds redirection if (input.at(i).at(0) == '>') { // cerr << "we output now" << endl; output_helper(input.at(i-1), input.at(i+1)); } } } int output_helper(string one, string two) { //cerr << one << " " << two << endl; int pid = fork(); if (pid == 0) { //child //open close dup if (open(two.c_str(), O_WRONLY | O_CREAT) != -1) { if(close(1) != -1) //stdin { if(dup(1) != -1) { cmd_interpreter(one); return 1; } else { perror("dup"); exit(1); } } else { perror("close"); exit(1); } } else { perror("open"); exit(1); } if (close(1) == -1) { perror("close"); exit(1); } } else { //parent // close(1); if (waitpid(-1, NULL, 0) == -1) { perror("waitpid"); exit(1); } if (close(1) == -1) { perror("close"); exit(1); } return 1; } return 0; } int cmd_interpreter(string input)//, char** argv) { //parse command to seperate command and parameters //int len = input.length(); vector<string> invector; string t; vector<char*> cinput; char_separator<char> sep(" "); tokenizer< char_separator<char> > tokens(input, sep); BOOST_FOREACH(t, tokens) //tokenize input string with flags to seperate items { char* stuff = const_cast<char*>(string(t).c_str()); cinput.push_back(stuff); } cinput.push_back(NULL); //put the null terminating charater in back char* envstr = getenv("PATH"); if (envstr == NULL) { perror("getenv"); exit(0); } string env (envstr); vector<string> paths; split(paths, env, is_any_of(":")); paths.push_back("."); //current directory last //iterate through entire path vector and check if file exists bool find_flag = false; for(unsigned i = 0; i < paths.size(); i++) { paths.at(i) += "/"; if(read_dir(paths.at(i).c_str(), cinput.at(0)) && !find_flag) { paths.at(i) += cinput.at(0); // cerr << "test" << endl; find_flag = true; int pid = fork(); if(pid == 0) { if ((execv(paths.at(i).c_str(), &cinput.front())) == -1) { perror("execv"); // throw an error exit(1); } else { return 1; } } else { //parent wait if (waitpid(-1, NULL, 0) == -1) { perror("waitpid"); exit(1); } } } } if (!find_flag) { cout << "Error: could not find " << cinput.at(0) << endl; } return 0; } string shell_prompt() { string in; char name[256]; size_t maxlen = 64; if (gethostname(name, maxlen) != -1) { errno = 0; char* strlogin = getlogin(); if (strlogin == NULL) { perror("getlogin"); exit(1); } errno = 0; char* strcwd = get_current_dir_name(); if (errno != 0) { perror("getcwd"); exit(1); } else { cout << strlogin << "@" << name << ":" << strcwd << "$ "; //custom prompt with hostname and login name } } else { perror("gethostname"); //throw error if not found } // cout << "rshell$ "; getline(cin, in); cin.clear(); return in; } const char* convert(const string &str) { return str.c_str(); } bool read_dir(const char* dirName, const char* name) { errno = 0; DIR *dirp = opendir(dirName); if(errno == 0) { // cerr << "searching..." << name << " in " << dirName << endl; while (true) { errno = 0; dirent *dp; if ((dp = readdir(dirp)) != NULL) { if(strcmp(dp->d_name, name) == 0) { if(closedir(dirp) != 0) { perror("closedir"); return false; } else { return true; } } } else { if (closedir(dirp) != 0) { perror("closedir"); return false; } return false; } } return false; } else { return false; perror("opendir"); // return false; } } <commit_msg>fixed missing parenthesis<commit_after>#include <errno.h> #include <iostream> #include <string> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <vector> #include <pwd.h> #include <algorithm> #include <functional> #include <dirent.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/utsname.h> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; string shell_prompt(); //prototype for prompt function int cmd_interpreter(string); //prototype for command interpreter void input_redir(vector<string>); //prototype for input redirection function int input_helper(string, string); void output_redir(vector<string>); //prototype for output redirection function int output_helper(string, string); const char* convert(const string); bool read_dir(const char*, const char*); void change_dir(string); int main (int argc, char** argv) { while(true) { vector<string> inVector; string input; input = shell_prompt(); //while (inVector.back() != "") if (input == "exit") { //exits cout << "Exiting rshell." << endl; exit(0); } else { //take in input char_separator<char> sep(";", "|&#<>"); string t; tokenizer< char_separator<char> > tokens(input, sep); BOOST_FOREACH(t, tokens) { //TODO do different things depending on delimiters in vector inVector.push_back(t); } //end BOOST_FOREACH bool comment_sentinel = true; bool pipe_sentinel = false; bool cd_sentinel = false; for (unsigned i = 0; i < inVector.size(); i++) //go through vector of commands - looking for comments { if((comment_sentinel)&&(!cd_sentinel)) //if a comment sign is not found, execute { string in = inVector.at(i); // cerr << "[ " << in << " ]" << endl; if (in.at(0) == '#') { comment_sentinel = false; } else { // if((in == "cd")||!cd_sentinel) string cd = "cd"; // cerr << "compare: " << in.compare(0,2, cd) << endl; if(in.compare(0, 2, cd) == 0 ) { //change directory change_dir(in); cd_sentinel = true; break; } else if (cd_sentinel) { break; } else { for (unsigned k = 0; k < inVector.size(); k++) { if (inVector.at(k).at(0) == '&') { //TODO: remove later and fix } else if (inVector.at(k).at(0) == '|') { if (inVector.at(k + 1).at(0) == '|') //likely to go out of range if at end of command { pipe_sentinel = true; } if (pipe_sentinel) { //TODO: remove later and fix } } else if (inVector.at(k).at(0) == '<') { //input redirection // cerr << "we indir i hope" << endl; input_redir(inVector); //input_redir handles comment_sentinel = false; //force a skip break; } else if (inVector.at(k).at(0) == '>') { //output redirection // cerr << "we outdir i hope" << endl; output_redir(inVector); //output_redir function handles this comment_sentinel = false; //force a skip break; } else { //nothing continue; } } cmd_interpreter(in); } } } //TODO: this is for connectors // check if the current in.at(0) character equals a connector // if it does, check if the next one equals a connector // if it does, run both commands // check return values of both commands // ???? // profit }//endfor }//endif }//endwhile return 0; } void change_dir(string in) { vector<string> input; string t; char_separator<char> sep(" "); tokenizer< char_separator<char> > tokens(in, sep); BOOST_FOREACH(t, tokens) //tokenize input string with flags to seperate items { input.push_back(t); } cerr << input.at(0) << " to " << input.at(1) << endl; //need chdir if (chdir(input.at(1).c_str()) == -1) { perror("chdir"); } } void input_redir(vector<string> input) { //handles all of input redirection for (unsigned i = 0; i < input.size(); i++) { if (input.at(i).at(0) == '<') { // cerr << "we input now" << endl; input_helper(input.at(i-1), input.at(i+1)); } } } int input_helper(string one, string two) { int pid = fork(); if (pid == 0) { //child //open close dup if (open(two.c_str(), O_RDONLY) != -1) { if(close(0) != -1) //stdin { if(dup(0) != -1) { //cerr << one << endl; cmd_interpreter(one); return 1; } else { perror("dup"); exit(1); } } else { perror("close"); exit(1); } } else { perror("open"); exit(1); } if (close(0) == -1) { perror("close"); exit(1); } } else { //parent // close(0); if (waitpid(-1, NULL, 0) == -1) { perror("waitpid"); exit(1); } if(close(0) == -1) { perror("close"); exit(1); } return 1; } return 0; } void output_redir(vector<string> input) { //handles all output redirectionThen pass it to your function via the .data() member of vector: for (unsigned i = 0; i < input.size(); i++) { //iterate through vector and finds redirection if (input.at(i).at(0) == '>') { // cerr << "we output now" << endl; output_helper(input.at(i-1), input.at(i+1)); } } } int output_helper(string one, string two) { //cerr << one << " " << two << endl; int pid = fork(); if (pid == 0) { //child //open close dup if (open(two.c_str(), O_WRONLY | O_CREAT) != -1) { if(close(1) != -1) //stdin { if(dup(1) != -1) { cmd_interpreter(one); return 1; } else { perror("dup"); exit(1); } } else { perror("close"); exit(1); } } else { perror("open"); exit(1); } if (close(1) == -1) { perror("close"); exit(1); } } else { //parent // close(1); if (waitpid(-1, NULL, 0) == -1) { perror("waitpid"); exit(1); } if (close(1) == -1) { perror("close"); exit(1); } return 1; } return 0; } int cmd_interpreter(string input)//, char** argv) { //parse command to seperate command and parameters //int len = input.length(); vector<string> invector; string t; vector<char*> cinput; char_separator<char> sep(" "); tokenizer< char_separator<char> > tokens(input, sep); BOOST_FOREACH(t, tokens) //tokenize input string with flags to seperate items { char* stuff = const_cast<char*>(string(t).c_str()); cinput.push_back(stuff); } cinput.push_back(NULL); //put the null terminating charater in back char* envstr = getenv("PATH"); if (envstr == NULL) { perror("getenv"); exit(0); } string env (envstr); vector<string> paths; split(paths, env, is_any_of(":")); paths.push_back("."); //current directory last //iterate through entire path vector and check if file exists bool find_flag = false; for(unsigned i = 0; i < paths.size(); i++) { paths.at(i) += "/"; if(read_dir(paths.at(i).c_str(), cinput.at(0)) && !find_flag) { paths.at(i) += cinput.at(0); // cerr << "test" << endl; find_flag = true; int pid = fork(); if(pid == 0) { if ((execv(paths.at(i).c_str(), &cinput.front())) == -1) { perror("execv"); // throw an error exit(1); } else { return 1; } } else { //parent wait if (waitpid(-1, NULL, 0) == -1) { perror("waitpid"); exit(1); } } } } if (!find_flag) { cout << "Error: could not find " << cinput.at(0) << endl; } return 0; } string shell_prompt() { string in; char name[256]; size_t maxlen = 64; if (gethostname(name, maxlen) != -1) { errno = 0; char* strlogin = getlogin(); if (strlogin == NULL) { perror("getlogin"); exit(1); } errno = 0; char* strcwd = get_current_dir_name(); if (errno != 0) { perror("getcwd"); exit(1); } else { cout << strlogin << "@" << name << ":" << strcwd << "$ "; //custom prompt with hostname and login name } } else { perror("gethostname"); //throw error if not found } // cout << "rshell$ "; getline(cin, in); cin.clear(); return in; } const char* convert(const string &str) { return str.c_str(); } bool read_dir(const char* dirName, const char* name) { errno = 0; DIR *dirp = opendir(dirName); if(errno == 0) { // cerr << "searching..." << name << " in " << dirName << endl; while (true) { errno = 0; dirent *dp; if ((dp = readdir(dirp)) != NULL) { if(strcmp(dp->d_name, name) == 0) { if(closedir(dirp) != 0) { perror("closedir"); return false; } else { return true; } } } else { if (closedir(dirp) != 0) { perror("closedir"); return false; } return false; } } return false; } else { return false; perror("opendir"); // return false; } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2003-2004 by * * Unai Garro (ugarro@users.sourceforge.net) * * Jason Kivlighn (mizunoami44@users.sourceforge.net) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "conversiontable.h" #include "editbox.h" #include "mixednumber.h" #include <qtooltip.h> #include <kglobal.h> #include <klocale.h> class ConversionTableToolTip : public QToolTip { public: ConversionTableToolTip( ConversionTable *t ) : QToolTip(t->viewport()), table(t) { } void maybeTip( const QPoint &pos ) { if ( !table ) return; QPoint cp = table->viewportToContents( pos ); int row = table->rowAt(cp.y()); int col = table->columnAt(cp.x()); if ( row == col ) return; QString row_unit = table->verticalHeader()->label(row); QString col_unit = table->horizontalHeader()->label(col); QString text = table->text(row,col); if ( text.isEmpty() ) text = "X"; //### Is this i18n friendly??? QRect cr = table->cellGeometry( row, col ); cr.moveTopLeft( table->contentsToViewport( cr.topLeft() ) ); tip( cr, QString("1 %1 = %2 %3").arg(row_unit).arg(text).arg(col_unit) ); } private: ConversionTable *table; }; ConversionTable::ConversionTable(QWidget* parent,int maxrows,int maxcols):QTable( maxrows, maxcols, parent, "table" ) { editBoxValue=-1; items.setAutoDelete(true); widgets.setAutoDelete(true); (void)new ConversionTableToolTip( this ); } ConversionTable::~ConversionTable() { } #include <kdebug.h> void ConversionTable::unitRemoved(int id) { int index = unitIDs.find(&id); kdDebug()<<"index:" <<index<<endl; removeRow(index); removeColumn(index); kdDebug()<<"done"<<endl; } void ConversionTable::unitCreated(const Unit &unit) { insertColumns(numCols()); insertRows(numRows()); unitIDs.append(new int(unit.id)); horizontalHeader()->setLabel(numRows()-1,unit.name); verticalHeader()->setLabel(numCols()-1,unit.name); } QTableItem* ConversionTable::item( int r, int c ) const { return items.find(indexOf(r,c)); } void ConversionTable::setItem(int r, int c, QTableItem *i ) { items.replace( indexOf( r, c ), i ); i->setRow(r); // Otherwise the item i->setCol(c); //doesn't know where it is! updateCell(r,c); } void ConversionTable::clearCell( int r, int c ) { items.remove(indexOf(r,c)); } void ConversionTable::takeItem(QTableItem *item) { items.setAutoDelete(false); items.remove(indexOf(item->row(),item->col())); items.setAutoDelete(true); } void ConversionTable::insertWidget(int r, int c, QWidget *w ) { widgets.replace(indexOf(r,c),w); } QWidget* ConversionTable::cellWidget( int r, int c ) const { return widgets.find( indexOf( r, c ) ); } void ConversionTable::clearCellWidget( int r, int c ) { QWidget *w = widgets.take(indexOf(r,c)); if (w) w->deleteLater(); } ConversionTableItem::ConversionTableItem( QTable *t, EditType et ):QTableItem( t, et, QString::null) { //wedonotwantthisitemtobereplaced setReplaceable( false ); } void ConversionTableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected ) { QColorGroup g(cg); // Draw in gray all those cells which are not editable if (row() == col()) g.setColor( QColorGroup::Base, gray ); QTableItem::paint( p, g, cr, selected ); } QWidget* ConversionTableItem::createEditor() const { EditBox *eb = new EditBox(table()->viewport()); eb->setPrecision(3); eb->setRange(1e-4,10000,1,false); eb->setValue(KGlobal::locale()->readNumber(text())); // Initialize the box with this value QObject::connect(eb,SIGNAL(valueChanged(double)),table(),SLOT(acceptValueAndClose())); return eb; } void ConversionTable::acceptValueAndClose() { QTable::endEdit(currentRow(),currentColumn(),true,false); } void ConversionTableItem::setContentFromEditor( QWidget *w ) { // theuser changed the value of the combobox, so synchronize the // value of the item (its text), with the value of the combobox if ( w->inherits( "EditBox" ) ) { EditBox *eb = (EditBox*)w; if (eb->accepted) { eb->accepted=false; setText(beautify(KGlobal::locale()->formatNumber(eb->value(),5))); // Only accept value if Ok was pressed before emit ratioChanged(row(),col(),eb->value()); // Signal to store } } else QTableItem::setContentFromEditor( w ); } void ConversionTableItem::setText( const QString &s ) { QTableItem::setText(s); } QString ConversionTable::text(int r, int c ) const // without this function, the usual (text(r,c)) won't work { if ( item(r,c) ) return item(r,c)->text(); //Note that item(r,c) was reimplemented here for large sparse tables... else return QString::null; } void ConversionTable::initTable() { for (int r=0;r<numRows();r++) { this->createNewItem(r,r,1.0); item(r,r)->setEnabled(false); // Diagonal is not editable } } void ConversionTable::createNewItem(int r, int c, double amount) { ConversionTableItem *ci= new ConversionTableItem(this,QTableItem::WhenCurrent); ci->setText(beautify(KGlobal::locale()->formatNumber(amount,5))); setItem(r,c, ci ); // connect signal (forward) to know when it's actually changed connect(ci, SIGNAL(ratioChanged(int,int,double)),this,SIGNAL(ratioChanged(int,int,double))); connect(ci, SIGNAL(signalRepaintCell(int,int)),this,SLOT(repaintCell(int,int))); } void ConversionTable::setUnitIDs(IDList &idList) { unitIDs.clear(); for (int *id=idList.first();id;id=idList.next()) { int *newId=new int; *newId=*id; unitIDs.append(newId); } } void ConversionTable::setRatio(int ingID1, int ingID2, double ratio) { int indexID1=unitIDs.find(&ingID1); int indexID2=unitIDs.find(&ingID2); createNewItem(indexID1,indexID2,ratio); } int ConversionTable::getUnitID(int rc) { return(*(unitIDs.at(rc))); return(1); } QWidget * ConversionTable::beginEdit ( int row, int col, bool replace ) { // If there's no item, create it first. if (!item(row,col)) { createNewItem(row,col,0); } // Then call normal beginEdit return QTable::beginEdit(row,col,replace); } void ConversionTableItem::setTextAndSave(const QString &s) { setText(s); // Change text emit signalRepaintCell(row(),col()); // Indicate to update the cell to the table. Otherwise it's not repainted emit ratioChanged(row(),col(),s.toDouble()); // Signal to store } void ConversionTable::repaintCell(int r,int c) { QTable::updateCell(r,c); } void ConversionTable::resize(int r,int c) { setNumRows(r); setNumCols(c); initTable(); } void ConversionTable::clear(void) { items.clear(); widgets.clear(); unitIDs.clear(); resize(0,0); } //TODO this is incomplete/wrong void ConversionTable::swapRows( int row1, int row2, bool swapHeader ) { //if ( swapHeader ) //((QTableHeader*)verticalHeader())->swapSections( row1, row2, FALSE ); QPtrVector<QTableItem> tmpContents; tmpContents.resize( numCols() ); QPtrVector<QWidget> tmpWidgets; tmpWidgets.resize( numCols() ); int i; items.setAutoDelete( FALSE ); widgets.setAutoDelete( FALSE ); for ( i = 0; i < numCols(); ++i ) { QTableItem *i1, *i2; i1 = item( row1, i ); i2 = item( row2, i ); if ( i1 || i2 ) { tmpContents.insert( i, i1 ); items.remove( indexOf( row1, i ) ); items.insert( indexOf( row1, i ), i2 ); items.remove( indexOf( row2, i ) ); items.insert( indexOf( row2, i ), tmpContents[ i ] ); if ( items[ indexOf( row1, i ) ] ) items[ indexOf( row1, i ) ]->setRow( row1 ); if ( items[ indexOf( row2, i ) ] ) items[ indexOf( row2, i ) ]->setRow( row2 ); } QWidget *w1, *w2; w1 = cellWidget( row1, i ); w2 = cellWidget( row2, i ); if ( w1 || w2 ) { tmpWidgets.insert( i, w1 ); widgets.remove( indexOf( row1, i ) ); widgets.insert( indexOf( row1, i ), w2 ); widgets.remove( indexOf( row2, i ) ); widgets.insert( indexOf( row2, i ), tmpWidgets[ i ] ); } } items.setAutoDelete( FALSE ); widgets.setAutoDelete( TRUE ); //updateRowWidgets( row1 ); //updateRowWidgets( row2 ); /* if ( curRow == row1 ) curRow = row2; else if ( curRow == row2 ) curRow = row1; if ( editRow == row1 ) editRow = row2; else if ( editRow == row2 ) editRow = row1;*/ } //TODO this is incomplete/wrong void ConversionTable::swapColumns( int col1, int col2, bool swapHeader ) { //if ( swapHeader ) //((QTableHeader*)horizontalHeader())->swapSections( col1, col2, FALSE ); QPtrVector<QTableItem> tmpContents; tmpContents.resize( numRows() ); QPtrVector<QWidget> tmpWidgets; tmpWidgets.resize( numRows() ); int i; items.setAutoDelete( FALSE ); widgets.setAutoDelete( FALSE ); for ( i = 0; i < numRows(); ++i ) { QTableItem *i1, *i2; i1 = item( i, col1 ); i2 = item( i, col2 ); if ( i1 || i2 ) { tmpContents.insert( i, i1 ); items.remove( indexOf( i, col1 ) ); items.insert( indexOf( i, col1 ), i2 ); items.remove( indexOf( i, col2 ) ); items.insert( indexOf( i, col2 ), tmpContents[ i ] ); if ( items[ indexOf( i, col1 ) ] ) items[ indexOf( i, col1 ) ]->setCol( col1 ); if ( items[ indexOf( i, col2 ) ] ) items[ indexOf( i, col2 ) ]->setCol( col2 ); } QWidget *w1, *w2; w1 = cellWidget( i, col1 ); w2 = cellWidget( i, col2 ); if ( w1 || w2 ) { tmpWidgets.insert( i, w1 ); widgets.remove( indexOf( i, col1 ) ); widgets.insert( indexOf( i, col1 ), w2 ); widgets.remove( indexOf( i, col2 ) ); widgets.insert( indexOf( i, col2 ), tmpWidgets[ i ] ); } } items.setAutoDelete( FALSE ); widgets.setAutoDelete( TRUE ); columnWidthChanged( col1 ); columnWidthChanged( col2 ); /* if ( curCol == col1 ) curCol = col2; else if ( curCol == col2 ) curCol = col1; if ( editCol == col1 ) editCol = col2; else if ( editCol == col2 ) editCol = col1;*/ } //TODO this is incomplete/wrong void ConversionTable::swapCells( int row1, int col1, int row2, int col2 ) { items.setAutoDelete( FALSE ); widgets.setAutoDelete( FALSE ); QTableItem *i1, *i2; i1 = item( row1, col1 ); i2 = item( row2, col2 ); if ( i1 || i2 ) { QTableItem *tmp = i1; items.remove( indexOf( row1, col1 ) ); items.insert( indexOf( row1, col1 ), i2 ); items.remove( indexOf( row2, col2 ) ); items.insert( indexOf( row2, col2 ), tmp ); if ( items[ indexOf( row1, col1 ) ] ) { items[ indexOf( row1, col1 ) ]->setRow( row1 ); items[ indexOf( row1, col1 ) ]->setCol( col1 ); } if ( items[ indexOf( row2, col2 ) ] ) { items[ indexOf( row2, col2 ) ]->setRow( row2 ); items[ indexOf( row2, col2 ) ]->setCol( col2 ); } } QWidget *w1, *w2; w1 = cellWidget( row1, col1 ); w2 = cellWidget( row2, col2 ); if ( w1 || w2 ) { QWidget *tmp = w1; widgets.remove( indexOf( row1, col1 ) ); widgets.insert( indexOf( row1, col1 ), w2 ); widgets.remove( indexOf( row2, col2 ) ); widgets.insert( indexOf( row2, col2 ), tmp ); } //updateRowWidgets( row1 ); //updateRowWidgets( row2 ); //updateColWidgets( col1 ); //updateColWidgets( col2 ); items.setAutoDelete( FALSE ); widgets.setAutoDelete( TRUE ); } #include "conversiontable.moc" <commit_msg>Up the precision in the conversion table<commit_after>/*************************************************************************** * Copyright (C) 2003-2004 by * * Unai Garro (ugarro@users.sourceforge.net) * * Jason Kivlighn (mizunoami44@users.sourceforge.net) * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "conversiontable.h" #include "editbox.h" #include "mixednumber.h" #include <qtooltip.h> #include <kglobal.h> #include <klocale.h> class ConversionTableToolTip : public QToolTip { public: ConversionTableToolTip( ConversionTable *t ) : QToolTip(t->viewport()), table(t) { } void maybeTip( const QPoint &pos ) { if ( !table ) return; QPoint cp = table->viewportToContents( pos ); int row = table->rowAt(cp.y()); int col = table->columnAt(cp.x()); if ( row == col ) return; QString row_unit = table->verticalHeader()->label(row); QString col_unit = table->horizontalHeader()->label(col); QString text = table->text(row,col); if ( text.isEmpty() ) text = "X"; //### Is this i18n friendly??? QRect cr = table->cellGeometry( row, col ); cr.moveTopLeft( table->contentsToViewport( cr.topLeft() ) ); tip( cr, QString("1 %1 = %2 %3").arg(row_unit).arg(text).arg(col_unit) ); } private: ConversionTable *table; }; ConversionTable::ConversionTable(QWidget* parent,int maxrows,int maxcols):QTable( maxrows, maxcols, parent, "table" ) { editBoxValue=-1; items.setAutoDelete(true); widgets.setAutoDelete(true); (void)new ConversionTableToolTip( this ); } ConversionTable::~ConversionTable() { } #include <kdebug.h> void ConversionTable::unitRemoved(int id) { int index = unitIDs.find(&id); kdDebug()<<"index:" <<index<<endl; removeRow(index); removeColumn(index); kdDebug()<<"done"<<endl; } void ConversionTable::unitCreated(const Unit &unit) { insertColumns(numCols()); insertRows(numRows()); unitIDs.append(new int(unit.id)); horizontalHeader()->setLabel(numRows()-1,unit.name); verticalHeader()->setLabel(numCols()-1,unit.name); } QTableItem* ConversionTable::item( int r, int c ) const { return items.find(indexOf(r,c)); } void ConversionTable::setItem(int r, int c, QTableItem *i ) { items.replace( indexOf( r, c ), i ); i->setRow(r); // Otherwise the item i->setCol(c); //doesn't know where it is! updateCell(r,c); } void ConversionTable::clearCell( int r, int c ) { items.remove(indexOf(r,c)); } void ConversionTable::takeItem(QTableItem *item) { items.setAutoDelete(false); items.remove(indexOf(item->row(),item->col())); items.setAutoDelete(true); } void ConversionTable::insertWidget(int r, int c, QWidget *w ) { widgets.replace(indexOf(r,c),w); } QWidget* ConversionTable::cellWidget( int r, int c ) const { return widgets.find( indexOf( r, c ) ); } void ConversionTable::clearCellWidget( int r, int c ) { QWidget *w = widgets.take(indexOf(r,c)); if (w) w->deleteLater(); } ConversionTableItem::ConversionTableItem( QTable *t, EditType et ):QTableItem( t, et, QString::null) { //wedonotwantthisitemtobereplaced setReplaceable( false ); } void ConversionTableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected ) { QColorGroup g(cg); // Draw in gray all those cells which are not editable if (row() == col()) g.setColor( QColorGroup::Base, gray ); QTableItem::paint( p, g, cr, selected ); } QWidget* ConversionTableItem::createEditor() const { EditBox *eb = new EditBox(table()->viewport()); eb->setPrecision(5); eb->setRange(1e-6,10000,1,false); eb->setValue(KGlobal::locale()->readNumber(text())); // Initialize the box with this value QObject::connect(eb,SIGNAL(valueChanged(double)),table(),SLOT(acceptValueAndClose())); return eb; } void ConversionTable::acceptValueAndClose() { QTable::endEdit(currentRow(),currentColumn(),true,false); } void ConversionTableItem::setContentFromEditor( QWidget *w ) { // theuser changed the value of the combobox, so synchronize the // value of the item (its text), with the value of the combobox if ( w->inherits( "EditBox" ) ) { EditBox *eb = (EditBox*)w; if (eb->accepted) { eb->accepted=false; setText(beautify(KGlobal::locale()->formatNumber(eb->value(),5))); // Only accept value if Ok was pressed before emit ratioChanged(row(),col(),eb->value()); // Signal to store } } else QTableItem::setContentFromEditor( w ); } void ConversionTableItem::setText( const QString &s ) { QTableItem::setText(s); } QString ConversionTable::text(int r, int c ) const // without this function, the usual (text(r,c)) won't work { if ( item(r,c) ) return item(r,c)->text(); //Note that item(r,c) was reimplemented here for large sparse tables... else return QString::null; } void ConversionTable::initTable() { for (int r=0;r<numRows();r++) { this->createNewItem(r,r,1.0); item(r,r)->setEnabled(false); // Diagonal is not editable } } void ConversionTable::createNewItem(int r, int c, double amount) { ConversionTableItem *ci= new ConversionTableItem(this,QTableItem::WhenCurrent); ci->setText(beautify(KGlobal::locale()->formatNumber(amount,5))); setItem(r,c, ci ); // connect signal (forward) to know when it's actually changed connect(ci, SIGNAL(ratioChanged(int,int,double)),this,SIGNAL(ratioChanged(int,int,double))); connect(ci, SIGNAL(signalRepaintCell(int,int)),this,SLOT(repaintCell(int,int))); } void ConversionTable::setUnitIDs(IDList &idList) { unitIDs.clear(); for (int *id=idList.first();id;id=idList.next()) { int *newId=new int; *newId=*id; unitIDs.append(newId); } } void ConversionTable::setRatio(int ingID1, int ingID2, double ratio) { int indexID1=unitIDs.find(&ingID1); int indexID2=unitIDs.find(&ingID2); createNewItem(indexID1,indexID2,ratio); } int ConversionTable::getUnitID(int rc) { return(*(unitIDs.at(rc))); return(1); } QWidget * ConversionTable::beginEdit ( int row, int col, bool replace ) { // If there's no item, create it first. if (!item(row,col)) { createNewItem(row,col,0); } // Then call normal beginEdit return QTable::beginEdit(row,col,replace); } void ConversionTableItem::setTextAndSave(const QString &s) { setText(s); // Change text emit signalRepaintCell(row(),col()); // Indicate to update the cell to the table. Otherwise it's not repainted emit ratioChanged(row(),col(),s.toDouble()); // Signal to store } void ConversionTable::repaintCell(int r,int c) { QTable::updateCell(r,c); } void ConversionTable::resize(int r,int c) { setNumRows(r); setNumCols(c); initTable(); } void ConversionTable::clear(void) { items.clear(); widgets.clear(); unitIDs.clear(); resize(0,0); } //TODO this is incomplete/wrong void ConversionTable::swapRows( int row1, int row2, bool swapHeader ) { //if ( swapHeader ) //((QTableHeader*)verticalHeader())->swapSections( row1, row2, FALSE ); QPtrVector<QTableItem> tmpContents; tmpContents.resize( numCols() ); QPtrVector<QWidget> tmpWidgets; tmpWidgets.resize( numCols() ); int i; items.setAutoDelete( FALSE ); widgets.setAutoDelete( FALSE ); for ( i = 0; i < numCols(); ++i ) { QTableItem *i1, *i2; i1 = item( row1, i ); i2 = item( row2, i ); if ( i1 || i2 ) { tmpContents.insert( i, i1 ); items.remove( indexOf( row1, i ) ); items.insert( indexOf( row1, i ), i2 ); items.remove( indexOf( row2, i ) ); items.insert( indexOf( row2, i ), tmpContents[ i ] ); if ( items[ indexOf( row1, i ) ] ) items[ indexOf( row1, i ) ]->setRow( row1 ); if ( items[ indexOf( row2, i ) ] ) items[ indexOf( row2, i ) ]->setRow( row2 ); } QWidget *w1, *w2; w1 = cellWidget( row1, i ); w2 = cellWidget( row2, i ); if ( w1 || w2 ) { tmpWidgets.insert( i, w1 ); widgets.remove( indexOf( row1, i ) ); widgets.insert( indexOf( row1, i ), w2 ); widgets.remove( indexOf( row2, i ) ); widgets.insert( indexOf( row2, i ), tmpWidgets[ i ] ); } } items.setAutoDelete( FALSE ); widgets.setAutoDelete( TRUE ); //updateRowWidgets( row1 ); //updateRowWidgets( row2 ); /* if ( curRow == row1 ) curRow = row2; else if ( curRow == row2 ) curRow = row1; if ( editRow == row1 ) editRow = row2; else if ( editRow == row2 ) editRow = row1;*/ } //TODO this is incomplete/wrong void ConversionTable::swapColumns( int col1, int col2, bool swapHeader ) { //if ( swapHeader ) //((QTableHeader*)horizontalHeader())->swapSections( col1, col2, FALSE ); QPtrVector<QTableItem> tmpContents; tmpContents.resize( numRows() ); QPtrVector<QWidget> tmpWidgets; tmpWidgets.resize( numRows() ); int i; items.setAutoDelete( FALSE ); widgets.setAutoDelete( FALSE ); for ( i = 0; i < numRows(); ++i ) { QTableItem *i1, *i2; i1 = item( i, col1 ); i2 = item( i, col2 ); if ( i1 || i2 ) { tmpContents.insert( i, i1 ); items.remove( indexOf( i, col1 ) ); items.insert( indexOf( i, col1 ), i2 ); items.remove( indexOf( i, col2 ) ); items.insert( indexOf( i, col2 ), tmpContents[ i ] ); if ( items[ indexOf( i, col1 ) ] ) items[ indexOf( i, col1 ) ]->setCol( col1 ); if ( items[ indexOf( i, col2 ) ] ) items[ indexOf( i, col2 ) ]->setCol( col2 ); } QWidget *w1, *w2; w1 = cellWidget( i, col1 ); w2 = cellWidget( i, col2 ); if ( w1 || w2 ) { tmpWidgets.insert( i, w1 ); widgets.remove( indexOf( i, col1 ) ); widgets.insert( indexOf( i, col1 ), w2 ); widgets.remove( indexOf( i, col2 ) ); widgets.insert( indexOf( i, col2 ), tmpWidgets[ i ] ); } } items.setAutoDelete( FALSE ); widgets.setAutoDelete( TRUE ); columnWidthChanged( col1 ); columnWidthChanged( col2 ); /* if ( curCol == col1 ) curCol = col2; else if ( curCol == col2 ) curCol = col1; if ( editCol == col1 ) editCol = col2; else if ( editCol == col2 ) editCol = col1;*/ } //TODO this is incomplete/wrong void ConversionTable::swapCells( int row1, int col1, int row2, int col2 ) { items.setAutoDelete( FALSE ); widgets.setAutoDelete( FALSE ); QTableItem *i1, *i2; i1 = item( row1, col1 ); i2 = item( row2, col2 ); if ( i1 || i2 ) { QTableItem *tmp = i1; items.remove( indexOf( row1, col1 ) ); items.insert( indexOf( row1, col1 ), i2 ); items.remove( indexOf( row2, col2 ) ); items.insert( indexOf( row2, col2 ), tmp ); if ( items[ indexOf( row1, col1 ) ] ) { items[ indexOf( row1, col1 ) ]->setRow( row1 ); items[ indexOf( row1, col1 ) ]->setCol( col1 ); } if ( items[ indexOf( row2, col2 ) ] ) { items[ indexOf( row2, col2 ) ]->setRow( row2 ); items[ indexOf( row2, col2 ) ]->setCol( col2 ); } } QWidget *w1, *w2; w1 = cellWidget( row1, col1 ); w2 = cellWidget( row2, col2 ); if ( w1 || w2 ) { QWidget *tmp = w1; widgets.remove( indexOf( row1, col1 ) ); widgets.insert( indexOf( row1, col1 ), w2 ); widgets.remove( indexOf( row2, col2 ) ); widgets.insert( indexOf( row2, col2 ), tmp ); } //updateRowWidgets( row1 ); //updateRowWidgets( row2 ); //updateColWidgets( col1 ); //updateColWidgets( col2 ); items.setAutoDelete( FALSE ); widgets.setAutoDelete( TRUE ); } #include "conversiontable.moc" <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} // make MTL MTL M=make_MTL(G,F); write_MTL_file; assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); printf("Number in each priority class. The last two are SF and SS.\n"); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; if(j%1000==0)diagnostic(M,G,F,A); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==1000 || j==3000) { printf ( "Redistribute and improve at j = %d\n",j); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //diagnostic(M,G,F,A); } } print_time(time,"# ... took :"); //diagnostic check on SS and SF for (int j=0;j<F.Nplate;++j){ for (int p=0; p<F.Npetal; ++p){ if(P[j].SS_in_petal[p]!=F.MaxSS){printf("SS j= %d p= %d number = %d\n",j,p,P[j].SS_in_petal[p]);} if(P[j].SF_in_petal[p]!=F.MaxSF){printf("SF j= %d p= %d number = %d\n",j,p,P[j].SF_in_petal[p]);} } } // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",G,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>fix typo<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n"); for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);} // make MTL MTL M=make_MTL(G,F); write_MTLfile; assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); printf("Number in each priority class. The last two are SF and SS.\n"); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; if(j%1000==0)diagnostic(M,G,F,A); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==1000 || j==3000) { printf ( "Redistribute and improve at j = %d\n",j); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //diagnostic(M,G,F,A); } } print_time(time,"# ... took :"); //diagnostic check on SS and SF for (int j=0;j<F.Nplate;++j){ for (int p=0; p<F.Npetal; ++p){ if(P[j].SS_in_petal[p]!=F.MaxSS){printf("SS j= %d p= %d number = %d\n",j,p,P[j].SS_in_petal[p]);} if(P[j].SF_in_petal[p]!=F.MaxSF){printf("SF j= %d p= %d number = %d\n",j,p,P[j].SF_in_petal[p]);} } } // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",G,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #if CROWN_BUILD_UNIT_TESTS #include "array.h" #include "dynamic_string.h" #include "json.h" #include "math_utils.h" #include "memory.h" #include "murmur.h" #include "path.h" #include "sjson.h" #include "string_id.h" #include "string_utils.h" #include "temp_allocator.h" #include "vector.h" namespace crown { static void test_array() { memory_globals::init(); Allocator& a = default_allocator(); { Array<int> v(a); CE_ENSURE(array::size(v) == 0); array::push_back(v, 1); CE_ENSURE(array::size(v) == 1); CE_ENSURE(v[0] == 1); } memory_globals::shutdown(); } static void test_vector() { memory_globals::init(); Allocator& a = default_allocator(); { Vector<int> v(a); CE_ENSURE(vector::size(v) == 0); vector::push_back(v, 1); CE_ENSURE(vector::size(v) == 1); CE_ENSURE(v[0] == 1); } memory_globals::shutdown(); } static void test_murmur() { const u32 m = murmur32("murmur32", 8, 0); CE_ENSURE(m == 0x7c2365dbu); const u64 n = murmur64("murmur64", 8, 0); CE_ENSURE(n == 0x90631502d1a3432bu); } static void test_string_id() { { StringId32 a("murmur32"); CE_ENSURE(a._id == 0x7c2365dbu); StringId32 b("murmur32", 8); CE_ENSURE(a._id == 0x7c2365dbu); char buf[128]; a.to_string(buf); CE_ENSURE(strcmp(buf, "7c2365db") == 0); } { StringId64 a("murmur64"); CE_ENSURE(a._id == 0x90631502d1a3432bu); StringId64 b("murmur64", 8); CE_ENSURE(a._id == 0x90631502d1a3432bu); char buf[128]; a.to_string(buf); CE_ENSURE(strcmp(buf, "90631502d1a3432b") == 0); } } static void test_json() { memory_globals::init(); { JsonValueType::Enum type = json::type("null"); CE_ENSURE(type == JsonValueType::NIL); type = json::type("true"); CE_ENSURE(type == JsonValueType::BOOL); type = json::type("false"); CE_ENSURE(type == JsonValueType::BOOL); type = json::type("3.14"); CE_ENSURE(type == JsonValueType::NUMBER); type = json::type("\"foo\""); CE_ENSURE(type == JsonValueType::STRING); type = json::type("[]"); CE_ENSURE(type == JsonValueType::ARRAY); type = json::type("{}"); CE_ENSURE(type == JsonValueType::OBJECT); const s32 i = json::parse_int("3.14"); CE_ENSURE(i == 3); const f32 f = json::parse_float("3.14"); CE_ENSURE(fequal(f, 3.14f)); const bool b = json::parse_bool("true"); CE_ENSURE(b == true); const bool c = json::parse_bool("false"); CE_ENSURE(c == false); TempAllocator1024 ta; DynamicString str(ta); json::parse_string("\"This is JSON\"", str); CE_ENSURE(strcmp(str.c_str(), "This is JSON") == 0); } memory_globals::shutdown(); } static void test_sjson() { memory_globals::init(); { JsonValueType::Enum type = json::type("null"); CE_ENSURE(type == JsonValueType::NIL); type = sjson::type("true"); CE_ENSURE(type == JsonValueType::BOOL); type = sjson::type("false"); CE_ENSURE(type == JsonValueType::BOOL); type = sjson::type("3.14"); CE_ENSURE(type == JsonValueType::NUMBER); type = sjson::type("\"foo\""); CE_ENSURE(type == JsonValueType::STRING); type = sjson::type("[]"); CE_ENSURE(type == JsonValueType::ARRAY); type = sjson::type("{}"); CE_ENSURE(type == JsonValueType::OBJECT); const s32 i = sjson::parse_int("3.14"); CE_ENSURE(i == 3); const f32 f = sjson::parse_float("3.14"); CE_ENSURE(fequal(f, 3.14f)); const bool b = sjson::parse_bool("true"); CE_ENSURE(b == true); const bool c = sjson::parse_bool("false"); CE_ENSURE(c == false); TempAllocator1024 ta; DynamicString str(ta); sjson::parse_string("\"This is SJSON\"", str); CE_ENSURE(strcmp(str.c_str(), "This is SJSON") == 0); } memory_globals::shutdown(); } static void test_path() { #if CROWN_PLATFORM_POSIX { const bool a = path::is_absolute("/home/foo"); CE_ENSURE(a == true); const bool b = path::is_absolute("home/foo"); CE_ENSURE(b == false); } { const bool a = path::is_relative("/home/foo"); CE_ENSURE(a == false); const bool b = path::is_relative("home/foo"); CE_ENSURE(b == true); } { const bool a = path::is_root("/"); CE_ENSURE(a == true); const bool b = path::is_root("/home"); CE_ENSURE(b == false); } #else { const bool a = path::is_absolute("C:\\Users\\foo"); CE_ENSURE(a == true); const bool b = path::is_absolute("Users\\foo"); CE_ENSURE(b == false); } { const bool a = path::is_relative("D:\\Users\\foo"); CE_ENSURE(a == false); const bool b = path::is_relative("Users\\foo"); CE_ENSURE(b == true); } { const bool a = path::is_root("E:\\"); CE_ENSURE(a == true); const bool b = path::is_root("E:\\Users"); CE_ENSURE(b == false); } #endif // CROWN_PLATFORM_POSIX { const char* p = path::basename(""); CE_ENSURE(strcmp(p, "") == 0); const char* q = path::basename("/"); CE_ENSURE(strcmp(q, "") == 0); const char* r = path::basename("boot.config"); CE_ENSURE(strcmp(r, "boot.config") == 0); const char* s = path::basename("foo/boot.config"); CE_ENSURE(strcmp(s, "boot.config") == 0); const char* t = path::basename("/foo/boot.config"); CE_ENSURE(strcmp(t, "boot.config") == 0); } { const char* p = path::extension(""); CE_ENSURE(p == NULL); const char* q = path::extension("boot"); CE_ENSURE(q == NULL); const char* r = path::extension("boot.bar.config"); CE_ENSURE(strcmp(r, "config") == 0); } } static void run_unit_tests() { test_array(); test_vector(); test_murmur(); test_string_id(); test_json(); test_sjson(); test_path(); } } // namespace crown #endif // CROWN_BUILD_UNIT_TESTS <commit_msg>Fix tests<commit_after>/* * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #if CROWN_BUILD_UNIT_TESTS #include "array.h" #include "dynamic_string.h" #include "json.h" #include "math_utils.h" #include "memory.h" #include "murmur.h" #include "path.h" #include "sjson.h" #include "string_id.h" #include "string_utils.h" #include "temp_allocator.h" #include "vector.h" namespace crown { static void test_array() { memory_globals::init(); Allocator& a = default_allocator(); { Array<int> v(a); CE_ENSURE(array::size(v) == 0); array::push_back(v, 1); CE_ENSURE(array::size(v) == 1); CE_ENSURE(v[0] == 1); } memory_globals::shutdown(); } static void test_vector() { memory_globals::init(); Allocator& a = default_allocator(); { Vector<int> v(a); CE_ENSURE(vector::size(v) == 0); vector::push_back(v, 1); CE_ENSURE(vector::size(v) == 1); CE_ENSURE(v[0] == 1); } memory_globals::shutdown(); } static void test_murmur() { const u32 m = murmur32("murmur32", 8, 0); CE_ENSURE(m == 0x7c2365dbu); const u64 n = murmur64("murmur64", 8, 0); CE_ENSURE(n == 0x90631502d1a3432bu); } static void test_string_id() { { StringId32 a("murmur32"); CE_ENSURE(a._id == 0x7c2365dbu); StringId32 b("murmur32", 8); CE_ENSURE(a._id == 0x7c2365dbu); char buf[128]; a.to_string(buf); CE_ENSURE(strcmp(buf, "7c2365db") == 0); } { StringId64 a("murmur64"); CE_ENSURE(a._id == 0x90631502d1a3432bu); StringId64 b("murmur64", 8); CE_ENSURE(a._id == 0x90631502d1a3432bu); char buf[128]; a.to_string(buf); CE_ENSURE(strcmp(buf, "90631502d1a3432b") == 0); } } static void test_json() { memory_globals::init(); { JsonValueType::Enum type = json::type("null"); CE_ENSURE(type == JsonValueType::NIL); type = json::type("true"); CE_ENSURE(type == JsonValueType::BOOL); type = json::type("false"); CE_ENSURE(type == JsonValueType::BOOL); type = json::type("3.14"); CE_ENSURE(type == JsonValueType::NUMBER); type = json::type("\"foo\""); CE_ENSURE(type == JsonValueType::STRING); type = json::type("[]"); CE_ENSURE(type == JsonValueType::ARRAY); type = json::type("{}"); CE_ENSURE(type == JsonValueType::OBJECT); const s32 i = json::parse_int("3.14"); CE_ENSURE(i == 3); const f32 f = json::parse_float("3.14"); CE_ENSURE(fequal(f, 3.14f)); const bool b = json::parse_bool("true"); CE_ENSURE(b == true); const bool c = json::parse_bool("false"); CE_ENSURE(c == false); TempAllocator1024 ta; DynamicString str(ta); json::parse_string("\"This is JSON\"", str); CE_ENSURE(strcmp(str.c_str(), "This is JSON") == 0); } memory_globals::shutdown(); } static void test_sjson() { memory_globals::init(); { JsonValueType::Enum type = sjson::type("null"); CE_ENSURE(type == JsonValueType::NIL); type = sjson::type("true"); CE_ENSURE(type == JsonValueType::BOOL); type = sjson::type("false"); CE_ENSURE(type == JsonValueType::BOOL); type = sjson::type("3.14"); CE_ENSURE(type == JsonValueType::NUMBER); type = sjson::type("\"foo\""); CE_ENSURE(type == JsonValueType::STRING); type = sjson::type("[]"); CE_ENSURE(type == JsonValueType::ARRAY); type = sjson::type("{}"); CE_ENSURE(type == JsonValueType::OBJECT); const s32 i = sjson::parse_int("3.14"); CE_ENSURE(i == 3); const f32 f = sjson::parse_float("3.14"); CE_ENSURE(fequal(f, 3.14f)); const bool b = sjson::parse_bool("true"); CE_ENSURE(b == true); const bool c = sjson::parse_bool("false"); CE_ENSURE(c == false); TempAllocator1024 ta; DynamicString str(ta); sjson::parse_string("\"This is SJSON\"", str); CE_ENSURE(strcmp(str.c_str(), "This is SJSON") == 0); } memory_globals::shutdown(); } static void test_path() { #if CROWN_PLATFORM_POSIX { const bool a = path::is_absolute("/home/foo"); CE_ENSURE(a == true); const bool b = path::is_absolute("home/foo"); CE_ENSURE(b == false); } { const bool a = path::is_relative("/home/foo"); CE_ENSURE(a == false); const bool b = path::is_relative("home/foo"); CE_ENSURE(b == true); } { const bool a = path::is_root("/"); CE_ENSURE(a == true); const bool b = path::is_root("/home"); CE_ENSURE(b == false); } #else { const bool a = path::is_absolute("C:\\Users\\foo"); CE_ENSURE(a == true); const bool b = path::is_absolute("Users\\foo"); CE_ENSURE(b == false); } { const bool a = path::is_relative("D:\\Users\\foo"); CE_ENSURE(a == false); const bool b = path::is_relative("Users\\foo"); CE_ENSURE(b == true); } { const bool a = path::is_root("E:\\"); CE_ENSURE(a == true); const bool b = path::is_root("E:\\Users"); CE_ENSURE(b == false); } #endif // CROWN_PLATFORM_POSIX { const char* p = path::basename(""); CE_ENSURE(strcmp(p, "") == 0); const char* q = path::basename("/"); CE_ENSURE(strcmp(q, "") == 0); const char* r = path::basename("boot.config"); CE_ENSURE(strcmp(r, "boot.config") == 0); const char* s = path::basename("foo/boot.config"); CE_ENSURE(strcmp(s, "boot.config") == 0); const char* t = path::basename("/foo/boot.config"); CE_ENSURE(strcmp(t, "boot.config") == 0); } { const char* p = path::extension(""); CE_ENSURE(p == NULL); const char* q = path::extension("boot"); CE_ENSURE(q == NULL); const char* r = path::extension("boot.bar.config"); CE_ENSURE(strcmp(r, "config") == 0); } } static void run_unit_tests() { test_array(); test_vector(); test_murmur(); test_string_id(); test_json(); test_sjson(); test_path(); } } // namespace crown #endif // CROWN_BUILD_UNIT_TESTS <|endoftext|>
<commit_before>#include <iostream> #include "../../hpp/tom/tom.hpp" #include "../../hpp/ax/impl/ax.hpp" #include "../../hpp/ax/impl/system.hpp" #include "../../hpp/ax/impl/basic_obj_model.hpp" namespace ax { // A trivial type to demonstrate the castable type. class castable_a : public ax::castable { public: int i = 0; protected: ENABLE_CAST(ax::castable_a, ax::castable); }; // A trivial type to demonstrate the castable type. class castable_b : public ax::castable_a { public: int j = 0; protected: ENABLE_CAST(ax::castable_b, ax::castable_a); }; // A trivial program type to demonstrate the eventable program mixin. class eventable_test final : public ax::eventable<ax::eventable_test> { protected: ENABLE_CAST(ax::eventable_test, ax::eventable<ax::eventable_test>); }; class reflectable_test final : public ax::reflectable { protected: ENABLE_REFLECTION_CUSTOM(ax::reflectable_test, ax::reflectable); const std::shared_ptr<ax::type> type = register_sub_type<ax::reflectable_test>(typeid(ax::reflectable), { { "bool_value", register_field<bool> (offsetof(ax::reflectable_test, bool_value)) }, { "int_value", register_field<int> (offsetof(ax::reflectable_test, int_value)) }, { "float_value", register_field<float> (offsetof(ax::reflectable_test, float_value)) }, { "name_value", register_field<ax::name> (offsetof(ax::reflectable_test, name_value)) }, { "address_value", register_field<ax::address> (offsetof(ax::reflectable_test, address_value)) }, { "vector_int_value", register_field<std::vector<int>> (offsetof(ax::reflectable_test, vector_int_value)) }, { "vector_string_value", register_field<std::vector<std::string>> (offsetof(ax::reflectable_test, vector_string_value)) }, { "shared_int_value", register_field<std::shared_ptr<int>> (offsetof(ax::reflectable_test, shared_int_value)) }, { "pair_value", register_field<ax::pair<int, int>> (offsetof(ax::reflectable_test, pair_value)) }, { "record_value", register_field<ax::record<int, int, int>> (offsetof(ax::reflectable_test, record_value)) }, { "option_some_value", register_field<ax::option<int>> (offsetof(ax::reflectable_test, option_some_value)) }, { "option_none_value", register_field<ax::option<int>> (offsetof(ax::reflectable_test, option_none_value)) }, { "either_right_value", register_field<ax::either<int, std::string>> (offsetof(ax::reflectable_test, either_right_value)) }, { "either_left_value", register_field<ax::either<int, std::string>> (offsetof(ax::reflectable_test, either_left_value)) }, { "choice_value", register_field<ax::choice<int, int, int>> (offsetof(ax::reflectable_test, choice_value)) } }); std::shared_ptr<ax::type> get_type() const override { return type; }; public: int bool_value; int int_value; float float_value; ax::name name_value; ax::address address_value; std::vector<int> vector_int_value; std::vector<std::string> vector_string_value; std::shared_ptr<int> shared_int_value; ax::pair<int, int> pair_value; ax::record<int, int, int> record_value; ax::option<int> option_some_value; ax::option<int> option_none_value; ax::either<int, std::string> either_right_value; ax::either<int, std::string> either_left_value; ax::choice<int, int, int> choice_value; reflectable_test() : bool_value(), int_value(), float_value(), name_value(), address_value(), vector_int_value(), vector_string_value(), shared_int_value(std::make_shared<int>()), pair_value(), record_value(), option_some_value(), option_none_value(), either_right_value(), either_left_value(), choice_value() { } reflectable_test( bool bool_value, int int_value, float float_value, ax::name name_value, ax::address address_value, const std::vector<int>& vector_int_value, const std::vector<std::string>& vector_string_value, int shared_int_value, ax::pair<int, int> pair_value, ax::record<int, int, int> record_value, ax::option<int> option_some_value, ax::option<int> option_none_value, ax::either<int, std::string> either_right_value, ax::either<int, std::string> either_left_value, ax::choice<int, int, int> choice_value) : bool_value(bool_value), int_value(int_value), float_value(float_value), name_value(name_value), address_value(address_value), vector_int_value(vector_int_value), vector_string_value(vector_string_value), shared_int_value(std::make_shared<int>(shared_int_value)), pair_value(pair_value), record_value(record_value), option_some_value(option_some_value), option_none_value(option_none_value), either_right_value(either_right_value), either_left_value(either_left_value), choice_value(choice_value) { } }; TEST("hash works") { CHECK(ax::get_hash(0) == std::hash<int>()(0)); } TEST("castable works") { ax::castable_b b; b.i = 10; b.j = 20; const ax::castable_a& a = ax::cast<ax::castable_a>(b); CHECK(a.i == 10); const ax::castable& c = ax::cast<ax::castable>(b); const ax::castable_a& a2 = ax::cast<ax::castable_a>(c); CHECK(a2.i == 10); const ax::castable_b& b2 = ax::cast<ax::castable_b>(c); CHECK(b2.i == 10); CHECK(b2.j == 20); } TEST("shared castable works") { std::shared_ptr<ax::castable_b> b = std::make_shared<ax::castable_b>(); b->i = 10; b->j = 20; std::shared_ptr<ax::castable_a> a = ax::cast<ax::castable_a>(b); CHECK(a->i == 10); std::shared_ptr<ax::castable> c = ax::cast<ax::castable>(b); std::shared_ptr<ax::castable_a> a2 = ax::cast<ax::castable_a>(c); CHECK(a2->i == 10); std::shared_ptr<ax::castable_b> b2 = cast<ax::castable_b>(c); CHECK(b2->i == 10); CHECK(b2->j == 20); } TEST("unique castable works") { std::unique_ptr<ax::castable_b> b = std::make_unique<ax::castable_b>(); b->i = 10; b->j = 20; std::unique_ptr<ax::castable_a> a = ax::cast<ax::castable_a>(std::move(b)); CHECK(a->i == 10); std::unique_ptr<ax::castable> c = ax::cast<ax::castable>(std::move(a)); std::unique_ptr<ax::castable_a> a2 = ax::cast<ax::castable_a>(std::move(c)); CHECK(a2->i == 10); std::unique_ptr<ax::castable_b> b2 = ax::cast<ax::castable_b>(std::move(a2)); CHECK(b2->i == 10); CHECK(b2->j == 20); } TEST("events work") { VAR i = 0; ax::eventable_test program; VAL& event_address = ax::address("event"); VAL participant = std::make_shared<ax::addressable>(ax::address("participant")); VAR handler = [&](VAL&, VAL&) { return ++i, true; }; VAR unsubscriber = program.subscribe_event<std::string>(event_address, participant, handler); program.publish_event("Event handled!"_s, event_address, participant); unsubscriber(program); program.publish_event("Event unhandled."_s, event_address, participant); CHECK(i == 1); } TEST("read and write value works") { ax::symbol symbol; ax::reflectable_test source( true, 5, 10.0f, "jim bob", ax::address("s/compton/la"), { 1, 3, 5 }, { "a", "bb", "ccc" }, 777, make_pair(50, 100), make_record(150, 200, 250), some(2), none<int>(), right<int, std::string>(4), left<int>("msg"_s), third<int, int, int>(3)); ax::reflectable_test target; ax::write_value(source, symbol); ax::read_value(symbol, target); CHECK(target.bool_value); CHECK(target.int_value == 5); CHECK(target.float_value == 10.0f); CHECK(target.name_value == "jim bob"); CHECK(target.address_value == ax::address("s/compton/la")); CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 })); CHECK(target.vector_string_value == std::vector<std::string>({ "a", "bb", "ccc" })); CHECK(*target.shared_int_value == 777); CHECK(target.pair_value.fst() == 50); CHECK(target.pair_value.snd() == 100); CHECK(target.record_value.fst() == 150); CHECK(target.record_value.snd() == 200); CHECK(target.record_value.thd() == 250); CHECK(*target.option_some_value == 2); CHECK(target.option_none_value.is_none()); CHECK(*target.either_right_value == 4); CHECK(~target.either_left_value == "msg"); CHECK(target.choice_value.get_third() == 3); } TEST("parser works") { VAL& str = "[true 5 10.0 \ \"jim bob\" \ \"s/compton/la\" \ [1 3 5] \ [\"a\" \"bb\" \"ccc\"] \ 777 \ [50 100] \ [150 200 250] \ [some 2] \ none \ [right 4] \ [left \"msg\"] \ [ third 3 ] ]"; // a little extra whitespace to try to throw off the parser VAL& parse = parse_symbol(str); VAL& symbol = parse.get_success(); ax::reflectable_test target; ax::read_value(symbol, target); CHECK(target.bool_value); CHECK(target.int_value == 5); CHECK(target.float_value == 10.0f); CHECK(target.name_value == "jim bob"); CHECK(target.address_value == ax::address("s/compton/la")); CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 })); CHECK(target.vector_string_value == std::vector<std::string>({ "a", "bb", "ccc" })); CHECK(*target.shared_int_value == 777); CHECK(target.pair_value.fst() == 50); CHECK(target.pair_value.snd() == 100); CHECK(target.record_value.fst() == 150); CHECK(target.record_value.snd() == 200); CHECK(target.record_value.thd() == 250); CHECK(*target.option_some_value == 2); CHECK(target.option_none_value.is_none()); CHECK(*target.either_right_value == 4); CHECK(~target.either_left_value == "msg"); CHECK(target.choice_value.get_third() == 3); } TEST("properties work") { ax::propertied p; p.attach("x", 0); CHECK(p.get<int>("x") == 0); p.set("x", 5); CHECK(p.get<int>("x") == 5); } TEST("misc") { std::cout << std::to_string(sizeof(std::string)) << std::endl; std::cout << std::to_string(sizeof(std::vector<std::size_t>)) << std::endl; std::cout << std::to_string(sizeof(ax::name)) << std::endl; std::cout << std::to_string(sizeof(ax::address)) << std::endl; std::cout << std::to_string(sizeof(ax::entity)) << std::endl; } TEST("main") { VAL width = 800; VAL height = 800; ax::tga_image image(width, height); ax::basic_obj_model model("../../../../data/model.obj"); for (VAR i = 0; i < model.nfaces(); i++) { VAL& face = model.face(i); for (VAR j = 0; j < 3; j++) { ax::v3 v0 = model.vert(face[j]); ax::v3 v1 = model.vert(face[(j + 1) % 3]); VAL x0 = static_cast<int>((v0.x + 1.0f) * width / 2.0f); VAL y0 = static_cast<int>((v0.y + 1.0f) * height / 2.0f); VAL x1 = static_cast<int>((v1.x + 1.0f) * width / 2.0f); VAL y1 = static_cast<int>((v1.y + 1.0f) * height / 2.0f); image.draw_line(x0, y0, x1, y1, ax::color(255, 255, 255, 255)); } } } } int main(int, char*[]) { ax::register_common_type_descriptors(); return tom::run_tests(); } <commit_msg>Wrote file.<commit_after>#include <iostream> #include "../../hpp/tom/tom.hpp" #include "../../hpp/ax/impl/ax.hpp" #include "../../hpp/ax/impl/system.hpp" #include "../../hpp/ax/impl/basic_obj_model.hpp" namespace ax { // A trivial type to demonstrate the castable type. class castable_a : public ax::castable { public: int i = 0; protected: ENABLE_CAST(ax::castable_a, ax::castable); }; // A trivial type to demonstrate the castable type. class castable_b : public ax::castable_a { public: int j = 0; protected: ENABLE_CAST(ax::castable_b, ax::castable_a); }; // A trivial program type to demonstrate the eventable program mixin. class eventable_test final : public ax::eventable<ax::eventable_test> { protected: ENABLE_CAST(ax::eventable_test, ax::eventable<ax::eventable_test>); }; class reflectable_test final : public ax::reflectable { protected: ENABLE_REFLECTION_CUSTOM(ax::reflectable_test, ax::reflectable); const std::shared_ptr<ax::type> type = register_sub_type<ax::reflectable_test>(typeid(ax::reflectable), { { "bool_value", register_field<bool> (offsetof(ax::reflectable_test, bool_value)) }, { "int_value", register_field<int> (offsetof(ax::reflectable_test, int_value)) }, { "float_value", register_field<float> (offsetof(ax::reflectable_test, float_value)) }, { "name_value", register_field<ax::name> (offsetof(ax::reflectable_test, name_value)) }, { "address_value", register_field<ax::address> (offsetof(ax::reflectable_test, address_value)) }, { "vector_int_value", register_field<std::vector<int>> (offsetof(ax::reflectable_test, vector_int_value)) }, { "vector_string_value", register_field<std::vector<std::string>> (offsetof(ax::reflectable_test, vector_string_value)) }, { "shared_int_value", register_field<std::shared_ptr<int>> (offsetof(ax::reflectable_test, shared_int_value)) }, { "pair_value", register_field<ax::pair<int, int>> (offsetof(ax::reflectable_test, pair_value)) }, { "record_value", register_field<ax::record<int, int, int>> (offsetof(ax::reflectable_test, record_value)) }, { "option_some_value", register_field<ax::option<int>> (offsetof(ax::reflectable_test, option_some_value)) }, { "option_none_value", register_field<ax::option<int>> (offsetof(ax::reflectable_test, option_none_value)) }, { "either_right_value", register_field<ax::either<int, std::string>> (offsetof(ax::reflectable_test, either_right_value)) }, { "either_left_value", register_field<ax::either<int, std::string>> (offsetof(ax::reflectable_test, either_left_value)) }, { "choice_value", register_field<ax::choice<int, int, int>> (offsetof(ax::reflectable_test, choice_value)) } }); std::shared_ptr<ax::type> get_type() const override { return type; }; public: int bool_value; int int_value; float float_value; ax::name name_value; ax::address address_value; std::vector<int> vector_int_value; std::vector<std::string> vector_string_value; std::shared_ptr<int> shared_int_value; ax::pair<int, int> pair_value; ax::record<int, int, int> record_value; ax::option<int> option_some_value; ax::option<int> option_none_value; ax::either<int, std::string> either_right_value; ax::either<int, std::string> either_left_value; ax::choice<int, int, int> choice_value; reflectable_test() : bool_value(), int_value(), float_value(), name_value(), address_value(), vector_int_value(), vector_string_value(), shared_int_value(std::make_shared<int>()), pair_value(), record_value(), option_some_value(), option_none_value(), either_right_value(), either_left_value(), choice_value() { } reflectable_test( bool bool_value, int int_value, float float_value, ax::name name_value, ax::address address_value, const std::vector<int>& vector_int_value, const std::vector<std::string>& vector_string_value, int shared_int_value, ax::pair<int, int> pair_value, ax::record<int, int, int> record_value, ax::option<int> option_some_value, ax::option<int> option_none_value, ax::either<int, std::string> either_right_value, ax::either<int, std::string> either_left_value, ax::choice<int, int, int> choice_value) : bool_value(bool_value), int_value(int_value), float_value(float_value), name_value(name_value), address_value(address_value), vector_int_value(vector_int_value), vector_string_value(vector_string_value), shared_int_value(std::make_shared<int>(shared_int_value)), pair_value(pair_value), record_value(record_value), option_some_value(option_some_value), option_none_value(option_none_value), either_right_value(either_right_value), either_left_value(either_left_value), choice_value(choice_value) { } }; TEST("hash works") { CHECK(ax::get_hash(0) == std::hash<int>()(0)); } TEST("castable works") { ax::castable_b b; b.i = 10; b.j = 20; const ax::castable_a& a = ax::cast<ax::castable_a>(b); CHECK(a.i == 10); const ax::castable& c = ax::cast<ax::castable>(b); const ax::castable_a& a2 = ax::cast<ax::castable_a>(c); CHECK(a2.i == 10); const ax::castable_b& b2 = ax::cast<ax::castable_b>(c); CHECK(b2.i == 10); CHECK(b2.j == 20); } TEST("shared castable works") { std::shared_ptr<ax::castable_b> b = std::make_shared<ax::castable_b>(); b->i = 10; b->j = 20; std::shared_ptr<ax::castable_a> a = ax::cast<ax::castable_a>(b); CHECK(a->i == 10); std::shared_ptr<ax::castable> c = ax::cast<ax::castable>(b); std::shared_ptr<ax::castable_a> a2 = ax::cast<ax::castable_a>(c); CHECK(a2->i == 10); std::shared_ptr<ax::castable_b> b2 = cast<ax::castable_b>(c); CHECK(b2->i == 10); CHECK(b2->j == 20); } TEST("unique castable works") { std::unique_ptr<ax::castable_b> b = std::make_unique<ax::castable_b>(); b->i = 10; b->j = 20; std::unique_ptr<ax::castable_a> a = ax::cast<ax::castable_a>(std::move(b)); CHECK(a->i == 10); std::unique_ptr<ax::castable> c = ax::cast<ax::castable>(std::move(a)); std::unique_ptr<ax::castable_a> a2 = ax::cast<ax::castable_a>(std::move(c)); CHECK(a2->i == 10); std::unique_ptr<ax::castable_b> b2 = ax::cast<ax::castable_b>(std::move(a2)); CHECK(b2->i == 10); CHECK(b2->j == 20); } TEST("events work") { VAR i = 0; ax::eventable_test program; VAL& event_address = ax::address("event"); VAL participant = std::make_shared<ax::addressable>(ax::address("participant")); VAR handler = [&](VAL&, VAL&) { return ++i, true; }; VAR unsubscriber = program.subscribe_event<std::string>(event_address, participant, handler); program.publish_event("Event handled!"_s, event_address, participant); unsubscriber(program); program.publish_event("Event unhandled."_s, event_address, participant); CHECK(i == 1); } TEST("read and write value works") { ax::symbol symbol; ax::reflectable_test source( true, 5, 10.0f, "jim bob", ax::address("s/compton/la"), { 1, 3, 5 }, { "a", "bb", "ccc" }, 777, make_pair(50, 100), make_record(150, 200, 250), some(2), none<int>(), right<int, std::string>(4), left<int>("msg"_s), third<int, int, int>(3)); ax::reflectable_test target; ax::write_value(source, symbol); ax::read_value(symbol, target); CHECK(target.bool_value); CHECK(target.int_value == 5); CHECK(target.float_value == 10.0f); CHECK(target.name_value == "jim bob"); CHECK(target.address_value == ax::address("s/compton/la")); CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 })); CHECK(target.vector_string_value == std::vector<std::string>({ "a", "bb", "ccc" })); CHECK(*target.shared_int_value == 777); CHECK(target.pair_value.fst() == 50); CHECK(target.pair_value.snd() == 100); CHECK(target.record_value.fst() == 150); CHECK(target.record_value.snd() == 200); CHECK(target.record_value.thd() == 250); CHECK(*target.option_some_value == 2); CHECK(target.option_none_value.is_none()); CHECK(*target.either_right_value == 4); CHECK(~target.either_left_value == "msg"); CHECK(target.choice_value.get_third() == 3); } TEST("parser works") { VAL& str = "[true 5 10.0 \ \"jim bob\" \ \"s/compton/la\" \ [1 3 5] \ [\"a\" \"bb\" \"ccc\"] \ 777 \ [50 100] \ [150 200 250] \ [some 2] \ none \ [right 4] \ [left \"msg\"] \ [ third 3 ] ]"; // a little extra whitespace to try to throw off the parser VAL& parse = parse_symbol(str); VAL& symbol = parse.get_success(); ax::reflectable_test target; ax::read_value(symbol, target); CHECK(target.bool_value); CHECK(target.int_value == 5); CHECK(target.float_value == 10.0f); CHECK(target.name_value == "jim bob"); CHECK(target.address_value == ax::address("s/compton/la")); CHECK(target.vector_int_value == std::vector<int>({ 1, 3, 5 })); CHECK(target.vector_string_value == std::vector<std::string>({ "a", "bb", "ccc" })); CHECK(*target.shared_int_value == 777); CHECK(target.pair_value.fst() == 50); CHECK(target.pair_value.snd() == 100); CHECK(target.record_value.fst() == 150); CHECK(target.record_value.snd() == 200); CHECK(target.record_value.thd() == 250); CHECK(*target.option_some_value == 2); CHECK(target.option_none_value.is_none()); CHECK(*target.either_right_value == 4); CHECK(~target.either_left_value == "msg"); CHECK(target.choice_value.get_third() == 3); } TEST("properties work") { ax::propertied p; p.attach("x", 0); CHECK(p.get<int>("x") == 0); p.set("x", 5); CHECK(p.get<int>("x") == 5); } TEST("misc") { std::cout << std::to_string(sizeof(std::string)) << std::endl; std::cout << std::to_string(sizeof(std::vector<std::size_t>)) << std::endl; std::cout << std::to_string(sizeof(ax::name)) << std::endl; std::cout << std::to_string(sizeof(ax::address)) << std::endl; std::cout << std::to_string(sizeof(ax::entity)) << std::endl; } TEST("main") { VAL width = 800; VAL height = 800; ax::tga_image image(width, height); ax::basic_obj_model model("../../../../data/model.obj"); for (VAR i = 0; i < model.nfaces(); i++) { VAL& face = model.face(i); for (VAR j = 0; j < 3; j++) { ax::v3 v0 = model.vert(face[j]); ax::v3 v1 = model.vert(face[(j + 1) % 3]); VAL x0 = static_cast<int>((v0.x + 1.0f) * width / 2.0f); VAL y0 = static_cast<int>((v0.y + 1.0f) * height / 2.0f); VAL x1 = static_cast<int>((v1.x + 1.0f) * width / 2.0f); VAL y1 = static_cast<int>((v1.y + 1.0f) * height / 2.0f); image.draw_line(x0, y0, x1, y1, ax::color(255, 255, 255, 255)); } } image.write_tga_file("../../../../data/image.tga"); } } int main(int, char*[]) { ax::register_common_type_descriptors(); return tom::run_tests(); } <|endoftext|>
<commit_before>#include "cmdline.hpp" #include <boost/lexical_cast.hpp> #include <boost/filesystem/operations.hpp> #include "State.hpp" #include "svc/LuaVm.hpp" #include "svc/FileSystem.hpp" #include "svc/ServiceLocator.hpp" #include "svc/Mainloop.hpp" #include "svc/DrawService.hpp" #include "svc/EventDispatcher.hpp" #include "svc/Configuration.hpp" #include "svc/StateManager.hpp" #include "svc/Timer.hpp" #include "svc/SoundManager.hpp" #include <SFML/Graphics/RenderWindow.hpp> #include <luabind/function.hpp> // call_function (used @ loadStateFromLua) #include <boost/bind.hpp> #include "Logfile.hpp" #include <physfs.h> #include "base64.hpp" #include "LuaUtils.hpp" #include <array> #include <luabind/adopt_policy.hpp> #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # define NOMINMAX # include <Windows.h> # endif #if defined(BOOST_MSVC) && defined(_DEBUG) && defined(JD_HAS_VLD) # include <vld.h> #endif namespace { static std::vector<std::string> cmdLine; static int argc_ = 0; static const char* const* argv_ = nullptr; template<typename T> struct ServiceEntry: public T { ServiceEntry() { ServiceLocator::registerService(*this); } }; static State* loadStateFromLua(std::string const& name) { std::string const filename = "lua/states/" + name + ".lua"; if (!PHYSFS_exists(filename.c_str())) return nullptr; LOG_D("Loading state \"" + name + "\"..."); State* s = nullptr; try { lua_State* L = ServiceLocator::luaVm().L(); luaU::load(ServiceLocator::luaVm().L(), filename); luabind::object chunk(luabind::from_stack(L, -1)); lua_pop(L, 1); // The state must stay alive as long as the StateManager. // However, if we simply use luabind::adopt here, we cause a memory // leak. So, instead we bind the lifetime of the state to the one // from the lua_State (== LuaVm in this case). As long as the LuaVm is // destroyed (shortly) *after* the StateManager it just works. // Otherwise, we would have a real problem: how could you possibly keep // a Lua object alive, longer than it's lua_State? luabind::object sobj = chunk(); s = luabind::object_cast<State*>(sobj); sobj.push(L); luaL_ref(L, LUA_REGISTRYINDEX); } catch (luabind::cast_failed const& e) { LOG_E("failed casting lua value to " + std::string(e.info().name())); } catch (luabind::error const& e) { LOG_E(luaU::Error(e, "failed loading state \"" + name + '\"').what()); } catch (std::exception const& e) { LOG_EX(e); } log().write( "Loading State " + name + (s ? " finished." : " failed."), s ? loglevel::debug : loglevel::error, LOGFILE_LOCATION); return s; } } // anonymous namespace int argc() { return argc_; } const char* const* argv() { return argv_; } std::vector<std::string> const& commandLine() { return cmdLine; } int main(int argc, char* argv[]) { // First thing to do: get the logfile opened. // Create directory for log file namespace fs = boost::filesystem; # ifdef _WIN32 fs::path const basepath(std::string(getenv("APPDATA")) + "/JadeEngine/"); # else fs::path const basepath("~/.jade/"); #endif fs::create_directories(basepath); int r = EXIT_FAILURE; try { // Open the logfile log().setMinLevel(loglevel::debug); log().open((basepath / "jd.log").string()); #ifndef NDEBUG LOG_I("This is a debug build."); #endif LOG_D("Initialization..."); // setup commandline functions // argc_ = argc; argv_ = argv; cmdLine.assign(argv, argv + argc); // Construct and register services // auto const regSvc = ServiceLocator::registerService; LOG_D("Initializing virtual filesystem..."); FileSystem::Init fsinit; regSvc(FileSystem::get()); fs::path datapath(basepath / "data"); fs::create_directories(datapath); if (!PHYSFS_setWriteDir(datapath.string().c_str())) throw FileSystem::Error("failed setting write directory"); LOG_D("Finished initializing virtual filesystem."); LOG_D("Initializing Lua..."); ServiceEntry<LuaVm> luaVm; try { luaVm.initLibs(); LOG_D("Finished initializing Lua."); ServiceEntry<Mainloop> mainloop; ServiceEntry<Configuration> conf; ServiceEntry<Timer> timer; ServiceEntry<SoundManager> sound; // Create the RenderWindow now, because some services depend on it. LOG_D("Preparing window and SFML..."); sf::RenderWindow window; LOG_D("Finished preparing window and SFML."); ServiceEntry<StateManager> stateManager; EventDispatcher eventDispatcher(window); regSvc(eventDispatcher); using boost::bind; mainloop.connect_processInput( bind(&EventDispatcher::dispatch, &eventDispatcher)); // Various other initializations // ServiceLocator::stateManager().setStateNotFoundCallback(&loadStateFromLua); LOG_D("Loading configuration..."); conf.load(); LOG_D("Finished loading configuration."); DrawService drawService(window, conf.get<std::size_t>("misc.layerCount", 1UL)); regSvc(drawService); mainloop.connect_preFrame(bind(&Timer::beginFrame, &timer)); mainloop.connect_update(bind(&Timer::processCallbacks, &timer)); mainloop.connect_update(bind(&SoundManager::fade, &sound)); mainloop.connect_preDraw(bind(&DrawService::clear, &drawService)); mainloop.connect_draw(bind(&DrawService::draw, &drawService)); mainloop.connect_postDraw(bind(&DrawService::display, &drawService)); mainloop.connect_postFrame(bind(&Timer::endFrame, &timer)); timer.callEvery(sf::seconds(10), bind(&SoundManager::tidy, &sound)); LOG_D("Creating window..."); std::string const title = conf.get<std::string>("misc.title", "Jade"); window.create( conf.get("video.mode", sf::VideoMode(800, 600)), title, conf.get("video.fullscreen", false) ? sf::Style::Close | sf::Style::Fullscreen : sf::Style::Default); window.setVerticalSyncEnabled(conf.get("video.vsync", true)); window.setFramerateLimit(conf.get("video.framelimit", 0U)); window.setKeyRepeatEnabled(false); LOG_D("Finished creating window."); drawService.resetLayerViews(); timer.callEvery(sf::milliseconds(600), [&timer, &window, &title]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); window.setTitle(title + " [" + fps + " fps]"); }); timer.callEvery(sf::seconds(60), [&timer]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); LOG_D("Current framerate (fps): " + fps); }); // Execute init.lua // # define INIT_LUA "lua/init.lua" LOG_D("Executing \"" INIT_LUA "\"..."); luaU::exec(luaVm.L(), INIT_LUA); LOG_D("Finished executing \"" INIT_LUA "\"."); # undef INIT_LUA LOG_D("Finished initialization."); // Run mainloop // LOG_D("Mainloop..."); r = ServiceLocator::mainloop().exec(); LOG_D("Mainloop finished with exit code " + boost::lexical_cast<std::string>(r) + "."); LOG_D("Cleanup..."); stateManager.clear(); luaVm.deinit(); } catch (luabind::error const& e) { throw luaU::Error(e); } catch (luabind::cast_failed const& e) { throw luaU::Error(e.what() + std::string("; type: ") + e.info().name()); } // In case of an exception, log it and notify the user // } catch (std::exception const& e) { log().logEx(e, loglevel::fatal, LOGFILE_LOCATION); # ifdef _WIN32 MessageBoxA(NULL, e.what(), "Jade Engine", MB_ICONERROR | MB_TASKMODAL); # else std::cerr << "Exception: " << e.what(); # endif return EXIT_FAILURE; } LOG_D("Cleanup finished."); return r; } <commit_msg>main: Mount write directory.<commit_after>#include "cmdline.hpp" #include <boost/lexical_cast.hpp> #include <boost/filesystem/operations.hpp> #include "State.hpp" #include "svc/LuaVm.hpp" #include "svc/FileSystem.hpp" #include "svc/ServiceLocator.hpp" #include "svc/Mainloop.hpp" #include "svc/DrawService.hpp" #include "svc/EventDispatcher.hpp" #include "svc/Configuration.hpp" #include "svc/StateManager.hpp" #include "svc/Timer.hpp" #include "svc/SoundManager.hpp" #include <SFML/Graphics/RenderWindow.hpp> #include <luabind/function.hpp> // call_function (used @ loadStateFromLua) #include <boost/bind.hpp> #include "Logfile.hpp" #include <physfs.h> #include "base64.hpp" #include "LuaUtils.hpp" #include <array> #include <luabind/adopt_policy.hpp> #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # define NOMINMAX # include <Windows.h> # endif #if defined(BOOST_MSVC) && defined(_DEBUG) && defined(JD_HAS_VLD) # include <vld.h> #endif namespace { static std::vector<std::string> cmdLine; static int argc_ = 0; static const char* const* argv_ = nullptr; template<typename T> struct ServiceEntry: public T { ServiceEntry() { ServiceLocator::registerService(*this); } }; static State* loadStateFromLua(std::string const& name) { std::string const filename = "lua/states/" + name + ".lua"; if (!PHYSFS_exists(filename.c_str())) return nullptr; LOG_D("Loading state \"" + name + "\"..."); State* s = nullptr; try { lua_State* L = ServiceLocator::luaVm().L(); luaU::load(ServiceLocator::luaVm().L(), filename); luabind::object chunk(luabind::from_stack(L, -1)); lua_pop(L, 1); // The state must stay alive as long as the StateManager. // However, if we simply use luabind::adopt here, we cause a memory // leak. So, instead we bind the lifetime of the state to the one // from the lua_State (== LuaVm in this case). As long as the LuaVm is // destroyed (shortly) *after* the StateManager it just works. // Otherwise, we would have a real problem: how could you possibly keep // a Lua object alive, longer than it's lua_State? luabind::object sobj = chunk(); s = luabind::object_cast<State*>(sobj); sobj.push(L); luaL_ref(L, LUA_REGISTRYINDEX); } catch (luabind::cast_failed const& e) { LOG_E("failed casting lua value to " + std::string(e.info().name())); } catch (luabind::error const& e) { LOG_E(luaU::Error(e, "failed loading state \"" + name + '\"').what()); } catch (std::exception const& e) { LOG_EX(e); } log().write( "Loading State " + name + (s ? " finished." : " failed."), s ? loglevel::debug : loglevel::error, LOGFILE_LOCATION); return s; } } // anonymous namespace int argc() { return argc_; } const char* const* argv() { return argv_; } std::vector<std::string> const& commandLine() { return cmdLine; } int main(int argc, char* argv[]) { // First thing to do: get the logfile opened. // Create directory for log file namespace fs = boost::filesystem; # ifdef _WIN32 fs::path const basepath(std::string(getenv("APPDATA")) + "/JadeEngine/"); # else fs::path const basepath("~/.jade/"); #endif fs::create_directories(basepath); int r = EXIT_FAILURE; try { // Open the logfile log().setMinLevel(loglevel::debug); log().open((basepath / "jd.log").string()); #ifndef NDEBUG LOG_I("This is a debug build."); #endif LOG_D("Initialization..."); // setup commandline functions // argc_ = argc; argv_ = argv; cmdLine.assign(argv, argv + argc); // Construct and register services // auto const regSvc = ServiceLocator::registerService; LOG_D("Initializing virtual filesystem..."); FileSystem::Init fsinit; regSvc(FileSystem::get()); fs::path datapath(basepath / "data"); fs::create_directories(datapath); if (!PHYSFS_setWriteDir(datapath.string().c_str())) throw FileSystem::Error("failed setting write directory"); if (!PHYSFS_mount(PHYSFS_getWriteDir(), nullptr, false /* prepend to path */)) throw FileSystem::Error("failed mounting write directory"); LOG_D("Finished initializing virtual filesystem."); LOG_D("Initializing Lua..."); ServiceEntry<LuaVm> luaVm; try { luaVm.initLibs(); LOG_D("Finished initializing Lua."); ServiceEntry<Mainloop> mainloop; ServiceEntry<Configuration> conf; ServiceEntry<Timer> timer; ServiceEntry<SoundManager> sound; // Create the RenderWindow now, because some services depend on it. LOG_D("Preparing window and SFML..."); sf::RenderWindow window; LOG_D("Finished preparing window and SFML."); ServiceEntry<StateManager> stateManager; EventDispatcher eventDispatcher(window); regSvc(eventDispatcher); using boost::bind; mainloop.connect_processInput( bind(&EventDispatcher::dispatch, &eventDispatcher)); // Various other initializations // ServiceLocator::stateManager().setStateNotFoundCallback(&loadStateFromLua); LOG_D("Loading configuration..."); conf.load(); LOG_D("Finished loading configuration."); DrawService drawService(window, conf.get<std::size_t>("misc.layerCount", 1UL)); regSvc(drawService); mainloop.connect_preFrame(bind(&Timer::beginFrame, &timer)); mainloop.connect_update(bind(&Timer::processCallbacks, &timer)); mainloop.connect_update(bind(&SoundManager::fade, &sound)); mainloop.connect_preDraw(bind(&DrawService::clear, &drawService)); mainloop.connect_draw(bind(&DrawService::draw, &drawService)); mainloop.connect_postDraw(bind(&DrawService::display, &drawService)); mainloop.connect_postFrame(bind(&Timer::endFrame, &timer)); timer.callEvery(sf::seconds(10), bind(&SoundManager::tidy, &sound)); LOG_D("Creating window..."); std::string const title = conf.get<std::string>("misc.title", "Jade"); window.create( conf.get("video.mode", sf::VideoMode(800, 600)), title, conf.get("video.fullscreen", false) ? sf::Style::Close | sf::Style::Fullscreen : sf::Style::Default); window.setVerticalSyncEnabled(conf.get("video.vsync", true)); window.setFramerateLimit(conf.get("video.framelimit", 0U)); window.setKeyRepeatEnabled(false); LOG_D("Finished creating window."); drawService.resetLayerViews(); timer.callEvery(sf::milliseconds(600), [&timer, &window, &title]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); window.setTitle(title + " [" + fps + " fps]"); }); timer.callEvery(sf::seconds(60), [&timer]() { std::string const fps = boost::lexical_cast<std::string>( 1.f / timer.frameDuration().asSeconds()); LOG_D("Current framerate (fps): " + fps); }); // Execute init.lua // # define INIT_LUA "lua/init.lua" LOG_D("Executing \"" INIT_LUA "\"..."); luaU::exec(luaVm.L(), INIT_LUA); LOG_D("Finished executing \"" INIT_LUA "\"."); # undef INIT_LUA LOG_D("Finished initialization."); // Run mainloop // LOG_D("Mainloop..."); r = ServiceLocator::mainloop().exec(); LOG_D("Mainloop finished with exit code " + boost::lexical_cast<std::string>(r) + "."); LOG_D("Cleanup..."); stateManager.clear(); luaVm.deinit(); } catch (luabind::error const& e) { throw luaU::Error(e); } catch (luabind::cast_failed const& e) { throw luaU::Error(e.what() + std::string("; type: ") + e.info().name()); } // In case of an exception, log it and notify the user // } catch (std::exception const& e) { log().logEx(e, loglevel::fatal, LOGFILE_LOCATION); # ifdef _WIN32 MessageBoxA(NULL, e.what(), "Jade Engine", MB_ICONERROR | MB_TASKMODAL); # else std::cerr << "Exception: " << e.what(); # endif return EXIT_FAILURE; } LOG_D("Cleanup finished."); return r; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Anthony Gutierrez */ /* @file * Implementation of a bi-mode branch predictor */ #include "cpu/pred/bi_mode.hh" #include "base/bitfield.hh" #include "base/intmath.hh" BiModeBP::BiModeBP(const BiModeBPParams *params) : BPredUnit(params), globalHistoryReg(params->numThreads, 0), globalHistoryBits(ceilLog2(params->globalPredictorSize)), choicePredictorSize(params->choicePredictorSize), choiceCtrBits(params->choiceCtrBits), globalPredictorSize(params->globalPredictorSize), globalCtrBits(params->globalCtrBits) { if (!isPowerOf2(choicePredictorSize)) fatal("Invalid choice predictor size.\n"); if (!isPowerOf2(globalPredictorSize)) fatal("Invalid global history predictor size.\n"); choiceCounters.resize(choicePredictorSize); takenCounters.resize(globalPredictorSize); notTakenCounters.resize(globalPredictorSize); for (int i = 0; i < choicePredictorSize; ++i) { choiceCounters[i].setBits(choiceCtrBits); } for (int i = 0; i < globalPredictorSize; ++i) { takenCounters[i].setBits(globalCtrBits); notTakenCounters[i].setBits(globalCtrBits); } historyRegisterMask = mask(globalHistoryBits); choiceHistoryMask = choicePredictorSize - 1; globalHistoryMask = globalPredictorSize - 1; choiceThreshold = (ULL(1) << (choiceCtrBits - 1)) - 1; takenThreshold = (ULL(1) << (choiceCtrBits - 1)) - 1; notTakenThreshold = (ULL(1) << (choiceCtrBits - 1)) - 1; } /* * For an unconditional branch we set its history such that * everything is set to taken. I.e., its choice predictor * chooses the taken array and the taken array predicts taken. */ void BiModeBP::uncondBranch(ThreadID tid, Addr pc, void * &bpHistory) { BPHistory *history = new BPHistory; history->globalHistoryReg = globalHistoryReg[tid]; history->takenUsed = true; history->takenPred = true; history->notTakenPred = true; history->finalPred = true; bpHistory = static_cast<void*>(history); updateGlobalHistReg(tid, true); } void BiModeBP::squash(ThreadID tid, void *bpHistory) { BPHistory *history = static_cast<BPHistory*>(bpHistory); globalHistoryReg[tid] = history->globalHistoryReg; delete history; } /* * Here we lookup the actual branch prediction. We use the PC to * identify the bias of a particular branch, which is based on the * prediction in the choice array. A hash of the global history * register and a branch's PC is used to index into both the taken * and not-taken predictors, which both present a prediction. The * choice array's prediction is used to select between the two * direction predictors for the final branch prediction. */ bool BiModeBP::lookup(ThreadID tid, Addr branchAddr, void * &bpHistory) { unsigned choiceHistoryIdx = ((branchAddr >> instShiftAmt) & choiceHistoryMask); unsigned globalHistoryIdx = (((branchAddr >> instShiftAmt) ^ globalHistoryReg[tid]) & globalHistoryMask); assert(choiceHistoryIdx < choicePredictorSize); assert(globalHistoryIdx < globalPredictorSize); bool choicePrediction = choiceCounters[choiceHistoryIdx].read() > choiceThreshold; bool takenGHBPrediction = takenCounters[globalHistoryIdx].read() > takenThreshold; bool notTakenGHBPrediction = notTakenCounters[globalHistoryIdx].read() > notTakenThreshold; bool finalPrediction; BPHistory *history = new BPHistory; history->globalHistoryReg = globalHistoryReg[tid]; history->takenUsed = choicePrediction; history->takenPred = takenGHBPrediction; history->notTakenPred = notTakenGHBPrediction; if (choicePrediction) { finalPrediction = takenGHBPrediction; } else { finalPrediction = notTakenGHBPrediction; } history->finalPred = finalPrediction; bpHistory = static_cast<void*>(history); updateGlobalHistReg(tid, finalPrediction); return finalPrediction; } void BiModeBP::btbUpdate(ThreadID tid, Addr branchAddr, void * &bpHistory) { globalHistoryReg[tid] &= (historyRegisterMask & ~ULL(1)); } /* Only the selected direction predictor will be updated with the final * outcome; the status of the unselected one will not be altered. The choice * predictor is always updated with the branch outcome, except when the * choice is opposite to the branch outcome but the selected counter of * the direction predictors makes a correct final prediction. */ void BiModeBP::update(ThreadID tid, Addr branchAddr, bool taken, void *bpHistory, bool squashed) { assert(bpHistory); BPHistory *history = static_cast<BPHistory*>(bpHistory); // We do not update the counters speculatively on a squash. // We just restore the global history register. if (squashed) { globalHistoryReg[tid] = (history->globalHistoryReg << 1) | taken; return; } unsigned choiceHistoryIdx = ((branchAddr >> instShiftAmt) & choiceHistoryMask); unsigned globalHistoryIdx = (((branchAddr >> instShiftAmt) ^ history->globalHistoryReg) & globalHistoryMask); assert(choiceHistoryIdx < choicePredictorSize); assert(globalHistoryIdx < globalPredictorSize); if (history->takenUsed) { // if the taken array's prediction was used, update it if (taken) { takenCounters[globalHistoryIdx].increment(); } else { takenCounters[globalHistoryIdx].decrement(); } } else { // if the not-taken array's prediction was used, update it if (taken) { notTakenCounters[globalHistoryIdx].increment(); } else { notTakenCounters[globalHistoryIdx].decrement(); } } if (history->finalPred == taken) { /* If the final prediction matches the actual branch's * outcome and the choice predictor matches the final * outcome, we update the choice predictor, otherwise it * is not updated. While the designers of the bi-mode * predictor don't explicity say why this is done, one * can infer that it is to preserve the choice predictor's * bias with respect to the branch being predicted; afterall, * the whole point of the bi-mode predictor is to identify the * atypical case when a branch deviates from its bias. */ if (history->finalPred == history->takenUsed) { if (taken) { choiceCounters[choiceHistoryIdx].increment(); } else { choiceCounters[choiceHistoryIdx].decrement(); } } } else { // always update the choice predictor on an incorrect prediction if (taken) { choiceCounters[choiceHistoryIdx].increment(); } else { choiceCounters[choiceHistoryIdx].decrement(); } } delete history; } unsigned BiModeBP::getGHR(ThreadID tid, void *bp_history) const { return static_cast<BPHistory*>(bp_history)->globalHistoryReg; } void BiModeBP::updateGlobalHistReg(ThreadID tid, bool taken) { globalHistoryReg[tid] = taken ? (globalHistoryReg[tid] << 1) | 1 : (globalHistoryReg[tid] << 1); globalHistoryReg[tid] &= historyRegisterMask; } BiModeBP* BiModeBPParams::create() { return new BiModeBP(this); } <commit_msg>cpu: Fix bi-mode branch predictor thresholds<commit_after>/* * Copyright (c) 2014 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Anthony Gutierrez */ /* @file * Implementation of a bi-mode branch predictor */ #include "cpu/pred/bi_mode.hh" #include "base/bitfield.hh" #include "base/intmath.hh" BiModeBP::BiModeBP(const BiModeBPParams *params) : BPredUnit(params), globalHistoryReg(params->numThreads, 0), globalHistoryBits(ceilLog2(params->globalPredictorSize)), choicePredictorSize(params->choicePredictorSize), choiceCtrBits(params->choiceCtrBits), globalPredictorSize(params->globalPredictorSize), globalCtrBits(params->globalCtrBits) { if (!isPowerOf2(choicePredictorSize)) fatal("Invalid choice predictor size.\n"); if (!isPowerOf2(globalPredictorSize)) fatal("Invalid global history predictor size.\n"); choiceCounters.resize(choicePredictorSize); takenCounters.resize(globalPredictorSize); notTakenCounters.resize(globalPredictorSize); for (int i = 0; i < choicePredictorSize; ++i) { choiceCounters[i].setBits(choiceCtrBits); } for (int i = 0; i < globalPredictorSize; ++i) { takenCounters[i].setBits(globalCtrBits); notTakenCounters[i].setBits(globalCtrBits); } historyRegisterMask = mask(globalHistoryBits); choiceHistoryMask = choicePredictorSize - 1; globalHistoryMask = globalPredictorSize - 1; choiceThreshold = (ULL(1) << (choiceCtrBits - 1)) - 1; takenThreshold = (ULL(1) << (globalCtrBits - 1)) - 1; notTakenThreshold = (ULL(1) << (globalCtrBits - 1)) - 1; } /* * For an unconditional branch we set its history such that * everything is set to taken. I.e., its choice predictor * chooses the taken array and the taken array predicts taken. */ void BiModeBP::uncondBranch(ThreadID tid, Addr pc, void * &bpHistory) { BPHistory *history = new BPHistory; history->globalHistoryReg = globalHistoryReg[tid]; history->takenUsed = true; history->takenPred = true; history->notTakenPred = true; history->finalPred = true; bpHistory = static_cast<void*>(history); updateGlobalHistReg(tid, true); } void BiModeBP::squash(ThreadID tid, void *bpHistory) { BPHistory *history = static_cast<BPHistory*>(bpHistory); globalHistoryReg[tid] = history->globalHistoryReg; delete history; } /* * Here we lookup the actual branch prediction. We use the PC to * identify the bias of a particular branch, which is based on the * prediction in the choice array. A hash of the global history * register and a branch's PC is used to index into both the taken * and not-taken predictors, which both present a prediction. The * choice array's prediction is used to select between the two * direction predictors for the final branch prediction. */ bool BiModeBP::lookup(ThreadID tid, Addr branchAddr, void * &bpHistory) { unsigned choiceHistoryIdx = ((branchAddr >> instShiftAmt) & choiceHistoryMask); unsigned globalHistoryIdx = (((branchAddr >> instShiftAmt) ^ globalHistoryReg[tid]) & globalHistoryMask); assert(choiceHistoryIdx < choicePredictorSize); assert(globalHistoryIdx < globalPredictorSize); bool choicePrediction = choiceCounters[choiceHistoryIdx].read() > choiceThreshold; bool takenGHBPrediction = takenCounters[globalHistoryIdx].read() > takenThreshold; bool notTakenGHBPrediction = notTakenCounters[globalHistoryIdx].read() > notTakenThreshold; bool finalPrediction; BPHistory *history = new BPHistory; history->globalHistoryReg = globalHistoryReg[tid]; history->takenUsed = choicePrediction; history->takenPred = takenGHBPrediction; history->notTakenPred = notTakenGHBPrediction; if (choicePrediction) { finalPrediction = takenGHBPrediction; } else { finalPrediction = notTakenGHBPrediction; } history->finalPred = finalPrediction; bpHistory = static_cast<void*>(history); updateGlobalHistReg(tid, finalPrediction); return finalPrediction; } void BiModeBP::btbUpdate(ThreadID tid, Addr branchAddr, void * &bpHistory) { globalHistoryReg[tid] &= (historyRegisterMask & ~ULL(1)); } /* Only the selected direction predictor will be updated with the final * outcome; the status of the unselected one will not be altered. The choice * predictor is always updated with the branch outcome, except when the * choice is opposite to the branch outcome but the selected counter of * the direction predictors makes a correct final prediction. */ void BiModeBP::update(ThreadID tid, Addr branchAddr, bool taken, void *bpHistory, bool squashed) { assert(bpHistory); BPHistory *history = static_cast<BPHistory*>(bpHistory); // We do not update the counters speculatively on a squash. // We just restore the global history register. if (squashed) { globalHistoryReg[tid] = (history->globalHistoryReg << 1) | taken; return; } unsigned choiceHistoryIdx = ((branchAddr >> instShiftAmt) & choiceHistoryMask); unsigned globalHistoryIdx = (((branchAddr >> instShiftAmt) ^ history->globalHistoryReg) & globalHistoryMask); assert(choiceHistoryIdx < choicePredictorSize); assert(globalHistoryIdx < globalPredictorSize); if (history->takenUsed) { // if the taken array's prediction was used, update it if (taken) { takenCounters[globalHistoryIdx].increment(); } else { takenCounters[globalHistoryIdx].decrement(); } } else { // if the not-taken array's prediction was used, update it if (taken) { notTakenCounters[globalHistoryIdx].increment(); } else { notTakenCounters[globalHistoryIdx].decrement(); } } if (history->finalPred == taken) { /* If the final prediction matches the actual branch's * outcome and the choice predictor matches the final * outcome, we update the choice predictor, otherwise it * is not updated. While the designers of the bi-mode * predictor don't explicity say why this is done, one * can infer that it is to preserve the choice predictor's * bias with respect to the branch being predicted; afterall, * the whole point of the bi-mode predictor is to identify the * atypical case when a branch deviates from its bias. */ if (history->finalPred == history->takenUsed) { if (taken) { choiceCounters[choiceHistoryIdx].increment(); } else { choiceCounters[choiceHistoryIdx].decrement(); } } } else { // always update the choice predictor on an incorrect prediction if (taken) { choiceCounters[choiceHistoryIdx].increment(); } else { choiceCounters[choiceHistoryIdx].decrement(); } } delete history; } unsigned BiModeBP::getGHR(ThreadID tid, void *bp_history) const { return static_cast<BPHistory*>(bp_history)->globalHistoryReg; } void BiModeBP::updateGlobalHistReg(ThreadID tid, bool taken) { globalHistoryReg[tid] = taken ? (globalHistoryReg[tid] << 1) | 1 : (globalHistoryReg[tid] << 1); globalHistoryReg[tid] &= historyRegisterMask; } BiModeBP* BiModeBPParams::create() { return new BiModeBP(this); } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <cstdio> const int SCREEN_WIDTH = 311; const int SCREEN_HEIGHT = 308; const int BUTTON_WIDTH = 94; const int BUTTON_HEIGHT = 94; const int BAR_SIZE = 4; const int COMP = 4; #define GRID_SIZE 3 int pressedPosition; int posX, posY; //Posições da matriz que representa o grid int gridMat[GRID_SIZE][GRID_SIZE]; int player; int winner; int ocupados; SDL_Surface *grid = NULL; SDL_Surface *xImage = NULL; SDL_Surface *oImage = NULL; SDL_Surface *screen = NULL; SDL_Surface *newGame = NULL; SDL_Window *window = NULL; SDL_Rect gridRect[9]; SDL_Event event; bool InitWindow(){ if (SDL_INIT_VIDEO < 0){ printf("Erro ao inicializar o vídeo!\n"); return 0; } else{ window = SDL_CreateWindow("TIC-TAC-TOE", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL){ printf("Erro ao inicializar a janela\n"); return 0; } else{ screen = SDL_GetWindowSurface(window); } } int imgFlags = IMG_INIT_PNG; if(!(IMG_Init(imgFlags) & imgFlags)){ printf("Erro. Não foi possível inicializar SDL_image!\n%s\n", IMG_GetError()); return 0; } if ((grid = IMG_Load("../img/grid.png")) == NULL){ printf("Erro ao carregar o background\n"); return 0; } if ((xImage = IMG_Load("../img/x.png")) == NULL){ printf("Erro %s\n", SDL_GetError()); return 0; } if ((oImage = IMG_Load("../img/o.png")) == NULL){ printf("Erro %s\n", SDL_GetError()); return 0; } if ((newGame = IMG_Load("../img/new_game.png")) == NULL){ printf("Erro %s\n", SDL_GetError()); return 0; } return 1; } bool newGameScreen(){ //TODO //O "new game" deve funcionar como um botão, e não fazer parte do background while(1){ SDL_BlitSurface(newGame, NULL, screen, NULL); SDL_UpdateWindowSurface(window); SDL_PollEvent(&event) != 0; if(event.type == SDL_MOUSEBUTTONDOWN){ int x, y; SDL_GetMouseState(&x, &y); if(((x >= 80) && (x <= 220)) && ((y >= 210) && (y <= 225))){ return 0; }else if(((x >= 115) && (x <= 170)) && ((y >= 250) && (y <= 265))){ return 1; } } } } void SetGridRect(){ gridRect[0].x = gridRect[0].y = COMP; gridRect[0].w = BUTTON_WIDTH; gridRect[0].h = BUTTON_HEIGHT; gridRect[1].x = BUTTON_WIDTH + COMP*3 + BAR_SIZE; gridRect[1].y = COMP; gridRect[1].w = BUTTON_WIDTH; gridRect[1].h = BUTTON_HEIGHT; gridRect[2].x = gridRect[1].x * 2 - COMP; gridRect[2].y = COMP; gridRect[2].w = BUTTON_WIDTH; gridRect[2].h = BUTTON_HEIGHT; gridRect[3].x = COMP; gridRect[3].y = BUTTON_WIDTH + BAR_SIZE + COMP*3; gridRect[3].w = BUTTON_WIDTH; gridRect[3].h = BUTTON_HEIGHT; gridRect[4].x = gridRect[1].x; gridRect[4].y = BUTTON_WIDTH + BAR_SIZE + COMP * 3; gridRect[4].w = BUTTON_WIDTH; gridRect[4].h = BUTTON_HEIGHT; gridRect[5].x = gridRect[2].x; gridRect[5].y = BUTTON_WIDTH + BAR_SIZE + COMP * 3; gridRect[5].w = BUTTON_WIDTH; gridRect[5].h = BUTTON_HEIGHT; gridRect[6].x = COMP; gridRect[6].y = BUTTON_WIDTH * 2 + BAR_SIZE * 2 + COMP * 5; gridRect[6].w = BUTTON_WIDTH; gridRect[6].h = BUTTON_HEIGHT; gridRect[7].x = gridRect[1].x; gridRect[7].y = BUTTON_WIDTH * 2 + BAR_SIZE * 2 + COMP * 5; gridRect[7].w = BUTTON_WIDTH; gridRect[7].h = BUTTON_HEIGHT; gridRect[8].x = gridRect[2].x; gridRect[8].y = BUTTON_WIDTH * 2 + BAR_SIZE * 2 + COMP * 5; gridRect[8].w = BUTTON_WIDTH; gridRect[8].h = BUTTON_HEIGHT; } void GetPosition(int x, int y){ if (x < gridRect[0].w && y < gridRect[0].h){ pressedPosition = 1; posX = 0; posY = 0; } else if (x >= gridRect[1].x && y >= gridRect[1].y && x <= (gridRect[1].x + gridRect[1].w) && y <= (gridRect[1].y + gridRect[1].h)){ pressedPosition = 2; posX = 0; posY = 1; } else if (x > gridRect[2].x && y > gridRect[2].y && x < (gridRect[2].x + gridRect[2].w) && y < (gridRect[2].y + gridRect[2].h)){ pressedPosition = 3; posX = 0; posY = 2; } else if (x > gridRect[3].x && y > gridRect[3].y && x < (gridRect[3].x + gridRect[3].w) && y < (gridRect[3].y + gridRect[3].h)){ pressedPosition = 4; posX = 1; posY = 0; } else if (x > gridRect[4].x && y > gridRect[4].y && x < (gridRect[4].x + gridRect[4].w) && y < (gridRect[4].y + gridRect[4].h)){ pressedPosition = 5; posX = 1; posY = 1; } else if (x > gridRect[5].x && y > gridRect[5].y && x < (gridRect[5].x + gridRect[5].w) && y < (gridRect[5].y + gridRect[5].h)){ pressedPosition = 6; posX = 1; posY = 2; } else if (x > gridRect[6].x && y > gridRect[6].y && x < (gridRect[6].x + gridRect[6].w) && y < (gridRect[6].y + gridRect[6].h)){ pressedPosition = 7; posX = 2; posY = 0; } else if (x > gridRect[7].x && y > gridRect[7].y && x < (gridRect[7].x + gridRect[7].w) && y < (gridRect[7].y + gridRect[7].h)){ pressedPosition = 8; posX = 2; posY = 1; } else if (x > gridRect[8].x && y > gridRect[8].y && x < (gridRect[8].x + gridRect[8].w) && y < (gridRect[8].y + gridRect[8].h)){ pressedPosition = 9; posX = 2; posY = 2; } else printf("NADA\n"); } bool GetEvents(){ while(SDL_PollEvent(&event) != 0){ if(event.type == SDL_QUIT){ return 1; } if(event.type == SDL_MOUSEBUTTONDOWN){ int x, y; SDL_GetMouseState(&x, &y); GetPosition(x, y); } if(event.type == SDL_KEYDOWN){ if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE){ return 1; } } } } void NewRound(){ for (int i = 0; i < GRID_SIZE; i++){ for (int j = 0; j < GRID_SIZE; j++){ gridMat[i][j] = -1; } } grid = IMG_Load("../img/grid.png"); if(grid == NULL){ printf("Erro ao carregar o grid. (New round)"); } winner = 0; ocupados = 0; player = 1; } bool CheckPosition(){ if (pressedPosition != 0){ if (gridMat[posX][posY] == -1){ gridMat[posX][posY] = player; player == 1 ? player = 2 : player = 1; return true; } } return false; } int ScanMatriz(){ int horizontal = 0, vertical = 0; int diagonal_1 = 0, diagonal_2 = 0; bool changedH = false, changedV = false, changedD1 = false, changedD2 = false; //Verifica as linhas e diagonais for (int i = 0; i < GRID_SIZE; i++){ for (int j = 0; j < GRID_SIZE; j++){ if (horizontal != 0 && horizontal != gridMat[i][j]){ changedH = true; } horizontal = gridMat[i][j]; if (i == j){ if (diagonal_1 != 0 && diagonal_1 != gridMat[i][j]){ changedD1 = true; } diagonal_1 = gridMat[i][j]; } if ((i + j) == 2){ if (diagonal_2 != 0 && diagonal_2 != gridMat[i][j]){ changedD2 = true; } diagonal_2 = gridMat[i][j]; } } if (!changedH){ return horizontal; } changedH = false; horizontal = 0; } if (!changedD1){ return diagonal_1; } if (!changedD2){ return diagonal_2; } //Verifica as colunas for (int i = 0; i < GRID_SIZE; i++){ for (int j = 0; j < GRID_SIZE; j++){ if (vertical != 0 && vertical != gridMat[j][i]){ changedV = true; } vertical = gridMat[j][i]; } if (!changedV){ return vertical; } changedV = false; vertical = 0; } return 0; } void Close(){ SDL_DestroyWindow(window); SDL_FreeSurface(grid); SDL_FreeSurface(xImage); SDL_FreeSurface(oImage); SDL_FreeSurface(newGame); } int main(int argc, char *argv[]){ bool quit; if (!InitWindow()){ printf("Erro total!\n"); return 0; } //Chama a tela inicial //Espera o jogador clicar em new game ou quit //Se new game continua caso contrario quit == true quit = newGameScreen(); SetGridRect(); NewRound(); while (!quit){ pressedPosition = 0; quit = GetEvents(); if (CheckPosition()){ SDL_BlitSurface(player == 1 ? xImage : oImage, NULL, grid, &gridRect[pressedPosition - 1]); ocupados++; if (ocupados > 4){ winner = ScanMatriz(); if (winner == 1 || winner == 2 || ocupados == 9){ if (ocupados == 9){ printf("Empate!\n"); }else{ printf("Player %d ganhou\n", winner); } SDL_BlitSurface(grid, NULL, screen, NULL); SDL_BlitSurface(player == 1 ? xImage : oImage, NULL, grid, &gridRect[pressedPosition - 1]); SDL_UpdateWindowSurface(window); SDL_Delay(1000); NewRound(); } } } SDL_BlitSurface(grid, NULL, screen, NULL); SDL_UpdateWindowSurface(window); SDL_Delay(10); } return 0; } <commit_msg>gameLoo() implemented<commit_after>#include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <cstdio> const int SCREEN_WIDTH = 311; const int SCREEN_HEIGHT = 308; const int BUTTON_WIDTH = 94; const int BUTTON_HEIGHT = 94; const int BAR_SIZE = 4; const int COMP = 4; #define GRID_SIZE 3 int pressedPosition; int posX, posY; //Posições da matriz que representa o grid int gridMat[GRID_SIZE][GRID_SIZE]; int player; int winner; int ocupados; SDL_Surface *grid = NULL; SDL_Surface *xImage = NULL; SDL_Surface *oImage = NULL; SDL_Surface *screen = NULL; SDL_Surface *newGame = NULL; SDL_Window *window = NULL; SDL_Rect gridRect[9]; SDL_Event event; bool InitWindow(){ if (SDL_INIT_VIDEO < 0){ printf("Erro ao inicializar o vídeo!\n"); return 0; } else{ window = SDL_CreateWindow("TIC-TAC-TOE", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL){ printf("Erro ao inicializar a janela\n"); return 0; } else{ screen = SDL_GetWindowSurface(window); } } int imgFlags = IMG_INIT_PNG; if(!(IMG_Init(imgFlags) & imgFlags)){ printf("Erro. Não foi possível inicializar SDL_image!\n%s\n", IMG_GetError()); return 0; } if ((grid = IMG_Load("../img/grid.png")) == NULL){ printf("Erro ao carregar o background\n"); return 0; } if ((xImage = IMG_Load("../img/x.png")) == NULL){ printf("Erro %s\n", SDL_GetError()); return 0; } if ((oImage = IMG_Load("../img/o.png")) == NULL){ printf("Erro %s\n", SDL_GetError()); return 0; } if ((newGame = IMG_Load("../img/new_game.png")) == NULL){ printf("Erro %s\n", SDL_GetError()); return 0; } return 1; } bool newGameScreen(){ //TODO //O "new game" deve funcionar como um botão, e não fazer parte do background while(1){ SDL_BlitSurface(newGame, NULL, screen, NULL); SDL_UpdateWindowSurface(window); SDL_PollEvent(&event); if(event.type == SDL_MOUSEBUTTONDOWN){ int x, y; SDL_GetMouseState(&x, &y); if(((x >= 80) && (x <= 220)) && ((y >= 210) && (y <= 225))){ return 0; }else if(((x >= 115) && (x <= 170)) && ((y >= 250) && (y <= 265))){ return 1; } } } } void SetGridRect(){ gridRect[0].x = gridRect[0].y = COMP; gridRect[0].w = BUTTON_WIDTH; gridRect[0].h = BUTTON_HEIGHT; gridRect[1].x = BUTTON_WIDTH + COMP*3 + BAR_SIZE; gridRect[1].y = COMP; gridRect[1].w = BUTTON_WIDTH; gridRect[1].h = BUTTON_HEIGHT; gridRect[2].x = gridRect[1].x * 2 - COMP; gridRect[2].y = COMP; gridRect[2].w = BUTTON_WIDTH; gridRect[2].h = BUTTON_HEIGHT; gridRect[3].x = COMP; gridRect[3].y = BUTTON_WIDTH + BAR_SIZE + COMP*3; gridRect[3].w = BUTTON_WIDTH; gridRect[3].h = BUTTON_HEIGHT; gridRect[4].x = gridRect[1].x; gridRect[4].y = BUTTON_WIDTH + BAR_SIZE + COMP * 3; gridRect[4].w = BUTTON_WIDTH; gridRect[4].h = BUTTON_HEIGHT; gridRect[5].x = gridRect[2].x; gridRect[5].y = BUTTON_WIDTH + BAR_SIZE + COMP * 3; gridRect[5].w = BUTTON_WIDTH; gridRect[5].h = BUTTON_HEIGHT; gridRect[6].x = COMP; gridRect[6].y = BUTTON_WIDTH * 2 + BAR_SIZE * 2 + COMP * 5; gridRect[6].w = BUTTON_WIDTH; gridRect[6].h = BUTTON_HEIGHT; gridRect[7].x = gridRect[1].x; gridRect[7].y = BUTTON_WIDTH * 2 + BAR_SIZE * 2 + COMP * 5; gridRect[7].w = BUTTON_WIDTH; gridRect[7].h = BUTTON_HEIGHT; gridRect[8].x = gridRect[2].x; gridRect[8].y = BUTTON_WIDTH * 2 + BAR_SIZE * 2 + COMP * 5; gridRect[8].w = BUTTON_WIDTH; gridRect[8].h = BUTTON_HEIGHT; } void GetPosition(int x, int y){ if (x < gridRect[0].w && y < gridRect[0].h){ pressedPosition = 1; posX = 0; posY = 0; } else if (x >= gridRect[1].x && y >= gridRect[1].y && x <= (gridRect[1].x + gridRect[1].w) && y <= (gridRect[1].y + gridRect[1].h)){ pressedPosition = 2; posX = 0; posY = 1; } else if (x > gridRect[2].x && y > gridRect[2].y && x < (gridRect[2].x + gridRect[2].w) && y < (gridRect[2].y + gridRect[2].h)){ pressedPosition = 3; posX = 0; posY = 2; } else if (x > gridRect[3].x && y > gridRect[3].y && x < (gridRect[3].x + gridRect[3].w) && y < (gridRect[3].y + gridRect[3].h)){ pressedPosition = 4; posX = 1; posY = 0; } else if (x > gridRect[4].x && y > gridRect[4].y && x < (gridRect[4].x + gridRect[4].w) && y < (gridRect[4].y + gridRect[4].h)){ pressedPosition = 5; posX = 1; posY = 1; } else if (x > gridRect[5].x && y > gridRect[5].y && x < (gridRect[5].x + gridRect[5].w) && y < (gridRect[5].y + gridRect[5].h)){ pressedPosition = 6; posX = 1; posY = 2; } else if (x > gridRect[6].x && y > gridRect[6].y && x < (gridRect[6].x + gridRect[6].w) && y < (gridRect[6].y + gridRect[6].h)){ pressedPosition = 7; posX = 2; posY = 0; } else if (x > gridRect[7].x && y > gridRect[7].y && x < (gridRect[7].x + gridRect[7].w) && y < (gridRect[7].y + gridRect[7].h)){ pressedPosition = 8; posX = 2; posY = 1; } else if (x > gridRect[8].x && y > gridRect[8].y && x < (gridRect[8].x + gridRect[8].w) && y < (gridRect[8].y + gridRect[8].h)){ pressedPosition = 9; posX = 2; posY = 2; } else printf("NADA\n"); } bool GetEvents(){ while(SDL_PollEvent(&event) != 0){ if(event.type == SDL_QUIT){ return 1; } if(event.type == SDL_MOUSEBUTTONDOWN){ int x, y; SDL_GetMouseState(&x, &y); GetPosition(x, y); } if(event.type == SDL_KEYDOWN){ if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE){ return 1; } } } } void NewRound(){ for (int i = 0; i < GRID_SIZE; i++){ for (int j = 0; j < GRID_SIZE; j++){ gridMat[i][j] = -1; } } grid = IMG_Load("../img/grid.png"); if(grid == NULL){ printf("Erro ao carregar o grid. (New round)"); } winner = 0; ocupados = 0; player = 1; } bool CheckPosition(){ if (pressedPosition != 0){ if (gridMat[posX][posY] == -1){ gridMat[posX][posY] = player; player == 1 ? player = 2 : player = 1; return true; } } return false; } int ScanMatriz(){ int horizontal = 0, vertical = 0; int diagonal_1 = 0, diagonal_2 = 0; bool changedH = false, changedV = false, changedD1 = false, changedD2 = false; //Verifica as linhas e diagonais for (int i = 0; i < GRID_SIZE; i++){ for (int j = 0; j < GRID_SIZE; j++){ if (horizontal != 0 && horizontal != gridMat[i][j]){ changedH = true; } horizontal = gridMat[i][j]; if (i == j){ if (diagonal_1 != 0 && diagonal_1 != gridMat[i][j]){ changedD1 = true; } diagonal_1 = gridMat[i][j]; } if ((i + j) == 2){ if (diagonal_2 != 0 && diagonal_2 != gridMat[i][j]){ changedD2 = true; } diagonal_2 = gridMat[i][j]; } } if (!changedH){ return horizontal; } changedH = false; horizontal = 0; } if (!changedD1){ return diagonal_1; } if (!changedD2){ return diagonal_2; } //Verifica as colunas for (int i = 0; i < GRID_SIZE; i++){ for (int j = 0; j < GRID_SIZE; j++){ if (vertical != 0 && vertical != gridMat[j][i]){ changedV = true; } vertical = gridMat[j][i]; } if (!changedV){ return vertical; } changedV = false; vertical = 0; } return 0; } void gameLoop(){ bool quit = false; while (!quit){ pressedPosition = 0; quit = GetEvents(); if (CheckPosition()){ SDL_BlitSurface(player == 1 ? xImage : oImage, NULL, grid, &gridRect[pressedPosition - 1]); ocupados++; if (ocupados > 4){ winner = ScanMatriz(); if (winner == 1 || winner == 2 || ocupados == 9){ if (ocupados == 9){ printf("Empate!\n"); }else{ printf("Player %d ganhou\n", winner); } SDL_BlitSurface(grid, NULL, screen, NULL); SDL_BlitSurface(player == 1 ? xImage : oImage, NULL, grid, &gridRect[pressedPosition - 1]); SDL_UpdateWindowSurface(window); SDL_Delay(1000); return; } } } SDL_BlitSurface(grid, NULL, screen, NULL); SDL_UpdateWindowSurface(window); } } void Close(){ SDL_DestroyWindow(window); SDL_FreeSurface(grid); SDL_FreeSurface(xImage); SDL_FreeSurface(oImage); SDL_FreeSurface(newGame); } int main(int argc, char *argv[]){ bool quit = false; if (!InitWindow()){ printf("Erro total!\n"); return 0; } while(!(quit = newGameScreen())){ SetGridRect(); NewRound(); gameLoop(); } return 0; } <|endoftext|>
<commit_before> #include "includes.h" #include "global.h" #include "fonctions.h" using namespace std; using namespace cv; using namespace raspicam; /** * \fn void initStruct(void) * \brief Initialisation des structures de l'application (tâches, mutex, * semaphore, etc.) */ void initStruct(void); /** * \fn void startTasks(void) * \brief Démarrage des tâches */ void startTasks(void); /** * \fn void deleteTasks(void) * \brief Arrêt des tâches */ void deleteTasks(void); int main(int argc, char**argv) { printf("#################################\n"); printf("# DE STIJL PROJECT #\n"); printf("#################################\n"); initStruct(); printf("Init struct done\n"); startTasks(); printf("Start done\n"); pause(); /*deleteTasks();*/ return 0; } void initStruct(void) { int err; /* Creation des mutex */ if ((err = rt_mutex_create(&mutexEtat, NULL))) { printf("Error mutex create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_mutex_create(&mutexMove, NULL))) { printf("Error mutex create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } /* Creation du semaphore */ if ((err = rt_sem_create(&semConnecterRobot, NULL, 0, S_FIFO))) { printf("Error semaphore create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } /* Creation des taches */ if ((err = rt_task_create(&tServeur, NULL, 0, PRIORITY_TSERVEUR, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_create(&tconnect, NULL, 0, PRIORITY_TCONNECT, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_create(&tmove, NULL, 0, PRIORITY_TMOVE, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_create(&tenvoyer, NULL, 0, PRIORITY_TENVOYER, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } /* Creation des files de messages */ /*if (err = rt_queue_create(&queueMsgGUI, "toto", MSG_QUEUE_SIZE*sizeof(DMessage), MSG_QUEUE_SIZE, Q_FIFO)){ printf("Error msg queue create: %s\n", strerror(-err)); exit(EXIT_FAILURE); }*/ /* Creation des structures globales du projet */ /*robot = d_new_robot(); move = d_new_movement(); serveur = d_new_server();*/ } void startTasks() { int err; if ((err = rt_task_start(&tconnect, &connecter, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_start(&tServeur, &communiquer, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_start(&tmove, &deplacer, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_start(&tenvoyer, &envoyer, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } } void deleteTasks() { rt_task_delete(&tServeur); rt_task_delete(&tconnect); rt_task_delete(&tmove); } <commit_msg>Add new threads<commit_after>#if 0 #include "includes.h" #include "global.h" #include "fonctions.h" using namespace std; using namespace cv; using namespace raspicam; /** * \fn void initStruct(void) * \brief Initialisation des structures de l'application (tâches, mutex, * semaphore, etc.) */ void initStruct(void); /** * \fn void startTasks(void) * \brief Démarrage des tâches */ void startTasks(void); /** * \fn void deleteTasks(void) * \brief Arrêt des tâches */ void deleteTasks(void); int main(int argc, char**argv) { printf("#################################\n"); printf("# DE STIJL PROJECT #\n"); printf("#################################\n"); initStruct(); printf("Init struct done\n"); startTasks(); printf("Start done\n"); pause(); /*deleteTasks();*/ return 0; } void initStruct(void) { int err; /* Creation des mutex */ if ((err = rt_mutex_create(&mutexEtat, "mutex_etat"))) { printf("Error mutex create : mutex_etat : %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_mutex_create(&mutexMove, "mutex_move"))) { printf("Error mutex create : mutex_move : %s\n", strerror(-err)); exit(EXIT_FAILURE); } /* Creation du semaphore */ if ((err = rt_sem_create(&semConnecterRobot, "sem_connect", 0, S_FIFO))) { printf("Error semaphore create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } /* Creation des taches */ if ((err = rt_task_create(&tServeur, NULL, 0, PRIORITY_TSERVEUR, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_create(&tconnect, NULL, 0, PRIORITY_TCONNECT, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_create(&tmove, NULL, 0, PRIORITY_TMOVE, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_create(&tenvoyer, NULL, 0, PRIORITY_TENVOYER, 0))) { printf("Error task create: %s\n", strerror(-err)); exit(EXIT_FAILURE); } /* Creation des files de messages */ /*if (err = rt_queue_create(&queueMsgGUI, "toto", MSG_QUEUE_SIZE*sizeof(DMessage), MSG_QUEUE_SIZE, Q_FIFO)){ printf("Error msg queue create: %s\n", strerror(-err)); exit(EXIT_FAILURE); }*/ /* Creation des structures globales du projet */ /*robot = d_new_robot(); move = d_new_movement(); serveur = d_new_server();*/ } void startTasks() { int err; if ((err = rt_task_start(&tconnect, &connecter, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_start(&tServeur, &communiquer, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_start(&tmove, &deplacer, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } if ((err = rt_task_start(&tenvoyer, &envoyer, NULL))) { printf("Error task start: %s\n", strerror(-err)); exit(EXIT_FAILURE); } } void deleteTasks() { rt_task_delete(&tServeur); rt_task_delete(&tconnect); rt_task_delete(&tmove); } #endif #include "imagerie.h" #include "serial.h" #include "tcpServer.h" // include himself imagerie.h #include "global.h" //#include <pthread.h> #include <task.h> #include <stdlib.h> using namespace std; using namespace cv; using namespace raspicam; #define START_MODE WITHOUT_WD bool m_exit = false; void threadVideo(void *arg) { printf("=> threadVideo created \n"); if(rt_sem_p(&semConnecterServeur, TM_INFINITE) != 0) perror("erreur lors de la prise du semConnecterServeur\n"); if(rt_task_set_periodic(NULL, TM_NOW, rt_timer_ns2ticks(500000000)) != 0) perror("erreur lors du lancement du thread\n"); else { printf("threadVideo lance \n"); Camera rpiCam; Image imgVideo; Arene monArene; position positionRobots[20]; Jpg compress; openCamera(&rpiCam); do { rt_task_wait_period(NULL); getImg(&rpiCam, &imgVideo); if(detectArena(&imgVideo, &monArene)==0) { detectPosition(&imgVideo,positionRobots,&monArene); drawArena(&imgVideo,&imgVideo,&monArene); } else detectPosition(&imgVideo,positionRobots); //envoie position dans msgGui { void* msg_serv; if(!(msg_serv = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg_serv,POS); rt_queue_send(&queueMsgGUI, msg_serv, 20, Q_NORMAL); // a vrifier void* msg_pos; if(!(msg_pos = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg_pos, (char*)positionRobots); rt_queue_send(&queueMsgGUI, msg_pos, 20, Q_NORMAL); // a vrifier } //fin envoie position dans msgGui drawPosition(&imgVideo,&imgVideo,&positionRobots[0]); imgCompress(&imgVideo,&compress); //envoie de l'image dans msgGUI { void* msg_serv; if(!(msg_serv = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg_serv,IMG); rt_queue_send(&queueMsgGUI, msg_serv, 20, Q_NORMAL); // a vrifier void* msg_img; if(!(msg_img = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg_img, (char*)(&compress)); rt_queue_send(&queueMsgGUI, msg_img, 20, Q_NORMAL); // a vrifier } //sendToUI("IMG",&compress); //envoie de l'image dans msgGUI } while(m_exit == false); closeCam(&rpiCam); if(rt_sem_v(&semConnecterServeur) != 0) perror("erreur lors de la libration du semConnecterServeur\n"); } printf("=> threadVideo kill\n"); } void threadConnecter(void *arg) { printf("=> threadConnecter create\n"); robotOpenCom(); void *msg; while(m_exit == false) { if(rt_sem_p(&semConnecterRobot, TM_INFINITE) != 0) perror("erreur lors de la prise du semConnecterRobot\n"); printf("debloquage du semaphore semConnecterRobot\n"); if(m_exit == false) { //Zone critique if(rt_mutex_acquire(&mutexEtat, TM_INFINITE) != 0) perror("erreur lors de la prise du mutexEtat\n"); else { if(etatCommRobot != 0) { etatCommRobot = robotCmd(START_MODE); if(etatCommRobot == 0) { if(!(msg = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg,ACK); rt_queue_send(&queueMsgGUI, msg, 20, Q_NORMAL); // a vrifier } } else { if(robotCmd('r') == 0) { etatCommRobot = -1; if(!(msg = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg,ACK); rt_queue_send(&queueMsgGUI, msg, 20, Q_NORMAL); // a vrifier } } } if(rt_mutex_release(&mutexEtat) != 0) perror("erreur lors de la libration du mutexEtat\n"); //fin de zone critique } } robotCloseCom(); printf("=> threadConnecter kill\n"); } void threadEnvoyer(void *arg) { printf("=> threadEnvoyer create\n"); void *msg; if(rt_queue_bind(&queueMsgGUI,"queueMsgGUI",TM_INFINITE) != 0) perror("bind queue error\n"); printf("threadEnvoyer initialise\n"); while(1) { rt_queue_receive(&queueMsgGUI, &msg,TM_INFINITE); printf("received message GUI> bytes s=%s\n",(const char *)msg); if(strcmp((char*)msg, "C") == 0) { rt_queue_free(&queueMsgGUI,msg); break; } else if(strcmp((char*)msg, BAT) == 0) { rt_queue_free(&queueMsgGUI,msg); rt_queue_receive(&queueMsgGUI, &msg,TM_INFINITE); sendToUI(BAT, msg); } else if(strcmp((char*)msg, POS) == 0) { rt_queue_free(&queueMsgGUI,msg); rt_queue_receive(&queueMsgGUI, &msg,TM_INFINITE); sendToUI(POS, msg); // a corriger } else if(strcmp((char*)msg, IMG) == 0) { rt_queue_free(&queueMsgGUI,msg); rt_queue_receive(&queueMsgGUI, &msg,TM_INFINITE); sendToUI(IMG, msg); } else sendToUI((char*)msg); rt_queue_free(&queueMsgGUI,msg); } rt_queue_unbind(&queueMsgGUI); printf("=> threadEnvoyer kill\n"); } void threadServeur(void *arg) { printf("=> threadServeur create\n"); if((etatCommMoniteur = serverOpen()) == 0) // init serveur + ouvrir connexion serveur { char header[4]; char data[20]; memset(data, '\0',20); memset(header,'\0',4); if(rt_sem_v(&semConnecterServeur) != 0) perror("erreur lors de la libration du semConnecterServeur\n"); do { receptionFromUI(header,data); if(strcmp(header, DMB) == 0) { printf("EVENEMENT DUMBER DETECTE AVEC LE MESSAGE :%s \n",data); if(data[0] == 'u' || data[0] == 'r') { if(rt_sem_v(&semConnecterRobot) != 0) perror("erreur lors de la liberation du semConnecterRobot\n"); } else { printf("movement : %c\n", data[0]); void* msg_rbt; if(!(msg_rbt = rt_queue_alloc(&queueMsgRobot,20))) perror("alloc queue error\n"); data[1] = '\0'; strcpy((char*)msg_rbt,data); rt_queue_send(&queueMsgRobot, msg_rbt, 20, Q_NORMAL); // a vrifier } } if(strcmp(header, MES) == 0) { printf("EVENEMENT MESSAGE DETECTE AVEC LE MESSAGE :%s \n",data); if(data[0] == 'C') { void* msg_serv; void* msg_rbt; if(!(msg_serv = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); if(!(msg_rbt = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg_serv,"C"); strcpy((char*)msg_rbt,"C"); rt_queue_send(&queueMsgGUI, msg_serv, 20, Q_NORMAL); // a vrifier rt_queue_send(&queueMsgRobot, msg_rbt, 20, Q_NORMAL); // a vrifier } } if(strcmp(header,POS)==0) { printf("EVENEMENT POSITION DETECTE AVEC LE MESSAGE :%s \n",data); } } while((strcmp(header,MES)!=0) || (data[0] != 'C')); m_exit = true; if(rt_sem_p(&semConnecterServeur, TM_INFINITE) != 0) perror("erreur lors de la libration du semConnecterServeur\n"); if(rt_sem_v(&semConnecterRobot) != 0) perror("erreur lors de la liberation du semConnecterRobot\n"); serverClose(); } printf("=> threadServeur kill\n"); } void threadMove(void* arg) { printf("=> threadMove create\n"); void *msg; if(rt_queue_bind(&queueMsgRobot,"queueMsgRobot",TM_INFINITE) != 0) perror("bind queue error\n"); printf("threadMove initialise\n"); while(1) { rt_queue_receive(&queueMsgRobot, &msg,TM_INFINITE); printf("received message> bytes s=%s\n",(const char *)msg); if(strcmp((char*)msg, "C") == 0) { rt_queue_free(&queueMsgRobot,msg); break; } int etat = -1; //Zone critique if(rt_mutex_acquire(&mutexEtat, TM_INFINITE) != 0) perror("erreur lors de la prise du mutexEtat\n"); else { etat = etatCommRobot; if(rt_mutex_release(&mutexEtat) != 0) perror("erreur lors de la liberation du mutexEtat\n"); } //fin de zone critique if(etat == 0) { printf("send %s to robot\n", (char*)msg); int err = robotCmd(((char*)msg)[0]); if(rt_mutex_acquire(&mutexEtat, TM_INFINITE) != 0) perror("erreur lors de la prise du mutexEtat\n"); else { etatCommRobot = err; if(rt_mutex_release(&mutexEtat) != 0) perror("erreur lors de la libration du mutexEtat\n"); } } //recup err rt_queue_free(&queueMsgRobot,msg); } rt_queue_unbind(&queueMsgRobot); printf("=> threadMove kill\n"); } void threadBatt(void* arg) { printf("=> threadBatt create\n"); if(rt_task_set_periodic(NULL, TM_NOW, rt_timer_ns2ticks(250000000)) != 0) perror("erreur lors du lancement du thread\n"); else { while(m_exit == false) { rt_task_wait_period(NULL); int tmpEtat = -1; if(rt_mutex_acquire(&mutexEtat, TM_INFINITE) != 0) perror("erreur lors de la prise du mutexEtat\n"); else { tmpEtat = etatCommRobot; if(rt_mutex_release(&mutexEtat) != 0) perror("erreur lors de la libration du mutexEtat\n"); } if(tmpEtat == 0) { int vbat = robotCmd(GETVBAT); void* msg_serv; if(!(msg_serv = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); strcpy((char*)msg_serv,BAT); rt_queue_send(&queueMsgGUI, msg_serv, 20, Q_NORMAL); // a vrifier void* msg_level; if(!(msg_level = rt_queue_alloc(&queueMsgGUI,20))) perror("alloc queue error\n"); char buffer[2]; sprintf (buffer, "%d", vbat); strcpy((char*)msg_level, buffer); rt_queue_send(&queueMsgGUI, msg_level, 20, Q_NORMAL); // a vrifier } } } printf("=> threadBatt kill\n"); } void threadWatchdog(void* arg) { printf("=> threadWatchdog create\n"); if(rt_task_set_periodic(NULL, TM_NOW, rt_timer_ns2ticks(10*1000000)) != 0) perror("erreur lors du lancement du thread\n"); else { while(m_exit == false) { rt_task_wait_period(NULL); int tmpEtat = -1; if(rt_mutex_acquire(&mutexEtat, TM_INFINITE) != 0) perror("erreur lors de la prise du mutexEtat\n"); else { tmpEtat = etatCommRobot; if(rt_mutex_release(&mutexEtat) != 0) perror("erreur lors de la libration du mutexEtat\n"); } printf("status : %d\r\n", tmpEtat); int status = robotCmd(RELOAD); if(rt_mutex_acquire(&mutexEtat, TM_INFINITE) != 0) perror("erreur lors de la prise du mutexEtat\n"); else { etatCommRobot = status; if(rt_mutex_release(&mutexEtat) != 0) perror("erreur lors de la libration du mutexEtat\n"); } } } printf("=> threadWatchdog kill\n"); } int main() { /*creation des semaphores*/ if(rt_sem_create(&semConnecterServeur, "semConnecterServeur", 0, S_PRIO) != 0) perror("erreur lors de la creation du sem ConnecterServeur\n"); if(rt_sem_create(&semConnecterRobot, "semConnecterRobot", 0, S_PRIO) != 0) perror("erreur lors de la creation du sem sConnecterRobot\n"); /*creation des mutex*/ if(rt_mutex_create(&mutexEtat, "mutexEtat") != 0) perror("erreur lors de la creation du mutex mutexEtat\n"); if(rt_mutex_create(&mutexMove, "mutexMove") != 0) perror("erreur lors de la creation du mutex mutexMove\n"); /*creation des queues*/ if(rt_queue_create(&queueMsgGUI, "queueMsgGUI", 30, Q_UNLIMITED, Q_PRIO) != 0) perror("erreur lors de la creation de la queue queueMsgGUI\n"); if(rt_queue_create(&queueMsgRobot, "queueMsgRobot", 20, Q_UNLIMITED, Q_PRIO) != 0) perror("erreur lors de la creation de la queue queueMsgRobot\n"); /*creation des taches*/ if(rt_task_spawn(&tServeur, "serveur", 0, 30, T_JOINABLE, &threadServeur, NULL) != 0) perror("erreur lors de la creation du thread Serveur\n"); if(rt_task_spawn(&tvideo,"tvideo", 0, 43, T_JOINABLE, &threadVideo, NULL) != 0) perror("erreur lors de la creation du thread Video\n"); if(rt_task_spawn(&tconnect,"tconnect", 0, 35, T_JOINABLE, &threadConnecter, NULL) != 0) perror("erreur lors de la creation du thread Video\n"); if(rt_task_spawn(&tenvoyer,"tenvoyer", 0, 44, T_JOINABLE, &threadEnvoyer, NULL) != 0) perror("erreur lors de la creation du thread envoyer\n"); if(rt_task_spawn(&tmove, "tmove", 0, 45, T_JOINABLE, &threadMove, NULL) != 0) perror("erreur lors de la creation du thread move\n"); if(rt_task_spawn(&tbattery, "tbattery", 0, 34, T_JOINABLE, &threadBatt, NULL) != 0) perror("erreur lors de la creation du thread batt\n"); if(START_MODE == WITH_WD) if(rt_task_spawn(&tWatchdog, "tWatchdog", 0, 99, T_JOINABLE, &threadWatchdog, NULL) != 0) perror("erreur lors de la creation du thread wdg\n"); rt_task_join(&tServeur); rt_task_join(&tvideo); rt_task_join(&tconnect); rt_task_join(&tenvoyer); rt_task_join(&tmove); rt_task_join(&tbattery); /*destruction des taches*/ rt_task_delete(&tServeur); rt_task_delete(&tvideo); rt_task_delete(&tconnect); rt_task_delete(&tenvoyer); rt_task_delete(&tmove); rt_task_delete(&tbattery); rt_task_delete(&tWatchdog); /*destruction des mutex*/ rt_mutex_delete(&mutexEtat); rt_mutex_delete(&mutexMove); /*destruction des semaphores*/ rt_sem_delete(&semConnecterServeur); rt_sem_delete(&semConnecterRobot); /*destruction de la queue*/ rt_queue_delete(&queueMsgGUI); rt_queue_delete(&queueMsgRobot); printf("end main \n"); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cstdint> #include <algorithm> #include <memory> #include <thread> #include <stdio.h> #include <unistd.h> #include <chrono> #include "dcpu.hpp" #include "disassembler.hpp" #include "gclock.hpp" #include "fake_lem1802.hpp" #include "lem1802.hpp" #include "lem1803.hpp" using namespace cpu; const long TOTALCPUS = 215*16; const long PERTHREAD = 16; // At 16 looks that is the ideal for the FX-4100 #define THREADS (TOTALCPUS/PERTHREAD) const long CYCLES = 1000*1000; const int BATCH = 10; std::vector<std::vector<std::shared_ptr<DCPU>>> threads; uint16_t* data; size_t size = 0; void benchmark(); void step(); void one_bench(); void run100k(); void cpu_in_thread(int n); int main (int argc, char **argv) { char* filename; std::ifstream binfile; /* std::cout << "cpu " << sizeof(DCPU) << " IHardware " << sizeof(IHardware); std::cout << " fake_LEM1802 " << sizeof(Fake_Lem1802) << std::endl;*/ if (argc <= 1) { std::cerr << "Missing input file\n"; return 0; } filename = argv[1]; std::cout << "Input BIN File : " << filename << "\n"; binfile.open (filename, std::ios::in | std::ios::binary ); if (!binfile) { std::cerr << "ERROR: I can open file\n"; exit (1); } // get length of file: binfile.seekg (0, binfile.end); size = binfile.tellg(); binfile.seekg (0, binfile.beg); data = new uint16_t[size / 2 + 1](); std::fill_n (data, size / 2, 0); // Clean it int i = 0; while (! binfile.eof() ) { uint16_t word = 0; binfile.read ( (char*) &word, 2); unsigned char tmp = ( (word & 0xFF00) >> 8) & 0x00FF; word = ( (word & 0x00FF) << 8) | tmp; data[i] = word; i++; } binfile.close(); std::cout << "Readed " << size << " bytes - " << size / 2 << " words\n"; size /= 2; badchar: std::cout << "Select what to do :" << std::endl; std::cout << "\tb -> benchmark s -> step execution o-> benchmark one VM r-> run 8888888800k cycles"; std::cout << std::endl << std::endl; char choose; std::cin >> choose; if (choose == 'b' || choose == 'B') { benchmark(); } else if ( choose == 's' || choose == 'S') { step(); } else if ( choose == 'o' || choose == 'O') { one_bench(); } else if ( choose == 'r' || choose == 'R') { run100k(); } else { goto badchar; /// HATE ME!!!! } delete[] data; return 0; } void benchmark() { // Load program to all CPUs for (int u=0; u< THREADS; u++) { std::vector<std::shared_ptr<DCPU>> cpus; cpus.reserve (PERTHREAD); for (int i = 0; i< PERTHREAD; i++) { auto cpu = std::make_shared<DCPU>(); //auto screen = std::make_shared<Fake_Lem1802>(); //screen->setEnable(false); // We not desire to write to stdout //cpu->attachHardware (screen); cpu->reset(); cpu->loadProgram (data, size); cpus.push_back(cpu); } threads.push_back(cpus); } std::thread tds[THREADS]; printf("Threads %ld\t CPU PerThread %ld\t", THREADS, PERTHREAD); printf("N cpus %ld\n", PERTHREAD * THREADS); printf("Cycles %ld\n", CYCLES); auto start = std::chrono::high_resolution_clock::now(); for (int i=0; i< THREADS; i++) { tds[i] = std::thread(cpu_in_thread, i); } for (int i=0; i< THREADS; i++) { tds[i].join(); } auto end = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); std::cout << "Measured time: " << dur.count() << "ms" << std::endl; } void step() { using namespace std; auto cpu = make_shared<DCPU>(); auto screen1 = std::make_shared<Lem1802>(); cpu->attachHardware (screen1); auto screen2 = std::make_shared<Lem1803>(); cpu->attachHardware (screen2); cpu->reset(); cpu->loadProgram (data, size); char c = getchar(); while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } while (c != 'q') { cout << cpu->dumpRegisters() << endl; cout << "T cycles " << dec << cpu->getTotCycles() << endl; cout << "> " << cpu->dumpRam() << " - "; string s = disassembly(cpu->getMem() + cpu->GetPC(), 3); cout << s << endl; if (cpu->GetSP() != 0x0000) cout << "STACK : "<< cpu->dumpRam(cpu->GetSP(), 0xFFFF) << endl; if (c == 'f') { for (int i = 0; i < 100; i++) cpu->tick(); } else { if (cpu->tick()) cout << "Execute! "; } cout << endl; while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } } } void one_bench() { using namespace std; using namespace std::chrono; const int times = 200; high_resolution_clock::time_point starts[times]; high_resolution_clock::time_point creates[times]; high_resolution_clock::time_point loadstarts[times]; high_resolution_clock::time_point loads[times]; high_resolution_clock::time_point finishs[times]; for (int x=0; x < times; x++) { using namespace std::chrono; starts[x] = high_resolution_clock::now(); auto cpu = make_shared<DCPU>(); creates[x] = high_resolution_clock::now(); auto screen = make_shared<Fake_Lem1802>(); screen->setEnable(false); // We not desire to write to stdout cpu->attachHardware (screen); loadstarts[x] = high_resolution_clock::now(); cpu->reset(); cpu->loadProgram (data, size); loads[x] = high_resolution_clock::now(); for (int i=0; i < 10000; i++) { cpu->tick(); } finishs[x] = high_resolution_clock::now(); } double d_create, d_load, d_execute; d_create = d_load = d_execute = 0; for (int x=0; x < times; x++) { auto tmp = duration_cast<chrono::microseconds> (creates[x] - starts[x]); d_create += tmp.count(); tmp = duration_cast<chrono::microseconds> (loads[x] - loadstarts[x]); d_load += tmp.count(); tmp = duration_cast<chrono::microseconds> (finishs[x] - loads[x]); d_execute += tmp.count(); } d_create /= times; d_load /= times; d_execute /= times; cout << "Measured time: " << endl; cout << "\tCreating time "<< d_create << "us" << endl; cout << "\tLoad time "<< d_load << "us" << endl; cout << "\tExecute 10k cycles time "<< d_execute << "us" << endl; } void run100k() { using namespace std; using namespace std::chrono; auto cpu = make_shared<DCPU>(); auto screen1 = std::make_shared<Lem1803>(); cpu->attachHardware (screen1); auto screen2 = make_shared<Lem1802>(); cpu->attachHardware (screen2); // FIXME See what fails with clock auto clock = make_shared<Generic_Clock>(); cpu->attachHardware (clock); cpu->reset(); cpu->loadProgram (data, size); high_resolution_clock::time_point b, e; for (int i=0; i < 800000; i++) { b = high_resolution_clock::now(); cpu->tick(); e = high_resolution_clock::now(); auto tmp = microseconds(1000000/cpu->cpu_clock) - duration_cast<chrono::microseconds>(e - b); this_thread::sleep_for(tmp); } cout << "Finished" << std::endl; char c; cin >> c; } // Runs PERTHREAD cpus, doing CYCLES cycles void cpu_in_thread(int n) { auto cpus = threads[n]; for (long i=0; i < CYCLES; i+= BATCH) { for (auto c = cpus.begin(); c != cpus.end(); c++) { for ( int j=0; j < BATCH; j++) (*c)->tick(); } } } <commit_msg>Now shows the running speed to the CPU in running mode<commit_after>#include <iostream> #include <fstream> #include <cstdint> #include <algorithm> #include <memory> #include <thread> #include <stdio.h> #include <unistd.h> #include <chrono> #include "dcpu.hpp" #include "disassembler.hpp" #include "gclock.hpp" #include "fake_lem1802.hpp" #include "lem1802.hpp" #include "lem1803.hpp" using namespace cpu; const long TOTALCPUS = 215*16; const long PERTHREAD = 16; // At 16 looks that is the ideal for the FX-4100 #define THREADS (TOTALCPUS/PERTHREAD) const long CYCLES = 1000*1000; const int BATCH = 10; std::vector<std::vector<std::shared_ptr<DCPU>>> threads; uint16_t* data; size_t size = 0; void benchmark(); void step(); void one_bench(); void run100k(); void cpu_in_thread(int n); int main (int argc, char **argv) { char* filename; std::ifstream binfile; /* std::cout << "cpu " << sizeof(DCPU) << " IHardware " << sizeof(IHardware); std::cout << " fake_LEM1802 " << sizeof(Fake_Lem1802) << std::endl;*/ if (argc <= 1) { std::cerr << "Missing input file\n"; return 0; } filename = argv[1]; std::cout << "Input BIN File : " << filename << "\n"; binfile.open (filename, std::ios::in | std::ios::binary ); if (!binfile) { std::cerr << "ERROR: I can open file\n"; exit (1); } // get length of file: binfile.seekg (0, binfile.end); size = binfile.tellg(); binfile.seekg (0, binfile.beg); data = new uint16_t[size / 2 + 1](); std::fill_n (data, size / 2, 0); // Clean it int i = 0; while (! binfile.eof() ) { uint16_t word = 0; binfile.read ( (char*) &word, 2); unsigned char tmp = ( (word & 0xFF00) >> 8) & 0x00FF; word = ( (word & 0x00FF) << 8) | tmp; data[i] = word; i++; } binfile.close(); std::cout << "Readed " << size << " bytes - " << size / 2 << " words\n"; size /= 2; badchar: std::cout << "Select what to do :" << std::endl; std::cout << "\tb -> benchmark s -> step execution o-> benchmark one VM r-> run 8888888800k cycles"; std::cout << std::endl << std::endl; char choose; std::cin >> choose; if (choose == 'b' || choose == 'B') { benchmark(); } else if ( choose == 's' || choose == 'S') { step(); } else if ( choose == 'o' || choose == 'O') { one_bench(); } else if ( choose == 'r' || choose == 'R') { run100k(); } else { goto badchar; /// HATE ME!!!! } delete[] data; return 0; } void benchmark() { // Load program to all CPUs for (int u=0; u< THREADS; u++) { std::vector<std::shared_ptr<DCPU>> cpus; cpus.reserve (PERTHREAD); for (int i = 0; i< PERTHREAD; i++) { auto cpu = std::make_shared<DCPU>(); //auto screen = std::make_shared<Fake_Lem1802>(); //screen->setEnable(false); // We not desire to write to stdout //cpu->attachHardware (screen); cpu->reset(); cpu->loadProgram (data, size); cpus.push_back(cpu); } threads.push_back(cpus); } std::thread tds[THREADS]; printf("Threads %ld\t CPU PerThread %ld\t", THREADS, PERTHREAD); printf("N cpus %ld\n", PERTHREAD * THREADS); printf("Cycles %ld\n", CYCLES); auto start = std::chrono::high_resolution_clock::now(); for (int i=0; i< THREADS; i++) { tds[i] = std::thread(cpu_in_thread, i); } for (int i=0; i< THREADS; i++) { tds[i].join(); } auto end = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); std::cout << "Measured time: " << dur.count() << "ms" << std::endl; } void step() { using namespace std; auto cpu = make_shared<DCPU>(); auto screen1 = std::make_shared<Lem1802>(); cpu->attachHardware (screen1); auto screen2 = std::make_shared<Lem1803>(); cpu->attachHardware (screen2); cpu->reset(); cpu->loadProgram (data, size); char c = getchar(); while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } while (c != 'q') { cout << cpu->dumpRegisters() << endl; cout << "T cycles " << dec << cpu->getTotCycles() << endl; cout << "> " << cpu->dumpRam() << " - "; string s = disassembly(cpu->getMem() + cpu->GetPC(), 3); cout << s << endl; if (cpu->GetSP() != 0x0000) cout << "STACK : "<< cpu->dumpRam(cpu->GetSP(), 0xFFFF) << endl; if (c == 'f') { for (int i = 0; i < 100; i++) cpu->tick(); } else { if (cpu->tick()) cout << "Execute! "; } cout << endl; while (1) { c = getchar(); if (c == 'f' || c == 'q' || c == '\n' ) break; } } } void one_bench() { using namespace std; using namespace std::chrono; const int times = 200; high_resolution_clock::time_point starts[times]; high_resolution_clock::time_point creates[times]; high_resolution_clock::time_point loadstarts[times]; high_resolution_clock::time_point loads[times]; high_resolution_clock::time_point finishs[times]; for (int x=0; x < times; x++) { using namespace std::chrono; starts[x] = high_resolution_clock::now(); auto cpu = make_shared<DCPU>(); creates[x] = high_resolution_clock::now(); auto screen = make_shared<Fake_Lem1802>(); screen->setEnable(false); // We not desire to write to stdout cpu->attachHardware (screen); loadstarts[x] = high_resolution_clock::now(); cpu->reset(); cpu->loadProgram (data, size); loads[x] = high_resolution_clock::now(); for (int i=0; i < 10000; i++) { cpu->tick(); } finishs[x] = high_resolution_clock::now(); } double d_create, d_load, d_execute; d_create = d_load = d_execute = 0; for (int x=0; x < times; x++) { auto tmp = duration_cast<chrono::microseconds> (creates[x] - starts[x]); d_create += tmp.count(); tmp = duration_cast<chrono::microseconds> (loads[x] - loadstarts[x]); d_load += tmp.count(); tmp = duration_cast<chrono::microseconds> (finishs[x] - loads[x]); d_execute += tmp.count(); } d_create /= times; d_load /= times; d_execute /= times; cout << "Measured time: " << endl; cout << "\tCreating time "<< d_create << "us" << endl; cout << "\tLoad time "<< d_load << "us" << endl; cout << "\tExecute 10k cycles time "<< d_execute << "us" << endl; } void run100k() { using namespace std; using namespace std::chrono; auto cpu = make_shared<DCPU>(); auto screen1 = std::make_shared<Lem1803>(); cpu->attachHardware (screen1); auto screen2 = make_shared<Lem1802>(); cpu->attachHardware (screen2); // FIXME See what fails with clock auto clock = make_shared<Generic_Clock>(); cpu->attachHardware (clock); cpu->reset(); cpu->loadProgram (data, size); high_resolution_clock::time_point b, e; for (int i=0; i < 800000; i++) { b = high_resolution_clock::now(); cpu->tick(); e = high_resolution_clock::now(); auto delta = duration_cast<chrono::nanoseconds>(e - b); auto rest = nanoseconds(1000000000/cpu->cpu_clock)-delta; if ((i % 50000) == 0) { // Not show running speed every clock tick double p = nanoseconds(1000000000/cpu->cpu_clock).count() / (double)(delta.count() + rest.count()); cerr << "Delta :" << delta.count() << " ns "; cerr << "Rest :" << rest.count() << " ns "; cerr << " Running at "<< p*100.0 << " % speed." << endl; } this_thread::sleep_for(duration_cast<chrono::nanoseconds>(rest)); } cout << "Finished" << std::endl; char c; cin >> c; } // Runs PERTHREAD cpus, doing CYCLES cycles void cpu_in_thread(int n) { auto cpus = threads[n]; for (long i=0; i < CYCLES; i+= BATCH) { for (auto c = cpus.begin(); c != cpus.end(); c++) { for ( int j=0; j < BATCH; j++) (*c)->tick(); } } } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <string> #include <string.h> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdio> #include <stdio.h> #include <vector> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <sys/stat.h> using namespace std; #define MAXSIZE 10000 void printAll() { cout << "printAll" << endl; //REMOVE } void printLong() { cout << "printLong" << endl; //REMOVE } void printRecursive() { cout << "printRecursive" << endl; //REMOVE } void printAllLong() { cout << "printAllLong" << endl; //REMOVE } void printAllRecursive() { cout << "printAllRecursive" << endl; //REMOVE } void printLongRecursive() { cout << "printLongRecursive" << endl; //REMOVE } void printAllLongRecursive() { cout << "printAllLongRecursive" << endl; //REMOVE } void fileSpecs(int argc/*argc needs to be the number of entries passed into argv*/, char* argv[]/*argv needs to be the directory pointer*/ )//insert parameters and return value { //May delete this functions and just put the directory stuff into the print functions to make coding easier if(argc <= 1) { perror("argc");//Nothing passed in to argc exit(1); } DIR *dirp; if(NULL == (dirp = opendir(argv[1]))) { perror("opendir()"); exit(1); } struct dirent *filespecs; errno = 0; while(NULL != (filespecs = readdir(dirp))) { //change to put files in certain order cout << filespecs->d_name << " "; } if(errno != 0) { perror("readdir()"); exit(1); } cout << endl; if(-1 == closedir(dirp)) { perror("closedir"); exit(1); } //return *filespecs; if used, return value is struct dirent } void ls_define(int argc, char* argv[])//insert parameters { //ls functionality cout << "ls" << endl;//REMOVE //fileSpecs(argc, directory_name); //create flags (-a, -l, -R) map<string, void(*)()> flag_functions; flag_functions["--all"] = printAll; flag_functions["-a"] = printAll; flag_functions["--long"] = printLong; flag_functions["-l"] = printLong; flag_functions["--recursive"] = printRecursive; flag_functions["-R"] = printRecursive; flag_functions["-al"] = printAllLong; flag_functions["-la"] = printAllLong; flag_functions["-aR"] = printAllRecursive; flag_functions["-Ra"] = printAllRecursive; flag_functions["-lR"] = printLongRecursive; flag_functions["-Rl"] = printLongRecursive; flag_functions["-alR"] = printAllLongRecursive; flag_functions["-aRl"] = printAllLongRecursive; flag_functions["-lRa"] = printAllLongRecursive; flag_functions["-laR"] = printAllLongRecursive; flag_functions["-Ral"] = printAllLongRecursive; flag_functions["-Rla"] = printAllLongRecursive; for(int i = 1; i < argc; i++) { void(*fp)() = flag_functions[string(argv[i])]; if(fp != NULL) { fp(); } else { cout << "Invalid Flag: " << argv[i] << endl; } } } void get_input(string& usr_input) { char arr[MAXSIZE]; char* argv[MAXSIZE]; char* argvcmd[MAXSIZE]; for(unsigned i = 0; i < MAXSIZE; i++) { arr[i] = 0; argv[i] = 0; argvcmd[i] = 0; } int index = 0; int start = 0; int j = 0; int n = 0; int c_cnt = 0; int tmp; for(unsigned i = 0; i < usr_input.size(); i++) { tmp = usr_input.at(i); if(tmp == ' ' || tmp == ';' || tmp == '&' || tmp == '|' || tmp == '#') { if(c_cnt > 0) { argv[j] = (char*)&arr[start]; j++; c_cnt = 0; arr[n] = '\0'; n++; } start = n; if(tmp != ' ') { if(tmp == '#') { start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; c_cnt = 0; i = usr_input.size(); j++; } else if(tmp == ';') { arr[n++] = ';'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; start = n; j++; c_cnt = 0; } else if(tmp == '&') { if(usr_input.at(i+1) == '&') { arr[n++] = '&'; arr[n++] = '&'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } else if(tmp == '|') { if(usr_input.at(i+1) == '|') { arr[n++] = '|'; arr[n++] = '|'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } } } else { arr[n] = usr_input.at(i); c_cnt++; n++; if(i == usr_input.size() - 1) { argv[j] = (char*)&arr[start]; n++; j++; } } } if(strcmp(argv[j-1], ";") != 0) { n++; start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; j++; } argv[j] = (char*)NULL; int status; for(int i = 0; i < j; i++) { if(strcmp(argv[i], "&&") == 0 || strcmp(argv[i], "||") == 0 || strcmp(argv[i], ";") == 0) { int pid; pid = fork(); if(pid < 0) { perror("fork"); } else if(pid == 0) { argvcmd[index] = NULL; if(!(strcmp(argvcmd[0], "ls"))) { ls_define(index, argvcmd); } else { status = execvp(argvcmd[0], argvcmd); } if(status == -1) { perror("execvp"); int x; int next = -1; if(strcmp(argv[i], "&&") == 0) { for(x = i + 1; x < j; x++) { if(strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } } if(next > 0) { i = next; } } } index = 0; exit(status); } else { } waitpid(-1, &status, 0); if(strcmp(argv[i], "&&") == 0 && (status > 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } if(strcmp(argv[i], "||") == 0 && (status == 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } index = 0; } else { if(index == 0 && (strcmp(argv[i], "exit")) == 0) { exit(1); } argvcmd[index] = argv[i]; index++; } } } void output() { char host[255]; string login = getlogin(); gethostname(host, 255); cout << login << "@" << host << " "; string usr_input; cout << "$"; cout << " "; getline(cin, usr_input); get_input(usr_input); } int main(int argc, char *argv[]) { while(1) { output(); } return 0; } <commit_msg>Fixed argument calls, still need to implement arguments and change the filespecs (sp) function<commit_after>#include <iostream> #include <map> #include <string> #include <string.h> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdio> #include <stdio.h> #include <vector> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <sys/stat.h> using namespace std; #define MAXSIZE 10000 void printNoArguments() { cout << "ls with no arguments" << endl; //REMOVE } void printAll() { cout << "printAll" << endl; //REMOVE } void printLong() { cout << "printLong" << endl; //REMOVE } void printRecursive() { cout << "printRecursive" << endl; //REMOVE } void printAllLong() { cout << "printAllLong" << endl; //REMOVE } void printAllRecursive() { cout << "printAllRecursive" << endl; //REMOVE } void printLongRecursive() { cout << "printLongRecursive" << endl; //REMOVE } void printAllLongRecursive() { cout << "printAllLongRecursive" << endl; //REMOVE } void fileSpecs(int argc/*argc needs to be the number of entries passed into argv*/, char* argv[]/*argv needs to be the directory pointer*/ )//insert parameters and return value { //May delete this functions and just put the directory stuff into the print functions to make coding easier if(argc <= 1) { perror("argc");//Nothing passed in to argc exit(1); } DIR *dirp; if(NULL == (dirp = opendir(argv[1]))) { perror("opendir()"); exit(1); } struct dirent *filespecs; errno = 0; while(NULL != (filespecs = readdir(dirp))) { //change to put files in certain order cout << filespecs->d_name << " "; } if(errno != 0) { perror("readdir()"); exit(1); } cout << endl; if(-1 == closedir(dirp)) { perror("closedir"); exit(1); } //return *filespecs; if used, return value is struct dirent } void ls_define(int argc, char* argv[])//insert parameters { //ls functionality cout << "ls" << endl;//REMOVE //fileSpecs(argc, directory_name); vector<string> destination; int arguments = 0; //000 int a = 0; while(a < argc) { if(a != 0 && argv[a][0] != '-') { cout << "destination: " << argv[a] << endl; destination.push_back(argv[a]); } else if(argv[a][0] == '-') { int b = 0; while(argv[a][b] != '\0') { if(argv[a][b] == 'a') { arguments = arguments | 1; } else if(argv[a][b] == 'l') { arguments = arguments | 2; } else if(argv[a][b] == 'R') { arguments = arguments | 4; } b++; } } a++; } if(destination.size() == 0) { destination.push_back(".");//Current destination } switch(arguments) { case 0: printNoArguments(); break; case 1: printAll(); break; case 2: printLong(); break; case 3: printAllLong(); break; case 4: printRecursive(); break; case 5: printAllRecursive(); break; case 6: printLongRecursive(); break; case 7: printAllLongRecursive(); break; default: cout << "Something went wrong" << endl; //REMOVE break; } /* //Need to figure out how to print -a -l as if it is -al for all arguments //create flags (-a, -l, -R) map<string, void(*)()> flag_functions; flag_functions["--all"] = printAll; flag_functions["-a"] = printAll; flag_functions["--long"] = printLong; flag_functions["-l"] = printLong; flag_functions["--recursive"] = printRecursive; flag_functions["-R"] = printRecursive; flag_functions["-al"] = printAllLong; flag_functions["-la"] = printAllLong; flag_functions["-aR"] = printAllRecursive; flag_functions["-Ra"] = printAllRecursive; flag_functions["-lR"] = printLongRecursive; flag_functions["-Rl"] = printLongRecursive; flag_functions["-alR"] = printAllLongRecursive; flag_functions["-aRl"] = printAllLongRecursive; flag_functions["-lRa"] = printAllLongRecursive; flag_functions["-laR"] = printAllLongRecursive; flag_functions["-Ral"] = printAllLongRecursive; flag_functions["-Rla"] = printAllLongRecursive; for(int i = 1; i < argc; i++) { void(*fp)() = flag_functions[string(argv[i])]; if(fp != NULL) { fp(); } else { cout << "Invalid Flag: " << argv[i] << endl; } } */ } void get_input(string& usr_input) { char arr[MAXSIZE]; char* argv[MAXSIZE]; char* argvcmd[MAXSIZE]; for(unsigned i = 0; i < MAXSIZE; i++) { arr[i] = 0; argv[i] = 0; argvcmd[i] = 0; } int index = 0; int start = 0; int j = 0; int n = 0; int c_cnt = 0; int tmp; for(unsigned i = 0; i < usr_input.size(); i++) { tmp = usr_input.at(i); if(tmp == ' ' || tmp == ';' || tmp == '&' || tmp == '|' || tmp == '#') { if(c_cnt > 0) { argv[j] = (char*)&arr[start]; j++; c_cnt = 0; arr[n] = '\0'; n++; } start = n; if(tmp != ' ') { if(tmp == '#') { start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; c_cnt = 0; i = usr_input.size(); j++; } else if(tmp == ';') { arr[n++] = ';'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; start = n; j++; c_cnt = 0; } else if(tmp == '&') { if(usr_input.at(i+1) == '&') { arr[n++] = '&'; arr[n++] = '&'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } else if(tmp == '|') { if(usr_input.at(i+1) == '|') { arr[n++] = '|'; arr[n++] = '|'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } } } else { arr[n] = usr_input.at(i); c_cnt++; n++; if(i == usr_input.size() - 1) { argv[j] = (char*)&arr[start]; n++; j++; } } } if(strcmp(argv[j-1], ";") != 0) { n++; start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; j++; } argv[j] = (char*)NULL; int status; for(int i = 0; i < j; i++) { if(strcmp(argv[i], "&&") == 0 || strcmp(argv[i], "||") == 0 || strcmp(argv[i], ";") == 0) { int pid; pid = fork(); if(pid < 0) { perror("fork"); } else if(pid == 0) { argvcmd[index] = NULL; if(!(strcmp(argvcmd[0], "ls"))) { ls_define(index, argvcmd); } else { status = execvp(argvcmd[0], argvcmd); } if(status == -1) { perror("execvp"); int x; int next = -1; if(strcmp(argv[i], "&&") == 0) { for(x = i + 1; x < j; x++) { if(strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } } if(next > 0) { i = next; } } } index = 0; exit(status); } else { } waitpid(-1, &status, 0); if(strcmp(argv[i], "&&") == 0 && (status > 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } if(strcmp(argv[i], "||") == 0 && (status == 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } index = 0; } else { if(index == 0 && (strcmp(argv[i], "exit")) == 0) { exit(1); } argvcmd[index] = argv[i]; index++; } } } void output() { char host[255]; string login = getlogin(); gethostname(host, 255); cout << login << "@" << host << " "; string usr_input; cout << "$"; cout << " "; getline(cin, usr_input); get_input(usr_input); } int main(int argc, char *argv[]) { while(1) { output(); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #pragma once #include <vector> #include <random> #include "vector.hpp" namespace lsh { /** * The mask class acts as sort of a bit mask that can reduce the dimensionality of * vectors by a projection. */ class mask { public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ virtual vector project(const vector& vector) const; }; class random_mask: public mask { private: /** * The number of dimensions in vector projections. */ unsigned int width_; /** * The randomly chosen indices to pick for vector projections. */ std::vector<unsigned int> indices_; public: /** * Construct a new mask. * * @param dimensionality The dimensionality of vectors to mask. * @param width The number of dimensions in vector projections. */ random_mask(unsigned int dimensions, unsigned int width); /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; }; class covering_mask: public mask { public: /** * A random mapping of vectors. */ typedef std::vector<vector> mapping; private: /** * The random mapping to use for this mask. */ mapping mapping_; public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; /** * Create a random mapping. * * @param dimensions The number of vectors in the mapping. * @param radius The radius that the mapping should cover. * @return The random mapping. */ static mapping create_mapping(unsigned int dimensions, unsigned int radius); }; } <commit_msg>Adjust a comment<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #pragma once #include <vector> #include <random> #include "vector.hpp" namespace lsh { /** * The mask class acts as sort of a bit mask that can reduce the dimensionality of * vectors by a projection. */ class mask { public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ virtual vector project(const vector& vector) const; }; class random_mask: public mask { private: /** * The number of dimensions in vector projections. */ unsigned int width_; /** * The randomly chosen indices to pick for vector projections. */ std::vector<unsigned int> indices_; public: /** * Construct a new random mask. * * @param dimensionality The dimensionality of vectors to mask. * @param width The number of dimensions in vector projections. */ random_mask(unsigned int dimensions, unsigned int width); /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; }; class covering_mask: public mask { public: /** * A random mapping of vectors. */ typedef std::vector<vector> mapping; private: /** * The random mapping to use for this mask. */ mapping mapping_; public: /** * Project a vector, reducing it to a dimensionality specified by this mask. * * @param vector The vector to project. * @return The projected vector. */ vector project(const vector& vector) const; /** * Create a random mapping. * * @param dimensions The number of vectors in the mapping. * @param radius The radius that the mapping should cover. * @return The random mapping. */ static mapping create_mapping(unsigned int dimensions, unsigned int radius); }; } <|endoftext|>
<commit_before>#include "mesh.h" #include "utils/logoutput.h" namespace cura { const int vertex_meld_distance = MM2INT(0.03); /*! * returns a hash for the location, but first divides by the vertex_meld_distance, * so that any point within a box of vertex_meld_distance by vertex_meld_distance would get mapped to the same hash. */ static inline uint32_t pointHash(const Point3& p) { return ((p.x + vertex_meld_distance/2) / vertex_meld_distance) ^ (((p.y + vertex_meld_distance/2) / vertex_meld_distance) << 10) ^ (((p.z + vertex_meld_distance/2) / vertex_meld_distance) << 20); } Mesh::Mesh(SettingsBaseVirtual* parent) : SettingsBase(parent) { } void Mesh::addFace(Point3& v0, Point3& v1, Point3& v2) { int vi0 = findIndexOfVertex(v0); int vi1 = findIndexOfVertex(v1); int vi2 = findIndexOfVertex(v2); if (vi0 == vi1 || vi1 == vi2 || vi0 == vi2) return; // the face has two vertices which get assigned the same location. Don't add the face. int idx = faces.size(); // index of face to be added faces.emplace_back(); MeshFace& face = faces[idx]; face.vertex_index[0] = vi0; face.vertex_index[1] = vi1; face.vertex_index[2] = vi2; vertices[face.vertex_index[0]].connected_faces.push_back(idx); vertices[face.vertex_index[1]].connected_faces.push_back(idx); vertices[face.vertex_index[2]].connected_faces.push_back(idx); } void Mesh::clear() { faces.clear(); vertices.clear(); vertex_hash_map.clear(); } void Mesh::finish() { // Finish up the mesh, clear the vertex_hash_map, as it's no longer needed from this point on and uses quite a bit of memory. vertex_hash_map.clear(); // For each face, store which other face is connected with it. for(unsigned int i=0; i<faces.size(); i++) { MeshFace& face = faces[i]; // faces are connected via the outside face.connected_face_index[0] = getFaceIdxWithPoints(face.vertex_index[0], face.vertex_index[1], i, face.vertex_index[2]); face.connected_face_index[1] = getFaceIdxWithPoints(face.vertex_index[1], face.vertex_index[2], i, face.vertex_index[0]); face.connected_face_index[2] = getFaceIdxWithPoints(face.vertex_index[2], face.vertex_index[0], i, face.vertex_index[1]); } } Point3 Mesh::min() const { return aabb.min; } Point3 Mesh::max() const { return aabb.max; } AABB3D Mesh::getAABB() const { return aabb; } int Mesh::findIndexOfVertex(const Point3& v) { uint32_t hash = pointHash(v); for(unsigned int idx = 0; idx < vertex_hash_map[hash].size(); idx++) { if ((vertices[vertex_hash_map[hash][idx]].p - v).testLength(vertex_meld_distance)) { return vertex_hash_map[hash][idx]; } } vertex_hash_map[hash].push_back(vertices.size()); vertices.emplace_back(v); aabb.include(v); return vertices.size() - 1; } /*! Returns the index of the 'other' face connected to the edge between vertices with indices idx0 and idx1. In case more than two faces are connected via the same edge, the next face in a counter-clockwise ordering (looking from idx1 to idx0) is returned. \cond DOXYGEN_EXCLUDE [NON-RENDERED COMENTS] For two faces abc and abd with normals n and m, we have that: \f{eqnarray*}{ n &=& \frac{ab \times ac}{\|ab \times ac\|} \\ m &=& \frac{ab \times ad}{\|ab \times ad\|} \\ n \times m &=& \|n\| \cdot \|m\| \mathbf{p} \sin \alpha \\ && (\mathbf{p} \perp n \wedge \mathbf{p} \perp m) \\ \sin \alpha &=& \|n \times m \| &=& \left\| \frac{(ab \times ac) \times (ab \times ad)}{\|ab \times ac\| \cdot \|ab \times ad\|} \right\| \\ &=& \left\| \frac{ (ab \cdot (ac \times ad)) ab }{\|ab \times ac\| \cdot \|ab \times ad\|} \right\| \\ &=& \frac{ (ab \cdot (ac \times ad)) \left\| ab \right\| }{\|ab\| \|ac\| \sin bac \cdot \|ab\| \|ad\| \sin bad} \\ &=& \frac{ ab \cdot (ac \times ad) }{\|ab\| \|ac\| \|ad\| \sin bac \sin bad} \\ \f}} \endcond See <a href="http://stackoverflow.com/questions/14066933/direct-way-of-computing-clockwise-angle-between-2-vectors">Direct way of computing clockwise angle between 2 vectors</a> */ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVertexIdx) const { std::vector<int> candidateFaces; // in case more than two faces meet at an edge, multiple candidates are generated for(int f : vertices[idx0].connected_faces) // search through all faces connected to the first vertex and find those that are also connected to the second { if (f == notFaceIdx) { continue; } if ( faces[f].vertex_index[0] == idx1 // && faces[f].vertex_index[1] == idx0 // next face should have the right direction! || faces[f].vertex_index[1] == idx1 // && faces[f].vertex_index[2] == idx0 || faces[f].vertex_index[2] == idx1 // && faces[f].vertex_index[0] == idx0 ) candidateFaces.push_back(f); } if (candidateFaces.size() == 0) { cura::logError("Couldn't find face connected to face %i.\n", notFaceIdx); return -1; } if (candidateFaces.size() == 1) { return candidateFaces[0]; } if (candidateFaces.size() % 2 == 0) cura::log("Warning! Edge with uneven number of faces connecting it!(%i)\n", candidateFaces.size()+1); FPoint3 vn = vertices[idx1].p - vertices[idx0].p; FPoint3 n = vn / vn.vSize(); // the normal of the plane in which all normals of faces connected to the edge lie => the normalized normal FPoint3 v0 = vertices[idx1].p - vertices[idx0].p; // the normals below are abnormally directed! : these normals all point counterclockwise (viewed from idx1 to idx0) from the face, irrespective of the direction of the face. FPoint3 n0 = FPoint3(vertices[notFaceVertexIdx].p - vertices[idx0].p).cross(v0); if (n0.vSize() <= 0) cura::log("Warning! Face %i has zero area!", notFaceIdx); double smallestAngle = 1000; // more then 2 PI (impossible angle) int bestIdx = -1; for (int candidateFace : candidateFaces) { int candidateVertex; {// find third vertex belonging to the face (besides idx0 and idx1) for (candidateVertex = 0; candidateVertex<3; candidateVertex++) if (faces[candidateFace].vertex_index[candidateVertex] != idx0 && faces[candidateFace].vertex_index[candidateVertex] != idx1) break; } FPoint3 v1 = vertices[candidateVertex].p -vertices[idx0].p; FPoint3 n1 = v1.cross(v0); double dot = n0 * n1; double det = n * n0.cross(n1); double angle = std::atan2(det, dot); if (angle < 0) angle += 2*M_PI; // 0 <= angle < 2* M_PI if (angle == 0) { cura::log("Warning! Overlapping faces: face %i and face %i.\n", notFaceIdx, candidateFace); std::cerr<< n.vSize() <<"; "<<n1.vSize()<<";"<<n0.vSize() <<std::endl; } if (angle < smallestAngle) { smallestAngle = angle; bestIdx = candidateFace; } } if (bestIdx < 0) cura::logError("Couldn't find face connected to face %i.\n", notFaceIdx); return bestIdx; } }//namespace cura <commit_msg>Removed anciend debug output<commit_after>#include "mesh.h" #include "utils/logoutput.h" namespace cura { const int vertex_meld_distance = MM2INT(0.03); /*! * returns a hash for the location, but first divides by the vertex_meld_distance, * so that any point within a box of vertex_meld_distance by vertex_meld_distance would get mapped to the same hash. */ static inline uint32_t pointHash(const Point3& p) { return ((p.x + vertex_meld_distance/2) / vertex_meld_distance) ^ (((p.y + vertex_meld_distance/2) / vertex_meld_distance) << 10) ^ (((p.z + vertex_meld_distance/2) / vertex_meld_distance) << 20); } Mesh::Mesh(SettingsBaseVirtual* parent) : SettingsBase(parent) { } void Mesh::addFace(Point3& v0, Point3& v1, Point3& v2) { int vi0 = findIndexOfVertex(v0); int vi1 = findIndexOfVertex(v1); int vi2 = findIndexOfVertex(v2); if (vi0 == vi1 || vi1 == vi2 || vi0 == vi2) return; // the face has two vertices which get assigned the same location. Don't add the face. int idx = faces.size(); // index of face to be added faces.emplace_back(); MeshFace& face = faces[idx]; face.vertex_index[0] = vi0; face.vertex_index[1] = vi1; face.vertex_index[2] = vi2; vertices[face.vertex_index[0]].connected_faces.push_back(idx); vertices[face.vertex_index[1]].connected_faces.push_back(idx); vertices[face.vertex_index[2]].connected_faces.push_back(idx); } void Mesh::clear() { faces.clear(); vertices.clear(); vertex_hash_map.clear(); } void Mesh::finish() { // Finish up the mesh, clear the vertex_hash_map, as it's no longer needed from this point on and uses quite a bit of memory. vertex_hash_map.clear(); // For each face, store which other face is connected with it. for(unsigned int i=0; i<faces.size(); i++) { MeshFace& face = faces[i]; // faces are connected via the outside face.connected_face_index[0] = getFaceIdxWithPoints(face.vertex_index[0], face.vertex_index[1], i, face.vertex_index[2]); face.connected_face_index[1] = getFaceIdxWithPoints(face.vertex_index[1], face.vertex_index[2], i, face.vertex_index[0]); face.connected_face_index[2] = getFaceIdxWithPoints(face.vertex_index[2], face.vertex_index[0], i, face.vertex_index[1]); } } Point3 Mesh::min() const { return aabb.min; } Point3 Mesh::max() const { return aabb.max; } AABB3D Mesh::getAABB() const { return aabb; } int Mesh::findIndexOfVertex(const Point3& v) { uint32_t hash = pointHash(v); for(unsigned int idx = 0; idx < vertex_hash_map[hash].size(); idx++) { if ((vertices[vertex_hash_map[hash][idx]].p - v).testLength(vertex_meld_distance)) { return vertex_hash_map[hash][idx]; } } vertex_hash_map[hash].push_back(vertices.size()); vertices.emplace_back(v); aabb.include(v); return vertices.size() - 1; } /*! Returns the index of the 'other' face connected to the edge between vertices with indices idx0 and idx1. In case more than two faces are connected via the same edge, the next face in a counter-clockwise ordering (looking from idx1 to idx0) is returned. \cond DOXYGEN_EXCLUDE [NON-RENDERED COMENTS] For two faces abc and abd with normals n and m, we have that: \f{eqnarray*}{ n &=& \frac{ab \times ac}{\|ab \times ac\|} \\ m &=& \frac{ab \times ad}{\|ab \times ad\|} \\ n \times m &=& \|n\| \cdot \|m\| \mathbf{p} \sin \alpha \\ && (\mathbf{p} \perp n \wedge \mathbf{p} \perp m) \\ \sin \alpha &=& \|n \times m \| &=& \left\| \frac{(ab \times ac) \times (ab \times ad)}{\|ab \times ac\| \cdot \|ab \times ad\|} \right\| \\ &=& \left\| \frac{ (ab \cdot (ac \times ad)) ab }{\|ab \times ac\| \cdot \|ab \times ad\|} \right\| \\ &=& \frac{ (ab \cdot (ac \times ad)) \left\| ab \right\| }{\|ab\| \|ac\| \sin bac \cdot \|ab\| \|ad\| \sin bad} \\ &=& \frac{ ab \cdot (ac \times ad) }{\|ab\| \|ac\| \|ad\| \sin bac \sin bad} \\ \f}} \endcond See <a href="http://stackoverflow.com/questions/14066933/direct-way-of-computing-clockwise-angle-between-2-vectors">Direct way of computing clockwise angle between 2 vectors</a> */ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVertexIdx) const { std::vector<int> candidateFaces; // in case more than two faces meet at an edge, multiple candidates are generated for(int f : vertices[idx0].connected_faces) // search through all faces connected to the first vertex and find those that are also connected to the second { if (f == notFaceIdx) { continue; } if ( faces[f].vertex_index[0] == idx1 // && faces[f].vertex_index[1] == idx0 // next face should have the right direction! || faces[f].vertex_index[1] == idx1 // && faces[f].vertex_index[2] == idx0 || faces[f].vertex_index[2] == idx1 // && faces[f].vertex_index[0] == idx0 ) candidateFaces.push_back(f); } if (candidateFaces.size() == 0) { cura::logError("Couldn't find face connected to face %i.\n", notFaceIdx); return -1; } if (candidateFaces.size() == 1) { return candidateFaces[0]; } if (candidateFaces.size() % 2 == 0) cura::log("Warning! Edge with uneven number of faces connecting it!(%i)\n", candidateFaces.size()+1); FPoint3 vn = vertices[idx1].p - vertices[idx0].p; FPoint3 n = vn / vn.vSize(); // the normal of the plane in which all normals of faces connected to the edge lie => the normalized normal FPoint3 v0 = vertices[idx1].p - vertices[idx0].p; // the normals below are abnormally directed! : these normals all point counterclockwise (viewed from idx1 to idx0) from the face, irrespective of the direction of the face. FPoint3 n0 = FPoint3(vertices[notFaceVertexIdx].p - vertices[idx0].p).cross(v0); if (n0.vSize() <= 0) cura::log("Warning! Face %i has zero area!", notFaceIdx); double smallestAngle = 1000; // more then 2 PI (impossible angle) int bestIdx = -1; for (int candidateFace : candidateFaces) { int candidateVertex; {// find third vertex belonging to the face (besides idx0 and idx1) for (candidateVertex = 0; candidateVertex<3; candidateVertex++) if (faces[candidateFace].vertex_index[candidateVertex] != idx0 && faces[candidateFace].vertex_index[candidateVertex] != idx1) break; } FPoint3 v1 = vertices[candidateVertex].p -vertices[idx0].p; FPoint3 n1 = v1.cross(v0); double dot = n0 * n1; double det = n * n0.cross(n1); double angle = std::atan2(det, dot); if (angle < 0) angle += 2*M_PI; // 0 <= angle < 2* M_PI if (angle == 0) { cura::log("Warning! Overlapping faces: face %i and face %i.\n", notFaceIdx, candidateFace); } if (angle < smallestAngle) { smallestAngle = angle; bestIdx = candidateFace; } } if (bestIdx < 0) cura::logError("Couldn't find face connected to face %i.\n", notFaceIdx); return bestIdx; } }//namespace cura <|endoftext|>
<commit_before>#include "nano.h" #include "losses/square.h" #include "losses/cauchy.h" #include "losses/logistic.h" #include "losses/classnll.h" #include "losses/exponential.h" #include "tasks/task_mnist.h" #include "tasks/task_cifar10.h" #include "tasks/task_cifar100.h" #include "tasks/task_stl10.h" #include "tasks/task_svhn.h" #include "tasks/task_charset.h" #include "tasks/task_affine.h" #include "layers/activation_unit.h" #include "layers/activation_tanh.h" #include "layers/activation_snorm.h" #include "layers/activation_splus.h" #include "layers/convolution.h" #include "layers/affine.h" #include "models/forward_network.h" #include "trainers/batch.h" #include "trainers/stochastic.h" #include "criteria/l2nreg.h" #include "criteria/varreg.h" #include "stoch/ag.h" #include "stoch/adam.h" #include "stoch/adagrad.h" #include "stoch/adadelta.h" #include "stoch/ngd.h" #include "stoch/sg.h" #include "stoch/sgm.h" #include "stoch/svrg.h" #include "stoch/asgd.h" #include "batch/gd.h" #include "batch/cgd.h" #include "batch/lbfgs.h" #include <cfenv> namespace nano { task_manager_t& get_tasks() { static task_manager_t manager; return manager; } layer_manager_t& get_layers() { static layer_manager_t manager; return manager; } model_manager_t& get_models() { static model_manager_t manager; return manager; } loss_manager_t& get_losses() { static loss_manager_t manager; return manager; } criterion_manager_t& get_criteria() { static criterion_manager_t manager; return manager; } trainer_manager_t& get_trainers() { static trainer_manager_t manager; return manager; } stoch_optimizer_manager_t& get_stoch_optimizers() { static stoch_optimizer_manager_t manager; return manager; } batch_optimizer_manager_t& get_batch_optimizers() { static batch_optimizer_manager_t manager; return manager; } template <typename tobject> static auto maker() { return [] (const string_t& config) { return std::make_unique<tobject>(config); }; } static void init_batch_optimizers() { auto& f = nano::get_batch_optimizers(); f.add("gd", "gradient descent", maker<batch_gd_t>()); f.add("cgd", "nonlinear conjugate gradient descent (default)", maker<batch_cgd_prp_t>()); f.add("cgd-n", "nonlinear conjugate gradient descent (N)", maker<batch_cgd_n_t>()); f.add("cgd-hs", "nonlinear conjugate gradient descent (HS)", maker<batch_cgd_hs_t>()); f.add("cgd-fr", "nonlinear conjugate gradient descent (FR)", maker<batch_cgd_fr_t>()); f.add("cgd-prp", "nonlinear conjugate gradient descent (PRP+)", maker<batch_cgd_prp_t>()); f.add("cgd-cd", "nonlinear conjugate gradient descent (CD)", maker<batch_cgd_cd_t>()); f.add("cgd-ls", "nonlinear conjugate gradient descent (LS)", maker<batch_cgd_ls_t>()); f.add("cgd-dy", "nonlinear conjugate gradient descent (DY)", maker<batch_cgd_dy_t>()); f.add("cgd-dycd", "nonlinear conjugate gradient descent (DYCD)", maker<batch_cgd_dycd_t>()); f.add("cgd-dyhs", "nonlinear conjugate gradient descent (DYHS)", maker<batch_cgd_dyhs_t>()); f.add("lbfgs", "limited-memory BFGS", maker<batch_lbfgs_t>()); } static void init_stoch_optimizers() { auto& f = nano::get_stoch_optimizers(); f.add("sg", "stochastic gradient (descent)", maker<stoch_sg_t>()); f.add("sgm", "stochastic gradient (descent) with momentum", maker<stoch_sgm_t>()); f.add("ngd", "stochastic normalized gradient", maker<stoch_ngd_t>()); f.add("svrg", "stochastic variance reduced gradient", maker<stoch_svrg_t>()); f.add("asgd", "averaged stochastic gradient (descent)", maker<stoch_asgd_t>()); f.add("ag", "Nesterov's accelerated gradient", maker<stoch_ag_t>()); f.add("agfr", "Nesterov's accelerated gradient with function value restarts", maker<stoch_agfr_t>()); f.add("aggr", "Nesterov's accelerated gradient with gradient restarts", maker<stoch_aggr_t>()); f.add("adam", "Adam (see citation)", maker<stoch_adam_t>()); f.add("adagrad", "AdaGrad (see citation)", maker<stoch_adagrad_t>()); f.add("adadelta", "AdaDelta (see citation)", maker<stoch_adadelta_t>()); } static void init_trainers() { auto& f = nano::get_trainers(); f.add("batch", "batch trainer", maker<batch_trainer_t>()); f.add("stoch", "stochastic trainer", maker<stochastic_trainer_t>()); } static void init_criteria() { auto& f = nano::get_criteria(); f.add("avg", "average loss", maker<average_criterion_t>()); f.add("avg-l2n", "L2-norm regularized average loss", maker<average_l2n_criterion_t>()); f.add("avg-var", "variance-regularized average loss", maker<average_var_criterion_t>()); f.add("max", "softmax loss", maker<softmax_criterion_t>()); f.add("max-l2n", "L2-norm regularized softmax loss", maker<softmax_l2n_criterion_t>()); f.add("max-var", "variance-regularized softmax loss", maker<softmax_var_criterion_t>()); } static void init_losses() { auto& f = nano::get_losses(); f.add("square", "square loss (regression)", maker<square_loss_t>()); f.add("cauchy", "Cauchy loss (regression)", maker<cauchy_loss_t>()); f.add("logistic", "logistic loss (multi-class classification)", maker<logistic_loss_t>()); f.add("classnll", "negative log-likelihood loss (multi-class classification)", maker<classnll_loss_t>()); f.add("exponential", "exponential loss (multi-class classification)", maker<exponential_loss_t>()); } static void init_tasks() { auto& f = nano::get_tasks(); f.add("mnist", "MNIST (1x28x28 digit classification)", maker<mnist_task_t>()); f.add("cifar10", "CIFAR-10 (3x32x32 object classification)", maker<cifar10_task_t>()); f.add("cifar100", "CIFAR-100 (3x32x32 object classification)", maker<cifar100_task_t>()); f.add("stl10", "STL-10 (3x96x96 semi-supervised object classification)", maker<stl10_task_t>()); f.add("svhn", "SVHN (3x32x32 digit classification in the wild)", maker<svhn_task_t>()); f.add("charset", "synthetic character classification", maker<charset_task_t>()); f.add("affine", "synthetic affine regression", maker<affine_task_t>()); } static void init_layers() { auto& f = nano::get_layers(); f.add("act-unit", "identity activation layer (for testing purposes)", maker<unit_activation_layer_t>()); f.add("act-tanh", "hyperbolic tangent activation layer", maker<tanh_activation_layer_t>()); f.add("act-snorm", "x/sqrt(1+x^2) activation layer", maker<snorm_activation_layer_t>()); f.add("act-splus", "soft-plus activation layer", maker<softplus_activation_layer_t>()); f.add("affine", "fully-connected affine layer", maker<affine_layer_t>()); f.add("conv", "convolution layer", maker<convolution_layer_t>()); } static void init_models() { auto& f = nano::get_models(); f.add("forward-network", "feed-forward network", maker<forward_network_t>()); } struct init_t { init_t() { // round to nearest integer std::fesetround(FE_TONEAREST); // use Eigen with multiple threads Eigen::initParallel(); Eigen::setNbThreads(0); // register objects init_tasks(); init_layers(); init_models(); init_losses(); init_criteria(); init_trainers(); init_batch_optimizers(); init_stoch_optimizers(); } }; static const init_t the_initializer; } <commit_msg>better format the description of layers and loss functions<commit_after>#include "nano.h" #include "losses/square.h" #include "losses/cauchy.h" #include "losses/logistic.h" #include "losses/classnll.h" #include "losses/exponential.h" #include "tasks/task_mnist.h" #include "tasks/task_cifar10.h" #include "tasks/task_cifar100.h" #include "tasks/task_stl10.h" #include "tasks/task_svhn.h" #include "tasks/task_charset.h" #include "tasks/task_affine.h" #include "layers/activation_unit.h" #include "layers/activation_tanh.h" #include "layers/activation_snorm.h" #include "layers/activation_splus.h" #include "layers/convolution.h" #include "layers/affine.h" #include "models/forward_network.h" #include "trainers/batch.h" #include "trainers/stochastic.h" #include "criteria/l2nreg.h" #include "criteria/varreg.h" #include "stoch/ag.h" #include "stoch/adam.h" #include "stoch/adagrad.h" #include "stoch/adadelta.h" #include "stoch/ngd.h" #include "stoch/sg.h" #include "stoch/sgm.h" #include "stoch/svrg.h" #include "stoch/asgd.h" #include "batch/gd.h" #include "batch/cgd.h" #include "batch/lbfgs.h" #include <cfenv> namespace nano { task_manager_t& get_tasks() { static task_manager_t manager; return manager; } layer_manager_t& get_layers() { static layer_manager_t manager; return manager; } model_manager_t& get_models() { static model_manager_t manager; return manager; } loss_manager_t& get_losses() { static loss_manager_t manager; return manager; } criterion_manager_t& get_criteria() { static criterion_manager_t manager; return manager; } trainer_manager_t& get_trainers() { static trainer_manager_t manager; return manager; } stoch_optimizer_manager_t& get_stoch_optimizers() { static stoch_optimizer_manager_t manager; return manager; } batch_optimizer_manager_t& get_batch_optimizers() { static batch_optimizer_manager_t manager; return manager; } template <typename tobject> static auto maker() { return [] (const string_t& config) { return std::make_unique<tobject>(config); }; } static void init_batch_optimizers() { auto& f = nano::get_batch_optimizers(); f.add("gd", "gradient descent", maker<batch_gd_t>()); f.add("cgd", "nonlinear conjugate gradient descent (default)", maker<batch_cgd_prp_t>()); f.add("cgd-n", "nonlinear conjugate gradient descent (N)", maker<batch_cgd_n_t>()); f.add("cgd-hs", "nonlinear conjugate gradient descent (HS)", maker<batch_cgd_hs_t>()); f.add("cgd-fr", "nonlinear conjugate gradient descent (FR)", maker<batch_cgd_fr_t>()); f.add("cgd-prp", "nonlinear conjugate gradient descent (PRP+)", maker<batch_cgd_prp_t>()); f.add("cgd-cd", "nonlinear conjugate gradient descent (CD)", maker<batch_cgd_cd_t>()); f.add("cgd-ls", "nonlinear conjugate gradient descent (LS)", maker<batch_cgd_ls_t>()); f.add("cgd-dy", "nonlinear conjugate gradient descent (DY)", maker<batch_cgd_dy_t>()); f.add("cgd-dycd", "nonlinear conjugate gradient descent (DYCD)", maker<batch_cgd_dycd_t>()); f.add("cgd-dyhs", "nonlinear conjugate gradient descent (DYHS)", maker<batch_cgd_dyhs_t>()); f.add("lbfgs", "limited-memory BFGS", maker<batch_lbfgs_t>()); } static void init_stoch_optimizers() { auto& f = nano::get_stoch_optimizers(); f.add("sg", "stochastic gradient (descent)", maker<stoch_sg_t>()); f.add("sgm", "stochastic gradient (descent) with momentum", maker<stoch_sgm_t>()); f.add("ngd", "stochastic normalized gradient", maker<stoch_ngd_t>()); f.add("svrg", "stochastic variance reduced gradient", maker<stoch_svrg_t>()); f.add("asgd", "averaged stochastic gradient (descent)", maker<stoch_asgd_t>()); f.add("ag", "Nesterov's accelerated gradient", maker<stoch_ag_t>()); f.add("agfr", "Nesterov's accelerated gradient with function value restarts", maker<stoch_agfr_t>()); f.add("aggr", "Nesterov's accelerated gradient with gradient restarts", maker<stoch_aggr_t>()); f.add("adam", "Adam (see citation)", maker<stoch_adam_t>()); f.add("adagrad", "AdaGrad (see citation)", maker<stoch_adagrad_t>()); f.add("adadelta", "AdaDelta (see citation)", maker<stoch_adadelta_t>()); } static void init_trainers() { auto& f = nano::get_trainers(); f.add("batch", "batch trainer", maker<batch_trainer_t>()); f.add("stoch", "stochastic trainer", maker<stochastic_trainer_t>()); } static void init_criteria() { auto& f = nano::get_criteria(); f.add("avg", "average loss", maker<average_criterion_t>()); f.add("avg-l2n", "L2-norm regularized average loss", maker<average_l2n_criterion_t>()); f.add("avg-var", "variance-regularized average loss", maker<average_var_criterion_t>()); f.add("max", "softmax loss", maker<softmax_criterion_t>()); f.add("max-l2n", "L2-norm regularized softmax loss", maker<softmax_l2n_criterion_t>()); f.add("max-var", "variance-regularized softmax loss", maker<softmax_var_criterion_t>()); } static void init_losses() { auto& f = nano::get_losses(); f.add("square", "multivariate regression: l(y, t) = 1/2 * L2(y, t)", maker<square_loss_t>()); f.add("cauchy", "multivariate regression: l(y, t) = log(1 + L2(y, t))", maker<cauchy_loss_t>()); f.add("logistic", "multi-class classification: l(y, t) = log(1 + exp(-t.dot(y)))", maker<logistic_loss_t>()); f.add("classnll", "single-class classification: l(y, t) = log(y.exp().sum()) + 1/2 * (1 + t).dot(y)", maker<classnll_loss_t>()); f.add("exponential", "multi-class classification: l(y, t) = exp(-t.dot(y))", maker<exponential_loss_t>()); } static void init_tasks() { auto& f = nano::get_tasks(); f.add("mnist", "MNIST (1x28x28 digit classification)", maker<mnist_task_t>()); f.add("cifar10", "CIFAR-10 (3x32x32 object classification)", maker<cifar10_task_t>()); f.add("cifar100", "CIFAR-100 (3x32x32 object classification)", maker<cifar100_task_t>()); f.add("stl10", "STL-10 (3x96x96 semi-supervised object classification)", maker<stl10_task_t>()); f.add("svhn", "SVHN (3x32x32 digit classification in the wild)", maker<svhn_task_t>()); f.add("charset", "synthetic character classification", maker<charset_task_t>()); f.add("affine", "synthetic affine regression", maker<affine_task_t>()); } static void init_layers() { auto& f = nano::get_layers(); f.add("act-unit", "activation: a(x) = x", maker<unit_activation_layer_t>()); f.add("act-tanh", "activation: a(x) = tanh(x)", maker<tanh_activation_layer_t>()); f.add("act-snorm", "activation: a(x) = x / sqrt(1 + x^2)", maker<snorm_activation_layer_t>()); f.add("act-splus", "activation: a(x) = log(1 + e^x)", maker<softplus_activation_layer_t>()); f.add("affine", "transform: L(x) = A * x + b", maker<affine_layer_t>()); f.add("conv", "transform: L(x) = conv3D(x, kernel) + b", maker<convolution_layer_t>()); } static void init_models() { auto& f = nano::get_models(); f.add("forward-network", "feed-forward network", maker<forward_network_t>()); } struct init_t { init_t() { // round to nearest integer std::fesetround(FE_TONEAREST); // use Eigen with multiple threads Eigen::initParallel(); Eigen::setNbThreads(0); // register objects init_tasks(); init_layers(); init_models(); init_losses(); init_criteria(); init_trainers(); init_batch_optimizers(); init_stoch_optimizers(); } }; static const init_t the_initializer; } <|endoftext|>
<commit_before>#include "oowe/oowe.h" #include <iostream> #include <iomanip> namespace oowe { void init(long flags) { OOWE_CHECK_ERROR_THROW(curl_global_init(flags)); } void init(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c) { OOWE_CHECK_ERROR_THROW(curl_global_init_mem(flags, m, f, r, s, c)); } void cleanup(void) { curl_global_cleanup(); } curl_version_info_data & version(CURLversion type) { return *curl_version_info(type); } char * version(void) { return curl_version(); } }; /* Namespace oowe */ #define COLOR(col, msg) "\033[" #col "m" msg "\033[0m" #define CHECK_FEATURES(feature, msg) \ if(info.features & CURL_VERSION_ ## feature) os << PREFIX " " << std::left << std::setw(41) << msg << " = " << COLOR(32, "yes") << std::endl; \ else os << PREFIX " " << std::left << std::setw(41) << msg << " = " << COLOR(31, "no" ) << std::endl; #define PREFIX "# " std::ostream & operator <<(std::ostream & os, curl_version_info_data & info) { int age = (int) info.age; os << PREFIX "Age = " << age << std::endl; if(age >= CURLVERSION_FIRST) { os << PREFIX "Version = \"" << info.version << '"' << std::endl; os << PREFIX "Version = " << CURL_VERSION_MAJOR(info.version_num) << '.' << CURL_VERSION_MINOR(info.version_num) << '.' << CURL_VERSION_PATCH(info.version_num) << std::endl; os << PREFIX "Host = \"" << info.host << '"' << std::endl; os << PREFIX "Features =" << std::endl; CHECK_FEATURES(IPV6 , "Support IPv6" ) CHECK_FEATURES(KERBEROS4 , "Support Kerberos V4 auth" ) CHECK_FEATURES(KERBEROS5 , "Support Kerberos V5 auth" ) CHECK_FEATURES(SSL , "Support SSL" ) CHECK_FEATURES(LIBZ , "Support libz" ) CHECK_FEATURES(NTLM , "Support NTLM auth" ) CHECK_FEATURES(GSSNEGOTIATE, "Support GSS Negotiate" ) CHECK_FEATURES(DEBUG , "Debug built" ) CHECK_FEATURES(ASYNCHDNS , "Asynchronous DNS resolves" ) CHECK_FEATURES(SPNEGO , "Support SPNEGO auth" ) CHECK_FEATURES(LARGEFILE , "Support files larger than 2GB" ) CHECK_FEATURES(IDN , "Support Internationized Domain Names" ) CHECK_FEATURES(SSPI , "Support Windows SSPI" ) CHECK_FEATURES(CONV , "Support character conversions" ) CHECK_FEATURES(CURLDEBUG , "Support debug memory tracking" ) CHECK_FEATURES(TLSAUTH_SRP , "Support TLS-SRP auth" ) CHECK_FEATURES(NTLM_WB , "Support NTLM delegation to winbind helper") CHECK_FEATURES(HTTP2 , "Support HTTP2" ) CHECK_FEATURES(GSSAPI , "GSS-API built" ) CHECK_FEATURES(UNIX_SOCKETS, "Support Unix domain sockets" ) os << PREFIX "SSL Version = \"" << info.ssl_version << "\" / " << info.ssl_version_num << std::endl; os << PREFIX "libz Version = \"" << info.libz_version << '"' << std::endl; os << PREFIX "Protocols = \""; for(int i = 0; info.protocols[i]; i++) { os << info.protocols[i]; if(info.protocols[i+1]) os << ' ' ; } os << '"' << std::endl; } if(age >= CURLVERSION_SECOND) os << PREFIX "Ares Version = \"" << (info.ares ? info.ares : "[" COLOR(31 ,"NONE") "]") << "\" / " << info.ares_num << std::endl; if(age >= CURLVERSION_THIRD) os << PREFIX "libidn Version = \"" << (info.libidn ? info.libidn : "[" COLOR(31 ,"NONE") "]") << '"' << std::endl; if(age >= CURLVERSION_FOURTH) { os << PREFIX "iconv Version = " << info.iconv_ver_num << std::endl; os << PREFIX "libssh Version = \"" << (info.libssh_version ? info.libssh_version : "[" COLOR(31 ,"NONE") "]") << '"' << std::endl; } return os; } <commit_msg>Versioning cURL features<commit_after>#include "oowe/oowe.h" #include <iostream> #include <iomanip> namespace oowe { void init(long flags) { OOWE_CHECK_ERROR_THROW(curl_global_init(flags)); } void init(long flags, curl_malloc_callback m, curl_free_callback f, curl_realloc_callback r, curl_strdup_callback s, curl_calloc_callback c) { OOWE_CHECK_ERROR_THROW(curl_global_init_mem(flags, m, f, r, s, c)); } void cleanup(void) { curl_global_cleanup(); } curl_version_info_data & version(CURLversion type) { return *curl_version_info(type); } char * version(void) { return curl_version(); } }; /* Namespace oowe */ #define COLOR(col, msg) "\033[" #col "m" msg "\033[0m" #define CHECK_FEATURES(feature, msg) \ if(info.features & CURL_VERSION_ ## feature) os << PREFIX " " << std::left << std::setw(41) << msg << " = " << COLOR(32, "yes") << std::endl; \ else os << PREFIX " " << std::left << std::setw(41) << msg << " = " << COLOR(31, "no" ) << std::endl; #define PREFIX "# " std::ostream & operator <<(std::ostream & os, curl_version_info_data & info) { int age = (int) info.age; os << PREFIX "Age = " << age << std::endl; if(age >= CURLVERSION_FIRST) { os << PREFIX "Version = \"" << info.version << '"' << std::endl; os << PREFIX "Version = " << CURL_VERSION_MAJOR(info.version_num) << '.' << CURL_VERSION_MINOR(info.version_num) << '.' << CURL_VERSION_PATCH(info.version_num) << std::endl; os << PREFIX "Host = \"" << info.host << '"' << std::endl; os << PREFIX "Features =" << std::endl; CHECK_FEATURES(IPV6 , "Support IPv6" ) CHECK_FEATURES(KERBEROS4 , "Support Kerberos V4 auth" ) #if CURL_VERSION_GREATER(7, 40, 0) CHECK_FEATURES(KERBEROS5 , "Support Kerberos V5 auth" ) #endif CHECK_FEATURES(SSL , "Support SSL" ) CHECK_FEATURES(LIBZ , "Support libz" ) CHECK_FEATURES(NTLM , "Support NTLM auth" ) CHECK_FEATURES(GSSNEGOTIATE, "Support GSS Negotiate" ) CHECK_FEATURES(DEBUG , "Debug built" ) CHECK_FEATURES(ASYNCHDNS , "Asynchronous DNS resolves" ) CHECK_FEATURES(SPNEGO , "Support SPNEGO auth" ) CHECK_FEATURES(LARGEFILE , "Support files larger than 2GB" ) CHECK_FEATURES(IDN , "Support Internationized Domain Names" ) CHECK_FEATURES(SSPI , "Support Windows SSPI" ) CHECK_FEATURES(CONV , "Support character conversions" ) CHECK_FEATURES(CURLDEBUG , "Support debug memory tracking" ) CHECK_FEATURES(TLSAUTH_SRP , "Support TLS-SRP auth" ) CHECK_FEATURES(NTLM_WB , "Support NTLM delegation to winbind helper") CHECK_FEATURES(HTTP2 , "Support HTTP2" ) CHECK_FEATURES(GSSAPI , "GSS-API built" ) #if CURL_VERSION_GREATER(7, 40, 0) CHECK_FEATURES(UNIX_SOCKETS, "Support Unix domain sockets" ) #endif os << PREFIX "SSL Version = \"" << info.ssl_version << "\" / " << info.ssl_version_num << std::endl; os << PREFIX "libz Version = \"" << info.libz_version << '"' << std::endl; os << PREFIX "Protocols = \""; for(int i = 0; info.protocols[i]; i++) { os << info.protocols[i]; if(info.protocols[i+1]) os << ' ' ; } os << '"' << std::endl; } if(age >= CURLVERSION_SECOND) os << PREFIX "Ares Version = \"" << (info.ares ? info.ares : "[" COLOR(31 ,"NONE") "]") << "\" / " << info.ares_num << std::endl; if(age >= CURLVERSION_THIRD) os << PREFIX "libidn Version = \"" << (info.libidn ? info.libidn : "[" COLOR(31 ,"NONE") "]") << '"' << std::endl; if(age >= CURLVERSION_FOURTH) { os << PREFIX "iconv Version = " << info.iconv_ver_num << std::endl; os << PREFIX "libssh Version = \"" << (info.libssh_version ? info.libssh_version : "[" COLOR(31 ,"NONE") "]") << '"' << std::endl; } return os; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2007 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <string> /* interface header */ #include "ServerItem.h" /* common implementation headers */ #include "TextUtils.h" #include "Protocol.h" #include "bzfio.h" /* local implementation headers */ #include "ServerListCache.h" ServerItem::ServerItem() : updateTime(0), cached(false), favorite(false) { } void ServerItem::writeToFile(std::ostream& out) const { char buffer[ServerListCache::max_string+1]; // ServerListCache::max_string is inherited from ServerListCache.h // write out desc. memset(buffer,0,sizeof(buffer)); int copyLength = int(description.size() < ServerListCache::max_string ? description.size(): ServerListCache::max_string); strncpy(&buffer[0],description.c_str(),copyLength); out.write(buffer,sizeof(buffer)); // write out name memset(buffer,0,sizeof(buffer)); copyLength = int(name.size() < ServerListCache::max_string ? name.size(): ServerListCache::max_string); strncpy(&buffer[0],name.c_str(),copyLength); out.write(buffer,sizeof(buffer)); // write out pingpacket ping.writeToFile(out); nboPackUByte(buffer, favorite); out.write(buffer, 1); // write out current time memset(buffer,0,sizeof(buffer)); nboPackInt(buffer,(int32_t)updateTime); out.write(&buffer[0], 4); } bool ServerItem::readFromFile(std::istream& in) { char buffer[ServerListCache::max_string+1]; //read description memset(buffer,0,sizeof(buffer)); in.read(buffer,sizeof(buffer)); if ((size_t)in.gcount() < sizeof(buffer)) return false; // failed to read entire string description = buffer; //read name memset(buffer,0,sizeof(buffer)); in.read(buffer,sizeof(buffer)); if ((size_t)in.gcount() < sizeof(buffer)) return false; // failed to read entire string name = buffer; bool pingWorked = ping.readFromFile(in); if (!pingWorked) return false; // pingpacket failed to read // read in favorite flag uint8_t fav; in.read(buffer, 1); nboUnpackUByte(buffer, fav); favorite = (fav != 0); // read in time in.read(&buffer[0],4); if (in.gcount() < 4) return false; int32_t theTime; nboUnpackInt(&buffer[0],theTime); updateTime = (time_t) theTime; cached = true; return true; } // set the last updated time to now void ServerItem::resetAge() { updateTime = getNow(); } /* set the age of this item (useful for updating entries while keeping * the server list sorted) */ void ServerItem::setAge(time_t minutes, time_t seconds) { updateTime = getNow() - (minutes * 60) - seconds; } // get current age in minutes time_t ServerItem::getAgeMinutes() const { time_t time = (getNow() - updateTime)/(time_t)60; return time; } // get current age in seconds time_t ServerItem::getAgeSeconds() const { time_t time = (getNow() - updateTime); return time; } // get a simple string which describes the age of item std::string ServerItem::getAgeString() const { std::string returnMe; char buffer [80]; time_t age = getAgeMinutes(); float fAge; if (age < 60){ // < 1 hr if (age < 1){ time_t ageSecs = getAgeSeconds(); sprintf(buffer,"%-3ld secs",(long)ageSecs); } else { sprintf(buffer,"%-3ld mins",(long)age); } } else { // >= 60 minutes if (age < (24*60)){ // < 24 hours & > 1 hr fAge = ((float)age / 60.0f); sprintf(buffer, "%-2.1f hrs", fAge); } else { // > 24 hrs if (age < (24*60*99)){ // > 1 day & < 99 days fAge = ((float) age / (60.0f*24.0f)); sprintf(buffer, "%-2.1f days", fAge); } else { // over 99 days fAge = ((float) age / (60.0f*24.0f)); sprintf(buffer, "%-3f days", fAge); //should not happen } } } returnMe = buffer; return returnMe; } // get the current time time_t ServerItem::getNow() const { #if defined(_WIN32) return time(NULL); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec; #endif } int ServerItem::getPlayerCount() const { // if null ping we return a 0 player count int curPlayer = 0; if (&ping != 0) { int maxPlayer = ping.maxPlayers; curPlayer = ping.rogueCount + ping.redCount + ping.greenCount + ping.blueCount + ping.purpleCount + ping.observerCount; if (curPlayer > maxPlayer) curPlayer = maxPlayer; } return curPlayer; } std::string ServerItem::getAddrName() const { if (name.size() <= 0) { return std::string(""); } return TextUtils::format("%s:%d", name.c_str(), ntohs(ping.serverId.port)); } unsigned int ServerItem::getSortFactor() const { // if null ping we return a 0 player count unsigned int value = 0; if (&ping != 0) { // real players are worth a 1000 value = ping.rogueCount + ping.redCount + ping.greenCount + ping.blueCount + ping.purpleCount; value *= 10000; // include the lowly observers, 1 point each value += ping.observerCount; } return value; } bool operator<(const ServerItem &left, const ServerItem &right) { // sorted "from least to greatest" in the list // so "return true" to go up, "return false" to go down // cached servers go to the bottom of the list if (left.cached && !right.cached) { return false; } else if (!left.cached && right.cached) { return true; } // sort by player count - more first if (left.getSortFactor() > right.getSortFactor()) { return true; } else if (left.getSortFactor() < right.getSortFactor()) { return false; } // sort by age - youngest first // note that noncached servers always have equal ages time_t ageLeft = (left.getAgeMinutes() * 60) + left.getAgeSeconds(); time_t ageRight = (right.getAgeMinutes() * 60) + right.getAgeSeconds(); if (ageLeft < ageRight) { return true; } else if (ageLeft > ageRight) { return false; } // hostname alphabetic sort - first goes first if (left.name < right.name) { return true; } else if (left.name > right.name) { return false; } // sort by port - default first, then lowest to highest if (left.port == ServerPort) { return true; } else if (right.port == ServerPort) { return false; } else if (left.port < right.port) { return true; } else { return false; } logDebugMessage(0, "Error: operator<: equality detected.\n"); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>unreachable code<commit_after>/* bzflag * Copyright (c) 1993 - 2007 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" /* system headers */ #include <string> /* interface header */ #include "ServerItem.h" /* common implementation headers */ #include "TextUtils.h" #include "Protocol.h" #include "bzfio.h" /* local implementation headers */ #include "ServerListCache.h" ServerItem::ServerItem() : updateTime(0), cached(false), favorite(false) { } void ServerItem::writeToFile(std::ostream& out) const { char buffer[ServerListCache::max_string+1]; // ServerListCache::max_string is inherited from ServerListCache.h // write out desc. memset(buffer,0,sizeof(buffer)); int copyLength = int(description.size() < ServerListCache::max_string ? description.size(): ServerListCache::max_string); strncpy(&buffer[0],description.c_str(),copyLength); out.write(buffer,sizeof(buffer)); // write out name memset(buffer,0,sizeof(buffer)); copyLength = int(name.size() < ServerListCache::max_string ? name.size(): ServerListCache::max_string); strncpy(&buffer[0],name.c_str(),copyLength); out.write(buffer,sizeof(buffer)); // write out pingpacket ping.writeToFile(out); nboPackUByte(buffer, favorite); out.write(buffer, 1); // write out current time memset(buffer,0,sizeof(buffer)); nboPackInt(buffer,(int32_t)updateTime); out.write(&buffer[0], 4); } bool ServerItem::readFromFile(std::istream& in) { char buffer[ServerListCache::max_string+1]; //read description memset(buffer,0,sizeof(buffer)); in.read(buffer,sizeof(buffer)); if ((size_t)in.gcount() < sizeof(buffer)) return false; // failed to read entire string description = buffer; //read name memset(buffer,0,sizeof(buffer)); in.read(buffer,sizeof(buffer)); if ((size_t)in.gcount() < sizeof(buffer)) return false; // failed to read entire string name = buffer; bool pingWorked = ping.readFromFile(in); if (!pingWorked) return false; // pingpacket failed to read // read in favorite flag uint8_t fav; in.read(buffer, 1); nboUnpackUByte(buffer, fav); favorite = (fav != 0); // read in time in.read(&buffer[0],4); if (in.gcount() < 4) return false; int32_t theTime; nboUnpackInt(&buffer[0],theTime); updateTime = (time_t) theTime; cached = true; return true; } // set the last updated time to now void ServerItem::resetAge() { updateTime = getNow(); } /* set the age of this item (useful for updating entries while keeping * the server list sorted) */ void ServerItem::setAge(time_t minutes, time_t seconds) { updateTime = getNow() - (minutes * 60) - seconds; } // get current age in minutes time_t ServerItem::getAgeMinutes() const { time_t time = (getNow() - updateTime)/(time_t)60; return time; } // get current age in seconds time_t ServerItem::getAgeSeconds() const { time_t time = (getNow() - updateTime); return time; } // get a simple string which describes the age of item std::string ServerItem::getAgeString() const { std::string returnMe; char buffer [80]; time_t age = getAgeMinutes(); float fAge; if (age < 60){ // < 1 hr if (age < 1){ time_t ageSecs = getAgeSeconds(); sprintf(buffer,"%-3ld secs",(long)ageSecs); } else { sprintf(buffer,"%-3ld mins",(long)age); } } else { // >= 60 minutes if (age < (24*60)){ // < 24 hours & > 1 hr fAge = ((float)age / 60.0f); sprintf(buffer, "%-2.1f hrs", fAge); } else { // > 24 hrs if (age < (24*60*99)){ // > 1 day & < 99 days fAge = ((float) age / (60.0f*24.0f)); sprintf(buffer, "%-2.1f days", fAge); } else { // over 99 days fAge = ((float) age / (60.0f*24.0f)); sprintf(buffer, "%-3f days", fAge); //should not happen } } } returnMe = buffer; return returnMe; } // get the current time time_t ServerItem::getNow() const { #if defined(_WIN32) return time(NULL); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec; #endif } int ServerItem::getPlayerCount() const { // if null ping we return a 0 player count int curPlayer = 0; if (&ping != 0) { int maxPlayer = ping.maxPlayers; curPlayer = ping.rogueCount + ping.redCount + ping.greenCount + ping.blueCount + ping.purpleCount + ping.observerCount; if (curPlayer > maxPlayer) curPlayer = maxPlayer; } return curPlayer; } std::string ServerItem::getAddrName() const { if (name.size() <= 0) { return std::string(""); } return TextUtils::format("%s:%d", name.c_str(), ntohs(ping.serverId.port)); } unsigned int ServerItem::getSortFactor() const { // if null ping we return a 0 player count unsigned int value = 0; if (&ping != 0) { // real players are worth a 1000 value = ping.rogueCount + ping.redCount + ping.greenCount + ping.blueCount + ping.purpleCount; value *= 10000; // include the lowly observers, 1 point each value += ping.observerCount; } return value; } bool operator<(const ServerItem &left, const ServerItem &right) { // sorted "from least to greatest" in the list // so "return true" to go up, "return false" to go down // cached servers go to the bottom of the list if (left.cached && !right.cached) { return false; } else if (!left.cached && right.cached) { return true; } // sort by player count - more first if (left.getSortFactor() > right.getSortFactor()) { return true; } else if (left.getSortFactor() < right.getSortFactor()) { return false; } // sort by age - youngest first // note that noncached servers always have equal ages time_t ageLeft = (left.getAgeMinutes() * 60) + left.getAgeSeconds(); time_t ageRight = (right.getAgeMinutes() * 60) + right.getAgeSeconds(); if (ageLeft < ageRight) { return true; } else if (ageLeft > ageRight) { return false; } // hostname alphabetic sort - first goes first if (left.name < right.name) { return true; } else if (left.name > right.name) { return false; } // sort by port - default first, then lowest to highest if (left.port == ServerPort) { return true; } else if (right.port == ServerPort) { return false; } else if (left.port < right.port) { return true; } else if (left.port > right.port) { return false; } logDebugMessage(0, "Error: operator<: equality detected.\n"); return false; // arbitrary } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "graphics/shader.h" #include "core/fs/file_system.h" #include "core/fs/ifile.h" #include "core/json_serializer.h" #include "core/log.h" #include "core/matrix.h" #include "core/profiler.h" #include "core/resource_manager.h" #include "core/resource_manager_base.h" #include "core/vec3.h" #include "graphics/gl_ext.h" #include "graphics/shader_manager.h" namespace Lumix { Shader::Shader(const Path& path, ResourceManager& resource_manager) : Resource(path, resource_manager) , m_vertex_id() , m_fragment_id() , m_is_shadowmap_required(true) { m_program_id = glCreateProgram(); } Shader::~Shader() { glDeleteProgram(m_program_id); glDeleteShader(m_vertex_id); glDeleteShader(m_fragment_id); } GLint Shader::getUniformLocation(const char* name, uint32_t name_hash) { for (int i = 0, c = m_uniforms.size(); i < c; ++i) { if (m_uniforms[i].m_name_hash == name_hash) { return m_uniforms[i].m_location; } } CachedUniform& unif = m_uniforms.pushEmpty(); unif.m_name_hash = name_hash; unif.m_location = glGetUniformLocation(m_program_id, name); return unif.m_location; } GLuint Shader::attach(GLenum type, const char* src, int32_t length) { GLuint id = glCreateShader(type); glShaderSource(id, 1, (const GLchar**)&src, &length); glCompileShader(id); glAttachShader(m_program_id, id); return id; } void Shader::loaded(FS::IFile* file, bool success, FS::FileSystem& fs) { if(success) { JsonSerializer serializer(*file, JsonSerializer::READ, m_path.c_str()); serializer.deserializeObjectBegin(); char attributes[MAX_ATTRIBUTE_COUNT][31]; int attribute_count = 0; while (!serializer.isObjectEnd()) { char label[256]; serializer.deserializeLabel(label, 255); if (strcmp(label, "attributes") == 0) { serializer.deserializeArrayBegin(); while (!serializer.isArrayEnd()) { serializer.deserializeArrayItem(attributes[attribute_count], 30); ++attribute_count; if (attribute_count == MAX_ATTRIBUTE_COUNT) { g_log_error.log("renderer") << "Too many vertex attributes in shader " << m_path.c_str(); onFailure(); fs.close(file); return; } } serializer.deserializeArrayEnd(); } else if (strcmp(label, "shadowmap_required") == 0) { serializer.deserialize(m_is_shadowmap_required); } } serializer.deserializeObjectEnd(); int32_t size = serializer.getRestOfFileSize(); ShaderManager* manager = static_cast<ShaderManager*>(getResourceManager().get(ResourceManager::SHADER)); char* buf = reinterpret_cast<char*>(manager->getBuffer(size + 1)); serializer.deserializeRawString(buf, size); buf[size] = '\0'; char* end = strstr(buf, "//~VS"); if (!end) { g_log_error.log("renderer") << "Could not process shader file " << m_path.c_str(); onFailure(); fs.close(file); return; } int32_t vs_len = (int32_t)(end - buf); buf[vs_len-1] = 0; m_vertex_id = attach(GL_VERTEX_SHADER, buf, vs_len); m_fragment_id = attach(GL_FRAGMENT_SHADER, buf + vs_len, size - vs_len); glLinkProgram(m_program_id); GLint link_status; glGetProgramiv(m_program_id, GL_LINK_STATUS, &link_status); if (link_status != GL_TRUE) { g_log_error.log("renderer") << "Could not link shader " << m_path.c_str(); onFailure(); fs.close(file); return; } for (int i = 0; i < attribute_count; ++i) { m_vertex_attributes_ids[i] = glGetAttribLocation(m_program_id, attributes[i]); } m_fixed_cached_uniforms[(int)FixedCachedUniforms::WORLD_MATRIX] = glGetUniformLocation(m_program_id, "world_matrix"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::GRASS_MATRICES] = glGetUniformLocation(m_program_id, "grass_matrices"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::MORPH_CONST] = glGetUniformLocation(m_program_id, "morph_const"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::QUAD_SIZE] = glGetUniformLocation(m_program_id, "quad_size"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::QUAD_MIN] = glGetUniformLocation(m_program_id, "quad_min"); m_size = file->size(); decrementDepCount(); } else { g_log_error.log("renderer") << "Could not load shader " << m_path.c_str(); onFailure(); } fs.close(file); } void Shader::doUnload(void) { glDeleteProgram(m_program_id); glDeleteShader(m_vertex_id); glDeleteShader(m_fragment_id); m_program_id = glCreateProgram(); m_vertex_id = 0; m_fragment_id = 0; m_size = 0; onEmpty(); } FS::ReadCallback Shader::getReadCallback() { FS::ReadCallback cb; cb.bind<Shader, &Shader::loaded>(this); return cb; } } // ~namespace Lumix <commit_msg>reset cached uniforms when a shader is reloaded<commit_after>#include "graphics/shader.h" #include "core/fs/file_system.h" #include "core/fs/ifile.h" #include "core/json_serializer.h" #include "core/log.h" #include "core/matrix.h" #include "core/profiler.h" #include "core/resource_manager.h" #include "core/resource_manager_base.h" #include "core/vec3.h" #include "graphics/gl_ext.h" #include "graphics/shader_manager.h" namespace Lumix { Shader::Shader(const Path& path, ResourceManager& resource_manager) : Resource(path, resource_manager) , m_vertex_id() , m_fragment_id() , m_is_shadowmap_required(true) { m_program_id = glCreateProgram(); } Shader::~Shader() { glDeleteProgram(m_program_id); glDeleteShader(m_vertex_id); glDeleteShader(m_fragment_id); } GLint Shader::getUniformLocation(const char* name, uint32_t name_hash) { for (int i = 0, c = m_uniforms.size(); i < c; ++i) { if (m_uniforms[i].m_name_hash == name_hash) { return m_uniforms[i].m_location; } } CachedUniform& unif = m_uniforms.pushEmpty(); unif.m_name_hash = name_hash; unif.m_location = glGetUniformLocation(m_program_id, name); return unif.m_location; } GLuint Shader::attach(GLenum type, const char* src, int32_t length) { GLuint id = glCreateShader(type); glShaderSource(id, 1, (const GLchar**)&src, &length); glCompileShader(id); glAttachShader(m_program_id, id); return id; } void Shader::loaded(FS::IFile* file, bool success, FS::FileSystem& fs) { if(success) { JsonSerializer serializer(*file, JsonSerializer::READ, m_path.c_str()); serializer.deserializeObjectBegin(); char attributes[MAX_ATTRIBUTE_COUNT][31]; int attribute_count = 0; while (!serializer.isObjectEnd()) { char label[256]; serializer.deserializeLabel(label, 255); if (strcmp(label, "attributes") == 0) { serializer.deserializeArrayBegin(); while (!serializer.isArrayEnd()) { serializer.deserializeArrayItem(attributes[attribute_count], 30); ++attribute_count; if (attribute_count == MAX_ATTRIBUTE_COUNT) { g_log_error.log("renderer") << "Too many vertex attributes in shader " << m_path.c_str(); onFailure(); fs.close(file); return; } } serializer.deserializeArrayEnd(); } else if (strcmp(label, "shadowmap_required") == 0) { serializer.deserialize(m_is_shadowmap_required); } } serializer.deserializeObjectEnd(); int32_t size = serializer.getRestOfFileSize(); ShaderManager* manager = static_cast<ShaderManager*>(getResourceManager().get(ResourceManager::SHADER)); char* buf = reinterpret_cast<char*>(manager->getBuffer(size + 1)); serializer.deserializeRawString(buf, size); buf[size] = '\0'; char* end = strstr(buf, "//~VS"); if (!end) { g_log_error.log("renderer") << "Could not process shader file " << m_path.c_str(); onFailure(); fs.close(file); return; } int32_t vs_len = (int32_t)(end - buf); buf[vs_len-1] = 0; m_vertex_id = attach(GL_VERTEX_SHADER, buf, vs_len); m_fragment_id = attach(GL_FRAGMENT_SHADER, buf + vs_len, size - vs_len); glLinkProgram(m_program_id); GLint link_status; glGetProgramiv(m_program_id, GL_LINK_STATUS, &link_status); if (link_status != GL_TRUE) { g_log_error.log("renderer") << "Could not link shader " << m_path.c_str(); onFailure(); fs.close(file); return; } for (int i = 0; i < attribute_count; ++i) { m_vertex_attributes_ids[i] = glGetAttribLocation(m_program_id, attributes[i]); } m_fixed_cached_uniforms[(int)FixedCachedUniforms::WORLD_MATRIX] = glGetUniformLocation(m_program_id, "world_matrix"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::GRASS_MATRICES] = glGetUniformLocation(m_program_id, "grass_matrices"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::MORPH_CONST] = glGetUniformLocation(m_program_id, "morph_const"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::QUAD_SIZE] = glGetUniformLocation(m_program_id, "quad_size"); m_fixed_cached_uniforms[(int)FixedCachedUniforms::QUAD_MIN] = glGetUniformLocation(m_program_id, "quad_min"); m_size = file->size(); decrementDepCount(); } else { g_log_error.log("renderer") << "Could not load shader " << m_path.c_str(); onFailure(); } fs.close(file); } void Shader::doUnload(void) { m_uniforms.clear(); glDeleteProgram(m_program_id); glDeleteShader(m_vertex_id); glDeleteShader(m_fragment_id); m_program_id = glCreateProgram(); m_vertex_id = 0; m_fragment_id = 0; m_size = 0; onEmpty(); } FS::ReadCallback Shader::getReadCallback() { FS::ReadCallback cb; cb.bind<Shader, &Shader::loaded>(this); return cb; } } // ~namespace Lumix <|endoftext|>
<commit_before>#include "DataSetModel.hh" #include "DataSetItem.hh" #include "MetaTypes.hh" #include <QDebug> #include <QIcon> namespace aleph { namespace gui { DataSetModel::DataSetModel( QObject* parent ) : QAbstractItemModel( parent ) , _root( new DataSetItem( QString(), QVariant() ) ) { QList<DataSetItem*> topLevelItems = { new DataSetItem( tr("Persistence diagrams"), QVariant::fromValue( PersistenceDiagram() ), _root ), new DataSetItem( tr("Point clouds") , QVariant(), _root ), new DataSetItem( tr("Simplicial complexes"), QVariant::fromValue( SimplicialComplex() ), _root ) }; foreach( DataSetItem* item, topLevelItems ) _root->append( item ); } DataSetModel::~DataSetModel() { delete _root; } QModelIndex DataSetModel::parent( const QModelIndex& index ) const { if( !index.isValid() ) return QModelIndex(); auto child = static_cast<DataSetItem*>( index.internalPointer() ); auto parent = child->parent(); if( parent == _root ) return QModelIndex(); return this->createIndex( parent->row(), 0, parent ); } QModelIndex DataSetModel::index( int row, int column, const QModelIndex& parent ) const { if( !this->hasIndex( row, column, parent ) ) return QModelIndex(); DataSetItem* parentItem = nullptr; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); auto child = parentItem->child( row ); if( child ) return this->createIndex( row, column, child ); else return QModelIndex(); } int DataSetModel::rowCount( const QModelIndex& parent ) const { DataSetItem* parentItem = nullptr; if( parent.column() > 0 ) return 0; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); return parentItem->childCount(); } int DataSetModel::columnCount( const QModelIndex& parent ) const { if( parent.isValid() ) return static_cast<DataSetItem*>( parent.internalPointer() )->columnCount(); else return _root->columnCount(); } QVariant DataSetModel::headerData( int section, Qt::Orientation orientation, int role ) const { if( orientation == Qt::Horizontal && role == Qt::DisplayRole ) return DataSetItem::columnNames[section]; return QVariant(); } QVariant DataSetModel::data( const QModelIndex& index, int role ) const { if( !index.isValid() ) return QVariant(); DataSetItem* item = static_cast<DataSetItem*>( index.internalPointer() ); if( role == Qt::DecorationRole && index.column() == 0 && item->parent() == _root ) return QIcon::fromTheme( "folder" ); else if( role == Qt::DisplayRole ) return item->data( index.column() ); return QVariant(); } void DataSetModel::add( const QString& title, const QVariant& data ) { int id_PersistenceDiagram = qMetaTypeId<PersistenceDiagram>(); int id_SimplicialComplex = qMetaTypeId<SimplicialComplex>(); int userType = data.userType(); if( userType != id_PersistenceDiagram && userType != id_SimplicialComplex ) { qDebug() << "Ignoring unknown user type"; return; } for( int i = 0; i < _root->childCount(); i++ ) { auto child = _root->child( i ); if( child && child->type() == userType ) { qDebug() << "Found proper parent item; adding data"; child->append( new DataSetItem( title, data, child ) ); } } } } // namespace gui } // namespace aleph <commit_msg>Fixed incorrect model insertion<commit_after>#include "DataSetModel.hh" #include "DataSetItem.hh" #include "MetaTypes.hh" #include <QDebug> #include <QIcon> namespace aleph { namespace gui { DataSetModel::DataSetModel( QObject* parent ) : QAbstractItemModel( parent ) , _root( new DataSetItem( QString(), QVariant() ) ) { QList<DataSetItem*> topLevelItems = { new DataSetItem( tr("Persistence diagrams"), QVariant::fromValue( PersistenceDiagram() ), _root ), new DataSetItem( tr("Point clouds") , QVariant(), _root ), new DataSetItem( tr("Simplicial complexes"), QVariant::fromValue( SimplicialComplex() ), _root ) }; foreach( DataSetItem* item, topLevelItems ) _root->append( item ); } DataSetModel::~DataSetModel() { delete _root; } QModelIndex DataSetModel::parent( const QModelIndex& index ) const { if( !index.isValid() ) return QModelIndex(); auto child = static_cast<DataSetItem*>( index.internalPointer() ); auto parent = child->parent(); if( parent == _root ) return QModelIndex(); return this->createIndex( parent->row(), 0, parent ); } QModelIndex DataSetModel::index( int row, int column, const QModelIndex& parent ) const { if( !this->hasIndex( row, column, parent ) ) return QModelIndex(); DataSetItem* parentItem = nullptr; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); auto child = parentItem->child( row ); if( child ) return this->createIndex( row, column, child ); else return QModelIndex(); } int DataSetModel::rowCount( const QModelIndex& parent ) const { DataSetItem* parentItem = nullptr; if( parent.column() > 0 ) return 0; if( !parent.isValid() ) parentItem = _root; else parentItem = static_cast<DataSetItem*>( parent.internalPointer() ); return parentItem->childCount(); } int DataSetModel::columnCount( const QModelIndex& parent ) const { if( parent.isValid() ) return static_cast<DataSetItem*>( parent.internalPointer() )->columnCount(); else return _root->columnCount(); } QVariant DataSetModel::headerData( int section, Qt::Orientation orientation, int role ) const { if( orientation == Qt::Horizontal && role == Qt::DisplayRole ) return DataSetItem::columnNames[section]; return QVariant(); } QVariant DataSetModel::data( const QModelIndex& index, int role ) const { if( !index.isValid() ) return QVariant(); DataSetItem* item = static_cast<DataSetItem*>( index.internalPointer() ); if( role == Qt::DecorationRole && index.column() == 0 && item->parent() == _root ) return QIcon::fromTheme( "folder" ); else if( role == Qt::DisplayRole ) return item->data( index.column() ); return QVariant(); } void DataSetModel::add( const QString& title, const QVariant& data ) { int id_PersistenceDiagram = qMetaTypeId<PersistenceDiagram>(); int id_SimplicialComplex = qMetaTypeId<SimplicialComplex>(); int userType = data.userType(); if( userType != id_PersistenceDiagram && userType != id_SimplicialComplex ) { qDebug() << "Ignoring unknown user type"; return; } for( int i = 0; i < _root->childCount(); i++ ) { auto child = _root->child( i ); if( child && child->type() == userType ) { auto index = this->index( child->row(), 0, this->index( _root->row(), 0 ) ); auto first = child->row() + 1; auto last = first; this->beginInsertRows( index, first, last ); qDebug() << "Found proper parent item; adding data"; child->append( new DataSetItem( title, data, child ) ); this->endInsertRows(); } } } } // namespace gui } // namespace aleph <|endoftext|>
<commit_before>#include "hext/match-tree.h" #include "hext/rule.h" namespace hext { match_tree::match_tree() : children(), matches(), r(nullptr) { } match_tree * match_tree::append_child_and_own(std::unique_ptr<match_tree> m) { this->children.push_back(std::move(m)); return this->children.back().get(); } void match_tree::append_match(const name_value_pair& p) { this->matches.push_back(p); } void match_tree::json_print(std::ostream& out) const { for(const auto& c : this->children) { out << "{"; infix_ostream_iterator<std::string> it_out(out, ", "); this->json_print_recursive(it_out); out << "}\n"; } } void match_tree::json_print_recursive( infix_ostream_iterator<std::string>& out ) const { for(const auto& p : this->matches) { std::string str("\""); str.append(util::escape_quotes(p.first)) .append("\": \"") .append(util::escape_quotes(p.second)) .append("\""); out = str; } for(const auto& c : this->children) c->json_print_recursive(out); } void match_tree::print(std::ostream& out) const { out << "digraph match_tree {\n" << " node [fontname=\"Arial\"];\n"; this->print_dot(out); out << "}\n"; } void match_tree::print_dot(std::ostream& out, int parent_id) const { static int node_index = 0; int this_node = ++node_index; std::string label; if( this->r == nullptr || this->r->get_tag_name().empty() ) label.append("[rule]"); else label.append(this->r->get_tag_name()); for(const auto& m : this->matches) { label.append(" "); label.append(m.first); } if( this->r && this->r->children_size() == 0 ) label.append("*"); out << " node_" << this_node << " [label=\"" << label << "\"];\n"; if( parent_id ) out << " node_" << parent_id << " -> node_" << this_node << ";\n"; for(const auto& c : this->children) c->print_dot(out, this_node); } void match_tree::set_rule(const rule * matching_rule) { this->r = matching_rule; } void match_tree::filter() { bool filter_ret = this->filter_recursive(); // TODO: move this into matcher? if( this->children.size() == 1 && this->matches.empty() ) { // TODO: is this bullet-proof? std::swap(this->children, this->children.front()->children); } } bool match_tree::filter_recursive() { // if the matching rule has no more children, we have a complete // match of a rule path, therefore we want to keep this branch by // returning false. if( this->r && this->r->children_size() == 0 ) return false; for(auto& c : this->children) { if( c->filter_recursive() ) c.reset(nullptr); } // erase all empty unique_ptr this->children.erase( std::remove(this->children.begin(), this->children.end(), nullptr), this->children.end() ); // if there is no matching rule and there are no children, the branch // is non matching and must be removed if( this->r == nullptr ) return this->children.empty(); // there must be at least as many matches as there are child-rules, // if not, this branch is non matching and must be removed else return this->r->children_size() > this->children.size(); } } // namespace hext <commit_msg>move empty match-tree reduction into filter_recursive<commit_after>#include "hext/match-tree.h" #include "hext/rule.h" namespace hext { match_tree::match_tree() : children(), matches(), r(nullptr) { } match_tree * match_tree::append_child_and_own(std::unique_ptr<match_tree> m) { this->children.push_back(std::move(m)); return this->children.back().get(); } void match_tree::append_match(const name_value_pair& p) { this->matches.push_back(p); } void match_tree::json_print(std::ostream& out) const { for(const auto& c : this->children) { out << "{"; infix_ostream_iterator<std::string> it_out(out, ", "); this->json_print_recursive(it_out); out << "}\n"; } } void match_tree::json_print_recursive( infix_ostream_iterator<std::string>& out ) const { for(const auto& p : this->matches) { std::string str("\""); str.append(util::escape_quotes(p.first)) .append("\": \"") .append(util::escape_quotes(p.second)) .append("\""); out = str; } for(const auto& c : this->children) c->json_print_recursive(out); } void match_tree::print(std::ostream& out) const { out << "digraph match_tree {\n" << " node [fontname=\"Arial\"];\n"; this->print_dot(out); out << "}\n"; } void match_tree::print_dot(std::ostream& out, int parent_id) const { static int node_index = 0; int this_node = ++node_index; std::string label; if( this->r == nullptr || this->r->get_tag_name().empty() ) label.append("[rule]"); else label.append(this->r->get_tag_name()); for(const auto& m : this->matches) { label.append(" "); label.append(m.first); } if( this->r && this->r->children_size() == 0 ) label.append("*"); out << " node_" << this_node << " [label=\"" << label << "\"];\n"; if( parent_id ) out << " node_" << parent_id << " -> node_" << this_node << ";\n"; for(const auto& c : this->children) c->print_dot(out, this_node); } void match_tree::set_rule(const rule * matching_rule) { this->r = matching_rule; } void match_tree::filter() { bool filter_ret = this->filter_recursive(); } bool match_tree::filter_recursive() { // TODO: move this into matcher? if( this->children.size() == 1 && this->matches.empty() ) { // TODO: is this bullet-proof? std::swap(this->children, this->children.front()->children); } // if the matching rule has no more children, we have a complete // match of a rule path, therefore we want to keep this branch by // returning false. if( this->r && this->r->children_size() == 0 ) return false; for(auto& c : this->children) { if( c->filter_recursive() ) c.reset(nullptr); } // erase all empty unique_ptr this->children.erase( std::remove(this->children.begin(), this->children.end(), nullptr), this->children.end() ); // if there is no matching rule and there are no children, the branch // is non matching and must be removed if( this->r == nullptr ) return this->children.empty(); // there must be at least as many matches as there are child-rules, // if not, this branch is non matching and must be removed else return this->r->children_size() > this->children.size(); } } // namespace hext <|endoftext|>
<commit_before>#include "HttpServer.h" #include "../string_utils.h" #include <iostream> Http::HttpServer::HttpServer(size_t threadCount) : threadCount(threadCount), server("0.0.0.0", "80") { threadpool.reserve(threadCount); } void Http::HttpServer::stop() { stopped = false; } bool Http::HttpServer::isStopped() const { return stopped; } void Http::HttpServer::start() { //Spawn worker threads for (size_t i = 0; i < threadCount; i++) { threadpool.push_back(std::thread([=] { threadNetworkHandler(); })); threadpool[i].detach(); } std::cout << "Listening for connections..." << std::endl; while (!stopped) { try { auto client = server.acceptfrom(); //Grab a lock for the queue to push the new connection too std::lock_guard<std::mutex> lock(clientQueueMutex); clientQueue.push(std::move(client)); clientQueueConditionVariable.notify_one(); } catch (sockets::StringError& e) { std::cout << e.what() << std::endl; } } } void Http::HttpServer::threadNetworkHandler() { while (!stopped) { //Aquire the lock (wait until lock is aquired) std::unique_lock<std::mutex> lock(clientQueueMutex); if (clientQueue.empty()) clientQueueConditionVariable.wait(lock); //Explicitly move the the connection out of the queue sockets::TCPConnection client; sockets::abl::IpAddress addr; std::tie(client, addr) = std::move(clientQueue.front()); clientQueue.pop(); std::cout << "[" << std::this_thread::get_id() << "] handling connection for " << addr.name() << std::endl; //We don't need the queue anymore lock.unlock(); try { //Read the client data auto buffer = client.read(HTTP_READ_AMOUNT); Http::HttpRequest req = Http::parseHttpRequest(std::string(buffer.begin(), buffer.end())); Http::HttpResponse res = httpRequestHandler(req); Http::sendResponse(client, res); } catch (Http::RequestError &e) { Http::HttpResponse res = buildError(400, "Bad Request", defaultHtml("400 - Bad Request", "400 - Bad Request", e.what())); Http::sendResponse(client, res); } catch (sockets::StringError &e) { std::cerr << "[" << std::this_thread::get_id() << "]" << "Error: " << e.what() << std::endl; } } } Http::HttpResponse Http::HttpServer::httpRequestHandler(HttpRequest req) const { if (req.method == GET) { std::ifstream file = Http::openFile(req); //C++ has no way to check if a file exists, or for file permissions, so we just assume it doesn't work if there's an error. if (!file) return buildError(404, "Not Found", defaultHtml("404 - Not Found", "404 - Not Found", "The requested resouce could not be found on this server")); //Extact the file contents into a string stream std::ostringstream fileContents; fileContents << file.rdbuf(); std::string body = fileContents.str(); file.close(); //Everything is okay. Reply with 200. HttpResponse rv { HTTP_VERSION, 200, "OK", std::map<std::string, std::string>{ {"Server", SERVER_NAME}, {"Content-Type", guessMime(req.path)}, {"Content-Length", std::to_string(body.length())}, {"Connection", "close"} }, body }; //Easter egg if (utils::string::endsWith(req.path, "html")) utils::string::replace(rv.body, "{SERVERNAME}", SERVER_NAME); return rv; } //For everything else, return not implemented return buildError(501, "Not Implemented", defaultHtml("501 - Not Implemented", "501 - Not Implemented", "The requested action is not implemented on this server.")); } <commit_msg>Updated StringUtils<commit_after>#include "HttpServer.h" #include "../StringUtils.h" #include <iostream> Http::HttpServer::HttpServer(size_t threadCount) : threadCount(threadCount), server("0.0.0.0", "80") { threadpool.reserve(threadCount); } void Http::HttpServer::stop() { stopped = false; } bool Http::HttpServer::isStopped() const { return stopped; } void Http::HttpServer::start() { //Spawn worker threads for (size_t i = 0; i < threadCount; i++) { threadpool.push_back(std::thread([=] { threadNetworkHandler(); })); threadpool[i].detach(); } std::cout << "Listening for connections..." << std::endl; while (!stopped) { try { auto client = server.acceptfrom(); //Grab a lock for the queue to push the new connection too std::lock_guard<std::mutex> lock(clientQueueMutex); clientQueue.push(std::move(client)); clientQueueConditionVariable.notify_one(); } catch (sockets::StringError& e) { std::cout << e.what() << std::endl; } } } void Http::HttpServer::threadNetworkHandler() { while (!stopped) { //Aquire the lock (wait until lock is aquired) std::unique_lock<std::mutex> lock(clientQueueMutex); if (clientQueue.empty()) clientQueueConditionVariable.wait(lock); //Explicitly move the the connection out of the queue sockets::TCPConnection client; sockets::abl::IpAddress addr; std::tie(client, addr) = std::move(clientQueue.front()); clientQueue.pop(); std::cout << "[" << std::this_thread::get_id() << "] handling connection for " << addr.name() << std::endl; //We don't need the queue anymore lock.unlock(); try { //Read the client data auto buffer = client.read(HTTP_READ_AMOUNT); Http::HttpRequest req = Http::parseHttpRequest(std::string(buffer.begin(), buffer.end())); Http::HttpResponse res = httpRequestHandler(req); Http::sendResponse(client, res); } catch (Http::RequestError &e) { Http::HttpResponse res = buildError(400, "Bad Request", defaultHtml("400 - Bad Request", "400 - Bad Request", e.what())); Http::sendResponse(client, res); } catch (sockets::StringError &e) { std::cerr << "[" << std::this_thread::get_id() << "]" << "Error: " << e.what() << std::endl; } } } Http::HttpResponse Http::HttpServer::httpRequestHandler(HttpRequest req) const { if (req.method == GET) { std::ifstream file = Http::openFile(req); //C++ has no way to check if a file exists, or for file permissions, so we just assume it doesn't work if there's an error. if (!file) return buildError(404, "Not Found", defaultHtml("404 - Not Found", "404 - Not Found", "The requested resouce could not be found on this server")); //Extact the file contents into a string stream std::ostringstream fileContents; fileContents << file.rdbuf(); std::string body = fileContents.str(); file.close(); //Everything is okay. Reply with 200. HttpResponse rv { HTTP_VERSION, 200, "OK", std::map<std::string, std::string>{ {"Server", SERVER_NAME}, {"Content-Type", guessMime(req.path)}, {"Content-Length", std::to_string(body.length())}, {"Connection", "close"} }, body }; //Easter egg if (utils::endsWith(req.path, "html")) utils::replace(rv.body, "{SERVERNAME}", SERVER_NAME); return rv; } //For everything else, return not implemented return buildError(501, "Not Implemented", defaultHtml("501 - Not Implemented", "501 - Not Implemented", "The requested action is not implemented on this server.")); } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/http_connection.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <asio/ip/tcp.hpp> #include <string> using boost::bind; namespace libtorrent { void http_connection::get(std::string const& url, time_duration timeout) { std::string protocol; std::string hostname; std::string path; int port; boost::tie(protocol, hostname, port, path) = parse_url_components(url); std::stringstream headers; headers << "GET " << path << " HTTP/1.0\r\n" "Host:" << hostname << "Connection: close\r\n" "\r\n\r\n"; sendbuffer = headers.str(); start(hostname, boost::lexical_cast<std::string>(port), timeout); } void http_connection::start(std::string const& hostname, std::string const& port , time_duration timeout) { m_timeout = timeout; m_timer.expires_from_now(m_timeout); m_timer.async_wait(bind(&http_connection::on_timeout , boost::weak_ptr<http_connection>(shared_from_this()), _1)); m_called = false; if (m_sock.is_open() && m_hostname == hostname && m_port == port) { m_parser.reset(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } else { m_sock.close(); tcp::resolver::query query(hostname, port); m_resolver.async_resolve(query, bind(&http_connection::on_resolve , shared_from_this(), _1, _2)); m_hostname = hostname; m_port = port; } } void http_connection::on_timeout(boost::weak_ptr<http_connection> p , asio::error_code const& e) { if (e == asio::error::operation_aborted) return; boost::shared_ptr<http_connection> c = p.lock(); if (!c) return; if (c->m_bottled && c->m_called) return; if (c->m_last_receive + c->m_timeout < time_now()) { c->m_called = true; c->m_handler(asio::error::timed_out, c->m_parser, 0, 0); return; } c->m_timer.expires_at(c->m_last_receive + c->m_timeout); c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1)); } void http_connection::close() { m_timer.cancel(); m_limiter_timer.cancel(); m_limiter_timer_active = false; m_sock.close(); m_hostname.clear(); m_port.clear(); } void http_connection::on_resolve(asio::error_code const& e , tcp::resolver::iterator i) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } assert(i != tcp::resolver::iterator()); m_sock.async_connect(*i, boost::bind(&http_connection::on_connect , shared_from_this(), _1/*, ++i*/)); } void http_connection::on_connect(asio::error_code const& e /*, tcp::resolver::iterator i*/) { if (!e) { m_last_receive = time_now(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } /* else if (i != tcp::resolver::iterator()) { // The connection failed. Try the next endpoint in the list. m_sock.close(); m_sock.async_connect(*i, bind(&http_connection::on_connect , shared_from_this(), _1, ++i)); } */ else { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } void http_connection::on_write(asio::error_code const& e) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } std::string().swap(sendbuffer); m_recvbuffer.resize(4096); int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_read(asio::error_code const& e , std::size_t bytes_transferred) { if (m_rate_limit) { m_download_quota -= bytes_transferred; assert(m_download_quota >= 0); } if (e == asio::error::eof) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error_code(), m_parser, 0, 0); return; } if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } m_read_pos += bytes_transferred; assert(m_read_pos <= int(m_recvbuffer.size())); if (m_bottled || !m_parser.header_finished()) { libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0] , &m_recvbuffer[0] + m_read_pos); m_parser.incoming(rcv_buf); if (!m_bottled && m_parser.header_finished()) { if (m_read_pos > m_parser.body_start()) m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start() , m_read_pos - m_parser.body_start()); m_read_pos = 0; m_last_receive = time_now(); } else if (m_bottled && m_parser.finished()) { m_timer.cancel(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } else { assert(!m_bottled); m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos); m_read_pos = 0; m_last_receive = time_now(); } if (int(m_recvbuffer.size()) == m_read_pos) m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500)); if (m_read_pos == 1024 * 500) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error::eof, m_parser, 0, 0); return; } int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_assign_bandwidth(asio::error_code const& e) { if (e == asio::error::operation_aborted && m_limiter_timer_active) { if (!m_bottled || !m_called) m_handler(e, m_parser, 0, 0); } m_limiter_timer_active = false; if (e) return; if (m_download_quota > 0) return; m_download_quota = m_rate_limit / 4; int amount_to_read = m_recvbuffer.size() - m_read_pos; if (amount_to_read > m_download_quota) amount_to_read = m_download_quota; m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } void http_connection::rate_limit(int limit) { if (!m_limiter_timer_active) { m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } m_rate_limit = limit; } } <commit_msg>fixed issue when aborting an http connection<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/http_connection.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <asio/ip/tcp.hpp> #include <string> using boost::bind; namespace libtorrent { void http_connection::get(std::string const& url, time_duration timeout) { std::string protocol; std::string hostname; std::string path; int port; boost::tie(protocol, hostname, port, path) = parse_url_components(url); std::stringstream headers; headers << "GET " << path << " HTTP/1.0\r\n" "Host:" << hostname << "Connection: close\r\n" "\r\n\r\n"; sendbuffer = headers.str(); start(hostname, boost::lexical_cast<std::string>(port), timeout); } void http_connection::start(std::string const& hostname, std::string const& port , time_duration timeout) { m_timeout = timeout; m_timer.expires_from_now(m_timeout); m_timer.async_wait(bind(&http_connection::on_timeout , boost::weak_ptr<http_connection>(shared_from_this()), _1)); m_called = false; if (m_sock.is_open() && m_hostname == hostname && m_port == port) { m_parser.reset(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } else { m_sock.close(); tcp::resolver::query query(hostname, port); m_resolver.async_resolve(query, bind(&http_connection::on_resolve , shared_from_this(), _1, _2)); m_hostname = hostname; m_port = port; } } void http_connection::on_timeout(boost::weak_ptr<http_connection> p , asio::error_code const& e) { if (e == asio::error::operation_aborted) return; boost::shared_ptr<http_connection> c = p.lock(); if (!c) return; if (c->m_bottled && c->m_called) return; if (c->m_last_receive + c->m_timeout < time_now()) { c->m_called = true; c->m_handler(asio::error::timed_out, c->m_parser, 0, 0); return; } c->m_timer.expires_at(c->m_last_receive + c->m_timeout); c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1)); } void http_connection::close() { m_timer.cancel(); m_limiter_timer.cancel(); m_sock.close(); m_hostname.clear(); m_port.clear(); } void http_connection::on_resolve(asio::error_code const& e , tcp::resolver::iterator i) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } assert(i != tcp::resolver::iterator()); m_sock.async_connect(*i, boost::bind(&http_connection::on_connect , shared_from_this(), _1/*, ++i*/)); } void http_connection::on_connect(asio::error_code const& e /*, tcp::resolver::iterator i*/) { if (!e) { m_last_receive = time_now(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } /* else if (i != tcp::resolver::iterator()) { // The connection failed. Try the next endpoint in the list. m_sock.close(); m_sock.async_connect(*i, bind(&http_connection::on_connect , shared_from_this(), _1, ++i)); } */ else { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } void http_connection::on_write(asio::error_code const& e) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } std::string().swap(sendbuffer); m_recvbuffer.resize(4096); int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_read(asio::error_code const& e , std::size_t bytes_transferred) { if (m_rate_limit) { m_download_quota -= bytes_transferred; assert(m_download_quota >= 0); } if (e == asio::error::eof) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error_code(), m_parser, 0, 0); return; } if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } m_read_pos += bytes_transferred; assert(m_read_pos <= int(m_recvbuffer.size())); if (m_bottled || !m_parser.header_finished()) { libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0] , &m_recvbuffer[0] + m_read_pos); m_parser.incoming(rcv_buf); if (!m_bottled && m_parser.header_finished()) { if (m_read_pos > m_parser.body_start()) m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start() , m_read_pos - m_parser.body_start()); m_read_pos = 0; m_last_receive = time_now(); } else if (m_bottled && m_parser.finished()) { m_timer.cancel(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } else { assert(!m_bottled); m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos); m_read_pos = 0; m_last_receive = time_now(); } if (int(m_recvbuffer.size()) == m_read_pos) m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500)); if (m_read_pos == 1024 * 500) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error::eof, m_parser, 0, 0); return; } int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_assign_bandwidth(asio::error_code const& e) { if ((e == asio::error::operation_aborted && m_limiter_timer_active) || !m_sock.is_open()) { if (!m_bottled || !m_called) m_handler(e, m_parser, 0, 0); } m_limiter_timer_active = false; if (e) return; if (m_download_quota > 0) return; m_download_quota = m_rate_limit / 4; int amount_to_read = m_recvbuffer.size() - m_read_pos; if (amount_to_read > m_download_quota) amount_to_read = m_download_quota; m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } void http_connection::rate_limit(int limit) { if (!m_limiter_timer_active) { m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } m_rate_limit = limit; } } <|endoftext|>
<commit_before>#include "prim.h" bool siren_prim_install(mrb_state* mrb, struct RClass* rclass) { // Class method mrb_define_class_method(mrb, rclass, "box", siren_prim_box, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_class_method(mrb, rclass, "box2p", siren_prim_box2p, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "boxax", siren_prim_boxax, MRB_ARGS_REQ(3)); mrb_define_class_method(mrb, rclass, "sphere", siren_prim_sphere, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_class_method(mrb, rclass, "cylinder", siren_prim_cylinder, MRB_ARGS_REQ(5)); mrb_define_class_method(mrb, rclass, "cone", siren_prim_cone, MRB_ARGS_REQ(6)); mrb_define_class_method(mrb, rclass, "torus", siren_prim_torus, MRB_ARGS_REQ(5)); mrb_define_class_method(mrb, rclass, "halfspace", siren_prim_halfspace, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "prism", siren_prim_prism, MRB_ARGS_NONE()); mrb_define_class_method(mrb, rclass, "revol", siren_prim_revol, MRB_ARGS_NONE()); mrb_define_class_method(mrb, rclass, "revolution",siren_prim_revolution,MRB_ARGS_NONE()); mrb_define_class_method(mrb, rclass, "wedge", siren_prim_wedge, MRB_ARGS_NONE()); // For mix-in mrb_define_method (mrb, rclass, "box", siren_prim_box, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_method (mrb, rclass, "box2p", siren_prim_box2p, MRB_ARGS_REQ(2)); mrb_define_method (mrb, rclass, "boxax", siren_prim_boxax, MRB_ARGS_REQ(3)); mrb_define_method (mrb, rclass, "sphere", siren_prim_sphere, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_method (mrb, rclass, "cylinder", siren_prim_cylinder, MRB_ARGS_REQ(5)); mrb_define_method (mrb, rclass, "cone", siren_prim_cone, MRB_ARGS_REQ(6)); mrb_define_method (mrb, rclass, "torus", siren_prim_torus, MRB_ARGS_REQ(5)); mrb_define_method (mrb, rclass, "halfspace", siren_prim_halfspace, MRB_ARGS_REQ(2)); mrb_define_method (mrb, rclass, "prism", siren_prim_prism, MRB_ARGS_NONE()); mrb_define_method (mrb, rclass, "revol", siren_prim_revol, MRB_ARGS_NONE()); mrb_define_method (mrb, rclass, "revolution",siren_prim_revolution,MRB_ARGS_NONE()); mrb_define_method (mrb, rclass, "wedge", siren_prim_wedge, MRB_ARGS_NONE()); return true; } mrb_value siren_prim_box(mrb_state* mrb, mrb_value self) { mrb_value size, pos; int argc = mrb_get_args(mrb, "A|A", &size, &pos); Standard_Real sx, sy, sz; siren_ary_to_xyz(mrb, size, sx, sy, sz); gp_Pnt op; if (argc == 2) { Standard_Real px, py, pz; siren_ary_to_xyz(mrb, pos, px, py, pz); op = gp_Pnt(px, py, pz); } else { op = gp_Pnt(0., 0., 0.); } BRepPrimAPI_MakeBox api(op, sx, sy, sz); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_box2p(mrb_state* mrb, mrb_value self) { mrb_value p1, p2; int argc = mrb_get_args(mrb, "AA", &p1, &p2); Standard_Real x1, y1, z1, x2, y2, z2; siren_ary_to_xyz(mrb, p1, x1, y1, z1); siren_ary_to_xyz(mrb, p2, x2, y2, z2); gp_Pnt point1(x1, x1, x1); gp_Pnt point2(x2, x2, x2); BRepPrimAPI_MakeBox api(point1, point2); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_boxax(mrb_state* mrb, mrb_value self) { mrb_value size, pos, dir; int argc = mrb_get_args(mrb, "AAA", &size, &pos, &dir); Standard_Real sx, sy, sz; siren_ary_to_xyz(mrb, size, sx, sy, sz); Standard_Real px, py, pz; siren_ary_to_xyz(mrb, pos, px, py, pz); Standard_Real dx, dy, dz; siren_ary_to_xyz(mrb, dir, dx, dy, dz); gp_Ax2 ax(gp_Pnt(px, py, pz), gp_Dir(dx, dy, dz)); BRepPrimAPI_MakeBox api(ax, sx, sy, sz); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_sphere(mrb_state* mrb, mrb_value self) { mrb_float r; mrb_value pos; int argc = mrb_get_args(mrb, "f|A", &r, &pos); gp_Pnt op; if (argc == 2) { Standard_Real px, py, pz; siren_ary_to_xyz(mrb, pos, px, py, pz); op = gp_Pnt(px, py, pz); } else { op = gp_Pnt(0., 0., 0.); } BRepPrimAPI_MakeSphere api(op, r); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_cylinder(mrb_state* mrb, mrb_value self) { mrb_value pos, norm; mrb_float r, h, a; int argc = mrb_get_args(mrb, "AAfff", &pos, &norm, &r, &h, &a); gp_Ax2 ax = siren_ary_to_ax2(mrb, pos, norm); BRepPrimAPI_MakeCylinder api(ax, r, h, a); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_cone(mrb_state* mrb, mrb_value self) { mrb_value pos, norm; mrb_float r1, r2, h, ang; int argc = mrb_get_args(mrb, "AAffff", &pos, &norm, &r1, &r2, &h, &ang); gp_Ax2 ax = siren_ary_to_ax2(mrb, pos, norm); BRepPrimAPI_MakeCone api(ax, r1, r2, h, ang); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_torus(mrb_state* mrb, mrb_value self) { mrb_float r1, r2, ang; mrb_value pos, norm; int argc = mrb_get_args(mrb, "AAfff", &pos, &norm, &r1, &r2, &ang); gp_Ax2 ax = siren_ary_to_ax2(mrb, pos, norm); BRepPrimAPI_MakeTorus api(ax, r1, r2, ang); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_halfspace(mrb_state* mrb, mrb_value self) { mrb_value surf, refpnt; int argc = mrb_get_args(mrb, "oA", &surf, &refpnt); TopoDS_Shape* shape = siren_shape_get(mrb, surf); if (shape == NULL || shape->IsNull()) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Specified shape is incorrect."); } TopoDS_Solid solid; gp_Pnt pnt = siren_ary_to_pnt(mrb, refpnt); if (shape->ShapeType() == TopAbs_FACE) { solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Face(*shape), pnt); } else if (shape->ShapeType() == TopAbs_SHELL) { solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Shell(*shape), pnt); } else { mrb_raise(mrb, E_ARGUMENT_ERROR, "Specified shape type is not FACE or SHELL."); } return siren_shape_new(mrb, solid); } mrb_value siren_prim_prism(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } mrb_value siren_prim_revol(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } mrb_value siren_prim_revolution(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } mrb_value siren_prim_wedge(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } <commit_msg>Support default parameter on making box or sphere.<commit_after>#include "prim.h" bool siren_prim_install(mrb_state* mrb, struct RClass* rclass) { // Class method mrb_define_class_method(mrb, rclass, "box", siren_prim_box, MRB_ARGS_OPT(2)); mrb_define_class_method(mrb, rclass, "box2p", siren_prim_box2p, MRB_ARGS_OPT(2)); mrb_define_class_method(mrb, rclass, "boxax", siren_prim_boxax, MRB_ARGS_REQ(3)); mrb_define_class_method(mrb, rclass, "sphere", siren_prim_sphere, MRB_ARGS_OPT(2)); mrb_define_class_method(mrb, rclass, "cylinder", siren_prim_cylinder, MRB_ARGS_REQ(5)); mrb_define_class_method(mrb, rclass, "cone", siren_prim_cone, MRB_ARGS_REQ(6)); mrb_define_class_method(mrb, rclass, "torus", siren_prim_torus, MRB_ARGS_REQ(5)); mrb_define_class_method(mrb, rclass, "halfspace", siren_prim_halfspace, MRB_ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "prism", siren_prim_prism, MRB_ARGS_NONE()); mrb_define_class_method(mrb, rclass, "revol", siren_prim_revol, MRB_ARGS_NONE()); mrb_define_class_method(mrb, rclass, "revolution",siren_prim_revolution,MRB_ARGS_NONE()); mrb_define_class_method(mrb, rclass, "wedge", siren_prim_wedge, MRB_ARGS_NONE()); // For mix-in mrb_define_method (mrb, rclass, "box", siren_prim_box, MRB_ARGS_OPT(2)); mrb_define_method (mrb, rclass, "box2p", siren_prim_box2p, MRB_ARGS_OPT(2)); mrb_define_method (mrb, rclass, "boxax", siren_prim_boxax, MRB_ARGS_REQ(3)); mrb_define_method (mrb, rclass, "sphere", siren_prim_sphere, MRB_ARGS_OPT(2)); mrb_define_method (mrb, rclass, "cylinder", siren_prim_cylinder, MRB_ARGS_REQ(5)); mrb_define_method (mrb, rclass, "cone", siren_prim_cone, MRB_ARGS_REQ(6)); mrb_define_method (mrb, rclass, "torus", siren_prim_torus, MRB_ARGS_REQ(5)); mrb_define_method (mrb, rclass, "halfspace", siren_prim_halfspace, MRB_ARGS_REQ(2)); mrb_define_method (mrb, rclass, "prism", siren_prim_prism, MRB_ARGS_NONE()); mrb_define_method (mrb, rclass, "revol", siren_prim_revol, MRB_ARGS_NONE()); mrb_define_method (mrb, rclass, "revolution",siren_prim_revolution,MRB_ARGS_NONE()); mrb_define_method (mrb, rclass, "wedge", siren_prim_wedge, MRB_ARGS_NONE()); return true; } mrb_value siren_prim_box(mrb_state* mrb, mrb_value self) { mrb_value size, pos; int argc = mrb_get_args(mrb, "|AA", &size, &pos); Standard_Real sx, sy, sz; if (argc >= 1) { siren_ary_to_xyz(mrb, size, sx, sy, sz); } else { sx = 1.0; sy = 1.0; sz = 1.0; } gp_Pnt op; if (argc >= 2) { Standard_Real px, py, pz; siren_ary_to_xyz(mrb, pos, px, py, pz); op = gp_Pnt(px, py, pz); } else { op = gp_Pnt(0., 0., 0.); } BRepPrimAPI_MakeBox api(op, sx, sy, sz); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_box2p(mrb_state* mrb, mrb_value self) { mrb_value p1, p2; int argc = mrb_get_args(mrb, "|AA", &p1, &p2); Standard_Real x1 = 0.0, y1 = 0.0, z1 = 0.0; Standard_Real x2 = 1.0, y2 = 1.0, z2 = 1.0; if (argc >= 1) { siren_ary_to_xyz(mrb, p1, x1, y1, z1); } if (argc >= 2) { siren_ary_to_xyz(mrb, p2, x2, y2, z2); } gp_Pnt point1(x1, x1, x1); gp_Pnt point2(x2, x2, x2); BRepPrimAPI_MakeBox api(point1, point2); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_boxax(mrb_state* mrb, mrb_value self) { mrb_value size, pos, dir; int argc = mrb_get_args(mrb, "AAA", &size, &pos, &dir); Standard_Real sx, sy, sz; siren_ary_to_xyz(mrb, size, sx, sy, sz); Standard_Real px, py, pz; siren_ary_to_xyz(mrb, pos, px, py, pz); Standard_Real dx, dy, dz; siren_ary_to_xyz(mrb, dir, dx, dy, dz); gp_Ax2 ax(gp_Pnt(px, py, pz), gp_Dir(dx, dy, dz)); BRepPrimAPI_MakeBox api(ax, sx, sy, sz); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_sphere(mrb_state* mrb, mrb_value self) { mrb_float r = 1.0; mrb_value pos; int argc = mrb_get_args(mrb, "|fA", &r, &pos); gp_Pnt op; if (argc == 2) { Standard_Real px, py, pz; siren_ary_to_xyz(mrb, pos, px, py, pz); op = gp_Pnt(px, py, pz); } else { op = gp_Pnt(0., 0., 0.); } BRepPrimAPI_MakeSphere api(op, r); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_cylinder(mrb_state* mrb, mrb_value self) { mrb_value pos, norm; mrb_float r, h, a; int argc = mrb_get_args(mrb, "AAfff", &pos, &norm, &r, &h, &a); gp_Ax2 ax = siren_ary_to_ax2(mrb, pos, norm); BRepPrimAPI_MakeCylinder api(ax, r, h, a); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_cone(mrb_state* mrb, mrb_value self) { mrb_value pos, norm; mrb_float r1, r2, h, ang; int argc = mrb_get_args(mrb, "AAffff", &pos, &norm, &r1, &r2, &h, &ang); gp_Ax2 ax = siren_ary_to_ax2(mrb, pos, norm); BRepPrimAPI_MakeCone api(ax, r1, r2, h, ang); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_torus(mrb_state* mrb, mrb_value self) { mrb_float r1, r2, ang; mrb_value pos, norm; int argc = mrb_get_args(mrb, "AAfff", &pos, &norm, &r1, &r2, &ang); gp_Ax2 ax = siren_ary_to_ax2(mrb, pos, norm); BRepPrimAPI_MakeTorus api(ax, r1, r2, ang); return siren_shape_new(mrb, api.Shape()); } mrb_value siren_prim_halfspace(mrb_state* mrb, mrb_value self) { mrb_value surf, refpnt; int argc = mrb_get_args(mrb, "oA", &surf, &refpnt); TopoDS_Shape* shape = siren_shape_get(mrb, surf); if (shape == NULL || shape->IsNull()) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Specified shape is incorrect."); } TopoDS_Solid solid; gp_Pnt pnt = siren_ary_to_pnt(mrb, refpnt); if (shape->ShapeType() == TopAbs_FACE) { solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Face(*shape), pnt); } else if (shape->ShapeType() == TopAbs_SHELL) { solid = BRepPrimAPI_MakeHalfSpace(TopoDS::Shell(*shape), pnt); } else { mrb_raise(mrb, E_ARGUMENT_ERROR, "Specified shape type is not FACE or SHELL."); } return siren_shape_new(mrb, solid); } mrb_value siren_prim_prism(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } mrb_value siren_prim_revol(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } mrb_value siren_prim_revolution(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } mrb_value siren_prim_wedge(mrb_state* mrb, mrb_value self) { mrb_raise(mrb, E_NOTIMP_ERROR, "Not implemented."); return mrb_nil_value(); } <|endoftext|>
<commit_before>#include "ten/task/qutex.hh" #include "proc.hh" namespace ten { void qutex::lock() { task *t = this_proc()->ctask; DCHECK(t) << "BUG: qutex::lock called outside of task"; { std::unique_lock<std::timed_mutex> lk(_m); if (_owner == nullptr || _owner == t) { _owner = t; DVLOG(5) << "LOCK qutex: " << this << " owner: " << _owner; return; } DVLOG(5) << "QUTEX[" << this << "] lock waiting add: " << t << " owner: " << _owner; _waiting.push_back(t); } try { // loop to handle spurious wakeups from other threads for (;;) { t->swap(); std::unique_lock<std::timed_mutex> lk(_m); if (_owner == this_proc()->ctask) { break; } } } catch (...) { std::unique_lock<std::timed_mutex> lk(_m); internal_unlock(lk); throw; } } bool qutex::try_lock() { task *t = this_proc()->ctask; DCHECK(t) << "BUG: qutex::try_lock called outside of task"; std::unique_lock<std::timed_mutex> lk(_m, std::try_to_lock); if (lk.owns_lock()) { if (_owner == nullptr) { _owner = t; return true; } } return false; } void qutex::unlock() { std::unique_lock<std::timed_mutex> lk(_m); internal_unlock(lk); } inline void qutex::internal_unlock(std::unique_lock<std::timed_mutex> &lk) { task *t = this_proc()->ctask; DCHECK(lk.owns_lock()) << "BUG: lock not owned " << t; DVLOG(5) << "QUTEX[" << this << "] unlock: " << t; if (t == _owner) { if (!_waiting.empty()) { t = _owner = _waiting.front(); _waiting.pop_front(); } else { t = _owner = nullptr; } DVLOG(5) << "UNLOCK qutex: " << this << " new owner: " << _owner << " waiting: " << _waiting.size(); lk.unlock(); // must use t here, not owner because // lock has been released if (t) t->ready(); } else { // this branch is taken when exception is thrown inside // a task that is currently waiting inside qutex::lock auto i = std::find(_waiting.begin(), _waiting.end(), t); if (i != _waiting.end()) { _waiting.erase(i); } } } } // namespace <commit_msg>don't allow recursive qutex locking<commit_after>#include "ten/task/qutex.hh" #include "proc.hh" namespace ten { void qutex::lock() { task *t = this_proc()->ctask; DCHECK(t) << "BUG: qutex::lock called outside of task"; { std::unique_lock<std::timed_mutex> lk(_m); DCHECK(_owner != t) << "no recursive locking"; if (_owner == nullptr) { _owner = t; DVLOG(5) << "LOCK qutex: " << this << " owner: " << _owner; return; } DVLOG(5) << "QUTEX[" << this << "] lock waiting add: " << t << " owner: " << _owner; _waiting.push_back(t); } try { // loop to handle spurious wakeups from other threads for (;;) { t->swap(); std::unique_lock<std::timed_mutex> lk(_m); if (_owner == this_proc()->ctask) { break; } } } catch (...) { std::unique_lock<std::timed_mutex> lk(_m); internal_unlock(lk); throw; } } bool qutex::try_lock() { task *t = this_proc()->ctask; DCHECK(t) << "BUG: qutex::try_lock called outside of task"; std::unique_lock<std::timed_mutex> lk(_m, std::try_to_lock); if (lk.owns_lock()) { if (_owner == nullptr) { _owner = t; return true; } } return false; } void qutex::unlock() { std::unique_lock<std::timed_mutex> lk(_m); internal_unlock(lk); } inline void qutex::internal_unlock(std::unique_lock<std::timed_mutex> &lk) { task *t = this_proc()->ctask; DCHECK(lk.owns_lock()) << "BUG: lock not owned " << t; DVLOG(5) << "QUTEX[" << this << "] unlock: " << t; if (t == _owner) { if (!_waiting.empty()) { t = _owner = _waiting.front(); _waiting.pop_front(); } else { t = _owner = nullptr; } DVLOG(5) << "UNLOCK qutex: " << this << " new owner: " << _owner << " waiting: " << _waiting.size(); lk.unlock(); // must use t here, not owner because // lock has been released if (t) t->ready(); } else { // this branch is taken when exception is thrown inside // a task that is currently waiting inside qutex::lock auto i = std::find(_waiting.begin(), _waiting.end(), t); if (i != _waiting.end()) { _waiting.erase(i); } } } } // namespace <|endoftext|>
<commit_before>#include "t_kv.h" #include "leveldb/write_batch.h" int SSDB::multi_set(const std::vector<Bytes> &kvs, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = kvs.begin() + offset; for(; it != kvs.end(); it += 2){ const Bytes &key = *it; const Bytes &val = *(it + 1); std::string buf = encode_kv_key(key); binlogs->Put(buf, val.Slice()); binlogs->add(log_type, BinlogCommand::KSET, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_set error: %s", s.ToString().c_str()); return -1; } return (kvs.size() - offset)/2; } int SSDB::multi_del(const std::vector<Bytes> &keys, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = keys.begin() + offset; for(; it != keys.end(); it += 2){ const Bytes &key = *it; std::string buf = encode_kv_key(key); binlogs->Delete(buf); binlogs->add(log_type, BinlogCommand::KDEL, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_del error: %s", s.ToString().c_str()); return -1; } return keys.size() - offset; } int SSDB::set(const Bytes &key, const Bytes &val, char log_type){ Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->Put(buf, val.Slice()); binlogs->add(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDB::del(const Bytes &key, char log_type){ Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->begin(); binlogs->Delete(buf); binlogs->add(log_type, BinlogCommand::KDEL, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDB::incr(const Bytes &key, int64_t by, std::string *new_val, char log_type){ Transaction trans(binlogs); int64_t val; std::string old; int ret = this->get(key, &old); if(ret == -1){ return -1; }else if(ret == 0){ val = by; }else{ val = str_to_int64(old.data(), old.size()) + by; } *new_val = int64_to_str(val); std::string buf = encode_kv_key(key); binlogs->Put(buf, *new_val); binlogs->add(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDB::get(const Bytes &key, std::string *val) const{ std::string buf = encode_kv_key(key); leveldb::Status s = db->Get(leveldb::ReadOptions(), buf, val); if(s.IsNotFound()){ return 0; } if(!s.ok()){ log_error("get error: %s", s.ToString().c_str()); return -1; } return 1; } KIterator* SSDB::scan(const Bytes &start, const Bytes &end, uint64_t limit) const{ std::string key_start, key_end; key_start = encode_kv_key(start); if(end.empty()){ key_end = ""; }else{ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->iterator(key_start, key_end, limit)); } KIterator* SSDB::rscan(const Bytes &start, const Bytes &end, uint64_t limit) const{ std::string key_start, key_end; key_start = encode_kv_key(start); if(start.empty()){ key_start.append(1, 255); } if(end.empty()){ key_end = ""; }else{ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->rev_iterator(key_start, key_end, limit)); } <commit_msg>fix multi_del bug<commit_after>#include "t_kv.h" #include "leveldb/write_batch.h" int SSDB::multi_set(const std::vector<Bytes> &kvs, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = kvs.begin() + offset; for(; it != kvs.end(); it += 2){ const Bytes &key = *it; const Bytes &val = *(it + 1); std::string buf = encode_kv_key(key); binlogs->Put(buf, val.Slice()); binlogs->add(log_type, BinlogCommand::KSET, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_set error: %s", s.ToString().c_str()); return -1; } return (kvs.size() - offset)/2; } int SSDB::multi_del(const std::vector<Bytes> &keys, int offset, char log_type){ Transaction trans(binlogs); std::vector<Bytes>::const_iterator it; it = keys.begin() + offset; for(; it != keys.end(); it++){ const Bytes &key = *it; std::string buf = encode_kv_key(key); binlogs->Delete(buf); binlogs->add(log_type, BinlogCommand::KDEL, buf); } leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("multi_del error: %s", s.ToString().c_str()); return -1; } return keys.size() - offset; } int SSDB::set(const Bytes &key, const Bytes &val, char log_type){ Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->Put(buf, val.Slice()); binlogs->add(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("set error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDB::del(const Bytes &key, char log_type){ Transaction trans(binlogs); std::string buf = encode_kv_key(key); binlogs->begin(); binlogs->Delete(buf); binlogs->add(log_type, BinlogCommand::KDEL, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDB::incr(const Bytes &key, int64_t by, std::string *new_val, char log_type){ Transaction trans(binlogs); int64_t val; std::string old; int ret = this->get(key, &old); if(ret == -1){ return -1; }else if(ret == 0){ val = by; }else{ val = str_to_int64(old.data(), old.size()) + by; } *new_val = int64_to_str(val); std::string buf = encode_kv_key(key); binlogs->Put(buf, *new_val); binlogs->add(log_type, BinlogCommand::KSET, buf); leveldb::Status s = binlogs->commit(); if(!s.ok()){ log_error("del error: %s", s.ToString().c_str()); return -1; } return 1; } int SSDB::get(const Bytes &key, std::string *val) const{ std::string buf = encode_kv_key(key); leveldb::Status s = db->Get(leveldb::ReadOptions(), buf, val); if(s.IsNotFound()){ return 0; } if(!s.ok()){ log_error("get error: %s", s.ToString().c_str()); return -1; } return 1; } KIterator* SSDB::scan(const Bytes &start, const Bytes &end, uint64_t limit) const{ std::string key_start, key_end; key_start = encode_kv_key(start); if(end.empty()){ key_end = ""; }else{ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->iterator(key_start, key_end, limit)); } KIterator* SSDB::rscan(const Bytes &start, const Bytes &end, uint64_t limit) const{ std::string key_start, key_end; key_start = encode_kv_key(start); if(start.empty()){ key_start.append(1, 255); } if(end.empty()){ key_end = ""; }else{ key_end = encode_kv_key(end); } //dump(key_start.data(), key_start.size(), "scan.start"); //dump(key_end.data(), key_end.size(), "scan.end"); return new KIterator(this->rev_iterator(key_start, key_end, limit)); } <|endoftext|>
<commit_before> /* * client.cpp * * Handles the client env. * * Created by Ryan Faulkner on 2014-06-08 * Copyright (c) 2014. All rights reserved. */ #include <iostream> #include <string> #include <vector> #include <regex> #include <assert.h> #include "column_types.h" #include "redis.h" #include "md5.h" #include "index.h" #include "bayes.h" #define REDISHOST "127.0.0.1" #define REDISPORT 6379 using namespace std; /** Test to ensure that redis keys are correctly returned */ void testRedisSet() { RedisHandler r; r.connect(); r.write("foo", "bar"); } /** Test to ensure that redis keys are correctly returned */ void testRedisGet() { RedisHandler r; r.connect(); cout << endl << "VALUE FOR KEY foo" << endl; cout << r.read("foo") << endl << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisKeys() { RedisHandler r; std::vector<std::string> vec; r.connect(); vec = r.keys("*"); cout << "KEY LIST FOR *" << endl; for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) { cout << *it << endl; } cout << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisIO() { RedisHandler r; std::vector<string>* vec; std::string outTrue, outFalse = ""; r.connect(); r.write("test_key", "test value"); outTrue = r.read("test_key"); assert(std::strcmp(outTrue.c_str(), "test value") == 0); r.deleteKey("test_key"); assert(!r.exists("test_key")); } /** Test to ensure that md5 hashing works */ void testMd5Hashing() { cout << endl << "md5 of 'mykey': " << md5("mykey") << endl; } /** Test to ensure that md5 hashing works */ void testRegexForTypes() { IntegerColumn ic; FloatColumn fc; assert(ic.validate("1981")); assert(fc.validate("5.2")); cout << "Passed regex tests." << endl; } /** Test to ensure that md5 hashing works */ void testOrderPairAlphaNumeric() { IndexHandler ih; assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0); cout << "Passed orderPairAlphaNumeric tests." << endl; } /** * Test to ensure that relation entities are encoded properly */ void testJSONEntityEncoding() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields Entity e("test", fields_ent); ih.writeEntity(e); // Create the entity ih.fetchEntity("test", json); // Fetch the entity representation cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl; // Assert that entity as read matches definition assert(std::strcmp(json["entity"].asCString(), "test") == 0 && std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 && json["fields"]["_itemcount"].asInt() == 1 ); ih.removeEntity("test"); // Remove the entity } /** * Test to ensure that relation fields are encoded properly */ void testJSONRelationEncoding() { IndexHandler ih; std::vector<Json::Value> ret; std::vector<std::pair<ColumnBase*, std::string>> fields_ent_1; std::vector<std::pair<ColumnBase*, std::string>> fields_ent_2; std::vector<std::pair<std::string, std::string>> fields_rel_1; std::vector<std::pair<std::string, std::string>> fields_rel_2; // Popualate fields fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a")); fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b")); fields_rel_1.push_back(std::make_pair("a", "1")); fields_rel_2.push_back(std::make_pair("b", "hello")); // Create entities Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2); ih.writeEntity(e1); ih.writeEntity(e2); // Create relation in redis Relation r("test_1", "test_2", fields_rel_1, fields_rel_2); ih.writeRelation(r); // Fetch the entity representation ret = ih.fetchRelationPrefix("test_1", "test_2"); cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl; // Assert that entity as read matches definition assert( std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 && std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 && std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 && std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 && ret[0]["fields_left"]["_itemcount"].asInt() == 1 && ret[0]["fields_right"]["_itemcount"].asInt() == 1 ); ih.removeEntity("test_1"); // Remove the entity ih.removeEntity("test_2"); // Remove the entity ih.removeRelation(r); // Remove the relation } /** * Tests that parseEntityAssignField correctly flags invalid assignments to integer fields */ void testFieldAssignTypeMismatchInteger() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields Entity e("test", fields_ent); ih.writeEntity(e); // Create the entity assert( ih.validateEntityFieldType("test", "a", "1") && ih.validateEntityFieldType("test", "a", "12345") && !ih.validateEntityFieldType("test", "a", "1.0") && !ih.validateEntityFieldType("test", "a", "string") ); ih.removeEntity("test"); } /** * Tests that parseEntityAssignField correctly flags invalid assignments to float fields */ void testFieldAssignTypeMismatchFloat() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields Entity e("test", fields_ent); // Create the entity ih.writeEntity(e); // Create the entity assert( ih.validateEntityFieldType("test", "a", "1.2") && ih.validateEntityFieldType("test", "a", "12.5") && !ih.validateEntityFieldType("test", "a", "string") ); ih.removeEntity("test"); } /** * Tests that parseEntityAssignField correctly flags invalid assignments to string fields */ void testFieldAssignTypeMismatchString() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields Entity e("test", fields_ent); ih.writeEntity(e); // Create the entity assert( ih.validateEntityFieldType("test", "a", "1") && ih.validateEntityFieldType("test", "a", "12345") && ih.validateEntityFieldType("test", "a", "string") ); ih.removeEntity("test"); } /** * Tests that existsEntityField correctly flags when entity does not contain a field */ void testEntityDoesNotContainField() { // TODO - implement } /** * Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct */ void testComputeMarginal() { Bayes bayes; IndexHandler ih; std::vector<Json::Value> ret; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; std::vector<std::pair<std::string, std::string>> fields_rel; long num_relations = ih.getRelationCountTotal(); // declare three entities Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent); ih.writeEntity(e1); ih.writeEntity(e2); ih.writeEntity(e3); ih.writeEntity(e4); // construct a number of relations Relation r1("_x", "_y", fields_rel, fields_rel); Relation r2("_x", "_y", fields_rel, fields_rel); Relation r3("_x", "_z", fields_rel, fields_rel); Relation r4("_x", "_z", fields_rel, fields_rel); Relation r5("_w", "_y", fields_rel, fields_rel); ih.writeRelation(r1); ih.writeRelation(r2); ih.writeRelation(r3); ih.writeRelation(r4); ih.writeRelation(r5); // Ensure marginal likelihood reflects the number of relations that contain each entity valpair attrs; // TODO - fix computeMarginal seg fault assert(bayes.computeMarginal(e1.name, attrs) == 4.0 / 5.0); assert(bayes.computeMarginal(e2.name, attrs) == 3.0 / 5.0); assert(bayes.computeMarginal(e3.name, attrs) == 2.0 / 5.0); assert(bayes.computeMarginal(e4.name, attrs) == 1.0 / 5.0); ih.removeEntity("_w"); ih.removeEntity("_x"); ih.removeEntity("_y"); ih.removeEntity("_z"); ih.removeRelation(r1); ih.removeRelation(r2); ih.removeRelation(r3); ih.removeRelation(r4); ih.removeRelation(r5); // Reset the relations count ih.setRelationCountTotal(num_relations); } int main() { cout << "-- TESTS BEGIN --" << endl << endl; // testRedisSet(); // testRedisGet(); // testRedisKeys(); // md5Hashing(); // testRedisIO(); // testRegexForTypes(); // testOrderPairAlphaNumeric(); // testJSONEntityEncoding(); // testJSONRelationEncoding(); // testFieldAssignTypeMismatchInteger(); // testFieldAssignTypeMismatchFloat(); // testFieldAssignTypeMismatchString(); testComputeMarginal(); cout << endl << "-- TESTS END --" << endl; return 0; } <commit_msg>add some test stubs for removal behavior<commit_after> /* * client.cpp * * Handles the client env. * * Created by Ryan Faulkner on 2014-06-08 * Copyright (c) 2014. All rights reserved. */ #include <iostream> #include <string> #include <vector> #include <regex> #include <assert.h> #include "column_types.h" #include "redis.h" #include "md5.h" #include "index.h" #include "bayes.h" #define REDISHOST "127.0.0.1" #define REDISPORT 6379 using namespace std; /** Test to ensure that redis keys are correctly returned */ void testRedisSet() { RedisHandler r; r.connect(); r.write("foo", "bar"); } /** Test to ensure that redis keys are correctly returned */ void testRedisGet() { RedisHandler r; r.connect(); cout << endl << "VALUE FOR KEY foo" << endl; cout << r.read("foo") << endl << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisKeys() { RedisHandler r; std::vector<std::string> vec; r.connect(); vec = r.keys("*"); cout << "KEY LIST FOR *" << endl; for (std::vector<std::string>::iterator it = vec.begin() ; it != vec.end(); ++it) { cout << *it << endl; } cout << endl; } /** Test to ensure that redis keys are correctly returned */ void testRedisIO() { RedisHandler r; std::vector<string>* vec; std::string outTrue, outFalse = ""; r.connect(); r.write("test_key", "test value"); outTrue = r.read("test_key"); assert(std::strcmp(outTrue.c_str(), "test value") == 0); r.deleteKey("test_key"); assert(!r.exists("test_key")); } /** Test to ensure that md5 hashing works */ void testMd5Hashing() { cout << endl << "md5 of 'mykey': " << md5("mykey") << endl; } /** Test to ensure that md5 hashing works */ void testRegexForTypes() { IntegerColumn ic; FloatColumn fc; assert(ic.validate("1981")); assert(fc.validate("5.2")); cout << "Passed regex tests." << endl; } /** Test to ensure that md5 hashing works */ void testOrderPairAlphaNumeric() { IndexHandler ih; assert(std::strcmp(ih.orderPairAlphaNumeric("b", "a").c_str(), "a_b") == 0); cout << "Passed orderPairAlphaNumeric tests." << endl; } /** * Test to ensure that relation entities are encoded properly */ void testJSONEntityEncoding() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields Entity e("test", fields_ent); ih.writeEntity(e); // Create the entity ih.fetchEntity("test", json); // Fetch the entity representation cout << "TEST ENTITY:" << endl << endl << json.toStyledString() << endl; // Assert that entity as read matches definition assert(std::strcmp(json["entity"].asCString(), "test") == 0 && std::strcmp(json["fields"]["a"].asCString(), "integer") == 0 && json["fields"]["_itemcount"].asInt() == 1 ); ih.removeEntity("test"); // Remove the entity } /** * Test to ensure that relation fields are encoded properly */ void testJSONRelationEncoding() { IndexHandler ih; std::vector<Json::Value> ret; std::vector<std::pair<ColumnBase*, std::string>> fields_ent_1; std::vector<std::pair<ColumnBase*, std::string>> fields_ent_2; std::vector<std::pair<std::string, std::string>> fields_rel_1; std::vector<std::pair<std::string, std::string>> fields_rel_2; // Popualate fields fields_ent_1.push_back(std::make_pair(getColumnType("integer"), "a")); fields_ent_2.push_back(std::make_pair(getColumnType("string"), "b")); fields_rel_1.push_back(std::make_pair("a", "1")); fields_rel_2.push_back(std::make_pair("b", "hello")); // Create entities Entity e1("test_1", fields_ent_1), e2("test_2", fields_ent_2); ih.writeEntity(e1); ih.writeEntity(e2); // Create relation in redis Relation r("test_1", "test_2", fields_rel_1, fields_rel_2); ih.writeRelation(r); // Fetch the entity representation ret = ih.fetchRelationPrefix("test_1", "test_2"); cout << "TEST RELATION:" << endl << endl << ret[0].toStyledString() << endl; // Assert that entity as read matches definition assert( std::strcmp(ret[0]["entity_left"].asCString(), "test_1") == 0 && std::strcmp(ret[0]["entity_right"].asCString(), "test_2") == 0 && std::strcmp(ret[0]["fields_left"]["a"].asCString(), "1") == 0 && std::strcmp(ret[0]["fields_right"]["b"].asCString(), "hello") == 0 && ret[0]["fields_left"]["_itemcount"].asInt() == 1 && ret[0]["fields_right"]["_itemcount"].asInt() == 1 ); ih.removeEntity("test_1"); // Remove the entity ih.removeEntity("test_2"); // Remove the entity ih.removeRelation(r); // Remove the relation } /** * Tests that parseEntityAssignField correctly flags invalid assignments to integer fields */ void testFieldAssignTypeMismatchInteger() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("integer"), "a")); // Create fields Entity e("test", fields_ent); ih.writeEntity(e); // Create the entity assert( ih.validateEntityFieldType("test", "a", "1") && ih.validateEntityFieldType("test", "a", "12345") && !ih.validateEntityFieldType("test", "a", "1.0") && !ih.validateEntityFieldType("test", "a", "string") ); ih.removeEntity("test"); } /** * Tests that parseEntityAssignField correctly flags invalid assignments to float fields */ void testFieldAssignTypeMismatchFloat() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("float"), "a")); // Create fields Entity e("test", fields_ent); // Create the entity ih.writeEntity(e); // Create the entity assert( ih.validateEntityFieldType("test", "a", "1.2") && ih.validateEntityFieldType("test", "a", "12.5") && !ih.validateEntityFieldType("test", "a", "string") ); ih.removeEntity("test"); } /** * Tests that parseEntityAssignField correctly flags invalid assignments to string fields */ void testFieldAssignTypeMismatchString() { IndexHandler ih; Json::Value json; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; fields_ent.push_back(std::make_pair(getColumnType("string"), "a")); // Create fields Entity e("test", fields_ent); ih.writeEntity(e); // Create the entity assert( ih.validateEntityFieldType("test", "a", "1") && ih.validateEntityFieldType("test", "a", "12345") && ih.validateEntityFieldType("test", "a", "string") ); ih.removeEntity("test"); } /** * Tests that existsEntityField correctly flags when entity does not contain a field */ void testEntityDoesNotContainField() { // TODO - implement } /** * Tests Bayes::computeMarginal function - ensure the marginal likelihood is correct */ void testComputeMarginal() { Bayes bayes; IndexHandler ih; std::vector<Json::Value> ret; std::vector<std::pair<ColumnBase*, std::string>> fields_ent; std::vector<std::pair<std::string, std::string>> fields_rel; long num_relations = ih.getRelationCountTotal(); // declare three entities Entity e1("_w", fields_ent), e2("_x", fields_ent), e3("_y", fields_ent), e4("_z", fields_ent); ih.writeEntity(e1); ih.writeEntity(e2); ih.writeEntity(e3); ih.writeEntity(e4); // construct a number of relations Relation r1("_x", "_y", fields_rel, fields_rel); Relation r2("_x", "_y", fields_rel, fields_rel); Relation r3("_x", "_z", fields_rel, fields_rel); Relation r4("_x", "_z", fields_rel, fields_rel); Relation r5("_w", "_y", fields_rel, fields_rel); ih.writeRelation(r1); ih.writeRelation(r2); ih.writeRelation(r3); ih.writeRelation(r4); ih.writeRelation(r5); // Ensure marginal likelihood reflects the number of relations that contain each entity valpair attrs; // TODO - fix computeMarginal seg fault cout << bayes.computeMarginal(e1.name, attrs) << endl; assert(bayes.computeMarginal(e1.name, attrs) == 4.0 / 5.0); assert(bayes.computeMarginal(e2.name, attrs) == 3.0 / 5.0); assert(bayes.computeMarginal(e3.name, attrs) == 2.0 / 5.0); assert(bayes.computeMarginal(e4.name, attrs) == 1.0 / 5.0); ih.removeEntity("_w"); ih.removeEntity("_x"); ih.removeEntity("_y"); ih.removeEntity("_z"); ih.removeRelation(r1); ih.removeRelation(r2); ih.removeRelation(r3); ih.removeRelation(r4); ih.removeRelation(r5); // Reset the relations count ih.setRelationCountTotal(num_relations); } /** * Tests that removal of entities functions properly */ void testEntityRemoval() { // TODO - implement } /** * Tests that removal of relations functions properly */ void testRelationRemoval() { // TODO - implement } /** * Tests that removal of relations cascading on entities functions properly */ void testEntityCascadeRemoval() { // TODO - implement } int main() { cout << "-- TESTS BEGIN --" << endl << endl; // testRedisSet(); // testRedisGet(); // testRedisKeys(); // md5Hashing(); // testRedisIO(); // testRegexForTypes(); // testOrderPairAlphaNumeric(); // testJSONEntityEncoding(); // testJSONRelationEncoding(); // testFieldAssignTypeMismatchInteger(); // testFieldAssignTypeMismatchFloat(); // testFieldAssignTypeMismatchString(); testComputeMarginal(); cout << endl << "-- TESTS END --" << endl; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2014-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/networkstyle.h> #include <qt/guiconstants.h> #include <QApplication> static const struct { const char *networkId; const char *appName; const int iconColorHueShift; const int iconColorSaturationReduction; const char *titleAddText; } network_styles[] = { {"main", QAPP_APP_NAME_DEFAULT, 0, 0, ""}, {"test", QAPP_APP_NAME_TESTNET, 0, 0, QT_TRANSLATE_NOOP("SplashScreen", "[testnet]")}, {"regtest", QAPP_APP_NAME_TESTNET, 60, 1, "[regtest]"} }; static const unsigned network_styles_count = sizeof(network_styles)/sizeof(*network_styles); // titleAddText needs to be const char* for tr() NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText): appName(_appName), titleAddText(qApp->translate("SplashScreen", _titleAddText)) { // load pixmap QPixmap pixmap; if (std::char_traits<char>::length(_titleAddText) == 0) { pixmap.load(":/icons/deeponion"); } else { pixmap.load(":/icons/deeponion_testnet"); } if(iconColorHueShift != 0 && iconColorSaturationReduction != 0) { // generate QImage from QPixmap QImage img = pixmap.toImage(); int h,s,l,a; // traverse though lines for(int y=0;y<img.height();y++) { QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) ); // loop through pixels for(int x=0;x<img.width();x++) { // preserve alpha because QColor::getHsl doesn't return the alpha value a = qAlpha(scL[x]); QColor col(scL[x]); // get hue value col.getHsl(&h,&s,&l); // rotate color on RGB color circle // 70° should end up with the typical "testnet" green h+=iconColorHueShift; // change saturation value if(s>iconColorSaturationReduction) { s -= iconColorSaturationReduction; } col.setHsl(h,s,l,a); // set the pixel scL[x] = col.rgba(); } } //convert back to QPixmap #if QT_VERSION >= 0x040700 pixmap.convertFromImage(img); #else pixmap = QPixmap::fromImage(img); #endif } appIcon = QIcon(pixmap); trayAndWindowIcon = QIcon(pixmap.scaled(QSize(256,256))); } const NetworkStyle *NetworkStyle::instantiate(const QString &networkId) { for (unsigned x=0; x<network_styles_count; ++x) { if (networkId == network_styles[x].networkId) { return new NetworkStyle( network_styles[x].appName, network_styles[x].iconColorHueShift, network_styles[x].iconColorSaturationReduction, network_styles[x].titleAddText); } } return 0; } <commit_msg>updated for splash<commit_after>// Copyright (c) 2014-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/networkstyle.h> #include <qt/guiconstants.h> #include <QApplication> static const struct { const char *networkId; const char *appName; const int iconColorHueShift; const int iconColorSaturationReduction; const char *titleAddText; } network_styles[] = { {"main", QAPP_APP_NAME_DEFAULT, 0, 0, ""}, {"test", QAPP_APP_NAME_TESTNET, 0, 0, QT_TRANSLATE_NOOP("SplashScreen", "[testnet]")}, {"regtest", QAPP_APP_NAME_TESTNET, 60, 1, "[regtest]"} }; static const unsigned network_styles_count = sizeof(network_styles)/sizeof(*network_styles); // titleAddText needs to be const char* for tr() NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText): appName(_appName), titleAddText(qApp->translate("SplashScreen", _titleAddText)) { // load pixmap QPixmap pixmap; QPixmap pixmap2; if (std::char_traits<char>::length(_titleAddText) == 0) { pixmap.load(":/images/splash"); pixmap2.load(":/icons/deeponion"); } else { pixmap.load(":/images/splash_testnet"); pixmap2.load(":/icons/deeponion_testnet"); } if(iconColorHueShift != 0 && iconColorSaturationReduction != 0) { // generate QImage from QPixmap QImage img = pixmap.toImage(); int h,s,l,a; // traverse though lines for(int y=0;y<img.height();y++) { QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) ); // loop through pixels for(int x=0;x<img.width();x++) { // preserve alpha because QColor::getHsl doesn't return the alpha value a = qAlpha(scL[x]); QColor col(scL[x]); // get hue value col.getHsl(&h,&s,&l); // rotate color on RGB color circle // 70° should end up with the typical "testnet" green h+=iconColorHueShift; // change saturation value if(s>iconColorSaturationReduction) { s -= iconColorSaturationReduction; } col.setHsl(h,s,l,a); // set the pixel scL[x] = col.rgba(); } } //convert back to QPixmap #if QT_VERSION >= 0x040700 pixmap.convertFromImage(img); #else pixmap = QPixmap::fromImage(img); #endif } appIcon = QIcon(pixmap); trayAndWindowIcon = QIcon(pixmap2.scaled(QSize(256,256))); } const NetworkStyle *NetworkStyle::instantiate(const QString &networkId) { for (unsigned x=0; x<network_styles_count; ++x) { if (networkId == network_styles[x].networkId) { return new NetworkStyle( network_styles[x].appName, network_styles[x].iconColorHueShift, network_styles[x].iconColorSaturationReduction, network_styles[x].titleAddText); } } return 0; } <|endoftext|>
<commit_before>// // QtOneLineTextWidget.cpp // MusicPlayer // // Created by Albert Zeyer on 23.01.14. // Copyright (c) 2014 Albert Zeyer. All rights reserved. // #include "QtOneLineTextWidget.hpp" #include "QtApp.hpp" #include "Builders.hpp" #include "PythonHelpers.h" #include "PyUtils.h" #include <string> #include <assert.h> RegisterControl(OneLineText) QtOneLineTextWidget::QtOneLineTextWidget(PyQtGuiObject* control) : QtBaseWidget(control) { PyScopedGIL gil; long w = attrChain_int_default(control->attr, "width", -1); long h = attrChain_int_default(control->attr, "height", -1); if(w < 0) w = 30; if(h < 0) h = 22; control->PresetSize = Vec((int)w, (int)h); resize(w, h); setBaseSize(w, h); lineEditWidget = new QLineEdit(this); lineEditWidget->resize(w, h); lineEditWidget->show(); bool withBorder = attrChain_bool_default(control->attr, "withBorder", false); lineEditWidget->setFrame(withBorder); // [self setBordered:NO]; /* if(withBorder) { [self setBezeled:YES]; [self setBezelStyle:NSTextFieldRoundedBezel]; } [self setDrawsBackground:NO]; [[self cell] setUsesSingleLineMode:YES]; [[self cell] setLineBreakMode:NSLineBreakByTruncatingTail]; */ lineEditWidget->setReadOnly(true); } void QtOneLineTextWidget::resizeEvent(QResizeEvent* ev) { QtBaseWidget::resizeEvent(ev); lineEditWidget->resize(size()); } PyObject* QtOneLineTextWidget::getTextObj() { PyQtGuiObject* control = getControl(); PyObject* textObj = control ? control->subjectObject : NULL; Py_XINCREF(textObj); Py_XDECREF(control); return textObj; } void QtOneLineTextWidget::updateContent() { PyQtGuiObject* control = NULL; std::string s = "???"; { PyScopedGIL gil; control = getControl(); if(!control) return; control->updateSubjectObject(); { PyObject* labelContent = getTextObj(); if(!labelContent && PyErr_Occurred()) PyErr_Print(); if(labelContent) { if(!pyStr(labelContent, s)) { if(PyErr_Occurred()) PyErr_Print(); } } } } WeakRef selfRefCopy(*this); // Note: We had this async before. But I think other code wants to know the actual size // and we only get it after we set the text. execInMainThread_sync([=]() { PyScopedGIL gil; ScopedRef selfRef(selfRefCopy.scoped()); if(selfRef) { auto self = dynamic_cast<QtOneLineTextWidget*>(selfRef.get()); assert(self); assert(self->lineEditWidget); self->lineEditWidget->setText(QString::fromStdString(s)); PyScopedGIL gil; /* NSColor* color = backgroundColor(control); if(color) { [self setDrawsBackground:YES]; [self setBackgroundColor:color]; } */ //[self setTextColor:foregroundColor(control)]; bool autosizeWidth = attrChain_bool_default(control->attr, "autosizeWidth", false); if(autosizeWidth) { QFontMetrics metrics(self->lineEditWidget->fontMetrics()); int w = metrics.boundingRect(self->lineEditWidget->text()).width(); self->resize(w, self->height()); PyObject* res = PyObject_CallMethod((PyObject*) control, (char*)"layoutLine", NULL); if(!res && PyErr_Occurred()) PyErr_Print(); Py_XDECREF(res); } } Py_DECREF(control); }); } <commit_msg>text margin size<commit_after>// // QtOneLineTextWidget.cpp // MusicPlayer // // Created by Albert Zeyer on 23.01.14. // Copyright (c) 2014 Albert Zeyer. All rights reserved. // #include "QtOneLineTextWidget.hpp" #include "QtApp.hpp" #include "Builders.hpp" #include "PythonHelpers.h" #include "PyUtils.h" #include <string> #include <assert.h> RegisterControl(OneLineText) QtOneLineTextWidget::QtOneLineTextWidget(PyQtGuiObject* control) : QtBaseWidget(control) { PyScopedGIL gil; long w = attrChain_int_default(control->attr, "width", -1); long h = attrChain_int_default(control->attr, "height", -1); if(w < 0) w = 30; if(h < 0) h = 22; control->PresetSize = Vec((int)w, (int)h); resize(w, h); setBaseSize(w, h); lineEditWidget = new QLineEdit(this); lineEditWidget->resize(w, h); lineEditWidget->show(); bool withBorder = attrChain_bool_default(control->attr, "withBorder", false); lineEditWidget->setFrame(withBorder); // [self setBordered:NO]; /* if(withBorder) { [self setBezeled:YES]; [self setBezelStyle:NSTextFieldRoundedBezel]; } [self setDrawsBackground:NO]; [[self cell] setUsesSingleLineMode:YES]; [[self cell] setLineBreakMode:NSLineBreakByTruncatingTail]; */ lineEditWidget->setReadOnly(true); } void QtOneLineTextWidget::resizeEvent(QResizeEvent* ev) { QtBaseWidget::resizeEvent(ev); lineEditWidget->resize(size()); } PyObject* QtOneLineTextWidget::getTextObj() { PyQtGuiObject* control = getControl(); PyObject* textObj = control ? control->subjectObject : NULL; Py_XINCREF(textObj); Py_XDECREF(control); return textObj; } void QtOneLineTextWidget::updateContent() { PyQtGuiObject* control = NULL; std::string s = "???"; { PyScopedGIL gil; control = getControl(); if(!control) return; control->updateSubjectObject(); { PyObject* labelContent = getTextObj(); if(!labelContent && PyErr_Occurred()) PyErr_Print(); if(labelContent) { if(!pyStr(labelContent, s)) { if(PyErr_Occurred()) PyErr_Print(); } } } } WeakRef selfRefCopy(*this); // Note: We had this async before. But I think other code wants to know the actual size // and we only get it after we set the text. execInMainThread_sync([=]() { PyScopedGIL gil; ScopedRef selfRef(selfRefCopy.scoped()); if(selfRef) { auto self = dynamic_cast<QtOneLineTextWidget*>(selfRef.get()); assert(self); assert(self->lineEditWidget); self->lineEditWidget->setText(QString::fromStdString(s)); PyScopedGIL gil; /* NSColor* color = backgroundColor(control); if(color) { [self setDrawsBackground:YES]; [self setBackgroundColor:color]; } */ //[self setTextColor:foregroundColor(control)]; bool autosizeWidth = attrChain_bool_default(control->attr, "autosizeWidth", false); if(autosizeWidth) { QFontMetrics metrics(self->lineEditWidget->fontMetrics()); int w = metrics.boundingRect(self->lineEditWidget->text()).width(); w += 5; // TODO: margin size? self->resize(w, self->height()); PyObject* res = PyObject_CallMethod((PyObject*) control, (char*)"layoutLine", NULL); if(!res && PyErr_Occurred()) PyErr_Print(); Py_XDECREF(res); } } Py_DECREF(control); }); } <|endoftext|>
<commit_before>#include "overviewpage.h" #include "ui_overviewpage.h" #include "clientmodel.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 3 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(qVariantCanConvert<QColor>(value)) { foreground = qvariant_cast<QColor>(value); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } <commit_msg>overviewpage: make some code Qt5 compatible<commit_after>#include "overviewpage.h" #include "ui_overviewpage.h" #include "clientmodel.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 3 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } <|endoftext|>
<commit_before>#include "overviewpage.h" #include "ui_overviewpage.h" #include "clientmodel.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #include "main.h" #include "bitcoinrpc.h" #include "util.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 3 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); if(GetBoolArg("-chart", true)) { // setup Plot // create graph ui->diffplot->addGraph(); // Use usual background ui->diffplot->setBackground(QBrush(QWidget::palette().color(this->backgroundRole()))); // give the axes some labels: ui->diffplot->xAxis->setLabel(tr("Blocks")); ui->diffplot->yAxis->setLabel(tr("Difficulty")); // set the pens ui->diffplot->graph(0)->setPen(QPen(QColor(76, 76, 229))); ui->diffplot->graph(0)->setLineStyle(QCPGraph::lsLine); // set axes label fonts: QFont label = font(); ui->diffplot->xAxis->setLabelFont(label); ui->diffplot->yAxis->setLabelFont(label); } else { ui->diffplot->setVisible(false); } } void OverviewPage::updatePlot() { static int64_t lastUpdate = 0; // Double Check to make sure we don't try to update the plot when it is disabled if(!GetBoolArg("-chart", true)) { return; } if (GetTime() - lastUpdate < 60) { return; } // This is just so it doesn't redraw rapidly during syncing int numLookBack = 4320; double diffMax = 0; CBlockIndex* pindex = pindexBest; int height = nBestHeight; int xStart = std::max<int>(height-numLookBack, 0) + 1; int xEnd = height; // Start at the end and walk backwards int i = numLookBack-1; int x = xEnd; // This should be a noop if the size is already 2000 vX.resize(numLookBack); vY.resize(numLookBack); CBlockIndex* itr = pindex; while(i >= 0 && itr != NULL) { vX[i] = itr->nHeight; vY[i] = GetDifficulty(itr); diffMax = std::max<double>(diffMax, vY[i]); itr = itr->pprev; i--; x--; } ui->diffplot->graph(0)->setData(vX, vY); // set axes ranges, so we see all data: ui->diffplot->xAxis->setRange((double)xStart, (double)xEnd); ui->diffplot->yAxis->setRange(0, diffMax+(diffMax/10)); ui->diffplot->xAxis->setAutoSubTicks(false); ui->diffplot->yAxis->setAutoSubTicks(false); ui->diffplot->xAxis->setSubTickCount(0); ui->diffplot->yAxis->setSubTickCount(0); ui->diffplot->replot(); lastUpdate = GetTime(); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } <commit_msg>Fix gitian build<commit_after>#include "overviewpage.h" #include "ui_overviewpage.h" #include "clientmodel.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" #include "transactiontablemodel.h" #include "transactionfilterproxy.h" #include "guiutil.h" #include "guiconstants.h" #ifndef Q_MOC_RUN #include "main.h" #include "bitcoinrpc.h" #include "util.h" #endif #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 64 #define NUM_ITEMS 3 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } painter->setPen(foreground); painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; }; #include "overviewpage.moc" OverviewPage::OverviewPage(QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), txdelegate(new TxViewDelegate()), filter(0) { ui->setupUi(this); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // init "out of sync" warning labels ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); if(GetBoolArg("-chart", true)) { // setup Plot // create graph ui->diffplot->addGraph(); // Use usual background ui->diffplot->setBackground(QBrush(QWidget::palette().color(this->backgroundRole()))); // give the axes some labels: ui->diffplot->xAxis->setLabel(tr("Blocks")); ui->diffplot->yAxis->setLabel(tr("Difficulty")); // set the pens ui->diffplot->graph(0)->setPen(QPen(QColor(76, 76, 229))); ui->diffplot->graph(0)->setLineStyle(QCPGraph::lsLine); // set axes label fonts: QFont label = font(); ui->diffplot->xAxis->setLabelFont(label); ui->diffplot->yAxis->setLabelFont(label); } else { ui->diffplot->setVisible(false); } } void OverviewPage::updatePlot() { static int64_t lastUpdate = 0; // Double Check to make sure we don't try to update the plot when it is disabled if(!GetBoolArg("-chart", true)) { return; } if (GetTime() - lastUpdate < 60) { return; } // This is just so it doesn't redraw rapidly during syncing int numLookBack = 4320; double diffMax = 0; CBlockIndex* pindex = pindexBest; int height = nBestHeight; int xStart = std::max<int>(height-numLookBack, 0) + 1; int xEnd = height; // Start at the end and walk backwards int i = numLookBack-1; int x = xEnd; // This should be a noop if the size is already 2000 vX.resize(numLookBack); vY.resize(numLookBack); CBlockIndex* itr = pindex; while(i >= 0 && itr != NULL) { vX[i] = itr->nHeight; vY[i] = GetDifficulty(itr); diffMax = std::max<double>(diffMax, vY[i]); itr = itr->pprev; i--; x--; } ui->diffplot->graph(0)->setData(vX, vY); // set axes ranges, so we see all data: ui->diffplot->xAxis->setRange((double)xStart, (double)xEnd); ui->diffplot->yAxis->setRange(0, diffMax+(diffMax/10)); ui->diffplot->xAxis->setAutoSubTicks(false); ui->diffplot->yAxis->setAutoSubTicks(false); ui->diffplot->xAxis->setSubTickCount(0); ui->diffplot->yAxis->setSubTickCount(0); ui->diffplot->replot(); lastUpdate = GetTime(); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) emit transactionClicked(filter->mapToSource(index)); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter = new TransactionFilterProxy(); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); ui->listTransactions->setModel(filter); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } <|endoftext|>
<commit_before>/** * @file ErrPair.hpp * @brief ErrPair class prototype. * @author zer0 * @date 2019-09-11 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_ERRPAIR_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_ERRPAIR_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Err.hpp> #include <type_traits> #include <string> #include <ostream> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- /** * ErrPair class template. * * @author zer0 * @date 2019-09-11 */ template <typename T> struct ErrPair { using ValueType = T; static_assert(!std::is_void<ValueType>::value, "Void type is not supported."); static_assert(!std::is_reference<ValueType>::value, "Reference type is not supported."); Err code; ValueType value; TBAG_CONSTEXPR static bool const nothrow_def = std::is_nothrow_default_constructible<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_copy = std::is_nothrow_copy_constructible<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_move = std::is_nothrow_move_constructible<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_copy_assign = std::is_nothrow_copy_assignable<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_move_assign = std::is_nothrow_move_assignable<ValueType>::value; ErrPair() TBAG_NOEXCEPT_SPECIFIER(nothrow_def) : code(E_UNKNOWN), value() { /* EMPTY. */ } ErrPair(Err c) TBAG_NOEXCEPT_SPECIFIER(nothrow_def) : code(c), value() { /* EMPTY. */ } ErrPair(ValueType const & v) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy) : code(E_UNKNOWN), value(v) { /* EMPTY. */ } ErrPair(Err c, ValueType const & v) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy) : code(c), value(v) { /* EMPTY. */ } ErrPair(ValueType && v) TBAG_NOEXCEPT_SPECIFIER(nothrow_move) : code(E_UNKNOWN), value(std::move(v)) { /* EMPTY. */ } ErrPair(Err c, ValueType && v) TBAG_NOEXCEPT_SPECIFIER(nothrow_move) : code(c), value(std::move(v)) { /* EMPTY. */ } ErrPair(ErrPair const & obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy) : code(obj.code), value(obj.value) { /* EMPTY. */ } ErrPair(ErrPair && obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_move) : code(obj.code), value(std::move(obj.value)) { /* EMPTY. */ } ~ErrPair() { /* EMPTY. */ } ErrPair & operator =(Err c) TBAG_NOEXCEPT { code = c; return *this; } ErrPair & operator =(ValueType const & v) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy_assign) { value = v; return *this; } ErrPair & operator =(ValueType && v) TBAG_NOEXCEPT_SPECIFIER(nothrow_move_assign) { value = std::move(v); return *this; } ErrPair & operator =(ErrPair const & obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy_assign) { if (this != &obj) { code = obj.code; value = obj.value; } return *this; } ErrPair & operator =(ErrPair && obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_move_assign) { if (this != &obj) { code = obj.code; value = std::move(obj.value); } return *this; } char const * name() const TBAG_NOEXCEPT { return libtbag::getErrName(code); } char const * detail() const TBAG_NOEXCEPT { return libtbag::getErrDetail(code); } inline operator Err() const TBAG_NOEXCEPT { return code; } inline operator bool() const TBAG_NOEXCEPT { return isSuccess(code); } inline int toInt() const TBAG_NOEXCEPT { return static_cast<int>(code); } inline void fromInt(int v) TBAG_NOEXCEPT { code = static_cast<Err>(v); } template <class CharT, class TraitsT> friend std::basic_ostream<CharT, TraitsT> & operator<<(std::basic_ostream<CharT, TraitsT> & os, ErrPair const & err) { return os << err.name(); } }; /** * ErrMsgPair class template. * * @author zer0 * @date 2019-11-11 */ template <typename T> struct ErrMsgPair : public ErrPair<T> { using BaseErrPair = ErrPair<T>; using ValueType = typename BaseErrPair::ValueType; TBAG_CONSTEXPR static bool const base_nothrow_move = std::is_nothrow_move_constructible<BaseErrPair>::value; TBAG_CONSTEXPR static bool const base_nothrow_move_assign = std::is_nothrow_move_assignable<BaseErrPair>::value; TBAG_CONSTEXPR static bool const str_nothrow_move = std::is_nothrow_move_constructible<std::string>::value; TBAG_CONSTEXPR static bool const str_nothrow_move_assign = std::is_nothrow_move_assignable<std::string>::value; std::string msg; ErrMsgPair() : ErrPair<T>() { /* EMPTY. */ } ErrMsgPair(Err c) : ErrPair<T>(c) { /* EMPTY. */ } ErrMsgPair(ValueType const & v) : ErrPair<T>(v) { /* EMPTY. */ } ErrMsgPair(Err c, ValueType const & v) : ErrPair<T>(c, v) { /* EMPTY. */ } ErrMsgPair(ValueType && v) : ErrPair<T>(std::move(v)) { /* EMPTY. */ } ErrMsgPair(Err c, ValueType && v) : ErrPair<T>(c, std::move(v)) { /* EMPTY. */ } ErrMsgPair(ErrMsgPair const & obj) : ErrPair<T>(obj), msg(obj.msg) { /* EMPTY. */ } ErrMsgPair(ErrMsgPair && obj) TBAG_NOEXCEPT_SPECIFIER(base_nothrow_move && str_nothrow_move) : ErrPair<T>(std::move(obj)), msg(std::move(obj.msg)) { /* EMPTY. */ } ~ErrMsgPair() { /* EMPTY. */ } ErrMsgPair & operator =(ErrMsgPair const & obj) { if (this != &obj) { ErrPair<T>::operator =(obj); msg = obj.msg; } return *this; } ErrMsgPair & operator =(ErrMsgPair && obj) TBAG_NOEXCEPT_SPECIFIER(base_nothrow_move_assign && str_nothrow_move_assign) { if (this != &obj) { ErrPair<T>::operator =(std::move(obj)); msg = std::move(obj.msg); } return *this; } }; // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_ERRPAIR_HPP__ <commit_msg>Create ErrPair::operator==() method.<commit_after>/** * @file ErrPair.hpp * @brief ErrPair class prototype. * @author zer0 * @date 2019-09-11 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_ERRPAIR_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_ERRPAIR_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <libtbag/Err.hpp> #include <type_traits> #include <string> #include <ostream> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- /** * ErrPair class template. * * @author zer0 * @date 2019-09-11 */ template <typename T> struct ErrPair { using ValueType = T; static_assert(!std::is_void<ValueType>::value, "Void type is not supported."); static_assert(!std::is_reference<ValueType>::value, "Reference type is not supported."); Err code; ValueType value; TBAG_CONSTEXPR static bool const nothrow_def = std::is_nothrow_default_constructible<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_copy = std::is_nothrow_copy_constructible<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_move = std::is_nothrow_move_constructible<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_copy_assign = std::is_nothrow_copy_assignable<ValueType>::value; TBAG_CONSTEXPR static bool const nothrow_move_assign = std::is_nothrow_move_assignable<ValueType>::value; ErrPair() TBAG_NOEXCEPT_SPECIFIER(nothrow_def) : code(E_UNKNOWN), value() { /* EMPTY. */ } ErrPair(Err c) TBAG_NOEXCEPT_SPECIFIER(nothrow_def) : code(c), value() { /* EMPTY. */ } ErrPair(ValueType const & v) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy) : code(E_UNKNOWN), value(v) { /* EMPTY. */ } ErrPair(Err c, ValueType const & v) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy) : code(c), value(v) { /* EMPTY. */ } ErrPair(ValueType && v) TBAG_NOEXCEPT_SPECIFIER(nothrow_move) : code(E_UNKNOWN), value(std::move(v)) { /* EMPTY. */ } ErrPair(Err c, ValueType && v) TBAG_NOEXCEPT_SPECIFIER(nothrow_move) : code(c), value(std::move(v)) { /* EMPTY. */ } ErrPair(ErrPair const & obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy) : code(obj.code), value(obj.value) { /* EMPTY. */ } ErrPair(ErrPair && obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_move) : code(obj.code), value(std::move(obj.value)) { /* EMPTY. */ } ~ErrPair() { /* EMPTY. */ } ErrPair & operator =(Err c) TBAG_NOEXCEPT { code = c; return *this; } ErrPair & operator =(ValueType const & v) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy_assign) { value = v; return *this; } ErrPair & operator =(ValueType && v) TBAG_NOEXCEPT_SPECIFIER(nothrow_move_assign) { value = std::move(v); return *this; } ErrPair & operator =(ErrPair const & obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_copy_assign) { if (this != &obj) { code = obj.code; value = obj.value; } return *this; } ErrPair & operator =(ErrPair && obj) TBAG_NOEXCEPT_SPECIFIER(nothrow_move_assign) { if (this != &obj) { code = obj.code; value = std::move(obj.value); } return *this; } inline bool operator ==(Err c) const TBAG_NOEXCEPT { return code == c; } char const * name() const TBAG_NOEXCEPT { return libtbag::getErrName(code); } char const * detail() const TBAG_NOEXCEPT { return libtbag::getErrDetail(code); } inline operator Err() const TBAG_NOEXCEPT { return code; } inline operator bool() const TBAG_NOEXCEPT { return isSuccess(code); } inline int toInt() const TBAG_NOEXCEPT { return static_cast<int>(code); } inline void fromInt(int v) TBAG_NOEXCEPT { code = static_cast<Err>(v); } template <class CharT, class TraitsT> friend std::basic_ostream<CharT, TraitsT> & operator<<(std::basic_ostream<CharT, TraitsT> & os, ErrPair const & err) { return os << err.name(); } }; /** * ErrMsgPair class template. * * @author zer0 * @date 2019-11-11 */ template <typename T> struct ErrMsgPair : public ErrPair<T> { using BaseErrPair = ErrPair<T>; using ValueType = typename BaseErrPair::ValueType; TBAG_CONSTEXPR static bool const base_nothrow_move = std::is_nothrow_move_constructible<BaseErrPair>::value; TBAG_CONSTEXPR static bool const base_nothrow_move_assign = std::is_nothrow_move_assignable<BaseErrPair>::value; TBAG_CONSTEXPR static bool const str_nothrow_move = std::is_nothrow_move_constructible<std::string>::value; TBAG_CONSTEXPR static bool const str_nothrow_move_assign = std::is_nothrow_move_assignable<std::string>::value; std::string msg; ErrMsgPair() : ErrPair<T>() { /* EMPTY. */ } ErrMsgPair(Err c) : ErrPair<T>(c) { /* EMPTY. */ } ErrMsgPair(ValueType const & v) : ErrPair<T>(v) { /* EMPTY. */ } ErrMsgPair(Err c, ValueType const & v) : ErrPair<T>(c, v) { /* EMPTY. */ } ErrMsgPair(ValueType && v) : ErrPair<T>(std::move(v)) { /* EMPTY. */ } ErrMsgPair(Err c, ValueType && v) : ErrPair<T>(c, std::move(v)) { /* EMPTY. */ } ErrMsgPair(ErrMsgPair const & obj) : ErrPair<T>(obj), msg(obj.msg) { /* EMPTY. */ } ErrMsgPair(ErrMsgPair && obj) TBAG_NOEXCEPT_SPECIFIER(base_nothrow_move && str_nothrow_move) : ErrPair<T>(std::move(obj)), msg(std::move(obj.msg)) { /* EMPTY. */ } ~ErrMsgPair() { /* EMPTY. */ } ErrMsgPair & operator =(ErrMsgPair const & obj) { if (this != &obj) { ErrPair<T>::operator =(obj); msg = obj.msg; } return *this; } ErrMsgPair & operator =(ErrMsgPair && obj) TBAG_NOEXCEPT_SPECIFIER(base_nothrow_move_assign && str_nothrow_move_assign) { if (this != &obj) { ErrPair<T>::operator =(std::move(obj)); msg = std::move(obj.msg); } return *this; } }; // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_ERRPAIR_HPP__ <|endoftext|>
<commit_before>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings //int paddingRight = 50; //int paddingTop = 50; //int titleVersionVSpace = 17; //int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down //QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); //QString copyrightText = QChar(0xA9)+QString(" 2009-2013 ") + QString(tr("The Bitcoin developers")); //QString copyrightText2 = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("The MaxCoin developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(100,100,100)); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } //pixPaint.setFont(QFont(font, 33*fontFactor)); //fm = pixPaint.fontMetrics(); //titleTextWidth = fm.width(titleText); //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText); //pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size //fm = pixPaint.fontMetrics(); //int versionTextWidth = fm.width(versionText); //if(versionTextWidth > titleTextWidth+paddingRight-10) { // pixPaint.setFont(QFont(font, 10*fontFactor)); // titleVersionVSpace -= 5; //} //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff //pixPaint.setFont(QFont(font, 10*fontFactor)); //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace+12,copyrightText2); // draw testnet string if -testnet is on if(QApplication::applicationName().contains(QString("-testnet"))) { // draw copyright stuff QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); } <commit_msg>Tweaking text color to lighter shade (after new bg change)<commit_after>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings //int paddingRight = 50; //int paddingTop = 50; //int titleVersionVSpace = 17; //int titleCopyrightVSpace = 40; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down //QString versionText = QString("Version %1").arg(QString::fromStdString(FormatFullVersion())); //QString copyrightText = QChar(0xA9)+QString(" 2009-2013 ") + QString(tr("The Bitcoin developers")); //QString copyrightText2 = QChar(0xA9)+QString(" %1 ").arg(COPYRIGHT_YEAR) + QString(tr("The MaxCoin developers")); QString testnetAddText = QString(tr("[testnet]")); // define text to place as single text object QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(200,200,200)); // check font size and drawing with pixPaint.setFont(QFont(font, 33*fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if(titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } //pixPaint.setFont(QFont(font, 33*fontFactor)); //fm = pixPaint.fontMetrics(); //titleTextWidth = fm.width(titleText); //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText); //pixPaint.setFont(QFont(font, 15*fontFactor)); // if the version string is to long, reduce size //fm = pixPaint.fontMetrics(); //int versionTextWidth = fm.width(versionText); //if(versionTextWidth > titleTextWidth+paddingRight-10) { // pixPaint.setFont(QFont(font, 10*fontFactor)); // titleVersionVSpace -= 5; //} //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText); // draw copyright stuff //pixPaint.setFont(QFont(font, 10*fontFactor)); //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText); //pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace+12,copyrightText2); // draw testnet string if -testnet is on if(QApplication::applicationName().contains(QString("-testnet"))) { // draw copyright stuff QFont boldFont = QFont(font, 10*fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int testnetAddTextWidth = fm.width(testnetAddText); pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText); } pixPaint.end(); this->setPixmap(newPixmap); } <|endoftext|>
<commit_before>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #undef loop /* ugh, remove this when the #define loop is gone from util.h */ #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingLeftCol2 = 230; int paddingTopCol2 = 376; int line1 = 0; int line2 = 13; int line3 = 26; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Developers")); QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Litecoin Developers")); QString copyrightText3 = QChar(0xA9)+QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Maplecoin Developers")); QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(70,70,70)); pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); pixPaint.end(); this->setPixmap(newPixmap); } <commit_msg>Update<commit_after>#include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #undef loop /* ugh, remove this when the #define loop is gone from util.h */ #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingLeftCol2 = 230; int paddingTopCol2 = 376; int line1 = 0; int line2 = 13; int line3 = 26; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText1 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Litecoin Developers")); QString copyrightText2 = QChar(0xA9)+QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Maplecoin Developers")); QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(70,70,70)); pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); pixPaint.end(); this->setPixmap(newPixmap); } <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "rdb_protocol/val.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/meta_utils.hpp" #include "rdb_protocol/pb_utils.hpp" #include "rdb_protocol/term.hpp" namespace ql { // Most of this logic is copy-pasted from the old query language. table_t::table_t(env_t *_env, uuid_u db_id, const std::string &name, bool _use_outdated, const pb_rcheckable_t *src) : pb_rcheckable_t(src), env(_env), use_outdated(_use_outdated) { name_string_t table_name; bool b = table_name.assign_value(name); rcheck(b, strprintf("Table name `%s` invalid (%s).", name.c_str(), valid_char_msg)); cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > namespaces_metadata = env->namespaces_semilattice_metadata->get(); cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> >::change_t namespaces_metadata_change(&namespaces_metadata); metadata_searcher_t<namespace_semilattice_metadata_t<rdb_protocol_t> > ns_searcher(&namespaces_metadata_change.get()->namespaces); //TODO: fold into iteration below namespace_predicate_t pred(&table_name, &db_id); uuid_u id = meta_get_uuid(&ns_searcher, pred, strprintf("Table `%s` does not exist.", table_name.c_str()), this); access.init(new namespace_repo_t<rdb_protocol_t>::access_t( env->ns_repo, id, env->interruptor)); metadata_search_status_t status; metadata_searcher_t<namespace_semilattice_metadata_t<rdb_protocol_t> >::iterator ns_metadata_it = ns_searcher.find_uniq(pred, &status); //meta_check(status, METADATA_SUCCESS, "FIND_TABLE " + table_name.str(), this); rcheck(status == METADATA_SUCCESS, strprintf("Table `%s` does not exist.", table_name.c_str())); guarantee(!ns_metadata_it->second.is_deleted()); r_sanity_check(!ns_metadata_it->second.get().primary_key.in_conflict()); pkey = ns_metadata_it->second.get().primary_key.get(); } datum_t *table_t::env_add_ptr(datum_t *d) { return env->add_ptr(d); } const datum_t *table_t::do_replace(const datum_t *orig, const map_wire_func_t &mwf, UNUSED bool _so_the_template_matches) { const std::string &pk = get_pkey(); if (orig->get_type() == datum_t::R_NULL) { map_wire_func_t mwf2 = mwf; orig = mwf2.compile(env)->call(orig)->as_datum(); if (orig->get_type() == datum_t::R_NULL) { datum_t *resp = env->add_ptr(new datum_t(datum_t::R_OBJECT)); const datum_t *num_1 = env->add_ptr(new ql::datum_t(1.0)); bool b = resp->add("skipped", num_1); r_sanity_check(!b); return resp; } } store_key_t store_key(orig->el(pk)->print_primary()); rdb_protocol_t::write_t write( rdb_protocol_t::point_replace_t(pk, store_key, mwf, env->get_all_optargs())); rdb_protocol_t::write_response_t response; access->get_namespace_if()->write( write, &response, order_token_t::ignore, env->interruptor); Datum *d = boost::get<Datum>(&response.response); return env->add_ptr(new datum_t(d, env)); } const datum_t *table_t::do_replace(const datum_t *orig, func_t *f, bool nondet_ok) { if (f->is_deterministic()) { return do_replace(orig, map_wire_func_t(env, f)); } else { r_sanity_check(nondet_ok); return do_replace(orig, f->call(orig)->as_datum(), true); } } const datum_t *table_t::do_replace(const datum_t *orig, const datum_t *d, bool upsert) { Term t; int x = env->gensym(); Term *arg = pb::set_func(&t, x); if (upsert) { d->write_to_protobuf(pb::set_datum(arg)); } else { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" N3(BRANCH, N2(EQ, NVAR(x), NDATUM(datum_t::R_NULL)), NDATUM(d), N1(ERROR, NDATUM("Duplicate primary key."))) #pragma GCC diagnostic pop } propagate(&t); return do_replace(orig, map_wire_func_t(t, nullptr)); } const std::string &table_t::get_pkey() { return pkey; } const datum_t *table_t::get_row(const datum_t *pval) { std::string pks = pval->print_primary(); rdb_protocol_t::read_t read((rdb_protocol_t::point_read_t(store_key_t(pks)))); rdb_protocol_t::read_response_t res; if (use_outdated) { access->get_namespace_if()->read_outdated(read, &res, env->interruptor); } else { access->get_namespace_if()->read( read, &res, order_token_t::ignore, env->interruptor); } rdb_protocol_t::point_read_response_t *p_res = boost::get<rdb_protocol_t::point_read_response_t>(&res.response); r_sanity_check(p_res); return env->add_ptr(new datum_t(p_res->data, env)); } datum_stream_t *table_t::as_datum_stream() { return env->add_ptr( new lazy_datum_stream_t(env, use_outdated, access.get(), this)); } val_t::type_t::type_t(val_t::type_t::raw_type_t _raw_type) : raw_type(_raw_type) { } // NOTE: This *MUST* be kept in sync with the surrounding code (not that it // should have to change very often). bool raw_type_is_convertible(val_t::type_t::raw_type_t _t1, val_t::type_t::raw_type_t _t2) { const int t1 = _t1, t2 = _t2, DB = val_t::type_t::DB, TABLE = val_t::type_t::TABLE, SELECTION = val_t::type_t::SELECTION, SEQUENCE = val_t::type_t::SEQUENCE, SINGLE_SELECTION = val_t::type_t::SINGLE_SELECTION, DATUM = val_t::type_t::DATUM, FUNC = val_t::type_t::FUNC; switch (t1) { case DB: return t2 == DB; case TABLE: return t2 == TABLE || t2 == SELECTION || t2 == SEQUENCE; case SELECTION: return t2 == SELECTION || t2 == SEQUENCE; case SEQUENCE: return t2 == SEQUENCE; case SINGLE_SELECTION: return t2 == SINGLE_SELECTION || t2 == DATUM; case DATUM: return t2 == DATUM || t2 == SEQUENCE; case FUNC: return t2 == FUNC; default: unreachable(); } unreachable(); } bool val_t::type_t::is_convertible(type_t rhs) const { return raw_type_is_convertible(raw_type, rhs.raw_type); } const char *val_t::type_t::name() const { switch (raw_type) { case DB: return "DATABASE"; case TABLE: return "TABLE"; case SELECTION: return "SELECTION"; case SEQUENCE: return "SEQUENCE"; case SINGLE_SELECTION: return "SINGLE_SELECTION"; case DATUM: return "DATUM"; case FUNC: return "FUNCTION"; default: unreachable(); } unreachable(); } val_t::val_t(const datum_t *_datum, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::DATUM), table(0), sequence(0), datum(env->add_ptr(_datum)), func(0) { guarantee(datum); } val_t::val_t(const datum_t *_datum, table_t *_table, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::SINGLE_SELECTION), table(env->add_ptr(_table)), sequence(0), datum(env->add_ptr(_datum)), func(0) { guarantee(table); guarantee(datum); } val_t::val_t(datum_stream_t *_sequence, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::SEQUENCE), table(0), sequence(env->add_ptr(_sequence)), datum(0), func(0) { guarantee(sequence); // Some streams are really arrays in disguise. if ((datum = sequence->as_array())) { sequence = 0; type = type_t::DATUM; } } val_t::val_t(table_t *_table, datum_stream_t *_sequence, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::SELECTION), table(env->add_ptr(_table)), sequence(env->add_ptr(_sequence)), datum(0), func(0) { guarantee(table); guarantee(sequence); } val_t::val_t(table_t *_table, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::TABLE), table(env->add_ptr(_table)), sequence(0), datum(0), func(0) { guarantee(table); } val_t::val_t(uuid_u _db, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::DB), db(_db), table(0), sequence(0), datum(0), func(0) { } val_t::val_t(func_t *_func, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::FUNC), table(0), sequence(0), datum(0), func(env->add_ptr(_func)) { guarantee(func); } val_t::type_t val_t::get_type() const { return type; } const char * val_t::get_type_name() const { return get_type().name(); } const datum_t *val_t::as_datum() { if (type.raw_type != type_t::DATUM && type.raw_type != type_t::SINGLE_SELECTION) { rcheck_literal_type(type_t::DATUM); } return datum; } table_t *val_t::as_table() { rcheck_literal_type(type_t::TABLE); return table; } datum_stream_t *val_t::as_seq() { if (type.raw_type == type_t::SEQUENCE || type.raw_type == type_t::SELECTION) { // passthru } else if (type.raw_type == type_t::TABLE) { if (!sequence) sequence = table->as_datum_stream(); } else if (type.raw_type == type_t::DATUM) { if (!sequence) sequence = datum->as_datum_stream(env, parent); } else { rcheck_literal_type(type_t::SEQUENCE); } return sequence; } std::pair<table_t *, datum_stream_t *> val_t::as_selection() { if (type.raw_type != type_t::TABLE && type.raw_type != type_t::SELECTION) { rcheck_literal_type(type_t::SELECTION); } return std::make_pair(table, as_seq()); } std::pair<table_t *, const datum_t *> val_t::as_single_selection() { rcheck_literal_type(type_t::SINGLE_SELECTION); return std::make_pair(table, datum); } func_t *val_t::as_func(function_shortcut_t shortcut) { if (shortcut == NO_SHORTCUT) { rcheck_literal_type(type_t::FUNC); r_sanity_check(func); } if (!func) { if (!type.is_convertible(type_t::DATUM)) { rcheck_literal_type(type_t::FUNC); } r_sanity_check(parent); switch (shortcut) { case IDENTITY_SHORTCUT: { func = env->add_ptr(func_t::new_identity_func(env, as_datum(), parent)); } break; case NO_SHORTCUT: // fallthru default: unreachable(); } } return func; } uuid_u val_t::as_db() { rcheck_literal_type(type_t::DB); return db; } bool val_t::as_bool() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_bool(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } double val_t::as_num() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_num(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } int64_t val_t::as_int() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_int(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } const std::string &val_t::as_str() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_str(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } void val_t::rcheck_literal_type(type_t::raw_type_t expected_raw_type) { rcheck(type.raw_type == expected_raw_type, strprintf("Expected type %s but found %s:\n%s", type_t(expected_raw_type).name(), type.name(), print().c_str())); } } //namespace ql <commit_msg>Adjusted some whitespace in val.cc.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "rdb_protocol/val.hpp" #include "rdb_protocol/env.hpp" #include "rdb_protocol/meta_utils.hpp" #include "rdb_protocol/pb_utils.hpp" #include "rdb_protocol/term.hpp" namespace ql { // Most of this logic is copy-pasted from the old query language. table_t::table_t(env_t *_env, uuid_u db_id, const std::string &name, bool _use_outdated, const pb_rcheckable_t *src) : pb_rcheckable_t(src), env(_env), use_outdated(_use_outdated) { name_string_t table_name; bool b = table_name.assign_value(name); rcheck(b, strprintf("Table name `%s` invalid (%s).", name.c_str(), valid_char_msg)); cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> > namespaces_metadata = env->namespaces_semilattice_metadata->get(); cow_ptr_t<namespaces_semilattice_metadata_t<rdb_protocol_t> >::change_t namespaces_metadata_change(&namespaces_metadata); metadata_searcher_t<namespace_semilattice_metadata_t<rdb_protocol_t> > ns_searcher(&namespaces_metadata_change.get()->namespaces); //TODO: fold into iteration below namespace_predicate_t pred(&table_name, &db_id); uuid_u id = meta_get_uuid(&ns_searcher, pred, strprintf("Table `%s` does not exist.", table_name.c_str()), this); access.init(new namespace_repo_t<rdb_protocol_t>::access_t( env->ns_repo, id, env->interruptor)); metadata_search_status_t status; metadata_searcher_t<namespace_semilattice_metadata_t<rdb_protocol_t> >::iterator ns_metadata_it = ns_searcher.find_uniq(pred, &status); //meta_check(status, METADATA_SUCCESS, "FIND_TABLE " + table_name.str(), this); rcheck(status == METADATA_SUCCESS, strprintf("Table `%s` does not exist.", table_name.c_str())); guarantee(!ns_metadata_it->second.is_deleted()); r_sanity_check(!ns_metadata_it->second.get().primary_key.in_conflict()); pkey = ns_metadata_it->second.get().primary_key.get(); } datum_t *table_t::env_add_ptr(datum_t *d) { return env->add_ptr(d); } const datum_t *table_t::do_replace(const datum_t *orig, const map_wire_func_t &mwf, UNUSED bool _so_the_template_matches) { const std::string &pk = get_pkey(); if (orig->get_type() == datum_t::R_NULL) { map_wire_func_t mwf2 = mwf; orig = mwf2.compile(env)->call(orig)->as_datum(); if (orig->get_type() == datum_t::R_NULL) { datum_t *resp = env->add_ptr(new datum_t(datum_t::R_OBJECT)); const datum_t *num_1 = env->add_ptr(new ql::datum_t(1.0)); bool b = resp->add("skipped", num_1); r_sanity_check(!b); return resp; } } store_key_t store_key(orig->el(pk)->print_primary()); rdb_protocol_t::write_t write(rdb_protocol_t::point_replace_t(pk, store_key, mwf, env->get_all_optargs())); rdb_protocol_t::write_response_t response; access->get_namespace_if()->write(write, &response, order_token_t::ignore, env->interruptor); Datum *d = boost::get<Datum>(&response.response); return env->add_ptr(new datum_t(d, env)); } const datum_t *table_t::do_replace(const datum_t *orig, func_t *f, bool nondet_ok) { if (f->is_deterministic()) { return do_replace(orig, map_wire_func_t(env, f)); } else { r_sanity_check(nondet_ok); return do_replace(orig, f->call(orig)->as_datum(), true); } } const datum_t *table_t::do_replace(const datum_t *orig, const datum_t *d, bool upsert) { Term t; int x = env->gensym(); Term *arg = pb::set_func(&t, x); if (upsert) { d->write_to_protobuf(pb::set_datum(arg)); } else { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" N3(BRANCH, N2(EQ, NVAR(x), NDATUM(datum_t::R_NULL)), NDATUM(d), N1(ERROR, NDATUM("Duplicate primary key."))) #pragma GCC diagnostic pop } propagate(&t); return do_replace(orig, map_wire_func_t(t, nullptr)); } const std::string &table_t::get_pkey() { return pkey; } const datum_t *table_t::get_row(const datum_t *pval) { std::string pks = pval->print_primary(); rdb_protocol_t::read_t read((rdb_protocol_t::point_read_t(store_key_t(pks)))); rdb_protocol_t::read_response_t res; if (use_outdated) { access->get_namespace_if()->read_outdated(read, &res, env->interruptor); } else { access->get_namespace_if()->read( read, &res, order_token_t::ignore, env->interruptor); } rdb_protocol_t::point_read_response_t *p_res = boost::get<rdb_protocol_t::point_read_response_t>(&res.response); r_sanity_check(p_res); return env->add_ptr(new datum_t(p_res->data, env)); } datum_stream_t *table_t::as_datum_stream() { return env->add_ptr( new lazy_datum_stream_t(env, use_outdated, access.get(), this)); } val_t::type_t::type_t(val_t::type_t::raw_type_t _raw_type) : raw_type(_raw_type) { } // NOTE: This *MUST* be kept in sync with the surrounding code (not that it // should have to change very often). bool raw_type_is_convertible(val_t::type_t::raw_type_t _t1, val_t::type_t::raw_type_t _t2) { const int t1 = _t1, t2 = _t2, DB = val_t::type_t::DB, TABLE = val_t::type_t::TABLE, SELECTION = val_t::type_t::SELECTION, SEQUENCE = val_t::type_t::SEQUENCE, SINGLE_SELECTION = val_t::type_t::SINGLE_SELECTION, DATUM = val_t::type_t::DATUM, FUNC = val_t::type_t::FUNC; switch (t1) { case DB: return t2 == DB; case TABLE: return t2 == TABLE || t2 == SELECTION || t2 == SEQUENCE; case SELECTION: return t2 == SELECTION || t2 == SEQUENCE; case SEQUENCE: return t2 == SEQUENCE; case SINGLE_SELECTION: return t2 == SINGLE_SELECTION || t2 == DATUM; case DATUM: return t2 == DATUM || t2 == SEQUENCE; case FUNC: return t2 == FUNC; default: unreachable(); } unreachable(); } bool val_t::type_t::is_convertible(type_t rhs) const { return raw_type_is_convertible(raw_type, rhs.raw_type); } const char *val_t::type_t::name() const { switch (raw_type) { case DB: return "DATABASE"; case TABLE: return "TABLE"; case SELECTION: return "SELECTION"; case SEQUENCE: return "SEQUENCE"; case SINGLE_SELECTION: return "SINGLE_SELECTION"; case DATUM: return "DATUM"; case FUNC: return "FUNCTION"; default: unreachable(); } unreachable(); } val_t::val_t(const datum_t *_datum, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::DATUM), table(0), sequence(0), datum(env->add_ptr(_datum)), func(0) { guarantee(datum); } val_t::val_t(const datum_t *_datum, table_t *_table, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::SINGLE_SELECTION), table(env->add_ptr(_table)), sequence(0), datum(env->add_ptr(_datum)), func(0) { guarantee(table); guarantee(datum); } val_t::val_t(datum_stream_t *_sequence, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::SEQUENCE), table(0), sequence(env->add_ptr(_sequence)), datum(0), func(0) { guarantee(sequence); // Some streams are really arrays in disguise. if ((datum = sequence->as_array())) { sequence = 0; type = type_t::DATUM; } } val_t::val_t(table_t *_table, datum_stream_t *_sequence, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::SELECTION), table(env->add_ptr(_table)), sequence(env->add_ptr(_sequence)), datum(0), func(0) { guarantee(table); guarantee(sequence); } val_t::val_t(table_t *_table, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::TABLE), table(env->add_ptr(_table)), sequence(0), datum(0), func(0) { guarantee(table); } val_t::val_t(uuid_u _db, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::DB), db(_db), table(0), sequence(0), datum(0), func(0) { } val_t::val_t(func_t *_func, const term_t *_parent, env_t *_env) : pb_rcheckable_t(_parent), parent(_parent), env(_env), type(type_t::FUNC), table(0), sequence(0), datum(0), func(env->add_ptr(_func)) { guarantee(func); } val_t::type_t val_t::get_type() const { return type; } const char * val_t::get_type_name() const { return get_type().name(); } const datum_t *val_t::as_datum() { if (type.raw_type != type_t::DATUM && type.raw_type != type_t::SINGLE_SELECTION) { rcheck_literal_type(type_t::DATUM); } return datum; } table_t *val_t::as_table() { rcheck_literal_type(type_t::TABLE); return table; } datum_stream_t *val_t::as_seq() { if (type.raw_type == type_t::SEQUENCE || type.raw_type == type_t::SELECTION) { // passthru } else if (type.raw_type == type_t::TABLE) { if (!sequence) sequence = table->as_datum_stream(); } else if (type.raw_type == type_t::DATUM) { if (!sequence) sequence = datum->as_datum_stream(env, parent); } else { rcheck_literal_type(type_t::SEQUENCE); } return sequence; } std::pair<table_t *, datum_stream_t *> val_t::as_selection() { if (type.raw_type != type_t::TABLE && type.raw_type != type_t::SELECTION) { rcheck_literal_type(type_t::SELECTION); } return std::make_pair(table, as_seq()); } std::pair<table_t *, const datum_t *> val_t::as_single_selection() { rcheck_literal_type(type_t::SINGLE_SELECTION); return std::make_pair(table, datum); } func_t *val_t::as_func(function_shortcut_t shortcut) { if (shortcut == NO_SHORTCUT) { rcheck_literal_type(type_t::FUNC); r_sanity_check(func); } if (!func) { if (!type.is_convertible(type_t::DATUM)) { rcheck_literal_type(type_t::FUNC); } r_sanity_check(parent); switch (shortcut) { case IDENTITY_SHORTCUT: { func = env->add_ptr(func_t::new_identity_func(env, as_datum(), parent)); } break; case NO_SHORTCUT: // fallthru default: unreachable(); } } return func; } uuid_u val_t::as_db() { rcheck_literal_type(type_t::DB); return db; } bool val_t::as_bool() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_bool(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } double val_t::as_num() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_num(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } int64_t val_t::as_int() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_int(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } const std::string &val_t::as_str() { try { const datum_t *d = as_datum(); r_sanity_check(d); return d->as_str(); } catch (const datum_exc_t &e) { rfail("%s", e.what()); unreachable(); } } void val_t::rcheck_literal_type(type_t::raw_type_t expected_raw_type) { rcheck(type.raw_type == expected_raw_type, strprintf("Expected type %s but found %s:\n%s", type_t(expected_raw_type).name(), type.name(), print().c_str())); } } //namespace ql <|endoftext|>
<commit_before>// Copyright (c) 2011-2012 Ryan Prichard // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <winpty.h> #include <windows.h> #include <assert.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <string> #include <vector> #include <sstream> #include "../shared/DebugClient.h" #include "../shared/AgentMsg.h" #include "../shared/Buffer.h" // TODO: Error handling, handle out-of-memory. #define AGENT_EXE L"winpty-agent.exe" static volatile LONG consoleCounter; struct winpty_s { winpty_s(); HANDLE controlPipe; HANDLE dataPipe; }; winpty_s::winpty_s() : controlPipe(NULL), dataPipe(NULL) { } static HMODULE getCurrentModule() { HMODULE module; if (!GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)getCurrentModule, &module)) { assert(false); } return module; } static std::wstring getModuleFileName(HMODULE module) { const int bufsize = 4096; wchar_t path[bufsize]; int size = GetModuleFileName(module, path, bufsize); assert(size != 0 && size != bufsize); return std::wstring(path); } static std::wstring dirname(const std::wstring &path) { std::wstring::size_type pos = path.find_last_of(L"\\/"); if (pos == std::wstring::npos) return L""; else return path.substr(0, pos); } static bool pathExists(const std::wstring &path) { return GetFileAttributes(path.c_str()) != 0xFFFFFFFF; } static std::wstring findAgentProgram() { std::wstring progDir = dirname(getModuleFileName(getCurrentModule())); std::wstring ret = progDir + L"\\"AGENT_EXE; assert(pathExists(ret)); return ret; } // Call ConnectNamedPipe and block, even for an overlapped pipe. If the // pipe is overlapped, create a temporary event for use connecting. static bool connectNamedPipe(HANDLE handle, bool overlapped) { OVERLAPPED over, *pover = NULL; if (overlapped) { pover = &over; memset(&over, 0, sizeof(over)); over.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); assert(over.hEvent != NULL); } bool success = ConnectNamedPipe(handle, pover); if (overlapped && !success && GetLastError() == ERROR_IO_PENDING) { DWORD actual; success = GetOverlappedResult(handle, pover, &actual, TRUE); } if (!success && GetLastError() == ERROR_PIPE_CONNECTED) success = TRUE; if (overlapped) CloseHandle(over.hEvent); return success; } static void writePacket(winpty_t *pc, const WriteBuffer &packet) { std::string payload = packet.str(); int32_t payloadSize = payload.size(); DWORD actual; BOOL success = WriteFile(pc->controlPipe, &payloadSize, sizeof(int32_t), &actual, NULL); assert(success && actual == sizeof(int32_t)); success = WriteFile(pc->controlPipe, payload.c_str(), payloadSize, &actual, NULL); assert(success && (int32_t)actual == payloadSize); } static int32_t readInt32(winpty_t *pc) { int32_t result; DWORD actual; BOOL success = ReadFile(pc->controlPipe, &result, sizeof(int32_t), &actual, NULL); assert(success && actual == sizeof(int32_t)); return result; } static HANDLE createNamedPipe(const std::wstring &name, bool overlapped) { return CreateNamedPipe(name.c_str(), /*dwOpenMode=*/ PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | (overlapped ? FILE_FLAG_OVERLAPPED : 0), /*dwPipeMode=*/0, /*nMaxInstances=*/1, /*nOutBufferSize=*/0, /*nInBufferSize=*/0, /*nDefaultTimeOut=*/3000, NULL); } struct BackgroundDesktop { HWINSTA originalStation; HWINSTA station; HDESK desktop; std::wstring desktopName; }; static std::wstring getObjectName(HANDLE object) { BOOL success; DWORD lengthNeeded = 0; GetUserObjectInformation(object, UOI_NAME, NULL, 0, &lengthNeeded); assert(lengthNeeded % sizeof(wchar_t) == 0); wchar_t *tmp = new wchar_t[lengthNeeded / 2]; success = GetUserObjectInformation(object, UOI_NAME, tmp, lengthNeeded, NULL); assert(success); std::wstring ret = tmp; delete [] tmp; return ret; } // Get a non-interactive window station for the agent. // TODO: review security w.r.t. windowstation and desktop. static BackgroundDesktop setupBackgroundDesktop() { BackgroundDesktop ret; ret.originalStation = GetProcessWindowStation(); ret.station = CreateWindowStation(NULL, 0, WINSTA_ALL_ACCESS, NULL); bool success = SetProcessWindowStation(ret.station); assert(success); ret.desktop = CreateDesktop(L"Default", NULL, NULL, 0, GENERIC_ALL, NULL); assert(ret.originalStation != NULL); assert(ret.station != NULL); assert(ret.desktop != NULL); ret.desktopName = getObjectName(ret.station) + L"\\" + getObjectName(ret.desktop); return ret; } static void restoreOriginalDesktop(const BackgroundDesktop &desktop) { SetProcessWindowStation(desktop.originalStation); CloseDesktop(desktop.desktop); CloseWindowStation(desktop.station); } static std::wstring getDesktopFullName() { // MSDN says that the handle returned by GetThreadDesktop does not need // to be passed to CloseDesktop. HWINSTA station = GetProcessWindowStation(); HDESK desktop = GetThreadDesktop(GetCurrentThreadId()); assert(station != NULL); assert(desktop != NULL); return getObjectName(station) + L"\\" + getObjectName(desktop); } static void startAgentProcess(const BackgroundDesktop &desktop, std::wstring &controlPipeName, std::wstring &dataPipeName, int cols, int rows) { bool success; std::wstring agentProgram = findAgentProgram(); std::wstringstream agentCmdLineStream; agentCmdLineStream << L"\"" << agentProgram << L"\" " << controlPipeName << " " << dataPipeName << " " << cols << " " << rows; std::wstring agentCmdLine = agentCmdLineStream.str(); // Start the agent. STARTUPINFO sui; memset(&sui, 0, sizeof(sui)); sui.cb = sizeof(sui); sui.lpDesktop = (LPWSTR)desktop.desktopName.c_str(); PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi)); std::vector<wchar_t> cmdline(agentCmdLine.size() + 1); agentCmdLine.copy(&cmdline[0], agentCmdLine.size()); cmdline[agentCmdLine.size()] = L'\0'; success = CreateProcess(agentProgram.c_str(), &cmdline[0], NULL, NULL, /*bInheritHandles=*/FALSE, /*dwCreationFlags=*/CREATE_NEW_CONSOLE, NULL, NULL, &sui, &pi); if (!success) { fprintf(stderr, "Error %#x starting %ls\n", (unsigned int)GetLastError(), agentCmdLine.c_str()); exit(1); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } WINPTY_API winpty_t *winpty_open(int cols, int rows) { winpty_t *pc = new winpty_t; // Start pipes. std::wstringstream pipeName; pipeName << L"\\\\.\\pipe\\winpty-" << GetCurrentProcessId() << L"-" << InterlockedIncrement(&consoleCounter); std::wstring controlPipeName = pipeName.str() + L"-control"; std::wstring dataPipeName = pipeName.str() + L"-data"; pc->controlPipe = createNamedPipe(controlPipeName, false); if (pc->controlPipe == INVALID_HANDLE_VALUE) { delete pc; return NULL; } pc->dataPipe = createNamedPipe(dataPipeName, true); if (pc->dataPipe == INVALID_HANDLE_VALUE) { delete pc; return NULL; } // Setup a background desktop for the agent. BackgroundDesktop desktop = setupBackgroundDesktop(); // Start the agent. startAgentProcess(desktop, controlPipeName, dataPipeName, cols, rows); // TODO: Frequently, I see the CreateProcess call return successfully, // but the agent immediately dies. The following pipe connect calls then // hang. These calls should probably timeout. Maybe this code could also // poll the agent process handle? // Connect the pipes. bool success; success = connectNamedPipe(pc->controlPipe, false); if (!success) { delete pc; return NULL; } success = connectNamedPipe(pc->dataPipe, true); if (!success) { delete pc; return NULL; } // Close handles to the background desktop and restore the original window // station. This must wait until we know the agent is running -- if we // close these handles too soon, then the desktop and windowstation will be // destroyed before the agent can connect with them. restoreOriginalDesktop(desktop); // The default security descriptor for a named pipe allows anyone to connect // to the pipe to read, but not to write. Only the "creator owner" and // various system accounts can write to the pipe. By sending and receiving // a dummy message on the control pipe, we should confirm that something // trusted (i.e. the agent we just started) successfully connected and wrote // to one of our pipes. WriteBuffer packet; packet.putInt(AgentMsg::Ping); writePacket(pc, packet); if (readInt32(pc) != 0) { delete pc; return NULL; } // TODO: On Windows Vista and forward, we could call // GetNamedPipeClientProcessId and verify that the PID is correct. We could // also pass the PIPE_REJECT_REMOTE_CLIENTS flag on newer OS's. // TODO: I suppose this code is still subject to a denial-of-service attack // from untrusted accounts making read-only connections to the pipe. It // should probably provide a SECURITY_DESCRIPTOR for the pipe, but the last // time I tried that (using SDDL), I couldn't get it to work (access denied // errors). // Aside: An obvious way to setup these handles is to open both ends of the // pipe in the parent process and let the child inherit its handles. // Unfortunately, the Windows API makes inheriting handles problematic. // MSDN says that handles have to be marked inheritable, and once they are, // they are inherited by any call to CreateProcess with // bInheritHandles==TRUE. To avoid accidental inheritance, the library's // clients would be obligated not to create new processes while a thread // was calling winpty_open. Moreover, to inherit handles, MSDN seems // to say that bInheritHandles must be TRUE[*], but I don't want to use a // TRUE bInheritHandles, because I want to avoid leaking handles into the // agent process, especially if the library someday allows creating the // agent process under a different user account. // // [*] The way that bInheritHandles and STARTF_USESTDHANDLES work together // is unclear in the documentation. On one hand, for STARTF_USESTDHANDLES, // it says that bInheritHandles must be TRUE. On Vista and up, isn't // PROC_THREAD_ATTRIBUTE_HANDLE_LIST an acceptable alternative to // bInheritHandles? On the other hand, KB315939 contradicts the // STARTF_USESTDHANDLES documentation by saying, "Your pipe handles will // still be duplicated because Windows will always duplicate the STD // handles, even when bInheritHandles is set to FALSE." IIRC, my testing // showed that the KB article was correct. return pc; } WINPTY_API int winpty_start_process(winpty_t *pc, const wchar_t *appname, const wchar_t *cmdline, const wchar_t *cwd, const wchar_t *env) { WriteBuffer packet; packet.putInt(AgentMsg::StartProcess); packet.putWString(appname ? appname : L""); packet.putWString(cmdline ? cmdline : L""); packet.putWString(cwd ? cwd : L""); std::wstring envStr; if (env != NULL) { const wchar_t *p = env; while (*p != L'\0') { p += wcslen(p) + 1; } p++; envStr.assign(env, p); // Can a Win32 environment be empty? If so, does it end with one NUL or // two? Add an extra NUL just in case it matters. envStr.push_back(L'\0'); } packet.putWString(envStr); packet.putWString(getDesktopFullName()); writePacket(pc, packet); return readInt32(pc); } WINPTY_API int winpty_get_exit_code(winpty_t *pc) { WriteBuffer packet; packet.putInt(AgentMsg::GetExitCode); writePacket(pc, packet); return readInt32(pc); } WINPTY_API int winpty_get_process_id(winpty_t *pc) { WriteBuffer packet; packet.putInt(AgentMsg::GetProcessId); writePacket(pc, packet); return readInt32(pc); } WINPTY_API HANDLE winpty_get_data_pipe(winpty_t *pc) { return pc->dataPipe; } WINPTY_API int winpty_set_size(winpty_t *pc, int cols, int rows) { WriteBuffer packet; packet.putInt(AgentMsg::SetSize); packet.putInt(cols); packet.putInt(rows); writePacket(pc, packet); return readInt32(pc); } WINPTY_API void winpty_close(winpty_t *pc) { CloseHandle(pc->controlPipe); CloseHandle(pc->dataPipe); delete pc; } WINPTY_API int winpty_set_console_mode(winpty_t *pc, int mode) { WriteBuffer packet; packet.putInt(AgentMsg::SetConsoleMode); packet.putInt(mode); writePacket(pc, packet); return readInt32(pc); } <commit_msg>Work around what I think is a typo in a MinGW header.<commit_after>// Copyright (c) 2011-2012 Ryan Prichard // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include <winpty.h> #include <windows.h> #include <assert.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <string> #include <vector> #include <sstream> #include "../shared/DebugClient.h" #include "../shared/AgentMsg.h" #include "../shared/Buffer.h" // Work around a bug with mingw-gcc-g++. mingw-w64 is unaffected. See // GitHub issue 27. #ifndef FILE_FLAG_FIRST_PIPE_INSTANCE #define FILE_FLAG_FIRST_PIPE_INSTANCE 0x00080000 #endif // TODO: Error handling, handle out-of-memory. #define AGENT_EXE L"winpty-agent.exe" static volatile LONG consoleCounter; struct winpty_s { winpty_s(); HANDLE controlPipe; HANDLE dataPipe; }; winpty_s::winpty_s() : controlPipe(NULL), dataPipe(NULL) { } static HMODULE getCurrentModule() { HMODULE module; if (!GetModuleHandleEx( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)getCurrentModule, &module)) { assert(false); } return module; } static std::wstring getModuleFileName(HMODULE module) { const int bufsize = 4096; wchar_t path[bufsize]; int size = GetModuleFileName(module, path, bufsize); assert(size != 0 && size != bufsize); return std::wstring(path); } static std::wstring dirname(const std::wstring &path) { std::wstring::size_type pos = path.find_last_of(L"\\/"); if (pos == std::wstring::npos) return L""; else return path.substr(0, pos); } static bool pathExists(const std::wstring &path) { return GetFileAttributes(path.c_str()) != 0xFFFFFFFF; } static std::wstring findAgentProgram() { std::wstring progDir = dirname(getModuleFileName(getCurrentModule())); std::wstring ret = progDir + L"\\"AGENT_EXE; assert(pathExists(ret)); return ret; } // Call ConnectNamedPipe and block, even for an overlapped pipe. If the // pipe is overlapped, create a temporary event for use connecting. static bool connectNamedPipe(HANDLE handle, bool overlapped) { OVERLAPPED over, *pover = NULL; if (overlapped) { pover = &over; memset(&over, 0, sizeof(over)); over.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); assert(over.hEvent != NULL); } bool success = ConnectNamedPipe(handle, pover); if (overlapped && !success && GetLastError() == ERROR_IO_PENDING) { DWORD actual; success = GetOverlappedResult(handle, pover, &actual, TRUE); } if (!success && GetLastError() == ERROR_PIPE_CONNECTED) success = TRUE; if (overlapped) CloseHandle(over.hEvent); return success; } static void writePacket(winpty_t *pc, const WriteBuffer &packet) { std::string payload = packet.str(); int32_t payloadSize = payload.size(); DWORD actual; BOOL success = WriteFile(pc->controlPipe, &payloadSize, sizeof(int32_t), &actual, NULL); assert(success && actual == sizeof(int32_t)); success = WriteFile(pc->controlPipe, payload.c_str(), payloadSize, &actual, NULL); assert(success && (int32_t)actual == payloadSize); } static int32_t readInt32(winpty_t *pc) { int32_t result; DWORD actual; BOOL success = ReadFile(pc->controlPipe, &result, sizeof(int32_t), &actual, NULL); assert(success && actual == sizeof(int32_t)); return result; } static HANDLE createNamedPipe(const std::wstring &name, bool overlapped) { return CreateNamedPipe(name.c_str(), /*dwOpenMode=*/ PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | (overlapped ? FILE_FLAG_OVERLAPPED : 0), /*dwPipeMode=*/0, /*nMaxInstances=*/1, /*nOutBufferSize=*/0, /*nInBufferSize=*/0, /*nDefaultTimeOut=*/3000, NULL); } struct BackgroundDesktop { HWINSTA originalStation; HWINSTA station; HDESK desktop; std::wstring desktopName; }; static std::wstring getObjectName(HANDLE object) { BOOL success; DWORD lengthNeeded = 0; GetUserObjectInformation(object, UOI_NAME, NULL, 0, &lengthNeeded); assert(lengthNeeded % sizeof(wchar_t) == 0); wchar_t *tmp = new wchar_t[lengthNeeded / 2]; success = GetUserObjectInformation(object, UOI_NAME, tmp, lengthNeeded, NULL); assert(success); std::wstring ret = tmp; delete [] tmp; return ret; } // Get a non-interactive window station for the agent. // TODO: review security w.r.t. windowstation and desktop. static BackgroundDesktop setupBackgroundDesktop() { BackgroundDesktop ret; ret.originalStation = GetProcessWindowStation(); ret.station = CreateWindowStation(NULL, 0, WINSTA_ALL_ACCESS, NULL); bool success = SetProcessWindowStation(ret.station); assert(success); ret.desktop = CreateDesktop(L"Default", NULL, NULL, 0, GENERIC_ALL, NULL); assert(ret.originalStation != NULL); assert(ret.station != NULL); assert(ret.desktop != NULL); ret.desktopName = getObjectName(ret.station) + L"\\" + getObjectName(ret.desktop); return ret; } static void restoreOriginalDesktop(const BackgroundDesktop &desktop) { SetProcessWindowStation(desktop.originalStation); CloseDesktop(desktop.desktop); CloseWindowStation(desktop.station); } static std::wstring getDesktopFullName() { // MSDN says that the handle returned by GetThreadDesktop does not need // to be passed to CloseDesktop. HWINSTA station = GetProcessWindowStation(); HDESK desktop = GetThreadDesktop(GetCurrentThreadId()); assert(station != NULL); assert(desktop != NULL); return getObjectName(station) + L"\\" + getObjectName(desktop); } static void startAgentProcess(const BackgroundDesktop &desktop, std::wstring &controlPipeName, std::wstring &dataPipeName, int cols, int rows) { bool success; std::wstring agentProgram = findAgentProgram(); std::wstringstream agentCmdLineStream; agentCmdLineStream << L"\"" << agentProgram << L"\" " << controlPipeName << " " << dataPipeName << " " << cols << " " << rows; std::wstring agentCmdLine = agentCmdLineStream.str(); // Start the agent. STARTUPINFO sui; memset(&sui, 0, sizeof(sui)); sui.cb = sizeof(sui); sui.lpDesktop = (LPWSTR)desktop.desktopName.c_str(); PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(pi)); std::vector<wchar_t> cmdline(agentCmdLine.size() + 1); agentCmdLine.copy(&cmdline[0], agentCmdLine.size()); cmdline[agentCmdLine.size()] = L'\0'; success = CreateProcess(agentProgram.c_str(), &cmdline[0], NULL, NULL, /*bInheritHandles=*/FALSE, /*dwCreationFlags=*/CREATE_NEW_CONSOLE, NULL, NULL, &sui, &pi); if (!success) { fprintf(stderr, "Error %#x starting %ls\n", (unsigned int)GetLastError(), agentCmdLine.c_str()); exit(1); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } WINPTY_API winpty_t *winpty_open(int cols, int rows) { winpty_t *pc = new winpty_t; // Start pipes. std::wstringstream pipeName; pipeName << L"\\\\.\\pipe\\winpty-" << GetCurrentProcessId() << L"-" << InterlockedIncrement(&consoleCounter); std::wstring controlPipeName = pipeName.str() + L"-control"; std::wstring dataPipeName = pipeName.str() + L"-data"; pc->controlPipe = createNamedPipe(controlPipeName, false); if (pc->controlPipe == INVALID_HANDLE_VALUE) { delete pc; return NULL; } pc->dataPipe = createNamedPipe(dataPipeName, true); if (pc->dataPipe == INVALID_HANDLE_VALUE) { delete pc; return NULL; } // Setup a background desktop for the agent. BackgroundDesktop desktop = setupBackgroundDesktop(); // Start the agent. startAgentProcess(desktop, controlPipeName, dataPipeName, cols, rows); // TODO: Frequently, I see the CreateProcess call return successfully, // but the agent immediately dies. The following pipe connect calls then // hang. These calls should probably timeout. Maybe this code could also // poll the agent process handle? // Connect the pipes. bool success; success = connectNamedPipe(pc->controlPipe, false); if (!success) { delete pc; return NULL; } success = connectNamedPipe(pc->dataPipe, true); if (!success) { delete pc; return NULL; } // Close handles to the background desktop and restore the original window // station. This must wait until we know the agent is running -- if we // close these handles too soon, then the desktop and windowstation will be // destroyed before the agent can connect with them. restoreOriginalDesktop(desktop); // The default security descriptor for a named pipe allows anyone to connect // to the pipe to read, but not to write. Only the "creator owner" and // various system accounts can write to the pipe. By sending and receiving // a dummy message on the control pipe, we should confirm that something // trusted (i.e. the agent we just started) successfully connected and wrote // to one of our pipes. WriteBuffer packet; packet.putInt(AgentMsg::Ping); writePacket(pc, packet); if (readInt32(pc) != 0) { delete pc; return NULL; } // TODO: On Windows Vista and forward, we could call // GetNamedPipeClientProcessId and verify that the PID is correct. We could // also pass the PIPE_REJECT_REMOTE_CLIENTS flag on newer OS's. // TODO: I suppose this code is still subject to a denial-of-service attack // from untrusted accounts making read-only connections to the pipe. It // should probably provide a SECURITY_DESCRIPTOR for the pipe, but the last // time I tried that (using SDDL), I couldn't get it to work (access denied // errors). // Aside: An obvious way to setup these handles is to open both ends of the // pipe in the parent process and let the child inherit its handles. // Unfortunately, the Windows API makes inheriting handles problematic. // MSDN says that handles have to be marked inheritable, and once they are, // they are inherited by any call to CreateProcess with // bInheritHandles==TRUE. To avoid accidental inheritance, the library's // clients would be obligated not to create new processes while a thread // was calling winpty_open. Moreover, to inherit handles, MSDN seems // to say that bInheritHandles must be TRUE[*], but I don't want to use a // TRUE bInheritHandles, because I want to avoid leaking handles into the // agent process, especially if the library someday allows creating the // agent process under a different user account. // // [*] The way that bInheritHandles and STARTF_USESTDHANDLES work together // is unclear in the documentation. On one hand, for STARTF_USESTDHANDLES, // it says that bInheritHandles must be TRUE. On Vista and up, isn't // PROC_THREAD_ATTRIBUTE_HANDLE_LIST an acceptable alternative to // bInheritHandles? On the other hand, KB315939 contradicts the // STARTF_USESTDHANDLES documentation by saying, "Your pipe handles will // still be duplicated because Windows will always duplicate the STD // handles, even when bInheritHandles is set to FALSE." IIRC, my testing // showed that the KB article was correct. return pc; } WINPTY_API int winpty_start_process(winpty_t *pc, const wchar_t *appname, const wchar_t *cmdline, const wchar_t *cwd, const wchar_t *env) { WriteBuffer packet; packet.putInt(AgentMsg::StartProcess); packet.putWString(appname ? appname : L""); packet.putWString(cmdline ? cmdline : L""); packet.putWString(cwd ? cwd : L""); std::wstring envStr; if (env != NULL) { const wchar_t *p = env; while (*p != L'\0') { p += wcslen(p) + 1; } p++; envStr.assign(env, p); // Can a Win32 environment be empty? If so, does it end with one NUL or // two? Add an extra NUL just in case it matters. envStr.push_back(L'\0'); } packet.putWString(envStr); packet.putWString(getDesktopFullName()); writePacket(pc, packet); return readInt32(pc); } WINPTY_API int winpty_get_exit_code(winpty_t *pc) { WriteBuffer packet; packet.putInt(AgentMsg::GetExitCode); writePacket(pc, packet); return readInt32(pc); } WINPTY_API int winpty_get_process_id(winpty_t *pc) { WriteBuffer packet; packet.putInt(AgentMsg::GetProcessId); writePacket(pc, packet); return readInt32(pc); } WINPTY_API HANDLE winpty_get_data_pipe(winpty_t *pc) { return pc->dataPipe; } WINPTY_API int winpty_set_size(winpty_t *pc, int cols, int rows) { WriteBuffer packet; packet.putInt(AgentMsg::SetSize); packet.putInt(cols); packet.putInt(rows); writePacket(pc, packet); return readInt32(pc); } WINPTY_API void winpty_close(winpty_t *pc) { CloseHandle(pc->controlPipe); CloseHandle(pc->dataPipe); delete pc; } WINPTY_API int winpty_set_console_mode(winpty_t *pc, int mode) { WriteBuffer packet; packet.putInt(AgentMsg::SetConsoleMode); packet.putInt(mode); writePacket(pc, packet); return readInt32(pc); } <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/torrent_handle.hpp> #include <boost/python.hpp> #include <boost/python/tuple.hpp> #include <boost/lexical_cast.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { list url_seeds(torrent_handle& handle) { list ret; std::set<std::string> urls; { allow_threading_guard guard; urls = handle.url_seeds(); } for (std::set<std::string>::iterator i(urls.begin()) , end(urls.end()); i != end; ++i) ret.append(*i); return ret; } list piece_availability(torrent_handle& handle) { list ret; std::vector<int> avail; { allow_threading_guard guard; handle.piece_availability(avail); } for (std::vector<int>::iterator i(avail.begin()) , end(avail.end()); i != end; ++i) ret.append(*i); return ret; } list piece_priorities(torrent_handle& handle) { list ret; std::vector<int> prio; { allow_threading_guard guard; prio = handle.piece_priorities(); } for (std::vector<int>::iterator i(prio.begin()) , end(prio.end()); i != end; ++i) ret.append(*i); return ret; } std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i) { allow_threading_guard guard; return i.trackers().begin(); } std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i) { allow_threading_guard guard; return i.trackers().end(); } } // namespace unnamed list file_progress(torrent_handle& handle) { std::vector<size_type> p; { allow_threading_guard guard; p.reserve(handle.get_torrent_info().num_files()); handle.file_progress(p); } list result; for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i) result.append(*i); return result; } list get_peer_info(torrent_handle const& handle) { std::vector<peer_info> pi; { allow_threading_guard guard; handle.get_peer_info(pi); } list result; for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i) result.append(*i); return result; } void prioritize_pieces(torrent_handle& info, object o) { std::vector<int> result; try { object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) )); while( 1 ) { object obj = extract<object>( iter_obj.attr( "next" )() ); result.push_back(extract<int const>( obj )); } } catch( error_already_set ) { PyErr_Clear(); info.prioritize_pieces(result); return; } } void prioritize_files(torrent_handle& info, object o) { std::vector<int> result; try { object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) )); while( 1 ) { object obj = extract<object>( iter_obj.attr( "next" )() ); result.push_back(extract<int const>( obj )); } } catch( error_already_set ) { PyErr_Clear(); info.prioritize_files(result); return; } } list file_priorities(torrent_handle& handle) { list ret; std::vector<int> priorities = handle.file_priorities(); for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i) ret.append(*i); return ret; } void replace_trackers(torrent_handle& info, object trackers) { object iter(trackers.attr("__iter__")()); std::vector<announce_entry> result; for (;;) { handle<> entry(allow_null(PyIter_Next(iter.ptr()))); if (entry == handle<>()) break; result.push_back(extract<announce_entry const&>(object(entry))); } allow_threading_guard guard; info.replace_trackers(result); } list get_download_queue(torrent_handle& handle) { using boost::python::make_tuple; list ret; std::vector<partial_piece_info> downloading; { allow_threading_guard guard; handle.get_download_queue(downloading); } for (std::vector<partial_piece_info>::iterator i = downloading.begin() , end(downloading.end()); i != end; ++i) { dict partial_piece; partial_piece["piece_index"] = i->piece_index; partial_piece["blocks_in_piece"] = i->blocks_in_piece; list block_list; for (int k = 0; k < i->blocks_in_piece; ++k) { dict block_info; block_info["state"] = i->blocks[k].state; block_info["num_peers"] = i->blocks[k].num_peers; block_info["bytes_progress"] = i->blocks[k].bytes_progress; block_info["block_size"] = i->blocks[k].block_size; block_info["peer"] = make_tuple( boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port()); block_list.append(block_info); } partial_piece["blocks"] = block_list; ret.append(partial_piece); } return ret; } namespace { tcp::endpoint tuple_to_endpoint(tuple const& t) { return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1])); } } void force_reannounce(torrent_handle& th, int s) { th.force_reannounce(boost::posix_time::seconds(s)); } void connect_peer(torrent_handle& th, tuple ip, int source) { th.connect_peer(tuple_to_endpoint(ip), source); } void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit) { th.set_peer_upload_limit(tuple_to_endpoint(ip), limit); } void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit) { th.set_peer_download_limit(tuple_to_endpoint(ip), limit); } void bind_torrent_handle() { void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce; int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority; void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority; void (torrent_handle::*move_storage0)(fs::path const&) const = &torrent_handle::move_storage; void (torrent_handle::*move_storage1)(fs::wpath const&) const = &torrent_handle::move_storage; void (torrent_handle::*rename_file0)(int, fs::path const&) const = &torrent_handle::rename_file; void (torrent_handle::*rename_file1)(int, fs::wpath const&) const = &torrent_handle::rename_file; #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries; void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries; #endif return_value_policy<copy_const_reference> copy; #define _ allow_threads class_<torrent_handle>("torrent_handle") .def("get_peer_info", get_peer_info) .def("status", _(&torrent_handle::status)) .def("get_download_queue", get_download_queue) .def("file_progress", file_progress) .def("trackers", range(begin_trackers, end_trackers)) .def("replace_trackers", replace_trackers) .def("add_url_seed", _(&torrent_handle::add_url_seed)) .def("remove_url_seed", _(&torrent_handle::remove_url_seed)) .def("url_seeds", url_seeds) .def("has_metadata", _(&torrent_handle::has_metadata)) .def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>()) .def("is_valid", _(&torrent_handle::is_valid)) .def("is_seed", _(&torrent_handle::is_seed)) .def("is_finished", _(&torrent_handle::is_finished)) .def("is_paused", _(&torrent_handle::is_paused)) .def("pause", _(&torrent_handle::pause)) .def("resume", _(&torrent_handle::resume)) .def("clear_error", _(&torrent_handle::clear_error)) .def("is_auto_managed", _(&torrent_handle::is_auto_managed)) .def("auto_managed", _(&torrent_handle::auto_managed)) .def("queue_position", _(&torrent_handle::queue_position)) .def("queue_position_up", _(&torrent_handle::queue_position_up)) .def("queue_position_down", _(&torrent_handle::queue_position_down)) .def("queue_position_top", _(&torrent_handle::queue_position_top)) .def("queue_position_bottom", _(&torrent_handle::queue_position_bottom)) #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES .def("resolve_countries", _(resolve_countries0)) .def("resolve_countries", _(resolve_countries1)) #endif // deprecated #ifndef TORRENT_NO_DEPRECATE .def("filter_piece", _(&torrent_handle::filter_piece)) .def("is_piece_filtered", _(&torrent_handle::is_piece_filtered)) .def("write_resume_data", _(&torrent_handle::write_resume_data)) #endif .def("piece_availability", piece_availability) .def("piece_priority", _(piece_priority0)) .def("piece_priority", _(piece_priority1)) .def("prioritize_pieces", prioritize_pieces) .def("piece_prioritize", piece_priorities) .def("prioritize_files", prioritize_files) .def("file_priorities", file_priorities) .def("use_interface", &torrent_handle::use_interface) .def("save_resume_data", _(&torrent_handle::save_resume_data)) .def("force_reannounce", _(force_reannounce0)) .def("force_reannounce", force_reannounce) .def("scrape_tracker", _(&torrent_handle::scrape_tracker)) .def("name", _(&torrent_handle::name)) .def("set_upload_limit", _(&torrent_handle::set_upload_limit)) .def("upload_limit", _(&torrent_handle::upload_limit)) .def("set_download_limit", _(&torrent_handle::set_download_limit)) .def("download_limit", _(&torrent_handle::download_limit)) .def("set_sequential_download", _(&torrent_handle::set_sequential_download)) .def("set_peer_upload_limit", set_peer_upload_limit) .def("set_peer_download_limit", set_peer_download_limit) .def("connect_peer", connect_peer) .def("set_ratio", _(&torrent_handle::set_ratio)) .def("save_path", _(&torrent_handle::save_path)) .def("set_max_uploads", _(&torrent_handle::set_max_uploads)) .def("set_max_connections", _(&torrent_handle::set_max_connections)) .def("set_tracker_login", _(&torrent_handle::set_tracker_login)) .def("move_storage", _(move_storage0)) .def("move_storage", _(move_storage1)) .def("info_hash", _(&torrent_handle::info_hash)) .def("force_recheck", _(&torrent_handle::force_recheck)) .def("rename_file", _(rename_file0)) .def("rename_file", _(rename_file1)) ; } <commit_msg>expose add_piece to the python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/torrent_handle.hpp> #include <boost/python.hpp> #include <boost/python/tuple.hpp> #include <boost/lexical_cast.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { list url_seeds(torrent_handle& handle) { list ret; std::set<std::string> urls; { allow_threading_guard guard; urls = handle.url_seeds(); } for (std::set<std::string>::iterator i(urls.begin()) , end(urls.end()); i != end; ++i) ret.append(*i); return ret; } list piece_availability(torrent_handle& handle) { list ret; std::vector<int> avail; { allow_threading_guard guard; handle.piece_availability(avail); } for (std::vector<int>::iterator i(avail.begin()) , end(avail.end()); i != end; ++i) ret.append(*i); return ret; } list piece_priorities(torrent_handle& handle) { list ret; std::vector<int> prio; { allow_threading_guard guard; prio = handle.piece_priorities(); } for (std::vector<int>::iterator i(prio.begin()) , end(prio.end()); i != end; ++i) ret.append(*i); return ret; } std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i) { allow_threading_guard guard; return i.trackers().begin(); } std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i) { allow_threading_guard guard; return i.trackers().end(); } } // namespace unnamed list file_progress(torrent_handle& handle) { std::vector<size_type> p; { allow_threading_guard guard; p.reserve(handle.get_torrent_info().num_files()); handle.file_progress(p); } list result; for (std::vector<size_type>::iterator i(p.begin()), e(p.end()); i != e; ++i) result.append(*i); return result; } list get_peer_info(torrent_handle const& handle) { std::vector<peer_info> pi; { allow_threading_guard guard; handle.get_peer_info(pi); } list result; for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i) result.append(*i); return result; } void prioritize_pieces(torrent_handle& info, object o) { std::vector<int> result; try { object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) )); while( 1 ) { object obj = extract<object>( iter_obj.attr( "next" )() ); result.push_back(extract<int const>( obj )); } } catch( error_already_set ) { PyErr_Clear(); info.prioritize_pieces(result); return; } } void prioritize_files(torrent_handle& info, object o) { std::vector<int> result; try { object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) )); while( 1 ) { object obj = extract<object>( iter_obj.attr( "next" )() ); result.push_back(extract<int const>( obj )); } } catch( error_already_set ) { PyErr_Clear(); info.prioritize_files(result); return; } } list file_priorities(torrent_handle& handle) { list ret; std::vector<int> priorities = handle.file_priorities(); for (std::vector<int>::iterator i = priorities.begin(); i != priorities.end(); ++i) ret.append(*i); return ret; } void replace_trackers(torrent_handle& info, object trackers) { object iter(trackers.attr("__iter__")()); std::vector<announce_entry> result; for (;;) { handle<> entry(allow_null(PyIter_Next(iter.ptr()))); if (entry == handle<>()) break; result.push_back(extract<announce_entry const&>(object(entry))); } allow_threading_guard guard; info.replace_trackers(result); } list get_download_queue(torrent_handle& handle) { using boost::python::make_tuple; list ret; std::vector<partial_piece_info> downloading; { allow_threading_guard guard; handle.get_download_queue(downloading); } for (std::vector<partial_piece_info>::iterator i = downloading.begin() , end(downloading.end()); i != end; ++i) { dict partial_piece; partial_piece["piece_index"] = i->piece_index; partial_piece["blocks_in_piece"] = i->blocks_in_piece; list block_list; for (int k = 0; k < i->blocks_in_piece; ++k) { dict block_info; block_info["state"] = i->blocks[k].state; block_info["num_peers"] = i->blocks[k].num_peers; block_info["bytes_progress"] = i->blocks[k].bytes_progress; block_info["block_size"] = i->blocks[k].block_size; block_info["peer"] = make_tuple( boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port()); block_list.append(block_info); } partial_piece["blocks"] = block_list; ret.append(partial_piece); } return ret; } namespace { tcp::endpoint tuple_to_endpoint(tuple const& t) { return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1])); } } void force_reannounce(torrent_handle& th, int s) { th.force_reannounce(boost::posix_time::seconds(s)); } void connect_peer(torrent_handle& th, tuple ip, int source) { th.connect_peer(tuple_to_endpoint(ip), source); } void set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit) { th.set_peer_upload_limit(tuple_to_endpoint(ip), limit); } void set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit) { th.set_peer_download_limit(tuple_to_endpoint(ip), limit); } void add_piece(torrent_handle& th, int piece, char const *data, int flags) { th.add_piece(piece, data, flags); } void bind_torrent_handle() { void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce; int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority; void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority; void (torrent_handle::*move_storage0)(fs::path const&) const = &torrent_handle::move_storage; void (torrent_handle::*move_storage1)(fs::wpath const&) const = &torrent_handle::move_storage; void (torrent_handle::*rename_file0)(int, fs::path const&) const = &torrent_handle::rename_file; void (torrent_handle::*rename_file1)(int, fs::wpath const&) const = &torrent_handle::rename_file; #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries; void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries; #endif return_value_policy<copy_const_reference> copy; #define _ allow_threads class_<torrent_handle>("torrent_handle") .def("get_peer_info", get_peer_info) .def("status", _(&torrent_handle::status)) .def("get_download_queue", get_download_queue) .def("file_progress", file_progress) .def("trackers", range(begin_trackers, end_trackers)) .def("replace_trackers", replace_trackers) .def("add_url_seed", _(&torrent_handle::add_url_seed)) .def("remove_url_seed", _(&torrent_handle::remove_url_seed)) .def("url_seeds", url_seeds) .def("has_metadata", _(&torrent_handle::has_metadata)) .def("get_torrent_info", _(&torrent_handle::get_torrent_info), return_internal_reference<>()) .def("is_valid", _(&torrent_handle::is_valid)) .def("is_seed", _(&torrent_handle::is_seed)) .def("is_finished", _(&torrent_handle::is_finished)) .def("is_paused", _(&torrent_handle::is_paused)) .def("pause", _(&torrent_handle::pause)) .def("resume", _(&torrent_handle::resume)) .def("clear_error", _(&torrent_handle::clear_error)) .def("is_auto_managed", _(&torrent_handle::is_auto_managed)) .def("auto_managed", _(&torrent_handle::auto_managed)) .def("queue_position", _(&torrent_handle::queue_position)) .def("queue_position_up", _(&torrent_handle::queue_position_up)) .def("queue_position_down", _(&torrent_handle::queue_position_down)) .def("queue_position_top", _(&torrent_handle::queue_position_top)) .def("queue_position_bottom", _(&torrent_handle::queue_position_bottom)) #ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES .def("resolve_countries", _(resolve_countries0)) .def("resolve_countries", _(resolve_countries1)) #endif // deprecated #ifndef TORRENT_NO_DEPRECATE .def("filter_piece", _(&torrent_handle::filter_piece)) .def("is_piece_filtered", _(&torrent_handle::is_piece_filtered)) .def("write_resume_data", _(&torrent_handle::write_resume_data)) #endif .def("add_piece", add_piece) .def("piece_availability", piece_availability) .def("piece_priority", _(piece_priority0)) .def("piece_priority", _(piece_priority1)) .def("prioritize_pieces", prioritize_pieces) .def("piece_prioritize", piece_priorities) .def("prioritize_files", prioritize_files) .def("file_priorities", file_priorities) .def("use_interface", &torrent_handle::use_interface) .def("save_resume_data", _(&torrent_handle::save_resume_data)) .def("force_reannounce", _(force_reannounce0)) .def("force_reannounce", force_reannounce) .def("scrape_tracker", _(&torrent_handle::scrape_tracker)) .def("name", _(&torrent_handle::name)) .def("set_upload_limit", _(&torrent_handle::set_upload_limit)) .def("upload_limit", _(&torrent_handle::upload_limit)) .def("set_download_limit", _(&torrent_handle::set_download_limit)) .def("download_limit", _(&torrent_handle::download_limit)) .def("set_sequential_download", _(&torrent_handle::set_sequential_download)) .def("set_peer_upload_limit", set_peer_upload_limit) .def("set_peer_download_limit", set_peer_download_limit) .def("connect_peer", connect_peer) .def("set_ratio", _(&torrent_handle::set_ratio)) .def("save_path", _(&torrent_handle::save_path)) .def("set_max_uploads", _(&torrent_handle::set_max_uploads)) .def("set_max_connections", _(&torrent_handle::set_max_connections)) .def("set_tracker_login", _(&torrent_handle::set_tracker_login)) .def("move_storage", _(move_storage0)) .def("move_storage", _(move_storage1)) .def("info_hash", _(&torrent_handle::info_hash)) .def("force_recheck", _(&torrent_handle::force_recheck)) .def("rename_file", _(rename_file0)) .def("rename_file", _(rename_file1)) ; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } typedef std::pair<char const*, char const*> map_entry; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { map_entry("A", "ABC") , map_entry("AR", "Arctic Torrent") , map_entry("AX", "BitPump") , map_entry("AZ", "Azureus") , map_entry("BB", "BitBuddy") , map_entry("BC", "BitComet") , map_entry("BF", "Bitflu") , map_entry("BG", "btgdaemon") , map_entry("BR", "BitRocket") , map_entry("BS", "BTSlave") , map_entry("BX", "BittorrentX") , map_entry("CD", "Enhanced CTorrent") , map_entry("CT", "CTorrent") , map_entry("DE", "Deluge") , map_entry("ES", "electric sheep") , map_entry("HL", "Halite") , map_entry("KT", "KTorrent") , map_entry("LK", "Linkage") , map_entry("LP", "lphant") , map_entry("LT", "libtorrent") , map_entry("M", "Mainline") , map_entry("ML", "MLDonkey") , map_entry("MO", "Mono Torrent") , map_entry("MP", "MooPolice") , map_entry("MT", "Moonlight Torrent") , map_entry("O", "Osprey Permaseed") , map_entry("QT", "Qt 4") , map_entry("R", "Tribler") , map_entry("S", "Shadow") , map_entry("SB", "Swiftbit") , map_entry("SN", "ShareNet") , map_entry("SS", "SwarmScope") , map_entry("SZ", "Shareaza") , map_entry("T", "BitTornado") , map_entry("TN", "Torrent.NET") , map_entry("TR", "Transmission") , map_entry("TS", "TorrentStorm") , map_entry("U", "UPnP") , map_entry("UL", "uLeecher") , map_entry("UT", "MicroTorrent") , map_entry("XT", "XanTorrent") , map_entry("XX", "Xtorrent") , map_entry("ZT", "ZipTorrent") , map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)") , map_entry("pX", "pHoeniX") , map_entry("qB", "qBittorrent") }; bool compare_first_string(map_entry const& lhs, map_entry const& rhs) { return lhs.first[0] < rhs.first[0] || ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry* i = std::lower_bound(name_map, name_map + size , map_entry(f.name, ""), &compare_first_string); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_first_string(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->first)) identity << i->second; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>added new knoen peer-ids<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } typedef std::pair<char const*, char const*> map_entry; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { map_entry("A", "ABC") , map_entry("A~", "Ares") , map_entry("AG", "Ares") , map_entry("AR", "Arctic Torrent") , map_entry("AV", "Avicora") , map_entry("AX", "BitPump") , map_entry("AZ", "Azureus") , map_entry("BB", "BitBuddy") , map_entry("BC", "BitComet") , map_entry("BF", "Bitflu") , map_entry("BG", "BTG") , map_entry("BR", "BitRocket") , map_entry("BS", "BTSlave") , map_entry("BX", "BittorrentX") , map_entry("CD", "Enhanced CTorrent") , map_entry("CT", "CTorrent") , map_entry("DE", "Deluge Torrent") , map_entry("ES", "electric sheep") , map_entry("EB", "EBit") , map_entry("HL", "Halite") , map_entry("HN", "Hydranode") , map_entry("KT", "KTorrent") , map_entry("LK", "Linkage") , map_entry("LP", "lphant") , map_entry("LT", "libtorrent") , map_entry("M", "Mainline") , map_entry("ML", "MLDonkey") , map_entry("MO", "Mono Torrent") , map_entry("MP", "MooPolice") , map_entry("MT", "Moonlight Torrent") , map_entry("O", "Osprey Permaseed") , map_entry("PD", "Pando") , map_entry("QT", "Qt 4") , map_entry("R", "Tribler") , map_entry("S", "Shadow") , map_entry("S~", "Shareaza (beta)") , map_entry("SB", "Swiftbit") , map_entry("SN", "ShareNet") , map_entry("SS", "SwarmScope") , map_entry("SZ", "Shareaza") , map_entry("T", "BitTornado") , map_entry("TN", "Torrent.NET") , map_entry("TR", "Transmission") , map_entry("TS", "TorrentStorm") , map_entry("TT", "TuoTu") , map_entry("U", "UPnP") , map_entry("UL", "uLeecher") , map_entry("UT", "MicroTorrent") , map_entry("XT", "XanTorrent") , map_entry("XX", "Xtorrent") , map_entry("ZT", "ZipTorrent") , map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)") , map_entry("pX", "pHoeniX") , map_entry("qB", "qBittorrent") }; bool compare_first_string(map_entry const& lhs, map_entry const& rhs) { return lhs.first[0] < rhs.first[0] || ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry* i = std::lower_bound(name_map, name_map + size , map_entry(f.name, ""), &compare_first_string); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_first_string(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->first)) identity << i->second; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>