text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: syshelp.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2006-09-25 13:25:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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 * ************************************************************************/ #include <syshelp.hxx> // NOT FULLY DEFINED SERVICES #include <string.h> #include "sistr.hxx" #include "list.hxx" #ifdef WNT #include <io.h> #elif defined(UNX) #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #define stricmp strcasecmp #else #error Must run under unix or windows, please define UNX or WNT. #endif char C_sSpaceInName[] = "&nbsp;&nbsp;&nbsp;"; void WriteName( std::ostream & o_rFile, const Simstr & i_rIdlDocuBaseDir, const Simstr & i_rName, E_LinkType i_eLinkType ) { if (i_rName.l() == 0) return; const char * pNameEnd = strstr( i_rName.str(), " in " ); // No link: if ( i_eLinkType == lt_nolink ) { if ( pNameEnd != 0 ) { const char * pStart = i_rName.str(); o_rFile.write( pStart, pNameEnd - pStart ); WriteStr( o_rFile, C_sSpaceInName ); WriteStr( o_rFile, pNameEnd ); } else { WriteStr( o_rFile, i_rName ); } return; } if ( i_eLinkType == lt_idl ) { Simstr sPath(i_rName); sPath.replace_all('.','/'); int nNameEnd = sPath.pos_first(' '); int nPathStart = sPath.pos_last(' '); WriteStr( o_rFile, "<A HREF=\"" ); if ( nNameEnd > -1 ) { WriteStr( o_rFile, "file:///" ); WriteStr( o_rFile, i_rIdlDocuBaseDir ); WriteStr( o_rFile, "/" ); WriteStr( o_rFile, sPath.str() + 1 + nPathStart ); WriteStr( o_rFile, "/" ); o_rFile.write( sPath.str(), nNameEnd ); WriteStr( o_rFile, ".html\">" ); } else { // Should not be reached: WriteStr(o_rFile, i_rName); return; } } else if ( i_eLinkType == lt_html ) { int nKomma = i_rName.pos_first(','); int nEnd = i_rName.pos_first(' '); if ( nKomma > -1 ) { o_rFile.write( i_rName.str(), nKomma ); WriteStr( o_rFile, ": " ); WriteStr( o_rFile, "<A HREF=\"" ); o_rFile.write( i_rName.str(), nKomma ); WriteStr( o_rFile, ".html#" ); if ( nEnd > -1 ) o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma ); else WriteStr( o_rFile, i_rName.str() + nKomma + 1 ); WriteStr( o_rFile, "\">" ); o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma ); } else { WriteStr( o_rFile, "<A HREF=\"" ); WriteStr( o_rFile, i_rName ); WriteStr( o_rFile, ".html\">" ); WriteStr( o_rFile, i_rName ); } WriteStr( o_rFile, "</A>" ); return; } if ( pNameEnd != 0 ) { const char * pStart = i_rName.str(); if ( pNameEnd > pStart ) o_rFile.write( pStart, pNameEnd - pStart ); WriteStr( o_rFile, "</A>" ); WriteStr( o_rFile, C_sSpaceInName ); WriteStr( o_rFile, pNameEnd ); } else { WriteStr( o_rFile, i_rName ); WriteStr( o_rFile, "</A>" ); } } void WriteStr( std::ostream & o_rFile, const char * i_sStr ) { o_rFile.write( i_sStr, (int) strlen(i_sStr) ); } void WriteStr( std::ostream & o_rFile, const Simstr & i_sStr ) { o_rFile.write( i_sStr.str(), i_sStr.l() ); } const char C_sXML_END[] = "\\*.xml"; void GatherFileNames( List<Simstr> & o_sFiles, const char * i_sSrcDirectory ) { static int nAliveCounter = 0; char * sNextDir = 0; Simstr sNew = 0; #ifdef WNT struct _finddata_t aEntry; long hFile = 0; int bFindMore = 0; char * sFilter = new char[ strlen(i_sSrcDirectory) + sizeof C_sXML_END ]; // Stayingalive sign if (++nAliveCounter % 100 == 1) std::cout << "." << std::flush; strcpy(sFilter, i_sSrcDirectory); // STRCPY SAFE HERE strcat(sFilter,C_sXML_END); // STRCAT SAFE HERE hFile = _findfirst( sFilter, &aEntry ); for ( bFindMore = hFile == -1; bFindMore == 0; bFindMore = _findnext( hFile, &aEntry ) ) { sNew = i_sSrcDirectory; sNew += "\\"; sNew += aEntry.name; o_sFiles.push_back(sNew); } // end for _findclose(hFile); delete [] sFilter; #elif defined(UNX) DIR * pDir = opendir( i_sSrcDirectory ); dirent * pEntry = 0; char * sEnding; // Stayingalive sign if (++nAliveCounter % 100 == 1) std::cout << "." << std::flush; while ( (pEntry = readdir(pDir)) != 0 ) { sEnding = strrchr(pEntry->d_name,'.'); if (sEnding != 0 ? stricmp(sEnding,".xml") == 0 : 0 ) { sNew = i_sSrcDirectory; sNew += "/"; sNew += pEntry->d_name; o_sFiles.push_back(sNew); } } // end while closedir( pDir ); #else #error Must run on unix or windows, please define UNX or WNT. #endif // gathering from subdirectories: List<Simstr> aSubDirectories; GatherSubDirectories( aSubDirectories, i_sSrcDirectory ); unsigned d_max = aSubDirectories.size(); for ( unsigned d = 0; d < d_max; ++d ) { sNextDir = new char[ strlen(i_sSrcDirectory) + 2 + aSubDirectories[d].l() ]; strcpy(sNextDir, i_sSrcDirectory); strcat(sNextDir, C_sSLASH); strcat(sNextDir, aSubDirectories[d].str()); GatherFileNames(o_sFiles, sNextDir); delete [] sNextDir; } } const char * C_sANYDIR = "\\*.*"; void GatherSubDirectories( List<Simstr> & o_sSubDirectories, const char * i_sParentdDirectory ) { Simstr sNew; #ifdef WNT struct _finddata_t aEntry; long hFile = 0; int bFindMore = 0; char * sFilter = new char[strlen(i_sParentdDirectory) + sizeof C_sANYDIR]; strcpy(sFilter, i_sParentdDirectory); strcat(sFilter,C_sANYDIR); hFile = _findfirst( sFilter, &aEntry ); for ( bFindMore = hFile == -1; bFindMore == 0; bFindMore = _findnext( hFile, &aEntry ) ) { if (aEntry.attrib == _A_SUBDIR) { // Do not gather . .. and outputtree directories if ( strchr(aEntry.name,'.') == 0 && strncmp(aEntry.name, "wnt", 3) != 0 && strncmp(aEntry.name, "unx", 3) != 0 ) { sNew = aEntry.name; o_sSubDirectories.push_back(sNew); } } // endif (aEntry.attrib == _A_SUBDIR) } // end for _findclose(hFile); delete [] sFilter; #elif defined(UNX) DIR * pDir = opendir( i_sParentdDirectory ); dirent * pEntry = 0; struct stat aEntryStatus; while ( ( pEntry = readdir(pDir) ) != 0 ) { stat(pEntry->d_name, &aEntryStatus); if ( ( aEntryStatus.st_mode & S_IFDIR ) == S_IFDIR ) { // Do not gather . .. and outputtree directories if ( strchr(pEntry->d_name,'.') == 0 && strncmp(pEntry->d_name, "wnt", 3) != 0 && strncmp(pEntry->d_name, "unx", 3) != 0 ) { sNew = pEntry->d_name; o_sSubDirectories.push_back(sNew); } } // endif (aEntry.attrib == _A_SUBDIR) } // end while closedir( pDir ); #else #error Must run on unix or windows, please define UNX or WNT. #endif } <commit_msg>INTEGRATION: CWS os2port02 (1.11.20); FILE MERGED 2007/10/04 19:45:25 ydario 1.11.20.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: syshelp.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-11-02 12:55:32 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * 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 * ************************************************************************/ #include <syshelp.hxx> // NOT FULLY DEFINED SERVICES #include <string.h> #include "sistr.hxx" #include "list.hxx" #ifdef WNT #include <io.h> #elif defined(UNX) || defined(OS2) #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #define stricmp strcasecmp #else #error Must run under unix or windows, please define UNX or WNT. #endif char C_sSpaceInName[] = "&nbsp;&nbsp;&nbsp;"; void WriteName( std::ostream & o_rFile, const Simstr & i_rIdlDocuBaseDir, const Simstr & i_rName, E_LinkType i_eLinkType ) { if (i_rName.l() == 0) return; const char * pNameEnd = strstr( i_rName.str(), " in " ); // No link: if ( i_eLinkType == lt_nolink ) { if ( pNameEnd != 0 ) { const char * pStart = i_rName.str(); o_rFile.write( pStart, pNameEnd - pStart ); WriteStr( o_rFile, C_sSpaceInName ); WriteStr( o_rFile, pNameEnd ); } else { WriteStr( o_rFile, i_rName ); } return; } if ( i_eLinkType == lt_idl ) { Simstr sPath(i_rName); sPath.replace_all('.','/'); int nNameEnd = sPath.pos_first(' '); int nPathStart = sPath.pos_last(' '); WriteStr( o_rFile, "<A HREF=\"" ); if ( nNameEnd > -1 ) { WriteStr( o_rFile, "file:///" ); WriteStr( o_rFile, i_rIdlDocuBaseDir ); WriteStr( o_rFile, "/" ); WriteStr( o_rFile, sPath.str() + 1 + nPathStart ); WriteStr( o_rFile, "/" ); o_rFile.write( sPath.str(), nNameEnd ); WriteStr( o_rFile, ".html\">" ); } else { // Should not be reached: WriteStr(o_rFile, i_rName); return; } } else if ( i_eLinkType == lt_html ) { int nKomma = i_rName.pos_first(','); int nEnd = i_rName.pos_first(' '); if ( nKomma > -1 ) { o_rFile.write( i_rName.str(), nKomma ); WriteStr( o_rFile, ": " ); WriteStr( o_rFile, "<A HREF=\"" ); o_rFile.write( i_rName.str(), nKomma ); WriteStr( o_rFile, ".html#" ); if ( nEnd > -1 ) o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma ); else WriteStr( o_rFile, i_rName.str() + nKomma + 1 ); WriteStr( o_rFile, "\">" ); o_rFile.write( i_rName.str() + nKomma + 1, nEnd - nKomma ); } else { WriteStr( o_rFile, "<A HREF=\"" ); WriteStr( o_rFile, i_rName ); WriteStr( o_rFile, ".html\">" ); WriteStr( o_rFile, i_rName ); } WriteStr( o_rFile, "</A>" ); return; } if ( pNameEnd != 0 ) { const char * pStart = i_rName.str(); if ( pNameEnd > pStart ) o_rFile.write( pStart, pNameEnd - pStart ); WriteStr( o_rFile, "</A>" ); WriteStr( o_rFile, C_sSpaceInName ); WriteStr( o_rFile, pNameEnd ); } else { WriteStr( o_rFile, i_rName ); WriteStr( o_rFile, "</A>" ); } } void WriteStr( std::ostream & o_rFile, const char * i_sStr ) { o_rFile.write( i_sStr, (int) strlen(i_sStr) ); } void WriteStr( std::ostream & o_rFile, const Simstr & i_sStr ) { o_rFile.write( i_sStr.str(), i_sStr.l() ); } const char C_sXML_END[] = "\\*.xml"; void GatherFileNames( List<Simstr> & o_sFiles, const char * i_sSrcDirectory ) { static int nAliveCounter = 0; char * sNextDir = 0; Simstr sNew = 0; #ifdef WNT struct _finddata_t aEntry; long hFile = 0; int bFindMore = 0; char * sFilter = new char[ strlen(i_sSrcDirectory) + sizeof C_sXML_END ]; // Stayingalive sign if (++nAliveCounter % 100 == 1) std::cout << "." << std::flush; strcpy(sFilter, i_sSrcDirectory); // STRCPY SAFE HERE strcat(sFilter,C_sXML_END); // STRCAT SAFE HERE hFile = _findfirst( sFilter, &aEntry ); for ( bFindMore = hFile == -1; bFindMore == 0; bFindMore = _findnext( hFile, &aEntry ) ) { sNew = i_sSrcDirectory; sNew += "\\"; sNew += aEntry.name; o_sFiles.push_back(sNew); } // end for _findclose(hFile); delete [] sFilter; #elif defined(UNX) || defined(OS2) DIR * pDir = opendir( i_sSrcDirectory ); dirent * pEntry = 0; char * sEnding; // Stayingalive sign if (++nAliveCounter % 100 == 1) std::cout << "." << std::flush; while ( (pEntry = readdir(pDir)) != 0 ) { sEnding = strrchr(pEntry->d_name,'.'); if (sEnding != 0 ? stricmp(sEnding,".xml") == 0 : 0 ) { sNew = i_sSrcDirectory; sNew += "/"; sNew += pEntry->d_name; o_sFiles.push_back(sNew); } } // end while closedir( pDir ); #else #error Must run on unix or windows, please define UNX or WNT. #endif // gathering from subdirectories: List<Simstr> aSubDirectories; GatherSubDirectories( aSubDirectories, i_sSrcDirectory ); unsigned d_max = aSubDirectories.size(); for ( unsigned d = 0; d < d_max; ++d ) { sNextDir = new char[ strlen(i_sSrcDirectory) + 2 + aSubDirectories[d].l() ]; strcpy(sNextDir, i_sSrcDirectory); strcat(sNextDir, C_sSLASH); strcat(sNextDir, aSubDirectories[d].str()); GatherFileNames(o_sFiles, sNextDir); delete [] sNextDir; } } const char * C_sANYDIR = "\\*.*"; void GatherSubDirectories( List<Simstr> & o_sSubDirectories, const char * i_sParentdDirectory ) { Simstr sNew; #ifdef WNT struct _finddata_t aEntry; long hFile = 0; int bFindMore = 0; char * sFilter = new char[strlen(i_sParentdDirectory) + sizeof C_sANYDIR]; strcpy(sFilter, i_sParentdDirectory); strcat(sFilter,C_sANYDIR); hFile = _findfirst( sFilter, &aEntry ); for ( bFindMore = hFile == -1; bFindMore == 0; bFindMore = _findnext( hFile, &aEntry ) ) { if (aEntry.attrib == _A_SUBDIR) { // Do not gather . .. and outputtree directories if ( strchr(aEntry.name,'.') == 0 && strncmp(aEntry.name, "wnt", 3) != 0 && strncmp(aEntry.name, "unx", 3) != 0 ) { sNew = aEntry.name; o_sSubDirectories.push_back(sNew); } } // endif (aEntry.attrib == _A_SUBDIR) } // end for _findclose(hFile); delete [] sFilter; #elif defined(UNX) || defined(OS2) DIR * pDir = opendir( i_sParentdDirectory ); dirent * pEntry = 0; struct stat aEntryStatus; while ( ( pEntry = readdir(pDir) ) != 0 ) { stat(pEntry->d_name, &aEntryStatus); if ( ( aEntryStatus.st_mode & S_IFDIR ) == S_IFDIR ) { // Do not gather . .. and outputtree directories if ( strchr(pEntry->d_name,'.') == 0 && strncmp(pEntry->d_name, "wnt", 3) != 0 && strncmp(pEntry->d_name, "unx", 3) != 0 ) { sNew = pEntry->d_name; o_sSubDirectories.push_back(sNew); } } // endif (aEntry.attrib == _A_SUBDIR) } // end while closedir( pDir ); #else #error Must run on unix or windows, please define UNX or WNT. #endif } <|endoftext|>
<commit_before>/** * domain.cpp * * by Mohammad Elmi * Created on 24 Oct 2013 */ #include "domain.h" namespace aban2 { varinfo::varinfo(std::string _name, char _rank, bool _show, void *_data): name(_name), rank(_rank), show(_show) { data.generic = _data; } domain *domain::create_from_file(std::string file_name) { Json::Reader reader; Json::Value root; std::ifstream ifile(file_name); reader.parse(ifile, root, false); ifile.close(); domain *result = new domain(&root); return result; } domain::domain(Json::Value *root): mesh(root) { t = 0; dt = root->get("dt", 1).asDouble(); tend = root->get("tend", 1).asDouble(); rho0 = root->get("rho0", 1000).asDouble(); rho1 = root->get("rho1", 1000).asDouble(); nu0 = root->get("nu0", 1e-3).asDouble(); nu1 = root->get("nu1", 1e-3).asDouble(); Json::Value gnode = (*root)["g"]; g = vector(gnode[0].asDouble(), gnode[1].asDouble(), gnode[2].asDouble()); write_interval = root->get("write_interval", 1).asInt(); boundaries = new flowbc*[256]; Json::Value boundaries_val = (*root)["boundaries"]; flowbc::create_bcs(&boundaries_val, boundaries, this); register_vars(); create_vars(); } void domain::register_vars() { varlist.push_back(varinfo("p", 1, true, &p)); varlist.push_back(varinfo("u", 2, true, &u)); varlist.push_back(varinfo("ustar", 2, true, &ustar)); varlist.push_back(varinfo("rho", 1, false, &rho)); varlist.push_back(varinfo("nu", 1, false, &nu)); varlist.push_back(varinfo("uf", 2, false, &uf)); varlist.push_back(varinfo("vof", 1, true, &vof)); varlist.push_back(varinfo("nb", 2, true, &nb)); } void domain::write_vtk(std::string file_name) { std::ofstream file(file_name); file << "# vtk DataFile Version 2.0" << std::endl; file << "aban2 output" << std::endl; file << "ASCII" << std::endl; file << "DATASET RECTILINEAR_GRID" << std::endl; file << "DIMENSIONS " << ndir[0] + 1 << " " << ndir[1] + 1 << " " << ndir[2] + 1 << std::endl; file << "X_COORDINATES " << ndir[0] + 1 << " float" << std::endl; for (int i = 0; i < ndir[0] + 1; ++i)file << (double)i *delta << " "; file << std::endl; file << "Y_COORDINATES " << ndir[1] + 1 << " float" << std::endl; for (int i = 0; i < ndir[1] + 1; ++i)file << (double)i *delta << " "; file << std::endl; file << "Z_COORDINATES " << ndir[2] + 1 << " float" << std::endl; for (int i = 0; i < ndir[2] + 1; ++i)file << (double)i *delta << " "; file << std::endl; file << "CELL_DATA " << ndir[0] *ndir[1] *ndir[2] << std::endl; file << "SCALARS existence int" << std::endl; file << "LOOKUP_TABLE default" << std::endl; for (int k = 0; k < ndir[2]; ++k) for (int j = 0; j < ndir[1]; ++j) for (int i = 0; i < ndir[0]; ++i) file << (exists(i, j, k) ? 1 : 0) << std::endl; for (auto &v : varlist) if (v.show) switch (v.rank) { case 1: file << "SCALARS " << v.name << " double" << std::endl; file << "LOOKUP_TABLE default" << std::endl; for (int k = 0; k < ndir[2]; ++k) for (int j = 0; j < ndir[1]; ++j) for (int i = 0; i < ndir[0]; ++i) { size_t x = idx(i, j, k); double val = 0; if (exists(i, j, k)) val = (*v.data.scalar)[cellnos[x]]; file << val << std::endl; } break; case 2: file << "VECTORS " << v.name << " double" << std::endl; for (int k = 0; k < ndir[2]; ++k) for (int j = 0; j < ndir[1]; ++j) for (int i = 0; i < ndir[0]; ++i) { size_t x = idx(i, j, k); vector val; if (exists(i, j, k)) val = vector::from_data(*v.data.vec, cellnos[x]); file << val.x << " " << val.y << " " << val.z << std::endl; } break; } file.close(); } double *domain::extract_scalars(mesh_row *row, double *var) { double *result = new double[row->n]; for (size_t i = 0; i < row->n; ++i) result[i] = var[cellno(row, i)]; return result; } void domain::insert_scalars(mesh_row *row, double *var, double *row_vals) { for (size_t i = 0; i < row->n; ++i) var[cellno(row, i)] = row_vals[i]; } vector *domain::extract_vectors(mesh_row *row, double **var) { vector *result = new vector[row->n]; for (size_t i = 0; i < row->n; ++i) result[i] = vector::from_data(var, cellno(row, i)); return result; } void domain::insert_vectors(mesh_row *row, double **var, vector *row_vals) { for (size_t i = 0; i < row->n; ++i) { size_t ix = cellno(row, i); var[0][ix] = row_vals[i].x; var[1][ix] = row_vals[i].y; var[2][ix] = row_vals[i].z; } } size_t *domain::get_row_cellnos(mesh_row *row) { size_t *row_idxs = new size_t[row->n]; for (size_t i = 0; i < row->n; ++i) row_idxs[i] = cellno(row, i); return row_idxs; } void *domain::create_var(size_t rank) { if (rank == 1) { double *result = new double[n]; std::fill_n(result, n, 0); return result; } else { void **result = new void *[3]; for (int i = 0; i < 3; ++i) result[i] = create_var(rank - 1); return result; } } void domain::delete_var(size_t rank, void *v) { if (v == nullptr) return; if (rank > 1) for (int i = 0; i < 3; ++i) delete_var(rank - 1, ((double **)v)[i]); delete[] (double *)v; } void domain::create_vars() { for (auto &v : varlist) { switch (v.rank) { case 1: *v.data.scalar = (double *)create_var(1); break; case 2: *v.data.vec = (double **)create_var(2); break; } } } void domain::delete_vars() { for (auto &v : varlist) { switch (v.rank) { case 1: delete_var(1, *v.data.scalar); break; case 2: delete_var(2, *v.data.vec); break; } } } double domain::rho_bar(double _vof) { return _vof * rho1 + (1.0 - _vof) * rho0; } double domain::nu_bar(double _vof) { return _vof * nu1 + (1.0 - _vof) * nu0; } } <commit_msg>no need to write ustar and nb<commit_after>/** * domain.cpp * * by Mohammad Elmi * Created on 24 Oct 2013 */ #include "domain.h" namespace aban2 { varinfo::varinfo(std::string _name, char _rank, bool _show, void *_data): name(_name), rank(_rank), show(_show) { data.generic = _data; } domain *domain::create_from_file(std::string file_name) { Json::Reader reader; Json::Value root; std::ifstream ifile(file_name); reader.parse(ifile, root, false); ifile.close(); domain *result = new domain(&root); return result; } domain::domain(Json::Value *root): mesh(root) { t = 0; dt = root->get("dt", 1).asDouble(); tend = root->get("tend", 1).asDouble(); rho0 = root->get("rho0", 1000).asDouble(); rho1 = root->get("rho1", 1000).asDouble(); nu0 = root->get("nu0", 1e-3).asDouble(); nu1 = root->get("nu1", 1e-3).asDouble(); Json::Value gnode = (*root)["g"]; g = vector(gnode[0].asDouble(), gnode[1].asDouble(), gnode[2].asDouble()); write_interval = root->get("write_interval", 1).asInt(); boundaries = new flowbc*[256]; Json::Value boundaries_val = (*root)["boundaries"]; flowbc::create_bcs(&boundaries_val, boundaries, this); register_vars(); create_vars(); } void domain::register_vars() { varlist.push_back(varinfo("p", 1, true, &p)); varlist.push_back(varinfo("u", 2, true, &u)); varlist.push_back(varinfo("ustar", 2, false, &ustar)); varlist.push_back(varinfo("rho", 1, false, &rho)); varlist.push_back(varinfo("nu", 1, false, &nu)); varlist.push_back(varinfo("uf", 2, false, &uf)); varlist.push_back(varinfo("vof", 1, true, &vof)); varlist.push_back(varinfo("nb", 2, false, &nb)); } void domain::write_vtk(std::string file_name) { std::ofstream file(file_name); file << "# vtk DataFile Version 2.0" << std::endl; file << "aban2 output" << std::endl; file << "ASCII" << std::endl; file << "DATASET RECTILINEAR_GRID" << std::endl; file << "DIMENSIONS " << ndir[0] + 1 << " " << ndir[1] + 1 << " " << ndir[2] + 1 << std::endl; file << "X_COORDINATES " << ndir[0] + 1 << " float" << std::endl; for (int i = 0; i < ndir[0] + 1; ++i)file << (double)i *delta << " "; file << std::endl; file << "Y_COORDINATES " << ndir[1] + 1 << " float" << std::endl; for (int i = 0; i < ndir[1] + 1; ++i)file << (double)i *delta << " "; file << std::endl; file << "Z_COORDINATES " << ndir[2] + 1 << " float" << std::endl; for (int i = 0; i < ndir[2] + 1; ++i)file << (double)i *delta << " "; file << std::endl; file << "CELL_DATA " << ndir[0] *ndir[1] *ndir[2] << std::endl; file << "SCALARS existence int" << std::endl; file << "LOOKUP_TABLE default" << std::endl; for (int k = 0; k < ndir[2]; ++k) for (int j = 0; j < ndir[1]; ++j) for (int i = 0; i < ndir[0]; ++i) file << (exists(i, j, k) ? 1 : 0) << std::endl; for (auto &v : varlist) if (v.show) switch (v.rank) { case 1: file << "SCALARS " << v.name << " double" << std::endl; file << "LOOKUP_TABLE default" << std::endl; for (int k = 0; k < ndir[2]; ++k) for (int j = 0; j < ndir[1]; ++j) for (int i = 0; i < ndir[0]; ++i) { size_t x = idx(i, j, k); double val = 0; if (exists(i, j, k)) val = (*v.data.scalar)[cellnos[x]]; file << val << std::endl; } break; case 2: file << "VECTORS " << v.name << " double" << std::endl; for (int k = 0; k < ndir[2]; ++k) for (int j = 0; j < ndir[1]; ++j) for (int i = 0; i < ndir[0]; ++i) { size_t x = idx(i, j, k); vector val; if (exists(i, j, k)) val = vector::from_data(*v.data.vec, cellnos[x]); file << val.x << " " << val.y << " " << val.z << std::endl; } break; } file.close(); } double *domain::extract_scalars(mesh_row *row, double *var) { double *result = new double[row->n]; for (size_t i = 0; i < row->n; ++i) result[i] = var[cellno(row, i)]; return result; } void domain::insert_scalars(mesh_row *row, double *var, double *row_vals) { for (size_t i = 0; i < row->n; ++i) var[cellno(row, i)] = row_vals[i]; } vector *domain::extract_vectors(mesh_row *row, double **var) { vector *result = new vector[row->n]; for (size_t i = 0; i < row->n; ++i) result[i] = vector::from_data(var, cellno(row, i)); return result; } void domain::insert_vectors(mesh_row *row, double **var, vector *row_vals) { for (size_t i = 0; i < row->n; ++i) { size_t ix = cellno(row, i); var[0][ix] = row_vals[i].x; var[1][ix] = row_vals[i].y; var[2][ix] = row_vals[i].z; } } size_t *domain::get_row_cellnos(mesh_row *row) { size_t *row_idxs = new size_t[row->n]; for (size_t i = 0; i < row->n; ++i) row_idxs[i] = cellno(row, i); return row_idxs; } void *domain::create_var(size_t rank) { if (rank == 1) { double *result = new double[n]; std::fill_n(result, n, 0); return result; } else { void **result = new void *[3]; for (int i = 0; i < 3; ++i) result[i] = create_var(rank - 1); return result; } } void domain::delete_var(size_t rank, void *v) { if (v == nullptr) return; if (rank > 1) for (int i = 0; i < 3; ++i) delete_var(rank - 1, ((double **)v)[i]); delete[] (double *)v; } void domain::create_vars() { for (auto &v : varlist) { switch (v.rank) { case 1: *v.data.scalar = (double *)create_var(1); break; case 2: *v.data.vec = (double **)create_var(2); break; } } } void domain::delete_vars() { for (auto &v : varlist) { switch (v.rank) { case 1: delete_var(1, *v.data.scalar); break; case 2: delete_var(2, *v.data.vec); break; } } } double domain::rho_bar(double _vof) { return _vof * rho1 + (1.0 - _vof) * rho0; } double domain::nu_bar(double _vof) { return _vof * nu1 + (1.0 - _vof) * nu0; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <random> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <signal.h> namespace { const std::size_t UNIX_PATH_MAX = 108; const char* server_socket_path = "/tmp/asgard_socket"; const char* client_socket_path = "/tmp/asgard_random_socket"; const std::size_t buffer_size = 4096; //Buffer char write_buffer[buffer_size]; char receive_buffer[buffer_size]; // The socket file descriptor int socket_fd; // The socket addresses struct sockaddr_un client_address; struct sockaddr_un server_address; // The remote IDs int source_id = -1; int sensor_id = -1; void stop(){ std::cout << "asgard:random: stop the driver" << std::endl; // Unregister the sensor, if necessary if(sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the source, if necessary if(source_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unlink the client socket unlink(client_socket_path); // Close the socket close(socket_fd); } void terminate(int){ stop(); std::exit(0); } } //End of anonymous namespace int main(){ // Open the socket socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(socket_fd < 0){ std::cerr << "asgard:random: socket() failed" << std::endl; return 1; } // Init the client address memset(&client_address, 0, sizeof(struct sockaddr_un)); client_address.sun_family = AF_UNIX; snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path); // Unlink the client socket unlink(client_socket_path); // Bind to client socket if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){ std::cerr << "asgard:random: bind() failed" << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); // Init the server address memset(&server_address, 0, sizeof(struct sockaddr_un)); server_address.sun_family = AF_UNIX; snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path); socklen_t address_length = sizeof(struct sockaddr_un); // Register the source auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE random"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; source_id = atoi(receive_buffer); std::cout << "asgard:random: remote source: " << source_id << std::endl; // Register the sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "RANDOM", "rand_100"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; sensor_id = atoi(receive_buffer); std::cout << "asgard:random: remote sensor: " << sensor_id << std::endl; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distribution(1, 100); while(true){ int value = distribution(gen); // Send the data nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %d", source_id, sensor_id, value); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); // Wait some time before messages usleep(5000000); } stop(); return 0; } <commit_msg>Refactorings<commit_after>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <random> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <signal.h> namespace { // Configuration (this should be in a configuration file) const char* server_socket_path = "/tmp/asgard_socket"; const char* client_socket_path = "/tmp/asgard_random_socket"; const std::size_t delay_ms = 5000; const std::size_t UNIX_PATH_MAX = 108; const std::size_t buffer_size = 4096; //Buffer char write_buffer[buffer_size]; char receive_buffer[buffer_size]; // The socket file descriptor int socket_fd; // The socket addresses struct sockaddr_un client_address; struct sockaddr_un server_address; // The remote IDs int source_id = -1; int sensor_id = -1; void stop(){ std::cout << "asgard:random: stop the driver" << std::endl; // Unregister the sensor, if necessary if(sensor_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unregister the source, if necessary if(source_id >= 0){ auto nbytes = snprintf(write_buffer, buffer_size, "UNREG_SOURCE %d", source_id); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); } // Unlink the client socket unlink(client_socket_path); // Close the socket close(socket_fd); } void terminate(int){ stop(); std::exit(0); } } //End of anonymous namespace int main(){ // Open the socket socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if(socket_fd < 0){ std::cerr << "asgard:random: socket() failed" << std::endl; return 1; } // Init the client address memset(&client_address, 0, sizeof(struct sockaddr_un)); client_address.sun_family = AF_UNIX; snprintf(client_address.sun_path, UNIX_PATH_MAX, client_socket_path); // Unlink the client socket unlink(client_socket_path); // Bind to client socket if(bind(socket_fd, (const struct sockaddr *) &client_address, sizeof(struct sockaddr_un)) < 0){ std::cerr << "asgard:random: bind() failed" << std::endl; return 1; } //Register signals for "proper" shutdown signal(SIGTERM, terminate); signal(SIGINT, terminate); // Init the server address memset(&server_address, 0, sizeof(struct sockaddr_un)); server_address.sun_family = AF_UNIX; snprintf(server_address.sun_path, UNIX_PATH_MAX, server_socket_path); socklen_t address_length = sizeof(struct sockaddr_un); // Register the source auto nbytes = snprintf(write_buffer, buffer_size, "REG_SOURCE random"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); auto bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; source_id = atoi(receive_buffer); std::cout << "asgard:random: remote source: " << source_id << std::endl; // Register the sensor nbytes = snprintf(write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, "RANDOM", "rand_100"); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); bytes_received = recvfrom(socket_fd, receive_buffer, buffer_size, 0, (struct sockaddr *) &(server_address), &address_length); receive_buffer[bytes_received] = '\0'; sensor_id = atoi(receive_buffer); std::cout << "asgard:random: remote sensor: " << sensor_id << std::endl; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distribution(1, 100); while(true){ int value = distribution(gen); // Send the data nbytes = snprintf(write_buffer, buffer_size, "DATA %d %d %d", source_id, sensor_id, value); sendto(socket_fd, write_buffer, nbytes, 0, (struct sockaddr *) &server_address, sizeof(struct sockaddr_un)); // Wait some time before messages usleep(delay_ms * 1000); } stop(); return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_TRACKING_IMPL_HSV_COLOR_COHERENCE_H_ #define PCL_TRACKING_IMPL_HSV_COLOR_COHERENCE_H_ #include <Eigen/Dense> #ifdef BUILD_Maintainer # if defined __GNUC__ # pragma GCC system_header # elif defined _MSC_VER # pragma warning(push, 1) # endif #endif namespace pcl { namespace tracking { // utility typedef union { struct /*anonymous*/ { unsigned char Blue; // Blue channel unsigned char Green; // Green channel unsigned char Red; // Red channel }; float float_value; long long_value; } RGBValue; /** \brief Convert a RGB tuple to an HSV one. * \param[in] r the input Red component * \param[in] g the input Green component * \param[in] b the input Blue component * \param[out] fh the output Hue component * \param[out] fs the output Saturation component * \param[out] fv the output Value component */ void RGB2HSV (int r, int g, int b, float& fh, float& fs, float& fv) { // mostly copied from opencv-svn/modules/imgproc/src/color.cpp // revision is 4351 const int hsv_shift = 12; static const int div_table[] = { 0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096 }; int hr = 180, hscale = 15; int h, s, v = b; int vmin = b, diff; int vr, vg; v = std::max<int> (v, g); v = std::max<int> (v, r); vmin = std::min<int> (vmin, g); vmin = std::min<int> (vmin, r); diff = v - vmin; vr = v == r ? -1 : 0; vg = v == g ? -1 : 0; s = diff * div_table[v] >> hsv_shift; h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); h = (h * div_table[diff] * hscale + (1 << (hsv_shift + 6))) >> (7 + hsv_shift); h += h < 0 ? hr : 0; fh = static_cast<float> (h) / 180.0f; fs = static_cast<float> (s) / 255.0f; fv = static_cast<float> (v) / 255.0f; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT> double HSVColorCoherence<PointInT>::computeCoherence (PointInT &source, PointInT &target) { // convert color space from RGB to HSV RGBValue source_rgb, target_rgb; source_rgb.float_value = static_cast<float> (source.rgba); target_rgb.float_value = static_cast<float> (target.rgba); float source_h, source_s, source_v, target_h, target_s, target_v; RGB2HSV (source_rgb.Red, source_rgb.Blue, source_rgb.Green, source_h, source_s, source_v); RGB2HSV (target_rgb.Red, target_rgb.Blue, target_rgb.Green, target_h, target_s, target_v); // hue value is in 0 ~ 2pi, but circulated. const float _h_diff = fabsf (source_h - target_h); float h_diff; if (_h_diff > 0.5f) h_diff = static_cast<float> (h_weight_) * (_h_diff - 0.5f) * (_h_diff - 0.5f); else h_diff = static_cast<float> (h_weight_) * _h_diff * _h_diff; const float s_diff = static_cast<float> (s_weight_) * (source_s - target_s) * (source_s - target_s); const float v_diff = static_cast<float> (v_weight_) * (source_v - target_v) * (source_v - target_v); const float diff2 = h_diff + s_diff + v_diff; return (1.0 / (1.0 + weight_ * diff2)); } } } #define PCL_INSTANTIATE_HSVColorCoherence(T) template class PCL_EXPORTS pcl::tracking::HSVColorCoherence<T>; #ifdef BUILD_Maintainer # if defined _MSC_VER # pragma warning(pop) # endif #endif #endif <commit_msg>avoid casting int to float when dealing with rgb field <commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_TRACKING_IMPL_HSV_COLOR_COHERENCE_H_ #define PCL_TRACKING_IMPL_HSV_COLOR_COHERENCE_H_ #include <Eigen/Dense> #ifdef BUILD_Maintainer # if defined __GNUC__ # pragma GCC system_header # elif defined _MSC_VER # pragma warning(push, 1) # endif #endif namespace pcl { namespace tracking { // utility typedef union { struct /*anonymous*/ { unsigned char Blue; // Blue channel unsigned char Green; // Green channel unsigned char Red; // Red channel }; float float_value; int int_value; } RGBValue; /** \brief Convert a RGB tuple to an HSV one. * \param[in] r the input Red component * \param[in] g the input Green component * \param[in] b the input Blue component * \param[out] fh the output Hue component * \param[out] fs the output Saturation component * \param[out] fv the output Value component */ void RGB2HSV (int r, int g, int b, float& fh, float& fs, float& fv) { // mostly copied from opencv-svn/modules/imgproc/src/color.cpp // revision is 4351 const int hsv_shift = 12; static const int div_table[] = { 0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096 }; int hr = 180, hscale = 15; int h, s, v = b; int vmin = b, diff; int vr, vg; v = std::max<int> (v, g); v = std::max<int> (v, r); vmin = std::min<int> (vmin, g); vmin = std::min<int> (vmin, r); diff = v - vmin; vr = v == r ? -1 : 0; vg = v == g ? -1 : 0; s = diff * div_table[v] >> hsv_shift; h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); h = (h * div_table[diff] * hscale + (1 << (hsv_shift + 6))) >> (7 + hsv_shift); h += h < 0 ? hr : 0; fh = static_cast<float> (h) / 180.0f; fs = static_cast<float> (s) / 255.0f; fv = static_cast<float> (v) / 255.0f; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT> double HSVColorCoherence<PointInT>::computeCoherence (PointInT &source, PointInT &target) { // convert color space from RGB to HSV RGBValue source_rgb, target_rgb; source_rgb.int_value = source.rgba; target_rgb.int_value = target.rgba; float source_h, source_s, source_v, target_h, target_s, target_v; RGB2HSV (source_rgb.Red, source_rgb.Blue, source_rgb.Green, source_h, source_s, source_v); RGB2HSV (target_rgb.Red, target_rgb.Blue, target_rgb.Green, target_h, target_s, target_v); // hue value is in 0 ~ 2pi, but circulated. const float _h_diff = fabsf (source_h - target_h); float h_diff; if (_h_diff > 0.5f) h_diff = static_cast<float> (h_weight_) * (_h_diff - 0.5f) * (_h_diff - 0.5f); else h_diff = static_cast<float> (h_weight_) * _h_diff * _h_diff; const float s_diff = static_cast<float> (s_weight_) * (source_s - target_s) * (source_s - target_s); const float v_diff = static_cast<float> (v_weight_) * (source_v - target_v) * (source_v - target_v); const float diff2 = h_diff + s_diff + v_diff; return (1.0 / (1.0 + weight_ * diff2)); } } } #define PCL_INSTANTIATE_HSVColorCoherence(T) template class PCL_EXPORTS pcl::tracking::HSVColorCoherence<T>; #ifdef BUILD_Maintainer # if defined _MSC_VER # pragma warning(pop) # endif #endif #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * Copyright (C) 2013 Rasmus Eskola <fruitiex@gmail.com> * based on sample.cpp sample module code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <dirent.h> #include <vector> #include <algorithm> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); private: bool inChan(const CString& Chan); }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { CString LogPath = sArgs; if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath? PutModule("LogPath is empty, set it with the LogPath command (help for more info)"); } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { } void CBacklogMod::OnModCommand(const CString& sCommand) { CString Arg = sCommand.Token(1); if (sCommand.Token(0).Equals("help")) { // TODO: proper help text, look how AddHelpCommand() does it in other ZNC code PutModule("Usage:"); PutModule("<window-name> [num-lines] (e.g. #foo 42)"); PutModule(""); PutModule("Commands:"); PutModule("Help (print this text)"); PutModule("LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date)"); PutModule("PrintStatusMsgs true/false (print join/part/rename messages)"); return; } else if (sCommand.Token(0).Equals("logpath")) { if(Arg.empty()) { PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date:)"); PutModule("Current LogPath is set to: " + GetNV("LogPath")); return; } CString LogPath = sCommand.Token(1, true); SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } else if (sCommand.Token(0).Equals("PrintStatusMsgs")) { if(Arg.empty() || (!Arg.Equals("true", true) && !Arg.Equals("false", true))) { PutModule("Usage: PrintStatusMsgs true/false"); return; } SetNV("PrintStatusMsgs", Arg); PutModule("PrintStatusMsgs set to: " + Arg); return; } // TODO: handle these differently depending on how the module was loaded CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"); CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc"); CString Channel = sCommand.Token(0); int printedLines = 0; int reqLines = sCommand.Token(1).ToInt(); if(reqLines <= 0) { reqLines = 150; } reqLines = std::max(std::min(reqLines, 1000), 1); CString Path = GetNV("LogPath").substr(); // make copy Path.Replace("$NETWORK", Network); Path.Replace("$WINDOW", Channel); Path.Replace("$USER", User); CString DirPath = Path.substr(0, Path.find_last_of("/")); CString FilePath; std::vector<CString> FileList; std::vector<CString> LinesToPrint; // gather list of all log files for requested channel/window DIR *dir; struct dirent *ent; if ((dir = opendir (DirPath.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { FilePath = DirPath + "/" + ent->d_name; //PutModule("DEBUG: " + FilePath + " " + Path); if(FilePath.AsLower().StrCmp(Path.AsLower(), Path.find_last_of("*")) == 0) { FileList.push_back(FilePath); } } closedir (dir); } else { PutModule("Could not list directory " + DirPath + ": " + strerror(errno)); return; } std::sort(FileList.begin(), FileList.end()); // loop through list of log files one by one starting from most recent... for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) { CFile LogFile(*it); CString Line; std::vector<CString> Lines; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { try { // is line a part/join/rename etc message (nick ***), do we want to print it? // find nick by finding first whitespace, then moving one char right if(Line.at(Line.find_first_of(' ') + 1) == '*' && !GetNV("PrintStatusMsgs").ToBool()) { continue; } Lines.push_back(Line); } catch (int e) { // malformed log line, ignore PutModule("Malformed log line found in " + *it + ": " + Line); } } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); continue; } LogFile.Close(); // loop through Lines in reverse order, push to LinesToPrint for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) { LinesToPrint.push_back(*itl); printedLines++; if(printedLines >= reqLines) { break; } } if(printedLines >= reqLines) { break; } } bool isInChan = CBacklogMod::inChan(Channel); if(printedLines == 0) { PutModule("No log files found for window " + Channel + " in " + DirPath + "/"); return; } else if (isInChan) { m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + Channel + " :Backlog playback...", GetClient()); } else { PutModule("*** Backlog playback..."); } // now actually print for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) { if(isInChan) { CString Line = *it; size_t FirstWS = Line.find_first_of(' '); // position of first whitespace char in line size_t NickLen = 3; CString Nick = "***"; try { // a log line looks like: [HH:MM:SS] <Nick> Message // < and > are illegal characters in nicknames, so we can // search for these if(Line.at(FirstWS + 1) == '<') { // normal message // nicklen includes surrounding < > NickLen = Line.find_first_of('>') - Line.find_first_of('<') + 1; // but we don't want them in Nick so subtract by two Nick = Line.substr(FirstWS + 2, NickLen - 2); } m_pNetwork->PutUser(":" + Nick + "!znc@znc.in PRIVMSG " + Channel + " :" + Line.substr(0, FirstWS) + Line.substr(FirstWS + NickLen + 1, Line.npos), GetClient()); } catch (int e) { PutModule("Malformed log line! " + Line); } } else { PutModule(*it); } } if (isInChan) { m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + Channel + " :" + "Playback Complete.", GetClient()); } else { PutModule("*** Playback Complete."); } } bool CBacklogMod::inChan(const CString& Chan) { const std::vector <CChan*>& vChans (m_pNetwork->GetChans()); for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) { CChan *curChan = *it; if(Chan.StrCmp(curChan->GetName()) == 0) { return true; } } return false; } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <commit_msg>tabs -> spaces<commit_after>/* * Copyright (C) 2004-2013 ZNC, see the NOTICE file for details. * Copyright (C) 2013 Rasmus Eskola <fruitiex@gmail.com> * based on sample.cpp sample module code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <znc/FileUtils.h> #include <znc/Client.h> #include <znc/Chan.h> #include <znc/User.h> #include <znc/IRCNetwork.h> #include <znc/Modules.h> #include <dirent.h> #include <vector> #include <algorithm> class CBacklogMod : public CModule { public: MODCONSTRUCTOR(CBacklogMod) {} virtual bool OnLoad(const CString& sArgs, CString& sMessage); virtual ~CBacklogMod(); virtual void OnModCommand(const CString& sCommand); private: bool inChan(const CString& Chan); }; bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) { CString LogPath = sArgs; if(LogPath.empty()) { LogPath = GetNV("LogPath"); if(LogPath.empty()) { // TODO: guess logpath? PutModule("LogPath is empty, set it with the LogPath command (help for more info)"); } } else { SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); } return true; } CBacklogMod::~CBacklogMod() { } void CBacklogMod::OnModCommand(const CString& sCommand) { CString Arg = sCommand.Token(1); if (sCommand.Token(0).Equals("help")) { // TODO: proper help text, look how AddHelpCommand() does it in other ZNC code PutModule("Usage:"); PutModule("<window-name> [num-lines] (e.g. #foo 42)"); PutModule(""); PutModule("Commands:"); PutModule("Help (print this text)"); PutModule("LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date)"); PutModule("PrintStatusMsgs true/false (print join/part/rename messages)"); return; } else if (sCommand.Token(0).Equals("logpath")) { if(Arg.empty()) { PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date:)"); PutModule("Current LogPath is set to: " + GetNV("LogPath")); return; } CString LogPath = sCommand.Token(1, true); SetNV("LogPath", LogPath); PutModule("LogPath set to: " + LogPath); return; } else if (sCommand.Token(0).Equals("PrintStatusMsgs")) { if(Arg.empty() || (!Arg.Equals("true", true) && !Arg.Equals("false", true))) { PutModule("Usage: PrintStatusMsgs true/false"); return; } SetNV("PrintStatusMsgs", Arg); PutModule("PrintStatusMsgs set to: " + Arg); return; } // TODO: handle these differently depending on how the module was loaded CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN"); CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc"); CString Channel = sCommand.Token(0); int printedLines = 0; int reqLines = sCommand.Token(1).ToInt(); if(reqLines <= 0) { reqLines = 150; } reqLines = std::max(std::min(reqLines, 1000), 1); CString Path = GetNV("LogPath").substr(); // make copy Path.Replace("$NETWORK", Network); Path.Replace("$WINDOW", Channel); Path.Replace("$USER", User); CString DirPath = Path.substr(0, Path.find_last_of("/")); CString FilePath; std::vector<CString> FileList; std::vector<CString> LinesToPrint; // gather list of all log files for requested channel/window DIR *dir; struct dirent *ent; if ((dir = opendir (DirPath.c_str())) != NULL) { while ((ent = readdir (dir)) != NULL) { FilePath = DirPath + "/" + ent->d_name; //PutModule("DEBUG: " + FilePath + " " + Path); if(FilePath.AsLower().StrCmp(Path.AsLower(), Path.find_last_of("*")) == 0) { FileList.push_back(FilePath); } } closedir (dir); } else { PutModule("Could not list directory " + DirPath + ": " + strerror(errno)); return; } std::sort(FileList.begin(), FileList.end()); // loop through list of log files one by one starting from most recent... for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) { CFile LogFile(*it); CString Line; std::vector<CString> Lines; if (LogFile.Open()) { while (LogFile.ReadLine(Line)) { try { // is line a part/join/rename etc message (nick ***), do we want to print it? // find nick by finding first whitespace, then moving one char right if(Line.at(Line.find_first_of(' ') + 1) == '*' && !GetNV("PrintStatusMsgs").ToBool()) { continue; } Lines.push_back(Line); } catch (int e) { // malformed log line, ignore PutModule("Malformed log line found in " + *it + ": " + Line); } } } else { PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno)); continue; } LogFile.Close(); // loop through Lines in reverse order, push to LinesToPrint for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) { LinesToPrint.push_back(*itl); printedLines++; if(printedLines >= reqLines) { break; } } if(printedLines >= reqLines) { break; } } bool isInChan = CBacklogMod::inChan(Channel); if(printedLines == 0) { PutModule("No log files found for window " + Channel + " in " + DirPath + "/"); return; } else if (isInChan) { m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + Channel + " :Backlog playback...", GetClient()); } else { PutModule("*** Backlog playback..."); } // now actually print for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) { if(isInChan) { CString Line = *it; size_t FirstWS = Line.find_first_of(' '); // position of first whitespace char in line size_t NickLen = 3; CString Nick = "***"; try { // a log line looks like: [HH:MM:SS] <Nick> Message // < and > are illegal characters in nicknames, so we can // search for these if(Line.at(FirstWS + 1) == '<') { // normal message // nicklen includes surrounding < > NickLen = Line.find_first_of('>') - Line.find_first_of('<') + 1; // but we don't want them in Nick so subtract by two Nick = Line.substr(FirstWS + 2, NickLen - 2); } m_pNetwork->PutUser(":" + Nick + "!znc@znc.in PRIVMSG " + Channel + " :" + Line.substr(0, FirstWS) + Line.substr(FirstWS + NickLen + 1, Line.npos), GetClient()); } catch (int e) { PutModule("Malformed log line! " + Line); } } else { PutModule(*it); } } if (isInChan) { m_pNetwork->PutUser(":***!znc@znc.in PRIVMSG " + Channel + " :" + "Playback Complete.", GetClient()); } else { PutModule("*** Playback Complete."); } } bool CBacklogMod::inChan(const CString& Chan) { const std::vector <CChan*>& vChans (m_pNetwork->GetChans()); for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) { CChan *curChan = *it; if(Chan.StrCmp(curChan->GetName()) == 0) { return true; } } return false; } template<> void TModInfo<CBacklogMod>(CModInfo& Info) { Info.AddType(CModInfo::NetworkModule); Info.AddType(CModInfo::GlobalModule); Info.SetWikiPage("backlog"); Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW"); Info.SetHasArgs(true); } NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.") <|endoftext|>
<commit_before>//GP.cpp #include "GP.hpp" #include <cstdlib> #include <iostream> GP::GP(int popSize, int maxDepth, int numberOfXs){ this->popSize = popSize; this->maxDepth = maxDepth; this->numberOfXs = numberOfXs; ramped_halfhalf(); } GP::~GP(){ for(int i=population.size() -1; i>=0; i--) { population.pop_back(); } } void GP::ramped_halfhalf(){ for (int i=0; i<popSize; i++){ if (i%2==0) population.push_back(new Individual(true, maxDepth, numberOfXs)); else population.push_back(new Individual(false, maxDepth, numberOfXs)); if (i % (popSize/5)==0) this->maxDepth= this->maxDepth + 1; } } void GP::print_GP_d(){ for (int i=0; i<population.size(); i++){ population[i]->print_expression_d(); std::cout << std::endl; } } <commit_msg>1.1.1 Simplificação ramped_halfhalf<commit_after>//GP.cpp #include "GP.hpp" #include <cstdlib> #include <iostream> GP::GP(int popSize, int maxDepth, int numberOfXs){ this->popSize = popSize; this->maxDepth = maxDepth; this->numberOfXs = numberOfXs; ramped_halfhalf(); } GP::~GP(){ for(int i=population.size() -1; i>=0; i--) { population.pop_back(); } } void GP::ramped_halfhalf(){ for (int i=1; i< (popSize+1); i++){ population.push_back(new Individual(i%2==0, maxDepth, numberOfXs)); if (i % (popSize/5)==0) this->maxDepth= this->maxDepth + 1; } } void GP::print_GP_d(){ for (int i=0; i<population.size(); i++){ population[i]->print_expression_d(); std::cout << std::endl; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Vsevolod Stakhov * * 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 AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <cerrno> #include <cstring> #include <arpa/inet.h> #include "encrypt.h" #include "nonce.h" #include "aead.h" #include "util.h" #include "kdf.h" #include "thread_pool.h" namespace hpenc { class HPEncEncrypt::impl { public: std::unique_ptr<HPEncKDF> kdf; std::vector <std::shared_ptr<HPencAead> > ciphers; std::unique_ptr<HPEncNonce> nonce; int fd_in, fd_out; unsigned block_size; std::vector<std::shared_ptr<std::vector<byte> > > io_bufs; HPEncHeader hdr; bool encode; bool random_mode; std::unique_ptr<ThreadPool> pool; impl(std::unique_ptr<HPEncKDF> &&_kdf, const std::string &in, const std::string &out, AeadAlgorithm alg, unsigned _block_size, unsigned nthreads = 0, bool _rmode = false) : kdf(std::move(_kdf)), block_size(_block_size), hdr(alg, _block_size), random_mode(_rmode) { if (!in.empty()) { fd_in = open(in.c_str(), O_RDONLY); if (fd_in == -1) { std::cerr << "Cannot open input file '" << in << "': " << ::strerror(errno) << std::endl; } } else { fd_in = STDIN_FILENO; } if (!out.empty()) { fd_out = open(out.c_str(), O_WRONLY | O_TRUNC); if (fd_out == -1) { std::cerr << "Cannot open output file '" << out << "': " << ::strerror(errno) << std::endl; } } else { fd_out = STDOUT_FILENO; } encode = false; pool.reset(new ThreadPool(nthreads)); io_bufs.resize(pool->size()); auto klen = AeadKeyLengths[static_cast<int>(alg)]; auto key = kdf->genKey(klen); for (auto i = 0U; i < pool->size(); i ++) { auto cipher = std::make_shared<HPencAead>(alg); cipher->setKey(key); if (!nonce) { nonce.reset(new HPEncNonce(cipher->noncelen())); } ciphers.push_back(cipher); io_bufs[i] = std::make_shared<std::vector<byte> >(); io_bufs[i]->resize(block_size + ciphers[0]->taglen()); } } virtual ~impl() { if (fd_in != -1) close(fd_in); if (fd_out != -1) close(fd_out); } bool writeHeader() { return hdr.toFd(fd_out, encode); } ssize_t writeBlock(ssize_t rd, std::vector<byte> *io_buf, const std::vector<byte> &n, std::shared_ptr<HPencAead> const &cipher) { if (rd > 0) { auto bs = htonl(rd); auto tag = cipher->encrypt(reinterpret_cast<byte *>(&bs), sizeof(bs), n.data(), n.size(), io_buf->data(), rd, io_buf->data()); if (!tag) { return -1; } auto mac_pos = io_buf->data() + rd; std::copy(tag->data, tag->data + tag->datalen, mac_pos); return (random_mode ? rd + tag->datalen : rd); } return -1; } size_t readBlock(std::vector<byte> *io_buf) { return util::atomicRead(fd_in, io_buf->data(), block_size); } }; HPEncEncrypt::HPEncEncrypt(std::unique_ptr<HPEncKDF> &&kdf, const std::string &in, const std::string &out, AeadAlgorithm alg, unsigned block_size, unsigned nthreads, bool random_mode) : pimpl(new impl(std::move(kdf), in, out, alg, block_size, nthreads, random_mode)) { } HPEncEncrypt::~HPEncEncrypt() { } void HPEncEncrypt::encrypt(bool encode, unsigned count) { pimpl->encode = encode; bool last = false; auto remain = count; if (pimpl->random_mode || pimpl->writeHeader()) { auto nblocks = 0U; for (;;) { auto blocks_read = 0; std::vector< std::future<ssize_t> > results; auto i = 0U; for (auto &buf : pimpl->io_bufs) { if (count > 0) { if (remain == 0) { last = true; break; } remain --; } auto rd = pimpl->block_size; if (!pimpl->random_mode) { // For random mode we skip reading rd = pimpl->readBlock(buf.get()); } if (rd > 0) { auto n = pimpl->nonce->incAndGet(); results.emplace_back( pimpl->pool->enqueue( &impl::writeBlock, pimpl.get(), rd, buf.get(), n, pimpl->ciphers[i] )); blocks_read ++; } else { last = true; } i ++; } i = 0; for(auto && result: results) { result.wait(); auto rd = result.get(); if (rd == -1) { throw std::runtime_error("Cannot encrypt block"); } else { if (rd > 0) { const auto &io_buf = pimpl->io_bufs[i].get(); if (encode) { auto b64_out = util::base64Encode(io_buf->data(), rd); if (util::atomicWrite(pimpl->fd_out, reinterpret_cast<const byte *>(b64_out.data()), b64_out.size()) == 0) { throw std::runtime_error("Cannot write encrypted block"); } } else { if (util::atomicWrite(pimpl->fd_out, io_buf->data(), rd) == 0) { throw std::runtime_error("Cannot write encrypted block"); } } } if (rd < pimpl->block_size) { // We are done return; } } i++; } if (last) { return; } if (++nblocks % rekey_blocks == 0) { // Rekey all cipers auto nkey = pimpl->kdf->genKey(pimpl->ciphers[0]->keylen()); for (auto const &cipher : pimpl->ciphers) { cipher->setKey(nkey); } } } } } } /* namespace hpenc */ <commit_msg>Fix stupid mistake.<commit_after>/* * Copyright (c) 2014, Vsevolod Stakhov * * 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 AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <iostream> #include <cerrno> #include <cstring> #include <arpa/inet.h> #include "encrypt.h" #include "nonce.h" #include "aead.h" #include "util.h" #include "kdf.h" #include "thread_pool.h" namespace hpenc { class HPEncEncrypt::impl { public: std::unique_ptr<HPEncKDF> kdf; std::vector <std::shared_ptr<HPencAead> > ciphers; std::unique_ptr<HPEncNonce> nonce; int fd_in, fd_out; unsigned block_size; std::vector<std::shared_ptr<std::vector<byte> > > io_bufs; HPEncHeader hdr; bool encode; bool random_mode; std::unique_ptr<ThreadPool> pool; impl(std::unique_ptr<HPEncKDF> &&_kdf, const std::string &in, const std::string &out, AeadAlgorithm alg, unsigned _block_size, unsigned nthreads = 0, bool _rmode = false) : kdf(std::move(_kdf)), block_size(_block_size), hdr(alg, _block_size), random_mode(_rmode) { if (!in.empty()) { fd_in = open(in.c_str(), O_RDONLY); if (fd_in == -1) { std::cerr << "Cannot open input file '" << in << "': " << ::strerror(errno) << std::endl; } } else { fd_in = STDIN_FILENO; } if (!out.empty()) { fd_out = open(out.c_str(), O_WRONLY | O_TRUNC); if (fd_out == -1) { std::cerr << "Cannot open output file '" << out << "': " << ::strerror(errno) << std::endl; } } else { fd_out = STDOUT_FILENO; } encode = false; pool.reset(new ThreadPool(nthreads)); io_bufs.resize(pool->size()); auto klen = AeadKeyLengths[static_cast<int>(alg)]; auto key = kdf->genKey(klen); for (auto i = 0U; i < pool->size(); i ++) { auto cipher = std::make_shared<HPencAead>(alg); cipher->setKey(key); if (!nonce) { nonce.reset(new HPEncNonce(cipher->noncelen())); } ciphers.push_back(cipher); io_bufs[i] = std::make_shared<std::vector<byte> >(); io_bufs[i]->resize(block_size + ciphers[0]->taglen()); } } virtual ~impl() { if (fd_in != -1) close(fd_in); if (fd_out != -1) close(fd_out); } bool writeHeader() { return hdr.toFd(fd_out, encode); } ssize_t writeBlock(ssize_t rd, std::vector<byte> *io_buf, const std::vector<byte> &n, std::shared_ptr<HPencAead> const &cipher) { if (rd > 0) { auto bs = htonl(rd); auto tag = cipher->encrypt(reinterpret_cast<byte *>(&bs), sizeof(bs), n.data(), n.size(), io_buf->data(), rd, io_buf->data()); if (!tag) { return -1; } auto mac_pos = io_buf->data() + rd; std::copy(tag->data, tag->data + tag->datalen, mac_pos); return (random_mode ? rd: rd + tag->datalen); } return -1; } size_t readBlock(std::vector<byte> *io_buf) { return util::atomicRead(fd_in, io_buf->data(), block_size); } }; HPEncEncrypt::HPEncEncrypt(std::unique_ptr<HPEncKDF> &&kdf, const std::string &in, const std::string &out, AeadAlgorithm alg, unsigned block_size, unsigned nthreads, bool random_mode) : pimpl(new impl(std::move(kdf), in, out, alg, block_size, nthreads, random_mode)) { } HPEncEncrypt::~HPEncEncrypt() { } void HPEncEncrypt::encrypt(bool encode, unsigned count) { pimpl->encode = encode; bool last = false; auto remain = count; if (pimpl->random_mode || pimpl->writeHeader()) { auto nblocks = 0U; for (;;) { auto blocks_read = 0; std::vector< std::future<ssize_t> > results; auto i = 0U; for (auto &buf : pimpl->io_bufs) { if (count > 0) { if (remain == 0) { last = true; break; } remain --; } auto rd = pimpl->block_size; if (!pimpl->random_mode) { // For random mode we skip reading rd = pimpl->readBlock(buf.get()); } if (rd > 0) { auto n = pimpl->nonce->incAndGet(); results.emplace_back( pimpl->pool->enqueue( &impl::writeBlock, pimpl.get(), rd, buf.get(), n, pimpl->ciphers[i] )); blocks_read ++; } else { last = true; break; } i ++; } i = 0; for(auto && result: results) { result.wait(); auto rd = result.get(); if (rd == -1) { throw std::runtime_error("Cannot encrypt block"); } else { if (rd > 0) { const auto &io_buf = pimpl->io_bufs[i].get(); if (encode) { auto b64_out = util::base64Encode(io_buf->data(), rd); if (util::atomicWrite(pimpl->fd_out, reinterpret_cast<const byte *>(b64_out.data()), b64_out.size()) == 0) { throw std::runtime_error("Cannot write encrypted block"); } } else { if (util::atomicWrite(pimpl->fd_out, io_buf->data(), rd) == 0) { throw std::runtime_error("Cannot write encrypted block"); } } } if (rd < pimpl->block_size) { // We are done return; } } i++; } if (last) { return; } if (++nblocks % rekey_blocks == 0) { // Rekey all cipers auto nkey = pimpl->kdf->genKey(pimpl->ciphers[0]->keylen()); for (auto const &cipher : pimpl->ciphers) { cipher->setKey(nkey); } } } } } } /* namespace hpenc */ <|endoftext|>
<commit_before>#include "game_board.hpp" #include "main.hpp" #include <string> GameBoard::GameBoard() : m_desc(new char[BOARD_DESC_SIZE]), m_board(COLS, std::vector<bool>(ROWS, false)) { } GameBoard::~GameBoard() { delete[] m_desc; } bool GameBoard::HasChanged(char const* desc) const { return (memcmp((void*)desc, (void*)m_desc, BOARD_DESC_SIZE) == 0); } <commit_msg>Fixed compilation issue on linux<commit_after>#include "game_board.hpp" #include "main.hpp" #include <string> #include <cstring> GameBoard::GameBoard() : m_desc(new char[BOARD_DESC_SIZE]), m_board(COLS, std::vector<bool>(ROWS, false)) { } GameBoard::~GameBoard() { delete[] m_desc; } bool GameBoard::HasChanged(char const* desc) const { return (memcmp((void*)desc, (void*)m_desc, BOARD_DESC_SIZE) == 0); } <|endoftext|>
<commit_before> #include "HS.hpp" #include <onions-common/containers/records/CreateR.hpp> #include <onions-common/tcp/SocksClient.hpp> #include <onions-common/Config.hpp> #include <onions-common/Log.hpp> #include <onions-common/Utils.hpp> #include <iostream> std::string HS::keyPath_; RecordPtr HS::createRecord(uint8_t workers) { auto r = promptForRecord(); std::cout << "\n" << *r << "\n" << std::endl; std::cout << "Record prepared. Hit Enter to begin making it valid. "; std::string tmp; std::getline(std::cin, tmp); r->makeValid(workers); std::cout << std::endl; std::cout << *r << std::endl; std::cout << std::endl; auto json = r->asJSON(); std::cout << "Final Record is " << json.length() << " bytes, ready for transmission: \n\n" << json << std::endl; return r; } RecordPtr HS::promptForRecord() { std::cout << "Here you can claim a .tor domain and multiple subdomains for your" " hidden service. They can point to either a .tor or a .onion domain," " keeping it all within Tor. For example, you may claim" " \"example.tor\" -> \"onions55e7yam27n.onion\", \"foo.example.tor\"" " -> \"foo.tor\", \"bar.example.tor\" -> \"bar.tor\", and" " \"a.b.c.example.tor\" -> \"3g2upl4pq6kufc4m.onion\"." " The association between these names and your hidden service is" " cryptographically locked and made valid after some computational" " work. This work will follow the prompts for the domains. \n"; std::string name; std::cout << "\nThe primary domain name must end in \".tor\"" << std::endl; while (name.length() < 5 || !Utils::strEndsWith(name, ".tor")) { std::cout << "The primary domain name: "; std::getline(std::cin, name); name = Utils::trimString(name); } std::string pgp; std::cout << "\nYou may optionally supply your PGP fingerprint, \n" "which must be a power of two in length." << std::endl; while (!Utils::isPowerOfTwo(pgp.length())) { std::cout << "Your PGP fingerprint: "; std::getline(std::cin, pgp); //"AD97364FC20BEC80" pgp = Utils::trimString(pgp); if (pgp.empty()) break; } std::cout << "\nYou may provide up to 24 subdomain-destination pairs.\n" "These must end with \"." << name << "\". Leave the " "subdomain blank when finished." << std::endl; NameList list; for (int n = 0; n < 24; n++) { std::string src = name, dest; while (!Utils::strEndsWith(src, "." + name)) { std::cout << "Subdomain " << (n + 1) << ": "; std::getline(std::cin, src); src = Utils::trimString(src); if (src.length() == 0) break; } if (src.length() == 0) break; while ((!Utils::strEndsWith(dest, ".tor") && !Utils::strEndsWith(dest, ".onion")) || (Utils::strEndsWith(dest, ".onion") && dest.length() != 16 + 6)) { std::cout << " Destination: "; std::getline(std::cin, dest); dest = Utils::trimString(dest); } src.erase(src.find("." + name)); list.push_back(std::make_pair(src, dest)); std::cout << std::endl; } std::cout << std::endl; auto r = std::make_shared<CreateR>(Utils::loadKey(keyPath_), name, pgp); r->setSubdomains(list); return r; } bool HS::sendRecord(const RecordPtr& r, short socksPort) { auto addr = Config::getQuorumNode()[0]; auto socks = SocksClient::getCircuitTo( addr["ip"].asString(), static_cast<short>(addr["port"].asInt()), socksPort); if (!socks) throw std::runtime_error("Unable to connect!"); std::cout << "Uploading Record..." << std::endl; auto received = socks->sendReceive("upload", r->asJSON()); if (received["type"].asString() == "error") { Log::get().error(received["value"].asString()); return false; } std::cout << "Record upload complete; your claim has been accepted.\n"; return true; } void HS::setKeyPath(const std::string& keyPath) { keyPath_ = keyPath; } <commit_msg>Change from SOCKS4 to SOCKS5<commit_after> #include "HS.hpp" #include <onions-common/containers/records/CreateR.hpp> #include <onions-common/tcp/TorStream.hpp> #include <onions-common/Config.hpp> #include <onions-common/Log.hpp> #include <onions-common/Utils.hpp> #include <iostream> std::string HS::keyPath_; RecordPtr HS::createRecord(uint8_t workers) { auto r = promptForRecord(); std::cout << "\n" << *r << "\n" << std::endl; std::cout << "Record prepared. Hit Enter to begin making it valid. "; std::string tmp; std::getline(std::cin, tmp); r->makeValid(workers); std::cout << std::endl; std::cout << *r << std::endl; std::cout << std::endl; auto json = r->asJSON(); std::cout << "Final Record is " << json.length() << " bytes, ready for transmission: \n\n" << json << std::endl; return r; } RecordPtr HS::promptForRecord() { std::cout << "Here you can claim a .tor domain and multiple subdomains for your" " hidden service. They can point to either a .tor or a .onion domain," " keeping it all within Tor. For example, you may claim" " \"example.tor\" -> \"onions55e7yam27n.onion\", \"foo.example.tor\"" " -> \"foo.tor\", \"bar.example.tor\" -> \"bar.tor\", and" " \"a.b.c.example.tor\" -> \"3g2upl4pq6kufc4m.onion\"." " The association between these names and your hidden service is" " cryptographically locked and made valid after some computational" " work. This work will follow the prompts for the domains. \n"; std::string name; std::cout << "\nThe primary domain name must end in \".tor\"" << std::endl; while (name.length() < 5 || !Utils::strEndsWith(name, ".tor")) { std::cout << "The primary domain name: "; std::getline(std::cin, name); name = Utils::trimString(name); } std::string pgp; std::cout << "\nYou may optionally supply your PGP fingerprint, \n" "which must be a power of two in length." << std::endl; while (!Utils::isPowerOfTwo(pgp.length())) { std::cout << "Your PGP fingerprint: "; std::getline(std::cin, pgp); //"AD97364FC20BEC80" pgp = Utils::trimString(pgp); if (pgp.empty()) break; } std::cout << "\nYou may provide up to 24 subdomain-destination pairs.\n" "These must end with \"." << name << "\". Leave the " "subdomain blank when finished." << std::endl; NameList list; for (int n = 0; n < 24; n++) { std::string src = name, dest; while (!Utils::strEndsWith(src, "." + name)) { std::cout << "Subdomain " << (n + 1) << ": "; std::getline(std::cin, src); src = Utils::trimString(src); if (src.length() == 0) break; } if (src.length() == 0) break; while ((!Utils::strEndsWith(dest, ".tor") && !Utils::strEndsWith(dest, ".onion")) || (Utils::strEndsWith(dest, ".onion") && dest.length() != 16 + 6)) { std::cout << " Destination: "; std::getline(std::cin, dest); dest = Utils::trimString(dest); } src.erase(src.find("." + name)); list.push_back(std::make_pair(src, dest)); std::cout << std::endl; } std::cout << std::endl; auto r = std::make_shared<CreateR>(Utils::loadKey(keyPath_), name, pgp); r->setSubdomains(list); return r; } bool HS::sendRecord(const RecordPtr& r, short socksPort) { auto nodeConf = Config::getQuorumNode()[0]; const auto SERVER_PORT = Const::SERVER_PORT; TorStream quorumNode("127.0.0.1", socksPort, nodeConf["addr"].asString(), SERVER_PORT); std::cout << "Uploading Record..." << std::endl; auto received = quorumNode.sendReceive("upload", r->asJSON()); if (received["type"].asString() == "error") { Log::get().error(received["value"].asString()); return false; } std::cout << "Record upload complete; your claim has been accepted.\n"; return true; } void HS::setKeyPath(const std::string& keyPath) { keyPath_ = keyPath; } <|endoftext|>
<commit_before>// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #ifndef CRUNCH_CONCURRENCY_WORK_STEALING_QUEUE_HPP #define CRUNCH_CONCURRENCY_WORK_STEALING_QUEUE_HPP #include "crunch/base/align.hpp" #include "crunch/base/noncopyable.hpp" #include "crunch/base/memory.hpp" #include "crunch/base/stdint.hpp" #include "crunch/concurrency/atomic.hpp" #include "crunch/concurrency/mpmc_lifo_list.hpp" namespace Crunch { namespace Concurrency { // TODO: steal half work queues // TODO: adaptive work stealing A-STEAL namespace Detail { struct WorkStealingQueueFreeListNode { WorkStealingQueueFreeListNode* next; }; inline void SetNext(WorkStealingQueueFreeListNode& node, WorkStealingQueueFreeListNode* next) { node.next = next; } inline WorkStealingQueueFreeListNode* GetNext(WorkStealingQueueFreeListNode& node) { return node.next; } } // Implementation of Chase and Lev "Dynamic Circular Work-Stealing Deque" template<typename T> class WorkStealingQueue : NonCopyable { public: // TODO: clean up free list in static destructor // Circular array with buffer embedded. Custom allocation with no system reclamation. // When array grows, it links back to previous smaller sized array. Arrays are only released to free list on shrink. class CircularArray : NonCopyable { public: static CircularArray* Create(uint32 logSize) { return new (Allocate(logSize)) CircularArray(logSize); } void Destroy() { Free(this, mLogSize); } CircularArray* Grow(int64 front, int64 back) { CircularArray* newArray = new (Allocate(mLogSize + 1)) CircularArray(this); for (int64 i = front; i < back; ++i) newArray->Set(i, Get(i)); return newArray; } CircularArray* Shrink(int64 front, int64 back) { CRUNCH_ASSERT(CanShrink()); CRUNCH_ASSERT((back - front) < GetSize() / 2); // TODO: Set watermark and only copy parts that have changed since grow CircularArray* newArray = mParent; for (int64 i = front; i < back; ++i) newArray->Set(i, Get(i)); return newArray; } bool CanShrink() const { return mParent != nullptr; } void Set(int64 index, T* value) { mElements[index & mSizeMinusOne] = value; } T* Get(int64 index) const { return mElements[index & mSizeMinusOne]; } int64 GetSize() const { return mSizeMinusOne + 1; } int64 GetSizeMinusOne() const { return mSizeMinusOne; } private: typedef Detail::WorkStealingQueueFreeListNode Node; CircularArray(uint32 logSize) : mParent(nullptr) , mLogSize(logSize) , mSizeMinusOne((1ll << logSize) - 1) {} CircularArray(CircularArray* parent) : mParent(parent) , mLogSize(parent->mLogSize + 1) , mSizeMinusOne((1ll << mLogSize) - 1) {} CircularArray* mParent; uint32 mLogSize; int64 mSizeMinusOne; T* mElements[1]; // Actually dynamically sized static void* Allocate(uint32 logSize) { CRUNCH_ASSERT(logSize <= MaxLogSize); if (Node* node = sFreeLists[logSize].Pop()) return node; // TODO: grow free list in batches return MallocAligned((std::size_t(1) << logSize) + sizeof(CircularArray), 128); } static void Free(void* buffer, uint32 logSize) { CRUNCH_ASSERT(logSize <= MaxLogSize); sFreeLists[logSize].Push(reinterpret_cast<Node*>(buffer)); } // Support logSize <= 32 static uint32 const MaxLogSize = 32; // Align to cacheline size. 64 should be sufficient on newer x86, but other archs often have larger line sizes // Some levels might also use larger lines typedef CRUNCH_ALIGN_PREFIX(128) MPMCLifoList<Node> CRUNCH_ALIGN_POSTFIX(128) FreeList; static FreeList sFreeLists[MaxLogSize]; }; WorkStealingQueue(uint32 initialLogSize = 6) : mArray(CircularArray::Create(initialLogSize)) {} // TODO: avoid front access in Push. Cache conservative front void Push(T* value) { int64 const back = mBack.Load(MEMORY_ORDER_ACQUIRE); int64 const front = mFront.Load(MEMORY_ORDER_ACQUIRE); CircularArray* array = mArray.Load(MEMORY_ORDER_ACQUIRE); int64 const size = back - front; if (size >= array->GetSizeMinusOne()) { array = array->Grow(front, back); mArray.Store(array, MEMORY_ORDER_RELEASE); } array->Set(back, value); mBack.Store(back + 1, MEMORY_ORDER_RELEASE); } // Fraction of spaced used to trigger shrink. Must be >= 3. static uint32 const ShrinkFraction = 3; T* Pop() { int64 back = mBack.Load(MEMORY_ORDER_ACQUIRE); CircularArray* array = mArray.Load(MEMORY_ORDER_ACQUIRE); back = back - 1; mBack.Store(back, MEMORY_ORDER_RELEASE); int64 front = mFront.Load(MEMORY_ORDER_ACQUIRE); int64 const size = back - front; if (size < 0) { mBack.Store(front, MEMORY_ORDER_RELEASE); return nullptr; // empty } T* value = array->Get(back); if (size > 0) { // Try shrink if (array->CanShrink() && size < array->GetSize() / ShrinkFraction) { CircularArray* newArray = array->Shrink(front, back); mArray.Store(newArray, MEMORY_ORDER_RELEASE); int64 const newSize = newArray->GetSize(); mBack.Store(back + newSize, MEMORY_ORDER_RELEASE); int64 front = mFront.Load(MEMORY_ORDER_ACQUIRE); if (!mFront.CompareAndSwap(front + newSize, front)) mBack.Store(back); array->Destroy(); } return value; } if (!mFront.CompareAndSwap(front + 1, front)) value = nullptr; // steal took last element mBack.Store(front + 1, MEMORY_ORDER_RELEASE); return value; } // TODO: differentiate empty and failed to steal? T* Steal() { int64 front = mFront.Load(MEMORY_ORDER_ACQUIRE); CircularArray* oldArray = mArray.Load(MEMORY_ORDER_ACQUIRE); int64 const back = mBack.Load(MEMORY_ORDER_ACQUIRE); CircularArray* array = mArray.Load(MEMORY_ORDER_ACQUIRE); int64 const size = back - front; if (size <= 0) return nullptr; // Empty if ((size & array->GetSizeMinusOne()) == 0) { if (array == oldArray && front == mFront.Load(MEMORY_ORDER_ACQUIRE)) return nullptr; // Empty else return nullptr; // Abort } T* value = array->Get(front); if (!mFront.CompareAndSwap(front + 1, front)) return nullptr; // Abort return value; } private: void Grow(); Atomic<int64> mFront; Atomic<int64> mBack; Atomic<CircularArray*> mArray; }; template<typename T> typename WorkStealingQueue<T>::CircularArray::FreeList WorkStealingQueue<T>::CircularArray::sFreeLists[WorkStealingQueue<T>::CircularArray::MaxLogSize]; }} #endif <commit_msg>Fix memory leak in WorkStealingQueue<commit_after>// Copyright (c) 2011, Christian Rorvik // Distributed under the Simplified BSD License (See accompanying file LICENSE.txt) #ifndef CRUNCH_CONCURRENCY_WORK_STEALING_QUEUE_HPP #define CRUNCH_CONCURRENCY_WORK_STEALING_QUEUE_HPP #include "crunch/base/align.hpp" #include "crunch/base/noncopyable.hpp" #include "crunch/base/memory.hpp" #include "crunch/base/stdint.hpp" #include "crunch/concurrency/atomic.hpp" #include "crunch/concurrency/mpmc_lifo_list.hpp" namespace Crunch { namespace Concurrency { // TODO: steal half work queues // TODO: adaptive work stealing A-STEAL namespace Detail { struct WorkStealingQueueFreeListNode { WorkStealingQueueFreeListNode* next; }; inline void SetNext(WorkStealingQueueFreeListNode& node, WorkStealingQueueFreeListNode* next) { node.next = next; } inline WorkStealingQueueFreeListNode* GetNext(WorkStealingQueueFreeListNode& node) { return node.next; } } // Implementation of Chase and Lev "Dynamic Circular Work-Stealing Deque" template<typename T> class WorkStealingQueue : NonCopyable { public: // TODO: clean up free list in static destructor // Circular array with buffer embedded. Custom allocation with no system reclamation. // When array grows, it links back to previous smaller sized array. Arrays are only released to free list on shrink. class CircularArray : NonCopyable { public: static CircularArray* Create(uint32 logSize) { return new (sAllocator.Allocate(logSize)) CircularArray(logSize); } void Destroy() { sAllocator.Free(this, mLogSize); } CircularArray* Grow(int64 front, int64 back) { CircularArray* newArray = new (sAllocator.Allocate(mLogSize + 1)) CircularArray(this); for (int64 i = front; i < back; ++i) newArray->Set(i, Get(i)); return newArray; } CircularArray* Shrink(int64 front, int64 back) { CRUNCH_ASSERT(CanShrink()); CRUNCH_ASSERT((back - front) < GetSize() / 2); // TODO: Set watermark and only copy parts that have changed since grow CircularArray* newArray = mParent; for (int64 i = front; i < back; ++i) newArray->Set(i, Get(i)); return newArray; } bool CanShrink() const { return mParent != nullptr; } void Set(int64 index, T* value) { mElements[index & mSizeMinusOne] = value; } T* Get(int64 index) const { return mElements[index & mSizeMinusOne]; } int64 GetSize() const { return mSizeMinusOne + 1; } int64 GetSizeMinusOne() const { return mSizeMinusOne; } private: CircularArray(uint32 logSize) : mParent(nullptr) , mLogSize(logSize) , mSizeMinusOne((1ll << logSize) - 1) {} CircularArray(CircularArray* parent) : mParent(parent) , mLogSize(parent->mLogSize + 1) , mSizeMinusOne((1ll << mLogSize) - 1) {} CircularArray* mParent; uint32 mLogSize; int64 mSizeMinusOne; T* mElements[1]; // Actually dynamically sized struct CRUNCH_ALIGN_PREFIX(128) Allocator { typedef Detail::WorkStealingQueueFreeListNode Node; ~Allocator() { for (uint32 i = 0; i < MaxLogSize; ++i) while (Node* node = mFreeLists[i].Pop()) FreeAligned(node); } void* Allocate(uint32 logSize) { CRUNCH_ASSERT(logSize <= MaxLogSize); if (Node* node = mFreeLists[logSize].Pop()) return node; // TODO: grow free list in batches return MallocAligned((std::size_t(1) << logSize) + sizeof(CircularArray), 128); } void Free(void* buffer, uint32 logSize) { CRUNCH_ASSERT(logSize <= MaxLogSize); mFreeLists[logSize].Push(reinterpret_cast<Node*>(buffer)); } // Support logSize <= 32 static uint32 const MaxLogSize = 32; // Align to cacheline size. 64 should be sufficient on newer x86, but other archs often have larger line sizes // Some levels might also use larger lines typedef CRUNCH_ALIGN_PREFIX(128) MPMCLifoList<Node> CRUNCH_ALIGN_POSTFIX(128) FreeList; FreeList mFreeLists[MaxLogSize]; } CRUNCH_ALIGN_POSTFIX(128); static Allocator sAllocator; }; WorkStealingQueue(uint32 initialLogSize = 6) : mArray(CircularArray::Create(initialLogSize)) {} ~WorkStealingQueue() { // Unwind chain of arrays and destroy them all CircularArray* array = mArray; while (array->CanShrink()) array = array->Shrink(0, 0); array->Destroy(); } // TODO: avoid front access in Push. Cache conservative front void Push(T* value) { int64 const back = mBack.Load(MEMORY_ORDER_ACQUIRE); int64 const front = mFront.Load(MEMORY_ORDER_ACQUIRE); CircularArray* array = mArray.Load(MEMORY_ORDER_ACQUIRE); int64 const size = back - front; if (size >= array->GetSizeMinusOne()) { array = array->Grow(front, back); mArray.Store(array, MEMORY_ORDER_RELEASE); } array->Set(back, value); mBack.Store(back + 1, MEMORY_ORDER_RELEASE); } // Fraction of spaced used to trigger shrink. Must be >= 3. static uint32 const ShrinkFraction = 3; T* Pop() { int64 back = mBack.Load(MEMORY_ORDER_ACQUIRE); CircularArray* array = mArray.Load(MEMORY_ORDER_ACQUIRE); back = back - 1; mBack.Store(back, MEMORY_ORDER_RELEASE); int64 front = mFront.Load(MEMORY_ORDER_ACQUIRE); int64 const size = back - front; if (size < 0) { mBack.Store(front, MEMORY_ORDER_RELEASE); return nullptr; // empty } T* value = array->Get(back); if (size > 0) { // Try shrink if (array->CanShrink() && size < array->GetSize() / ShrinkFraction) { CircularArray* newArray = array->Shrink(front, back); mArray.Store(newArray, MEMORY_ORDER_RELEASE); int64 const newSize = newArray->GetSize(); mBack.Store(back + newSize, MEMORY_ORDER_RELEASE); int64 front = mFront.Load(MEMORY_ORDER_ACQUIRE); if (!mFront.CompareAndSwap(front + newSize, front)) mBack.Store(back); array->Destroy(); } return value; } if (!mFront.CompareAndSwap(front + 1, front)) value = nullptr; // steal took last element mBack.Store(front + 1, MEMORY_ORDER_RELEASE); return value; } // TODO: differentiate empty and failed to steal? T* Steal() { int64 front = mFront.Load(MEMORY_ORDER_ACQUIRE); CircularArray* oldArray = mArray.Load(MEMORY_ORDER_ACQUIRE); int64 const back = mBack.Load(MEMORY_ORDER_ACQUIRE); CircularArray* array = mArray.Load(MEMORY_ORDER_ACQUIRE); int64 const size = back - front; if (size <= 0) return nullptr; // Empty if ((size & array->GetSizeMinusOne()) == 0) { if (array == oldArray && front == mFront.Load(MEMORY_ORDER_ACQUIRE)) return nullptr; // Empty else return nullptr; // Abort } T* value = array->Get(front); if (!mFront.CompareAndSwap(front + 1, front)) return nullptr; // Abort return value; } private: void Grow(); Atomic<int64> mFront; Atomic<int64> mBack; Atomic<CircularArray*> mArray; }; template<typename T> typename WorkStealingQueue<T>::CircularArray::Allocator WorkStealingQueue<T>::CircularArray::sAllocator; }} #endif <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __aal_hh__ #define __aal_hh__ #include "factory.hh" #include <vector> #include <string> class aal { public: virtual int adapter_execute(int action)=0; virtual int model_execute(int action) =0; virtual int getActions(int** act) =0; virtual bool reset() { return true; } virtual std::vector<std::string>& getActionNames() { return action_names; } virtual void push() {} virtual void pop() {} protected: std::vector<int> actions; std::vector<std::string> action_names; /* action names.. */ }; #include "model.hh" #include "adapter.hh" #include "awrapper.hh" #include "mwrapper.hh" #endif <commit_msg>yet another virtual destructor<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef __aal_hh__ #define __aal_hh__ #include "factory.hh" #include <vector> #include <string> class aal { public: virtual ~aal() {}; virtual int adapter_execute(int action)=0; virtual int model_execute(int action) =0; virtual int getActions(int** act) =0; virtual bool reset() { return true; } virtual std::vector<std::string>& getActionNames() { return action_names; } virtual void push() {} virtual void pop() {} protected: std::vector<int> actions; std::vector<std::string> action_names; /* action names.. */ }; #include "model.hh" #include "adapter.hh" #include "awrapper.hh" #include "mwrapper.hh" #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WebKitPrefix.h" <commit_msg>Touch file to force WebKit rebuild<commit_after>/* * Copyright (C) 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WebKitPrefix.h" <|endoftext|>
<commit_before>#include "gpio.h" #include "nvic.h" #include "driver/timer.hpp" extern "C" void __cxa_pure_virtual() { while (1); } namespace { int counter = 0; void toggle_leds() { ++counter; auto gpio_n = 17 + (counter & 3); gpio_toggle(0, (1 << gpio_n)); } } int main(void) { nvic_init(); auto* rtc = driver::Timer::get_by_id(driver::Timer::ID::RTC0); rtc->set_prescaler(0xfff - 1); rtc->set_irq_handler(toggle_leds); rtc->enable_tick_interrupt(); rtc->start(); while (1); } <commit_msg>Use new API in rtc-blinker app<commit_after>#include "gpio.h" #include "nvic.h" #include "driver/timer.hpp" #include "memio.h" namespace { int counter = 0; void toggle_leds(int) { auto gpio_n = 17 + (counter++ & 3); gpio_toggle(0, (1 << gpio_n)); } } int main(void) { nvic_init(); gpio_set_option(0, (1 << 17) | (1 << 18) | (1 << 19) | (1 << 20), GPIO_OPT_OUTPUT); auto* rtc = driver::Timer::get_by_id(driver::Timer::ID::RTC0); rtc->stop(); rtc->set_prescaler(0xffd); rtc->add_event_handler(0, toggle_leds); rtc->enable_tick_interrupt(); rtc->start(); while (1); } <|endoftext|>
<commit_before>#ifndef H_DSCPP_API #define H_DSCPP_API #include <stdint.h> #include <stdio.h> #include "rapidjson/document.h" namespace dsc { typedef snowflake uint64_t; typedef discriminator short; enum RAPIRespCode : unsigned short { OK = 0, CURL_INIT_FAILED, CURL_PERFORM_FAILED, JSON_PARSE_FAILED, UNKNOWN_ACCOUNT = 1*10^4+1, UNKNOWN_APPLICATION, UNKNOWN_CHANNEL, UKNOWN_GUILD, UNKNOWN_INTEGRATION, UNKNOWN_INVITE, UKNOWN_MEMBER, UNKNOWN_MESSAGE, UNKNOWN_OVERWRITE, UNKNOWN_PROVIDER, UNKNOWN_ROLE, UNKNOWN_USER, UNKNOWN_EMOJI, BOTS_NOT_PERMITTED = 2*10^4+1, BOTS_ONLY_PERMITTED, MAX_GUILDS_REACHED = 3*10^4+1, MAX_FRIENDS_REACHED, MAX_PINS_REACHED, MAX_GUILD_ROLES_REACHED, TOO_MANY_REACTIONS, UNAUTHORIZED = 4*10^4+1, MISSING_ACCESS = 5*10^4+1, INVALID_ACCOUNT_TYPE, CANNOT_EXECUTE_ON_DM, EMBED_DISABLED, CANNOT_EDIT_O_USR_MSG, CANNOT_SEND_EMPTY_MSG, CANNOT_SEND_MSG_TO_USR, CANNOT_SEND_MSG_IN_VOICE_CHANNEL, CHANNEL_VERIFICATION_LVL_TOO_HIGH, OAUTH_APP_DOES_NOT_HAVE_BOT, OAUTH_APP_LIMIT_REACHED, INVALID_OAUTH_STATE, MISSING_PERMISSIONS, INVALID_AUTH_TOKEN, NOTE_TOO_LONG, INVALID_MSG_COUNT, MSG_PIN_CHANNEL_INVALID, MSG_TOO_OLD, REACTION_BLOCKED = 9*10^4+1 }; class Fetchable { private: snowflake id; friend class Client; public: snowflake getId(); virtual RAPIRespCode fetch(snowflake id); virtual RAPIRespCode parse(rapidjson::Document v); bool matches(snowflake id); }; snowflake Fetchable::getId() { return id; }; bool Fetchable::matches(snowflake id) { return id == this.id; }; class Pushable : Fetchable { private: typedef size_t(*CURL_WRITEFUNCTION_PTR)(void*, size_t, size_t, void*); rapidjson::Document serialize(); const char* endpoint_name; void buildEndpointUri(char* out); bool getRespCode(rapidjson::Document* d, RAPIRespCode* r); public: marshal(char* out); // to make thread-safe, call curl_global_init() RAPIRespCode push(Client* c, CURLcode* r); // to make thread-safe, call curl_global_init() RAPIRespCode delete(Client* c, CURLcode* r); }; void Pushable::marshal(char* out) { using namespace rapidjson; Document d = serialize(); StringBuffer buf; Writer<StringBuffer> writer(buf); d.Accept(writer); out = buf.GetString(); }; void Pushable::buildEndpointUri(Client* c, char* out) { sprintf(out, "%s/%s/llu", c->sessionEndpointUri, endpoint_name, id); } bool Pushable::getRespCode(rapidjson::Document* d, RAPIRespCode* r) { *r = static_cast<RAPIRespCode>(d["code"].GetInt()); return true; } long Pushable::push(Client* c, RAPIRespCode* r, bool mkNew = false) { char* uri; RAPIRespCode res; buildEndpointUri(c, uri); curl_global_init(); CURL* curl = c->getCurl(); if(!curl) *r = CURL_INIT_FAILED; return CURL_INIT_FAILED; curl_easy_setopt(curl, CURLOPT_URL, uri); if(mkNew) { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); } else { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH"); } struct curl_slist* header; header = curl_slist_append(header, "Content-Type:application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); char* payload; marshal(payload); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); auto wfunc = [](void* dat, size_t size, size_t nmemb, void* userp) { using namespace rapidjson; Document d = new Document(); ParseResult ok = d.Parse(static_cast<char*>(dat)); if(!ok) return ok; long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); if(httpStat != 200) { getRespCode(d, r); } else { *r = NIL; } return size * nmemb; }; curl_easy_setopt(curl, CURLOPT_WRITEFUNC, static_cast<CURLOPT_WRITEFUNCTION_PTR>(&wfunc)); CURLcode res = curl_easy_perform(curl); if(cresp != CURLE_OK) return res; curl_easy_cleanup(c->getCurl()); curl_slist_free(header); return NULL; } long Pushable::delete(Client* c, RAPIRespCode* r) { char* uri; buildEndpointUri(c, uri); curl_global_init(); CURL* curl = curl_easy_init(); if(!curl) return CURL_INIT_FAILED; curl_easy_setopt(curl, CURLOPT_URL, uri); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); CURLcode res = curl_easy_perform(curl); if(res != CURLE_OK) { *r = CURL_PERFORM_FAILED; return res; } long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); if(httpStat != 200) { getRespCode(d, r); } else { *r = NIL; } curl_easy_cleanup(c->getCurl()); return res; } } #endif<commit_msg>Include API headers<commit_after>#ifndef H_DSCPP_API #define H_DSCPP_API #include <stdint.h> #include <stdio.h> #include <curl/curl.h> #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" namespace dsc { typedef snowflake uint64_t; typedef discriminator short; enum RAPIRespCode : unsigned short { OK = 0, CURL_INIT_FAILED, CURL_PERFORM_FAILED, JSON_PARSE_FAILED, UNKNOWN_ACCOUNT = 1*10^4+1, UNKNOWN_APPLICATION, UNKNOWN_CHANNEL, UKNOWN_GUILD, UNKNOWN_INTEGRATION, UNKNOWN_INVITE, UKNOWN_MEMBER, UNKNOWN_MESSAGE, UNKNOWN_OVERWRITE, UNKNOWN_PROVIDER, UNKNOWN_ROLE, UNKNOWN_USER, UNKNOWN_EMOJI, BOTS_NOT_PERMITTED = 2*10^4+1, BOTS_ONLY_PERMITTED, MAX_GUILDS_REACHED = 3*10^4+1, MAX_FRIENDS_REACHED, MAX_PINS_REACHED, MAX_GUILD_ROLES_REACHED, TOO_MANY_REACTIONS, UNAUTHORIZED = 4*10^4+1, MISSING_ACCESS = 5*10^4+1, INVALID_ACCOUNT_TYPE, CANNOT_EXECUTE_ON_DM, EMBED_DISABLED, CANNOT_EDIT_O_USR_MSG, CANNOT_SEND_EMPTY_MSG, CANNOT_SEND_MSG_TO_USR, CANNOT_SEND_MSG_IN_VOICE_CHANNEL, CHANNEL_VERIFICATION_LVL_TOO_HIGH, OAUTH_APP_DOES_NOT_HAVE_BOT, OAUTH_APP_LIMIT_REACHED, INVALID_OAUTH_STATE, MISSING_PERMISSIONS, INVALID_AUTH_TOKEN, NOTE_TOO_LONG, INVALID_MSG_COUNT, MSG_PIN_CHANNEL_INVALID, MSG_TOO_OLD, REACTION_BLOCKED = 9*10^4+1 }; class Fetchable { private: snowflake id; friend class Client; public: snowflake getId(); virtual RAPIRespCode fetch(snowflake id); virtual RAPIRespCode parse(rapidjson::Document v); bool matches(snowflake id); }; snowflake Fetchable::getId() { return id; }; bool Fetchable::matches(snowflake id) { return id == this.id; }; class Pushable : Fetchable { private: typedef size_t(*CURL_WRITEFUNCTION_PTR)(void*, size_t, size_t, void*); rapidjson::Document serialize(); const char* endpoint_name; void buildEndpointUri(char* out); bool getRespCode(rapidjson::Document* d, RAPIRespCode* r); public: marshal(char* out); // to make thread-safe, call curl_global_init() RAPIRespCode push(Client* c, CURLcode* r); // to make thread-safe, call curl_global_init() RAPIRespCode delete(Client* c, CURLcode* r); }; void Pushable::marshal(char* out) { using namespace rapidjson; Document d = serialize(); StringBuffer buf; Writer<StringBuffer> writer(buf); d.Accept(writer); out = buf.GetString(); }; void Pushable::buildEndpointUri(Client* c, char* out) { sprintf(out, "%s/%s/llu", c->sessionEndpointUri, endpoint_name, id); } bool Pushable::getRespCode(rapidjson::Document* d, RAPIRespCode* r) { *r = static_cast<RAPIRespCode>(d["code"].GetInt()); return true; } long Pushable::push(Client* c, RAPIRespCode* r, bool mkNew = false) { char* uri; RAPIRespCode res; buildEndpointUri(c, uri); curl_global_init(); CURL* curl = c->getCurl(); if(!curl) *r = CURL_INIT_FAILED; return CURL_INIT_FAILED; curl_easy_setopt(curl, CURLOPT_URL, uri); if(mkNew) { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); } else { curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH"); } struct curl_slist* header; header = curl_slist_append(header, "Content-Type:application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); char* payload; marshal(payload); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); auto wfunc = [](void* dat, size_t size, size_t nmemb, void* userp) { using namespace rapidjson; Document d = new Document(); ParseResult ok = d.Parse(static_cast<char*>(dat)); if(!ok) return ok; long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); if(httpStat != 200) { getRespCode(d, r); } else { *r = NIL; } return size * nmemb; }; curl_easy_setopt(curl, CURLOPT_WRITEFUNC, static_cast<CURLOPT_WRITEFUNCTION_PTR>(&wfunc)); CURLcode res = curl_easy_perform(curl); if(cresp != CURLE_OK) return res; curl_easy_cleanup(c->getCurl()); curl_slist_free(header); return NULL; } long Pushable::delete(Client* c, RAPIRespCode* r) { char* uri; buildEndpointUri(c, uri); curl_global_init(); CURL* curl = curl_easy_init(); if(!curl) return CURL_INIT_FAILED; curl_easy_setopt(curl, CURLOPT_URL, uri); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); CURLcode res = curl_easy_perform(curl); if(res != CURLE_OK) { *r = CURL_PERFORM_FAILED; return res; } long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); if(httpStat != 200) { getRespCode(d, r); } else { *r = NIL; } curl_easy_cleanup(c->getCurl()); return res; } } #endif<|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #include <vector> #include <bbcat-base/LoadedVersions.h> #include <bbcat-base/UDPSocket.h> #include <bbcat-base/Thread.h> #include <bbcat-base/LockFreeBuffer.h> using namespace bbcat; // ensure the version numbers of the linked libraries and registered BBC_AUDIOTOOLBOX_REQUIRE(bbcat_base_version); typedef struct { uint64_t ticks; std::vector<uint8_t> data; } PACKET; typedef struct { UDPSocket udp; LockFreeBuffer<PACKET> packets; } THREAD_CONTEXT; // thread routine void *receivethread(Thread& thread, void *arg) { THREAD_CONTEXT& context = *(THREAD_CONTEXT *)arg; UDPSocket& udp = context.udp; printf("Thread started\n"); while (!thread.StopRequested()) { PACKET *packet; sint_t bytes; // wait for UDP data if (udp.wait(200)) { // find out if bytes available if ((bytes = udp.recv(NULL, 0)) > 0) { // try to get a writable buffer if ((packet = context.packets.GetWriteBuffer()) != NULL) { sint_t bytes1; // ensure buffer is big enough for the data if (packet->data.size() < (size_t)bytes) packet->data.resize(bytes); // save time of receive packet->ticks = GetNanosecondTicks(); // receive data if ((bytes1 = udp.recv(&packet->data[0], bytes)) == bytes) { // increment write index context.packets.IncrementWrite(); } else { fprintf(stderr, "Failed to receive %d bytes from UDP socket (received %d bytes)\n", bytes, bytes1); thread.Stop(false); // MUST use false here otherwise the thread will hang waiting for itself to complete! } } else printf("No data slots available!\n"); } else { // probably socket closed fprintf(stderr, "Socket error\n"); thread.Stop(false); // MUST use false here otherwise the thread will hang waiting for itself to complete! } } } printf("Thread complete\n"); return NULL; } // CTRL-C handling bool quit = false; void chkabort(int sig) { (void)sig; quit = true; } int main(int argc, char *argv[]) { uint_t port = 4244, buflen = 100; // allow CTRL-C to gracefully stop program signal(SIGINT, chkabort); // print library versions (the actual loaded versions, if dynamically linked) printf("Versions:\n%s\n", LoadedVersions::Get().GetVersionsList().c_str()); if ((argc >= 2) && ((strcmp(argv[1], "-help") == 0) || (strcmp(argv[1], "-h") == 0))) { fprintf(stderr, "Usage: udp-demp [-p <udp-port>] [-l <buffer-len>]\n"); exit(1); } int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-p") == 0) port = atoi(argv[++i]); else if (strcmp(argv[i], "-l") == 0) buflen = atoi(argv[++i]); else { fprintf(stderr, "Unrecognized option '%s'\n", argv[i]); } } THREAD_CONTEXT context; if (context.udp.bind(port)) { Thread th; // set number of queued packets for thread context.packets.Resize(buflen); if (th.Start(&receivethread, &context)) { while (!quit && th.IsRunning() && !th.HasCompleted()) { PACKET *packet; // see if there is a packet available if ((packet = context.packets.GetReadBuffer()) != NULL) { // data available printf("Packet received at %016" PRINTF_64BIT "uns: %u bytes (delay %016" PRINTF_64BIT "uns)\n", packet->ticks, (uint_t)packet->data.size(), GetNanosecondTicks() - packet->ticks); context.packets.IncrementRead(); } else { // nothing to read usleep(10000); } } th.Stop(); } else fprintf(stderr, "Failed to start thread: %s\n", strerror(errno)); } else fprintf(stderr, "Unable to bind UDP socket to port %u: %s\n", port, strerror(errno)); return 0; } <commit_msg>Fix udp-demo build for Mac/Linux.<commit_after> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #ifndef TARGET_OS_WINDOWS // for usleep() #include <unistd.h> #endif #include <vector> #include <bbcat-base/LoadedVersions.h> #include <bbcat-base/UDPSocket.h> #include <bbcat-base/Thread.h> #include <bbcat-base/LockFreeBuffer.h> using namespace bbcat; // ensure the version numbers of the linked libraries and registered BBC_AUDIOTOOLBOX_REQUIRE(bbcat_base_version); typedef struct { uint64_t ticks; std::vector<uint8_t> data; } PACKET; typedef struct { UDPSocket udp; LockFreeBuffer<PACKET> packets; } THREAD_CONTEXT; // thread routine void *receivethread(Thread& thread, void *arg) { THREAD_CONTEXT& context = *(THREAD_CONTEXT *)arg; UDPSocket& udp = context.udp; printf("Thread started\n"); while (!thread.StopRequested()) { PACKET *packet; sint_t bytes; // wait for UDP data if (udp.wait(200)) { // find out if bytes available if ((bytes = udp.recv(NULL, 0)) > 0) { // try to get a writable buffer if ((packet = context.packets.GetWriteBuffer()) != NULL) { sint_t bytes1; // ensure buffer is big enough for the data if (packet->data.size() < (size_t)bytes) packet->data.resize(bytes); // save time of receive packet->ticks = GetNanosecondTicks(); // receive data if ((bytes1 = udp.recv(&packet->data[0], bytes)) == bytes) { // increment write index context.packets.IncrementWrite(); } else { fprintf(stderr, "Failed to receive %d bytes from UDP socket (received %d bytes)\n", bytes, bytes1); thread.Stop(false); // MUST use false here otherwise the thread will hang waiting for itself to complete! } } else printf("No data slots available!\n"); } else { // probably socket closed fprintf(stderr, "Socket error\n"); thread.Stop(false); // MUST use false here otherwise the thread will hang waiting for itself to complete! } } } printf("Thread complete\n"); return NULL; } // CTRL-C handling bool quit = false; void chkabort(int sig) { (void)sig; quit = true; } int main(int argc, char *argv[]) { uint_t port = 4244, buflen = 100; // allow CTRL-C to gracefully stop program signal(SIGINT, chkabort); // print library versions (the actual loaded versions, if dynamically linked) printf("Versions:\n%s\n", LoadedVersions::Get().GetVersionsList().c_str()); if ((argc >= 2) && ((strcmp(argv[1], "-help") == 0) || (strcmp(argv[1], "-h") == 0))) { fprintf(stderr, "Usage: udp-demp [-p <udp-port>] [-l <buffer-len>]\n"); exit(1); } int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-p") == 0) port = atoi(argv[++i]); else if (strcmp(argv[i], "-l") == 0) buflen = atoi(argv[++i]); else { fprintf(stderr, "Unrecognized option '%s'\n", argv[i]); } } THREAD_CONTEXT context; if (context.udp.bind(port)) { Thread th; // set number of queued packets for thread context.packets.Resize(buflen); if (th.Start(&receivethread, &context)) { while (!quit && th.IsRunning() && !th.HasCompleted()) { PACKET *packet; // see if there is a packet available if ((packet = context.packets.GetReadBuffer()) != NULL) { // data available printf("Packet received at %016" PRINTF_64BIT "uns: %u bytes (delay %016" PRINTF_64BIT "uns)\n", packet->ticks, (uint_t)packet->data.size(), GetNanosecondTicks() - packet->ticks); context.packets.IncrementRead(); } else { // nothing to read usleep(10000); } } th.Stop(); } else fprintf(stderr, "Failed to start thread: %s\n", strerror(errno)); } else fprintf(stderr, "Unable to bind UDP socket to port %u: %s\n", port, strerror(errno)); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <amgcl/amgcl.hpp> #include <amgcl/interp_smoothed_aggr.hpp> #include <amgcl/aggr_plain.hpp> #include <amgcl/level_viennacl.hpp> #ifdef VIENNACL_WITH_OPENCL # include <vexcl/devlist.hpp> #endif #if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_CUDA) # include <viennacl/hyb_matrix.hpp> #else # include <viennacl/compressed_matrix.hpp> #endif #include <viennacl/vector.hpp> #include <viennacl/linalg/cg.hpp> #include "read.hpp" // Simple wrapper around amgcl::solver that provides ViennaCL's preconditioner // interface. struct amg_precond { typedef amgcl::solver< double, int, amgcl::interp::smoothed_aggregation<amgcl::aggr::plain>, #ifdef VIENNACL_WITH_OPENCL amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_HYB> #else amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_CRS> #endif > AMG; typedef typename AMG::params params; // Build AMG hierarchy. template <class matrix> amg_precond(const matrix &A, const params &prm = params()) : amg(A, prm), r(amgcl::sparse::matrix_rows(A)) { std::cout << amg << std::endl; } // Use one V-cycle with zero initial approximation as a preconditioning step. void apply(viennacl::vector<double> &x) const { r.clear(); amg.apply(x, r); viennacl::copy(r, x); } // Build VexCL-based hierarchy: mutable AMG amg; mutable viennacl::vector<double> r; }; int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <problem.dat>" << std::endl; return 1; } amgcl::profiler<> prof; #ifdef VIENNACL_WITH_OPENCL // There is no easy way to select compute device in ViennaCL, so just use // VexCL for that. vex::Context ctx( vex::Filter::Env && vex::Filter::DoublePrecision && vex::Filter::Count(1) ); std::vector<cl_device_id> dev_id(1, ctx.queue(0).getInfo<CL_QUEUE_DEVICE>()()); std::vector<cl_command_queue> queue_id(1, ctx.queue(0)()); viennacl::ocl::setup_context(0, ctx.context(0)(), dev_id, queue_id); std::cout << ctx << std::endl; #endif // Read matrix and rhs from a binary file. std::vector<int> row; std::vector<int> col; std::vector<double> val; std::vector<double> rhs; int n = read_problem(argv[1], row, col, val, rhs); // Wrap the matrix into amgcl::sparse::map: amgcl::sparse::matrix_map<double, int> A( n, n, row.data(), col.data(), val.data() ); // Use K-Cycle on each level to improve convergence: typename amg_precond::AMG::params prm; prm.level.kcycle = 1; // Build the preconditioner. prof.tic("setup"); amg_precond amg(A, prm); prof.toc("setup"); // Copy matrix and rhs to GPU(s). #if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_CUDA) viennacl::hyb_matrix<double> Agpu; #else viennacl::compressed_matrix<double> Agpu; #endif viennacl::copy(amgcl::sparse::viennacl_map(A), Agpu); viennacl::vector<double> f(n); viennacl::fast_copy(rhs, f); // Solve the problem with CG method from ViennaCL. Use AMG as a // preconditioner: prof.tic("solve"); viennacl::linalg::cg_tag tag(1e-8, 100); viennacl::vector<double> x = viennacl::linalg::solve(Agpu, f, tag, amg); prof.toc("solve"); std::cout << "Iterations: " << tag.iters() << std::endl << "Error: " << tag.error() << std::endl; std::cout << prof; #ifdef VIENNACL_WITH_OPENCL // Prevent ViennaCL from segfaulting: exit(0); #endif } <commit_msg>Use viennacl::hyb_matrix for OpenCL _and_ CUDA<commit_after>#include <iostream> #include <cstdlib> #include <amgcl/amgcl.hpp> #include <amgcl/interp_smoothed_aggr.hpp> #include <amgcl/aggr_plain.hpp> #include <amgcl/level_viennacl.hpp> #ifdef VIENNACL_WITH_OPENCL # include <vexcl/devlist.hpp> #endif #if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_CUDA) # include <viennacl/hyb_matrix.hpp> #else # include <viennacl/compressed_matrix.hpp> #endif #include <viennacl/vector.hpp> #include <viennacl/linalg/cg.hpp> #include "read.hpp" // Simple wrapper around amgcl::solver that provides ViennaCL's preconditioner // interface. struct amg_precond { typedef amgcl::solver< double, int, amgcl::interp::smoothed_aggregation<amgcl::aggr::plain>, #if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_CUDA) amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_HYB> #else amgcl::level::ViennaCL<amgcl::level::CL_MATRIX_CRS> #endif > AMG; typedef typename AMG::params params; // Build AMG hierarchy. template <class matrix> amg_precond(const matrix &A, const params &prm = params()) : amg(A, prm), r(amgcl::sparse::matrix_rows(A)) { std::cout << amg << std::endl; } // Use one V-cycle with zero initial approximation as a preconditioning step. void apply(viennacl::vector<double> &x) const { r.clear(); amg.apply(x, r); viennacl::copy(r, x); } // Build VexCL-based hierarchy: mutable AMG amg; mutable viennacl::vector<double> r; }; int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "Usage: " << argv[0] << " <problem.dat>" << std::endl; return 1; } amgcl::profiler<> prof; #ifdef VIENNACL_WITH_OPENCL // There is no easy way to select compute device in ViennaCL, so just use // VexCL for that. vex::Context ctx( vex::Filter::Env && vex::Filter::DoublePrecision && vex::Filter::Count(1) ); std::vector<cl_device_id> dev_id(1, ctx.queue(0).getInfo<CL_QUEUE_DEVICE>()()); std::vector<cl_command_queue> queue_id(1, ctx.queue(0)()); viennacl::ocl::setup_context(0, ctx.context(0)(), dev_id, queue_id); std::cout << ctx << std::endl; #endif // Read matrix and rhs from a binary file. std::vector<int> row; std::vector<int> col; std::vector<double> val; std::vector<double> rhs; int n = read_problem(argv[1], row, col, val, rhs); // Wrap the matrix into amgcl::sparse::map: amgcl::sparse::matrix_map<double, int> A( n, n, row.data(), col.data(), val.data() ); // Use K-Cycle on each level to improve convergence: typename amg_precond::AMG::params prm; prm.level.kcycle = 1; // Build the preconditioner. prof.tic("setup"); amg_precond amg(A, prm); prof.toc("setup"); // Copy matrix and rhs to GPU(s). #if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_CUDA) viennacl::hyb_matrix<double> Agpu; #else viennacl::compressed_matrix<double> Agpu; #endif viennacl::copy(amgcl::sparse::viennacl_map(A), Agpu); viennacl::vector<double> f(n); viennacl::fast_copy(rhs, f); // Solve the problem with CG method from ViennaCL. Use AMG as a // preconditioner: prof.tic("solve"); viennacl::linalg::cg_tag tag(1e-8, 100); viennacl::vector<double> x = viennacl::linalg::solve(Agpu, f, tag, amg); prof.toc("solve"); std::cout << "Iterations: " << tag.iters() << std::endl << "Error: " << tag.error() << std::endl; std::cout << prof; #ifdef VIENNACL_WITH_OPENCL // Prevent ViennaCL from segfaulting: exit(0); #endif } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "Ditch.h" #include "Logger/Logger.h" #include "Basics/MutexLocker.h" #include "VocBase/datafile.h" using namespace arangodb; Ditch::Ditch(Ditches* ditches, char const* filename, int line) : _ditches(ditches), _prev(nullptr), _next(nullptr), _filename(filename), _line(line) {} Ditch::~Ditch() {} /// @brief return the associated collection LogicalCollection* Ditch::collection() const { return _ditches->collection(); } DocumentDitch::DocumentDitch(Ditches* ditches, bool usedByTransaction, char const* filename, int line) : Ditch(ditches, filename, line), _usedByTransaction(usedByTransaction) {} DocumentDitch::~DocumentDitch() {} ReplicationDitch::ReplicationDitch(Ditches* ditches, char const* filename, int line) : Ditch(ditches, filename, line) {} ReplicationDitch::~ReplicationDitch() {} CompactionDitch::CompactionDitch(Ditches* ditches, char const* filename, int line) : Ditch(ditches, filename, line) {} CompactionDitch::~CompactionDitch() {} DropDatafileDitch::DropDatafileDitch( Ditches* ditches, TRI_datafile_t* datafile, LogicalCollection* collection, std::function<void(TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) : Ditch(ditches, filename, line), _datafile(datafile), _collection(collection), _callback(callback) {} DropDatafileDitch::~DropDatafileDitch() { delete _datafile; } RenameDatafileDitch::RenameDatafileDitch( Ditches* ditches, TRI_datafile_t* datafile, TRI_datafile_t* compactor, LogicalCollection* collection, std::function<void(TRI_datafile_t*, TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) : Ditch(ditches, filename, line), _datafile(datafile), _compactor(compactor), _collection(collection), _callback(callback) {} RenameDatafileDitch::~RenameDatafileDitch() {} UnloadCollectionDitch::UnloadCollectionDitch( Ditches* ditches, LogicalCollection* collection, std::function<bool(LogicalCollection*)> const& callback, char const* filename, int line) : Ditch(ditches, filename, line), _collection(collection), _callback(callback) {} UnloadCollectionDitch::~UnloadCollectionDitch() {} DropCollectionDitch::DropCollectionDitch( Ditches* ditches, arangodb::LogicalCollection* collection, std::function<bool(arangodb::LogicalCollection*)> callback, char const* filename, int line) : Ditch(ditches, filename, line), _collection(collection), _callback(callback) {} DropCollectionDitch::~DropCollectionDitch() {} Ditches::Ditches(LogicalCollection* collection) : _collection(collection), _lock(), _begin(nullptr), _end(nullptr), _numDocumentDitches(0) { TRI_ASSERT(_collection != nullptr); } Ditches::~Ditches() { destroy(); } /// @brief destroy the ditches - to be called on shutdown only void Ditches::destroy() { MUTEX_LOCKER(mutexLocker, _lock); auto* ptr = _begin; while (ptr != nullptr) { auto* next = ptr->next(); auto const type = ptr->type(); if (type == Ditch::TRI_DITCH_COLLECTION_UNLOAD || type == Ditch::TRI_DITCH_COLLECTION_DROP || type == Ditch::TRI_DITCH_DATAFILE_DROP || type == Ditch::TRI_DITCH_DATAFILE_RENAME || type == Ditch::TRI_DITCH_REPLICATION || type == Ditch::TRI_DITCH_COMPACTION) { delete ptr; } else if (type == Ditch::TRI_DITCH_DOCUMENT) { LOG(ERR) << "logic error. shouldn't have document ditches on unload"; } else { LOG(ERR) << "unknown ditch type"; } ptr = next; } } /// @brief return the associated collection LogicalCollection* Ditches::collection() const { return _collection; } /// @brief run a user-defined function under the lock void Ditches::executeProtected(std::function<void()> callback) { MUTEX_LOCKER(mutexLocker, _lock); callback(); } /// @brief process the first element from the list /// the list will remain unchanged if the first element is either a /// DocumentDitch, a ReplicationDitch or a CompactionDitch, or if the list /// contains any DocumentDitches. Ditch* Ditches::process(bool& popped, std::function<bool(Ditch const*)> callback) { popped = false; MUTEX_LOCKER(mutexLocker, _lock); auto ditch = _begin; if (ditch == nullptr) { // nothing to do return nullptr; } TRI_ASSERT(ditch != nullptr); auto const type = ditch->type(); // if it is a DocumentDitch, it means that there is still a reference held // to document data in a datafile. We must then not unload or remove a file if (type == Ditch::TRI_DITCH_DOCUMENT || type == Ditch::TRI_DITCH_REPLICATION || type == Ditch::TRI_DITCH_COMPACTION || _numDocumentDitches > 0) { // did not find anything at the head of the barrier list or found an element // marker // this means we must exit and cannot throw away datafiles and can unload // collections return nullptr; } // no DocumentDitch at the head of the ditches list. This means that there is // some other action we can perform (i.e. unloading a datafile or a // collection) // note that there is no need to check the entire list for a DocumentDitch as // the list is filled up in chronological order. New ditches are always added // to the // tail of the list, and if we have the following list // HEAD -> TRI_DITCH_DATAFILE_CALLBACK -> TRI_DITCH_DOCUMENT // then it is still safe to execute the datafile callback operation, even if // there // is a TRI_DITCH_DOCUMENT after it. // This is the case because the TRI_DITCH_DATAFILE_CALLBACK is only put into // the // ditches list after changing the pointers in all headers. After the pointers // are // changed, it is safe to unload/remove an old datafile (that noone points // to). And // any newer TRI_DITCH_DOCUMENTs will always reference data inside other // datafiles. if (!callback(ditch)) { return ditch; } // found an element to go on with - now unlink the element from the list unlink(ditch); popped = true; return ditch; } /// @brief return the type name of the ditch at the head of the active ditches char const* Ditches::head() { MUTEX_LOCKER(mutexLocker, _lock); auto ditch = _begin; if (ditch == nullptr) { return nullptr; } return ditch->typeName(); } /// @brief return the number of document ditches active uint64_t Ditches::numDocumentDitches() { MUTEX_LOCKER(mutexLocker, _lock); return _numDocumentDitches; } /// @brief check whether the ditches contain a ditch of a certain type bool Ditches::contains(Ditch::DitchType type) { MUTEX_LOCKER(mutexLocker, _lock); if (type == Ditch::TRI_DITCH_DOCUMENT) { // shortcut return (_numDocumentDitches > 0); } auto const* ptr = _begin; while (ptr != nullptr) { if (ptr->type() == type) { return true; } ptr = ptr->_next; } return false; } /// @brief removes and frees a ditch void Ditches::freeDitch(Ditch* ditch) { TRI_ASSERT(ditch != nullptr); { MUTEX_LOCKER(mutexLocker, _lock); unlink(ditch); if (ditch->type() == Ditch::TRI_DITCH_DOCUMENT) { // decrease counter --_numDocumentDitches; } } delete ditch; } /// @brief removes and frees a ditch /// this is used for ditches used by transactions or by externals to protect /// the flags by the lock void Ditches::freeDocumentDitch(DocumentDitch* ditch, bool fromTransaction) { TRI_ASSERT(ditch != nullptr); // First see who might still be using the ditch: if (fromTransaction) { TRI_ASSERT(ditch->usedByTransaction() == true); } { MUTEX_LOCKER(mutexLocker, _lock); unlink(ditch); // decrease counter --_numDocumentDitches; } delete ditch; } /// @brief creates a new document ditch and links it DocumentDitch* Ditches::createDocumentDitch(bool usedByTransaction, char const* filename, int line) { try { auto ditch = new DocumentDitch(this, usedByTransaction, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new replication ditch and links it ReplicationDitch* Ditches::createReplicationDitch(char const* filename, int line) { try { auto ditch = new ReplicationDitch(this, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new compaction ditch and links it CompactionDitch* Ditches::createCompactionDitch(char const* filename, int line) { try { auto ditch = new CompactionDitch(this, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new datafile deletion ditch DropDatafileDitch* Ditches::createDropDatafileDitch( TRI_datafile_t* datafile, LogicalCollection* collection, std::function<void(TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) { try { auto ditch = new DropDatafileDitch(this, datafile, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new datafile rename ditch RenameDatafileDitch* Ditches::createRenameDatafileDitch( TRI_datafile_t* datafile, TRI_datafile_t* compactor, LogicalCollection* collection, std::function<void(TRI_datafile_t*, TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) { try { auto ditch = new RenameDatafileDitch(this, datafile, compactor, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new collection unload ditch UnloadCollectionDitch* Ditches::createUnloadCollectionDitch( LogicalCollection* collection, std::function<bool(LogicalCollection*)> const& callback, char const* filename, int line) { try { auto ditch = new UnloadCollectionDitch(this, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new datafile drop ditch DropCollectionDitch* Ditches::createDropCollectionDitch( arangodb::LogicalCollection* collection, std::function<bool(arangodb::LogicalCollection*)> callback, char const* filename, int line) { try { auto ditch = new DropCollectionDitch(this, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief inserts the ditch into the linked list of ditches void Ditches::link(Ditch* ditch) { TRI_ASSERT(ditch != nullptr); ditch->_next = nullptr; ditch->_prev = nullptr; bool const isDocumentDitch = (ditch->type() == Ditch::TRI_DITCH_DOCUMENT); MUTEX_LOCKER(mutexLocker, _lock); // FIX_MUTEX // empty list if (_end == nullptr) { _begin = ditch; _end = ditch; } // add to the end else { ditch->_prev = _end; _end->_next = ditch; _end = ditch; } if (isDocumentDitch) { // increase counter ++_numDocumentDitches; } } /// @brief unlinks the ditch from the linked list of ditches void Ditches::unlink(Ditch* ditch) { // ditch is at the beginning of the chain if (ditch->_prev == nullptr) { _begin = ditch->_next; } else { ditch->_prev->_next = ditch->_next; } // ditch is at the end of the chain if (ditch->_next == nullptr) { _end = ditch->_prev; } else { ditch->_next->_prev = ditch->_prev; } } <commit_msg>simplify<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "Ditch.h" #include "Logger/Logger.h" #include "Basics/MutexLocker.h" #include "VocBase/datafile.h" using namespace arangodb; Ditch::Ditch(Ditches* ditches, char const* filename, int line) : _ditches(ditches), _prev(nullptr), _next(nullptr), _filename(filename), _line(line) {} Ditch::~Ditch() {} /// @brief return the associated collection LogicalCollection* Ditch::collection() const { return _ditches->collection(); } DocumentDitch::DocumentDitch(Ditches* ditches, bool usedByTransaction, char const* filename, int line) : Ditch(ditches, filename, line), _usedByTransaction(usedByTransaction) {} DocumentDitch::~DocumentDitch() {} ReplicationDitch::ReplicationDitch(Ditches* ditches, char const* filename, int line) : Ditch(ditches, filename, line) {} ReplicationDitch::~ReplicationDitch() {} CompactionDitch::CompactionDitch(Ditches* ditches, char const* filename, int line) : Ditch(ditches, filename, line) {} CompactionDitch::~CompactionDitch() {} DropDatafileDitch::DropDatafileDitch( Ditches* ditches, TRI_datafile_t* datafile, LogicalCollection* collection, std::function<void(TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) : Ditch(ditches, filename, line), _datafile(datafile), _collection(collection), _callback(callback) {} DropDatafileDitch::~DropDatafileDitch() { delete _datafile; } RenameDatafileDitch::RenameDatafileDitch( Ditches* ditches, TRI_datafile_t* datafile, TRI_datafile_t* compactor, LogicalCollection* collection, std::function<void(TRI_datafile_t*, TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) : Ditch(ditches, filename, line), _datafile(datafile), _compactor(compactor), _collection(collection), _callback(callback) {} RenameDatafileDitch::~RenameDatafileDitch() {} UnloadCollectionDitch::UnloadCollectionDitch( Ditches* ditches, LogicalCollection* collection, std::function<bool(LogicalCollection*)> const& callback, char const* filename, int line) : Ditch(ditches, filename, line), _collection(collection), _callback(callback) {} UnloadCollectionDitch::~UnloadCollectionDitch() {} DropCollectionDitch::DropCollectionDitch( Ditches* ditches, arangodb::LogicalCollection* collection, std::function<bool(arangodb::LogicalCollection*)> callback, char const* filename, int line) : Ditch(ditches, filename, line), _collection(collection), _callback(callback) {} DropCollectionDitch::~DropCollectionDitch() {} Ditches::Ditches(LogicalCollection* collection) : _collection(collection), _lock(), _begin(nullptr), _end(nullptr), _numDocumentDitches(0) { TRI_ASSERT(_collection != nullptr); } Ditches::~Ditches() { destroy(); } /// @brief destroy the ditches - to be called on shutdown only void Ditches::destroy() { MUTEX_LOCKER(mutexLocker, _lock); auto* ptr = _begin; while (ptr != nullptr) { auto* next = ptr->next(); auto const type = ptr->type(); if (type == Ditch::TRI_DITCH_COLLECTION_UNLOAD || type == Ditch::TRI_DITCH_COLLECTION_DROP || type == Ditch::TRI_DITCH_DATAFILE_DROP || type == Ditch::TRI_DITCH_DATAFILE_RENAME || type == Ditch::TRI_DITCH_REPLICATION || type == Ditch::TRI_DITCH_COMPACTION) { delete ptr; } else if (type == Ditch::TRI_DITCH_DOCUMENT) { LOG(ERR) << "logic error. shouldn't have document ditches on unload"; } else { LOG(ERR) << "unknown ditch type"; } ptr = next; } } /// @brief return the associated collection LogicalCollection* Ditches::collection() const { return _collection; } /// @brief run a user-defined function under the lock void Ditches::executeProtected(std::function<void()> callback) { MUTEX_LOCKER(mutexLocker, _lock); callback(); } /// @brief process the first element from the list /// the list will remain unchanged if the first element is either a /// DocumentDitch, a ReplicationDitch or a CompactionDitch, or if the list /// contains any DocumentDitches. Ditch* Ditches::process(bool& popped, std::function<bool(Ditch const*)> callback) { popped = false; MUTEX_LOCKER(mutexLocker, _lock); auto ditch = _begin; if (ditch == nullptr) { // nothing to do return nullptr; } TRI_ASSERT(ditch != nullptr); auto const type = ditch->type(); // if it is a DocumentDitch, it means that there is still a reference held // to document data in a datafile. We must then not unload or remove a file if (type == Ditch::TRI_DITCH_DOCUMENT || type == Ditch::TRI_DITCH_REPLICATION || type == Ditch::TRI_DITCH_COMPACTION || _numDocumentDitches > 0) { // did not find anything at the head of the barrier list or found an element // marker // this means we must exit and cannot throw away datafiles and can unload // collections return nullptr; } // no DocumentDitch at the head of the ditches list. This means that there is // some other action we can perform (i.e. unloading a datafile or a // collection) // note that there is no need to check the entire list for a DocumentDitch as // the list is filled up in chronological order. New ditches are always added // to the // tail of the list, and if we have the following list // HEAD -> TRI_DITCH_DATAFILE_CALLBACK -> TRI_DITCH_DOCUMENT // then it is still safe to execute the datafile callback operation, even if // there // is a TRI_DITCH_DOCUMENT after it. // This is the case because the TRI_DITCH_DATAFILE_CALLBACK is only put into // the // ditches list after changing the pointers in all headers. After the pointers // are // changed, it is safe to unload/remove an old datafile (that noone points // to). And // any newer TRI_DITCH_DOCUMENTs will always reference data inside other // datafiles. if (!callback(ditch)) { return ditch; } // found an element to go on with - now unlink the element from the list unlink(ditch); popped = true; return ditch; } /// @brief return the type name of the ditch at the head of the active ditches char const* Ditches::head() { MUTEX_LOCKER(mutexLocker, _lock); auto ditch = _begin; if (ditch == nullptr) { return nullptr; } return ditch->typeName(); } /// @brief return the number of document ditches active uint64_t Ditches::numDocumentDitches() { MUTEX_LOCKER(mutexLocker, _lock); return _numDocumentDitches; } /// @brief check whether the ditches contain a ditch of a certain type bool Ditches::contains(Ditch::DitchType type) { MUTEX_LOCKER(mutexLocker, _lock); if (type == Ditch::TRI_DITCH_DOCUMENT) { // shortcut return (_numDocumentDitches > 0); } auto const* ptr = _begin; while (ptr != nullptr) { if (ptr->type() == type) { return true; } ptr = ptr->_next; } return false; } /// @brief removes and frees a ditch void Ditches::freeDitch(Ditch* ditch) { TRI_ASSERT(ditch != nullptr); bool const isDocumentDitch = (ditch->type() == Ditch::TRI_DITCH_DOCUMENT); { MUTEX_LOCKER(mutexLocker, _lock); unlink(ditch); if (isDocumentDitch) { // decrease counter --_numDocumentDitches; } } delete ditch; } /// @brief removes and frees a ditch /// this is used for ditches used by transactions or by externals to protect /// the flags by the lock void Ditches::freeDocumentDitch(DocumentDitch* ditch, bool fromTransaction) { TRI_ASSERT(ditch != nullptr); // First see who might still be using the ditch: if (fromTransaction) { TRI_ASSERT(ditch->usedByTransaction() == true); } { MUTEX_LOCKER(mutexLocker, _lock); unlink(ditch); // decrease counter --_numDocumentDitches; } delete ditch; } /// @brief creates a new document ditch and links it DocumentDitch* Ditches::createDocumentDitch(bool usedByTransaction, char const* filename, int line) { try { auto ditch = new DocumentDitch(this, usedByTransaction, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new replication ditch and links it ReplicationDitch* Ditches::createReplicationDitch(char const* filename, int line) { try { auto ditch = new ReplicationDitch(this, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new compaction ditch and links it CompactionDitch* Ditches::createCompactionDitch(char const* filename, int line) { try { auto ditch = new CompactionDitch(this, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new datafile deletion ditch DropDatafileDitch* Ditches::createDropDatafileDitch( TRI_datafile_t* datafile, LogicalCollection* collection, std::function<void(TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) { try { auto ditch = new DropDatafileDitch(this, datafile, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new datafile rename ditch RenameDatafileDitch* Ditches::createRenameDatafileDitch( TRI_datafile_t* datafile, TRI_datafile_t* compactor, LogicalCollection* collection, std::function<void(TRI_datafile_t*, TRI_datafile_t*, LogicalCollection*)> const& callback, char const* filename, int line) { try { auto ditch = new RenameDatafileDitch(this, datafile, compactor, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new collection unload ditch UnloadCollectionDitch* Ditches::createUnloadCollectionDitch( LogicalCollection* collection, std::function<bool(LogicalCollection*)> const& callback, char const* filename, int line) { try { auto ditch = new UnloadCollectionDitch(this, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief creates a new datafile drop ditch DropCollectionDitch* Ditches::createDropCollectionDitch( arangodb::LogicalCollection* collection, std::function<bool(arangodb::LogicalCollection*)> callback, char const* filename, int line) { try { auto ditch = new DropCollectionDitch(this, collection, callback, filename, line); link(ditch); return ditch; } catch (...) { return nullptr; } } /// @brief inserts the ditch into the linked list of ditches void Ditches::link(Ditch* ditch) { TRI_ASSERT(ditch != nullptr); ditch->_next = nullptr; ditch->_prev = nullptr; bool const isDocumentDitch = (ditch->type() == Ditch::TRI_DITCH_DOCUMENT); MUTEX_LOCKER(mutexLocker, _lock); // FIX_MUTEX // empty list if (_end == nullptr) { _begin = ditch; } // add to the end else { ditch->_prev = _end; _end->_next = ditch; } _end = ditch; if (isDocumentDitch) { // increase counter ++_numDocumentDitches; } } /// @brief unlinks the ditch from the linked list of ditches void Ditches::unlink(Ditch* ditch) { // ditch is at the beginning of the chain if (ditch->_prev == nullptr) { _begin = ditch->_next; } else { ditch->_prev->_next = ditch->_next; } // ditch is at the end of the chain if (ditch->_next == nullptr) { _end = ditch->_prev; } else { ditch->_next->_prev = ditch->_prev; } } <|endoftext|>
<commit_before>//===--- InitHeaderSearch.cpp - Initialize header search paths ----------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the InitHeaderSearch class. // //===----------------------------------------------------------------------===// #include "clang/Driver/InitHeaderSearch.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/System/Path.h" #include "llvm/Config/config.h" #include <vector> using namespace clang; void InitHeaderSearch::AddPath(const std::string &Path, IncludeDirGroup Group, bool isCXXAware, bool isUserSupplied, bool isFramework) { assert(!Path.empty() && "can't handle empty path here"); FileManager &FM = Headers.getFileMgr(); // Compute the actual path, taking into consideration -isysroot. llvm::SmallString<256> MappedPath; // Handle isysroot. if (Group == System) { // FIXME: Portability. This should be a sys::Path interface, this doesn't // handle things like C:\ right, nor win32 \\network\device\blah. if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present. MappedPath.append(isysroot.begin(), isysroot.end()); } MappedPath.append(Path.begin(), Path.end()); // Compute the DirectoryLookup type. SrcMgr::CharacteristicKind Type; if (Group == Quoted || Group == Angled) Type = SrcMgr::C_User; else if (isCXXAware) Type = SrcMgr::C_System; else Type = SrcMgr::C_ExternCSystem; // If the directory exists, add it. if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0], &MappedPath[0]+ MappedPath.size())) { IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied, isFramework)); return; } // Check to see if this is an apple-style headermap (which are not allowed to // be frameworks). if (!isFramework) { if (const FileEntry *FE = FM.getFile(&MappedPath[0], &MappedPath[0]+MappedPath.size())) { if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) { // It is a headermap, add it to the search path. IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied)); return; } } } if (Verbose) fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str()); } void InitHeaderSearch::AddEnvVarPaths(const char *Name) { const char* at = getenv(Name); if (!at || *at == 0) // Empty string should not add '.' path. return; const char* delim = strchr(at, llvm::sys::PathSeparator); while (delim != 0) { if (delim-at == 0) AddPath(".", Angled, false, true, false); else AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false, true, false); at = delim + 1; delim = strchr(at, llvm::sys::PathSeparator); } if (*at == 0) AddPath(".", Angled, false, true, false); else AddPath(at, Angled, false, true, false); } void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang) { // FIXME: temporary hack: hard-coded paths. // FIXME: get these from the target? #ifdef LLVM_ON_WIN32 if (Lang.CPlusPlus) { // Mingw32 GCC version 4 AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++", System, true, false, false); AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/mingw32", System, true, false, false); AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/backward", System, true, false, false); } // Mingw32 GCC version 4 AddPath("C:/mingw/lib/gcc/mingw32/4.3.0/include", System, false, false, false); AddPath("C:/mingw/include", System, false, false, false); #else if (Lang.CPlusPlus) { AddPath("/usr/include/c++/4.2.1", System, true, false, false); AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false, false); AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false); AddPath("/usr/include/c++/4.0.0", System, true, false, false); AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false, false); AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false); // Ubuntu 7.10 - Gutsy Gibbon AddPath("/usr/include/c++/4.1.3", System, true, false, false); AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false, false); AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false); // Fedora 8 AddPath("/usr/include/c++/4.1.2", System, true, false, false); AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false); // Fedora 9 AddPath("/usr/include/c++/4.3.0", System, true, false, false); AddPath("/usr/include/c++/4.3.0/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.3.0/backward", System, true, false, false); // Fedora 10 AddPath("/usr/include/c++/4.3.2", System, true, false, false); AddPath("/usr/include/c++/4.3.2/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.3.2/backward", System, true, false, false); // Arch Linux 2008-06-24 AddPath("/usr/include/c++/4.3.1", System, true, false, false); AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false, false); AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false); AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true, false, false); // Gentoo x86 stable AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4", System, true, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/" "i686-pc-linux-gnu", System, true, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/backward", System, true, false, false); // DragonFly AddPath("/usr/include/c++/4.1", System, true, false, false); } AddPath("/usr/local/include", System, false, false, false); AddPath("/usr/lib/gcc/i686-apple-darwin10/4.2.1/include", System, false, false, false); AddPath("/usr/lib/gcc/powerpc-apple-darwin10/4.2.1/include", System, false, false, false); // leopard AddPath("/usr/lib/gcc/i686-apple-darwin9/4.0.1/include", System, false, false, false); AddPath("/usr/lib/gcc/powerpc-apple-darwin9/4.0.1/include", System, false, false, false); AddPath("/usr/lib/gcc/powerpc-apple-darwin9/" "4.0.1/../../../../powerpc-apple-darwin0/include", System, false, false, false); // tiger AddPath("/usr/lib/gcc/i686-apple-darwin8/4.0.1/include", System, false, false, false); AddPath("/usr/lib/gcc/powerpc-apple-darwin8/4.0.1/include", System, false, false, false); AddPath("/usr/lib/gcc/powerpc-apple-darwin8/" "4.0.1/../../../../powerpc-apple-darwin8/include", System, false, false, false); // Ubuntu 7.10 - Gutsy Gibbon AddPath("/usr/lib/gcc/i486-linux-gnu/4.1.3/include", System, false, false, false); // Fedora 8 AddPath("/usr/lib/gcc/i386-redhat-linux/4.1.2/include", System, false, false, false); // Fedora 9 AddPath("/usr/lib/gcc/i386-redhat-linux/4.3.0/include", System, false, false, false); // Fedora 10 AddPath("/usr/lib/gcc/i386-redhat-linux/4.3.2/include", System, false, false, false); //Debian testing/lenny x86 AddPath("/usr/lib/gcc/i486-linux-gnu/4.2.3/include", System, false, false, false); //Debian testing/lenny amd64 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/include", System, false, false, false); // Debian sid amd64 AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.3/include", System, false, false, false); AddPath("/usr/lib/gcc/x86_64-linux-gnu/4.3/include-fixed", System, false, false, false); // Arch Linux 2008-06-24 AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include", System, false, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.3.1/include-fixed", System, false, false, false); AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include", System, false, false, false); AddPath("/usr/lib/gcc/x86_64-unknown-linux-gnu/4.3.1/include-fixed", System, false, false, false); // Debian testing/lenny ppc32 AddPath("/usr/lib/gcc/powerpc-linux-gnu/4.2.3/include", System, false, false, false); // Gentoo x86 stable AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include", System, false, false, false); // DragonFly AddPath("/usr/libdata/gcc41", System, true, false, false); AddPath("/usr/include", System, false, false, false); AddPath("/System/Library/Frameworks", System, true, false, true); AddPath("/Library/Frameworks", System, true, false, true); #endif } void InitHeaderSearch::AddDefaultEnvVarPaths(const LangOptions &Lang) { AddEnvVarPaths("CPATH"); if (Lang.CPlusPlus && Lang.ObjC1) AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH"); else if (Lang.CPlusPlus) AddEnvVarPaths("CPLUS_INCLUDE_PATH"); else if (Lang.ObjC1) AddEnvVarPaths("OBJC_INCLUDE_PATH"); else AddEnvVarPaths("C_INCLUDE_PATH"); } /// RemoveDuplicates - If there are duplicate directory entries in the specified /// search list, remove the later (dead) ones. static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList, bool Verbose) { llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs; llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs; llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps; for (unsigned i = 0; i != SearchList.size(); ++i) { unsigned DirToRemove = i; const DirectoryLookup &CurEntry = SearchList[i]; if (CurEntry.isNormalDir()) { // If this isn't the first time we've seen this dir, remove it. if (SeenDirs.insert(CurEntry.getDir())) continue; } else if (CurEntry.isFramework()) { // If this isn't the first time we've seen this framework dir, remove it. if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir())) continue; } else { assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); // If this isn't the first time we've seen this headermap, remove it. if (SeenHeaderMaps.insert(CurEntry.getHeaderMap())) continue; } // If we have a normal #include dir/framework/headermap that is shadowed // later in the chain by a system include location, we actually want to // ignore the user's request and drop the user dir... keeping the system // dir. This is weird, but required to emulate GCC's search path correctly. // // Since dupes of system dirs are rare, just rescan to find the original // that we're nuking instead of using a DenseMap. if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) { // Find the dir that this is the same of. unsigned FirstDir; for (FirstDir = 0; ; ++FirstDir) { assert(FirstDir != i && "Didn't find dupe?"); const DirectoryLookup &SearchEntry = SearchList[FirstDir]; // If these are different lookup types, then they can't be the dupe. if (SearchEntry.getLookupType() != CurEntry.getLookupType()) continue; bool isSame; if (CurEntry.isNormalDir()) isSame = SearchEntry.getDir() == CurEntry.getDir(); else if (CurEntry.isFramework()) isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir(); else { assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap(); } if (isSame) break; } // If the first dir in the search path is a non-system dir, zap it // instead of the system one. if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User) DirToRemove = FirstDir; } if (Verbose) { fprintf(stderr, "ignoring duplicate directory \"%s\"\n", CurEntry.getName()); if (DirToRemove != i) fprintf(stderr, " as it is a non-system directory that duplicates" " a system directory\n"); } // This is reached if the current entry is a duplicate. Remove the // DirToRemove (usually the current dir). SearchList.erase(SearchList.begin()+DirToRemove); --i; } } void InitHeaderSearch::Realize() { // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList. std::vector<DirectoryLookup> SearchList; SearchList = IncludeGroup[Angled]; SearchList.insert(SearchList.end(), IncludeGroup[System].begin(), IncludeGroup[System].end()); SearchList.insert(SearchList.end(), IncludeGroup[After].begin(), IncludeGroup[After].end()); RemoveDuplicates(SearchList, Verbose); RemoveDuplicates(IncludeGroup[Quoted], Verbose); // Prepend QUOTED list on the search list. SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(), IncludeGroup[Quoted].end()); bool DontSearchCurDir = false; // TODO: set to true if -I- is set? Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(), DontSearchCurDir); // If verbose, print the list of directories that will be searched. if (Verbose) { fprintf(stderr, "#include \"...\" search starts here:\n"); unsigned QuotedIdx = IncludeGroup[Quoted].size(); for (unsigned i = 0, e = SearchList.size(); i != e; ++i) { if (i == QuotedIdx) fprintf(stderr, "#include <...> search starts here:\n"); const char *Name = SearchList[i].getName(); const char *Suffix; if (SearchList[i].isNormalDir()) Suffix = ""; else if (SearchList[i].isFramework()) Suffix = " (framework directory)"; else { assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup"); Suffix = " (headermap)"; } fprintf(stderr, " %s%s\n", Name, Suffix); } fprintf(stderr, "End of search list.\n"); } } <commit_msg>stop searching GCC install directories for standard C headers (but keep searching for C++ headers when in C++ mode). In theory clang should be able to find all of its own headers now. If not, the CPATH or C_INCLUDE_PATH environment variables can be specified to add a include path.<commit_after>//===--- InitHeaderSearch.cpp - Initialize header search paths ----------*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the InitHeaderSearch class. // //===----------------------------------------------------------------------===// #include "clang/Driver/InitHeaderSearch.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/System/Path.h" #include "llvm/Config/config.h" #include <vector> using namespace clang; void InitHeaderSearch::AddPath(const std::string &Path, IncludeDirGroup Group, bool isCXXAware, bool isUserSupplied, bool isFramework) { assert(!Path.empty() && "can't handle empty path here"); FileManager &FM = Headers.getFileMgr(); // Compute the actual path, taking into consideration -isysroot. llvm::SmallString<256> MappedPath; // Handle isysroot. if (Group == System) { // FIXME: Portability. This should be a sys::Path interface, this doesn't // handle things like C:\ right, nor win32 \\network\device\blah. if (isysroot.size() != 1 || isysroot[0] != '/') // Add isysroot if present. MappedPath.append(isysroot.begin(), isysroot.end()); } MappedPath.append(Path.begin(), Path.end()); // Compute the DirectoryLookup type. SrcMgr::CharacteristicKind Type; if (Group == Quoted || Group == Angled) Type = SrcMgr::C_User; else if (isCXXAware) Type = SrcMgr::C_System; else Type = SrcMgr::C_ExternCSystem; // If the directory exists, add it. if (const DirectoryEntry *DE = FM.getDirectory(&MappedPath[0], &MappedPath[0]+ MappedPath.size())) { IncludeGroup[Group].push_back(DirectoryLookup(DE, Type, isUserSupplied, isFramework)); return; } // Check to see if this is an apple-style headermap (which are not allowed to // be frameworks). if (!isFramework) { if (const FileEntry *FE = FM.getFile(&MappedPath[0], &MappedPath[0]+MappedPath.size())) { if (const HeaderMap *HM = Headers.CreateHeaderMap(FE)) { // It is a headermap, add it to the search path. IncludeGroup[Group].push_back(DirectoryLookup(HM, Type,isUserSupplied)); return; } } } if (Verbose) fprintf(stderr, "ignoring nonexistent directory \"%s\"\n", Path.c_str()); } void InitHeaderSearch::AddEnvVarPaths(const char *Name) { const char* at = getenv(Name); if (!at || *at == 0) // Empty string should not add '.' path. return; const char* delim = strchr(at, llvm::sys::PathSeparator); while (delim != 0) { if (delim-at == 0) AddPath(".", Angled, false, true, false); else AddPath(std::string(at, std::string::size_type(delim-at)), Angled, false, true, false); at = delim + 1; delim = strchr(at, llvm::sys::PathSeparator); } if (*at == 0) AddPath(".", Angled, false, true, false); else AddPath(at, Angled, false, true, false); } void InitHeaderSearch::AddDefaultSystemIncludePaths(const LangOptions &Lang) { // FIXME: temporary hack: hard-coded paths. // FIXME: get these from the target? #ifdef LLVM_ON_WIN32 if (Lang.CPlusPlus) { // Mingw32 GCC version 4 AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++", System, true, false, false); AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/mingw32", System, true, false, false); AddPath("c:/mingw/lib/gcc/mingw32/4.3.0/include/c++/backward", System, true, false, false); } // Mingw32 GCC version 4 AddPath("C:/mingw/include", System, false, false, false); #else if (Lang.CPlusPlus) { AddPath("/usr/include/c++/4.2.1", System, true, false, false); AddPath("/usr/include/c++/4.2.1/i686-apple-darwin10", System, true, false, false); AddPath("/usr/include/c++/4.2.1/backward", System, true, false, false); AddPath("/usr/include/c++/4.0.0", System, true, false, false); AddPath("/usr/include/c++/4.0.0/i686-apple-darwin8", System, true, false, false); AddPath("/usr/include/c++/4.0.0/backward", System, true, false, false); // Ubuntu 7.10 - Gutsy Gibbon AddPath("/usr/include/c++/4.1.3", System, true, false, false); AddPath("/usr/include/c++/4.1.3/i486-linux-gnu", System, true, false, false); AddPath("/usr/include/c++/4.1.3/backward", System, true, false, false); // Fedora 8 AddPath("/usr/include/c++/4.1.2", System, true, false, false); AddPath("/usr/include/c++/4.1.2/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.1.2/backward", System, true, false, false); // Fedora 9 AddPath("/usr/include/c++/4.3.0", System, true, false, false); AddPath("/usr/include/c++/4.3.0/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.3.0/backward", System, true, false, false); // Fedora 10 AddPath("/usr/include/c++/4.3.2", System, true, false, false); AddPath("/usr/include/c++/4.3.2/i386-redhat-linux", System, true, false, false); AddPath("/usr/include/c++/4.3.2/backward", System, true, false, false); // Arch Linux 2008-06-24 AddPath("/usr/include/c++/4.3.1", System, true, false, false); AddPath("/usr/include/c++/4.3.1/i686-pc-linux-gnu", System, true, false, false); AddPath("/usr/include/c++/4.3.1/backward", System, true, false, false); AddPath("/usr/include/c++/4.3.1/x86_64-unknown-linux-gnu", System, true, false, false); // Gentoo x86 stable AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4", System, true, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/" "i686-pc-linux-gnu", System, true, false, false); AddPath("/usr/lib/gcc/i686-pc-linux-gnu/4.1.2/include/g++-v4/backward", System, true, false, false); // DragonFly AddPath("/usr/include/c++/4.1", System, true, false, false); } AddPath("/usr/local/include", System, false, false, false); AddPath("/usr/include", System, false, false, false); AddPath("/System/Library/Frameworks", System, true, false, true); AddPath("/Library/Frameworks", System, true, false, true); #endif } void InitHeaderSearch::AddDefaultEnvVarPaths(const LangOptions &Lang) { AddEnvVarPaths("CPATH"); if (Lang.CPlusPlus && Lang.ObjC1) AddEnvVarPaths("OBJCPLUS_INCLUDE_PATH"); else if (Lang.CPlusPlus) AddEnvVarPaths("CPLUS_INCLUDE_PATH"); else if (Lang.ObjC1) AddEnvVarPaths("OBJC_INCLUDE_PATH"); else AddEnvVarPaths("C_INCLUDE_PATH"); } /// RemoveDuplicates - If there are duplicate directory entries in the specified /// search list, remove the later (dead) ones. static void RemoveDuplicates(std::vector<DirectoryLookup> &SearchList, bool Verbose) { llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenDirs; llvm::SmallPtrSet<const DirectoryEntry *, 8> SeenFrameworkDirs; llvm::SmallPtrSet<const HeaderMap *, 8> SeenHeaderMaps; for (unsigned i = 0; i != SearchList.size(); ++i) { unsigned DirToRemove = i; const DirectoryLookup &CurEntry = SearchList[i]; if (CurEntry.isNormalDir()) { // If this isn't the first time we've seen this dir, remove it. if (SeenDirs.insert(CurEntry.getDir())) continue; } else if (CurEntry.isFramework()) { // If this isn't the first time we've seen this framework dir, remove it. if (SeenFrameworkDirs.insert(CurEntry.getFrameworkDir())) continue; } else { assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); // If this isn't the first time we've seen this headermap, remove it. if (SeenHeaderMaps.insert(CurEntry.getHeaderMap())) continue; } // If we have a normal #include dir/framework/headermap that is shadowed // later in the chain by a system include location, we actually want to // ignore the user's request and drop the user dir... keeping the system // dir. This is weird, but required to emulate GCC's search path correctly. // // Since dupes of system dirs are rare, just rescan to find the original // that we're nuking instead of using a DenseMap. if (CurEntry.getDirCharacteristic() != SrcMgr::C_User) { // Find the dir that this is the same of. unsigned FirstDir; for (FirstDir = 0; ; ++FirstDir) { assert(FirstDir != i && "Didn't find dupe?"); const DirectoryLookup &SearchEntry = SearchList[FirstDir]; // If these are different lookup types, then they can't be the dupe. if (SearchEntry.getLookupType() != CurEntry.getLookupType()) continue; bool isSame; if (CurEntry.isNormalDir()) isSame = SearchEntry.getDir() == CurEntry.getDir(); else if (CurEntry.isFramework()) isSame = SearchEntry.getFrameworkDir() == CurEntry.getFrameworkDir(); else { assert(CurEntry.isHeaderMap() && "Not a headermap or normal dir?"); isSame = SearchEntry.getHeaderMap() == CurEntry.getHeaderMap(); } if (isSame) break; } // If the first dir in the search path is a non-system dir, zap it // instead of the system one. if (SearchList[FirstDir].getDirCharacteristic() == SrcMgr::C_User) DirToRemove = FirstDir; } if (Verbose) { fprintf(stderr, "ignoring duplicate directory \"%s\"\n", CurEntry.getName()); if (DirToRemove != i) fprintf(stderr, " as it is a non-system directory that duplicates" " a system directory\n"); } // This is reached if the current entry is a duplicate. Remove the // DirToRemove (usually the current dir). SearchList.erase(SearchList.begin()+DirToRemove); --i; } } void InitHeaderSearch::Realize() { // Concatenate ANGLE+SYSTEM+AFTER chains together into SearchList. std::vector<DirectoryLookup> SearchList; SearchList = IncludeGroup[Angled]; SearchList.insert(SearchList.end(), IncludeGroup[System].begin(), IncludeGroup[System].end()); SearchList.insert(SearchList.end(), IncludeGroup[After].begin(), IncludeGroup[After].end()); RemoveDuplicates(SearchList, Verbose); RemoveDuplicates(IncludeGroup[Quoted], Verbose); // Prepend QUOTED list on the search list. SearchList.insert(SearchList.begin(), IncludeGroup[Quoted].begin(), IncludeGroup[Quoted].end()); bool DontSearchCurDir = false; // TODO: set to true if -I- is set? Headers.SetSearchPaths(SearchList, IncludeGroup[Quoted].size(), DontSearchCurDir); // If verbose, print the list of directories that will be searched. if (Verbose) { fprintf(stderr, "#include \"...\" search starts here:\n"); unsigned QuotedIdx = IncludeGroup[Quoted].size(); for (unsigned i = 0, e = SearchList.size(); i != e; ++i) { if (i == QuotedIdx) fprintf(stderr, "#include <...> search starts here:\n"); const char *Name = SearchList[i].getName(); const char *Suffix; if (SearchList[i].isNormalDir()) Suffix = ""; else if (SearchList[i].isFramework()) Suffix = " (framework directory)"; else { assert(SearchList[i].isHeaderMap() && "Unknown DirectoryLookup"); Suffix = " (headermap)"; } fprintf(stderr, " %s%s\n", Name, Suffix); } fprintf(stderr, "End of search list.\n"); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FEMTruss.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. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEM.h" #include "itkFEMItpackLinearSystemWrapper.h" #include <iostream> #include <fstream> #include <string> using namespace itk::fem; using namespace std; /** * Easy access to the FEMObjectFactory. We create a new class * whose name is shorter and it's not templated... */ class FEMOF : public FEMObjectFactory<FEMLightObject> {}; /** * This example constructs a same problem as described in file truss.fem * by creating the appropriate classes. */ int main( int argc, char *argv[] ) { /** * First we create the FEM solver object. This object stores pointers * to all objects that define the FEM problem. One solver object * effectively defines one FEM problem. */ Solver S; /** * Below we'll define a FEM problem described in the chapter 25.3-4, * from the book, which can also be downloaded from * http://titan.colorado.edu/courses.d/IFEM.d/IFEM.Ch25.d/IFEM.Ch25.pdf */ /** * We start by creating four Node objects. One of them is of * class NodeXY. It has two displacements in two degrees of freedom. * 3 of them are of class NodeXYrotZ, which also includes the rotation * around Z axis. */ /** We'll need these pointers to create and initialize the objects. */ NodeXYrotZ::Pointer n1; NodeXY::Pointer n2; /** * We create the objects through the object factory to make everything * compatible when both smart and dumb pointers are used. Since we * want to cast the pointer to the NodeXYrotZ object, not the SmartPointer * class, we use both reference and de-reference operator (&*). This * has absolutely no effect on a compiled code when smart pointers are * not used. The resulting (dumb) pointer NodeXYrotZ* is then automatically * converted to SmartPointer if necessary and stored in n1. */ n1=static_cast<NodeXYrotZ*>( &*FEMOF::Create(NodeXYrotZ::OFID) ); /** * Additionally we could create the objects in the standard way... */ //n1=new NodeXYrotZ; /** * ... or using SmartPointers... */ //n1=NodeXYrotZ::New(); /** * Initialize the data members inside the node objects. Basically here * we only have to specify the X and Y coordinate of the node in global * coordinate system. */ n1->X=-4.0; n1->Y=3.0; /** * Convert the node pointer into a special pointer (FEMP) and add it to * the nodes array inside the solver class. The special pointer now * owns the object and we don't have to keep track of it anymore. * Here we again have to use both reference and de-reference operator (&*), * because we can't cast SmartPointer<NodeXYrotZ> to SmartPointer<Node>. * If smart pointers are not used, the operators have no effect on the * compiled code. */ S.node.push_back( FEMP<Node>(&*n1) ); /** * Special pointers (class FEMP) create a copy of the objects, * when a pointer object is copied. We can use that feature to quickly * create many similar objects without using the FEMObjectFactory, * New() function, or new operator. * * Operator[] on FEMPArray returns the special pointer (FEMP), while * the function operator () returns the actual pointer. */ S.node.push_back( S.node[0] ); S.node.push_back( S.node[0] ); /** * Now we have to update coordinates inside the newly created nodes. * Since we're getting back the pointers to base class, we need to * cast it to the proper class. dynamic_cast is used in this case. * Note that the Y coordinate of a node remains 3.0, so we don't have * to change it. */ dynamic_cast<NodeXYrotZ*>( &*S.node(1) )->X=0.0; dynamic_cast<NodeXYrotZ*>( &*S.node(2) )->X=4.0; /** * Note that we could also create new objects by always using the * FEMObjectFactory and not copying the objects inside arrays. * This is what we'll do for the final node. */ n2=static_cast<NodeXY*>( &*FEMOF::Create(NodeXY::OFID) ); n2->X=0.0; n2->Y=0.0; S.node.push_back( FEMP<Node>(&*n2) ); /** * Automatically assign the global numbers (IDs) to * all the objects in the array. (first object gets number 0, * second 1, and so on). We could have also specified the GN * member in all the created objects above, but this is easier. */ S.node.Renumber(); /** * Then we have to create the materials that will define * the elements. */ MaterialStandard::Pointer m; m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=0; /** Global number of the material */ m->E=30000.0; /** Young modulus */ m->A=0.02; /** Crossection area */ m->I=0.004; /** Momemt of inertia */ S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=1; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.001; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=2; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.003; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); /** * Next we create the finite elements that use the above * created nodes. We'll have 3 Bar elements ( a simple * spring in 2D space ) and 2 Beam elements that also * accounts for bending. */ Beam2D::Pointer e1; Bar2D::Pointer e2; e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); /** * Initialize the pointers to correct node objects. We use the * Find function of the FEMPArray to search for object (in this * case node) with given GN. Since the Beam2D element requires * nodes of class NodeXYrotZ, we have to make sure that we * have the right node object by using dynamic_cast. */ e1->GN=0; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(0) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); /** same for material */ e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** Create the other elements */ e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); e1->GN=1; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(2) ); e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** * Note that Bar2D requires nodes of class NodeXY. But since the * class NodeXYrotZ is derived from NodeXY, we can cast it * to NodeXY without loosing any information and seemlessly * connect these two elements together. Error checking is * guarantied by compiler either at compile time or by * dynamic_cast operator. */ e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=2; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(0) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=3; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(1) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(2) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=4; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(2) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); /** * Apply the boundary conditions and external forces (loads). */ /** * The first node is completely fixed i.e. both displacements * are fixed to 0. * * This is done by using the LoadBC class. */ LoadBC::Pointer l1; l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); /** * Here we're saying that the first degree of freedom at first node * is fixed to value m_value=0.0. See comments in class LoadBC declaration * for more information. Note that the m_value is a vector. This is useful * when having isotropic elements. This is not the case here, so we only * have a scalar. */ l1->m_element = &*S.el.Find(0); l1->m_dof = 0; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * In a same way we also fix the second DOF in a first node and the * second DOF in a third node (it's only fixed in Y direction). */ l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(0); l1->m_dof = 1; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(1); l1->m_dof = 4; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * Now we apply the external force on the fourth node. The force is specified * by a vector [20,-20] in global coordinate system. This is the second point * of the third element in a system. */ LoadNode::Pointer l2; l2=static_cast<LoadNode*>( &*FEMOF::Create(LoadNode::OFID) ); l2->m_element=S.el.Find(2); l2->m_pt=1; l2->F=vnl_vector<double>(2); l2->F[0]=20; l2->F[1]=-20; S.load.push_back( FEMP<Load>(&*l2) ); /** * The whole problem is now stored inside the Solver class. * Note that in the code above we don't use any of the * constructors that make creation of objects easier and with * less code. See declaration of classes for more info. */ /** * We can now solve for displacements. */ /** * Assign a unique id (global freedom number - GFN) * to every degree of freedom (DOF) in a system. */ S.GenerateGFN(); /** * Assemble the master stiffness matrix. In order to do this * the GFN's should already be assigned to every DOF. */ S.AssembleK(); /** * Invert the master stiffness matrix. */ S.DecomposeK(); /** * Assemble the master force vector (from the applied loads) */ S.AssembleF(); /** * Solve the system of equations for displacements (u=K^-1*F) */ S.Solve(); /** * Copy the displacemenets which are now stored inside * the solver class back to nodes, where they belong. */ S.UpdateDisplacements(); /** * Output displacements of all nodes in a system; */ std::cout<<"\nNodal displacements:\n"; for( ::itk::fem::Solver::NodeArray::iterator n = S.node.begin(); n!=S.node.end(); n++) { std::cout<<"Node#: "<<(*n)->GN<<": "; /** For each DOF in the node... */ for( unsigned int d=0, dof; (dof=(*n)->GetDegreeOfFreedom(d))!=::itk::fem::Element::InvalidDegreeOfFreedomID; d++ ) { std::cout<<S.GetSolution(dof); std::cout<<", "; } std::cout<<"\b\b\b \b\n"; } cout<<"\n"; return 0; } <commit_msg>FIX: Removed unnecessary includes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FEMTruss.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. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEM.h" #include <iostream> using namespace itk::fem; using namespace std; /** * Easy access to the FEMObjectFactory. We create a new class * whose name is shorter and it's not templated... */ class FEMOF : public FEMObjectFactory<FEMLightObject> {}; /** * This example constructs a same problem as described in file truss.fem * by creating the appropriate classes. */ int main( int argc, char *argv[] ) { /** * First we create the FEM solver object. This object stores pointers * to all objects that define the FEM problem. One solver object * effectively defines one FEM problem. */ Solver S; /** * Below we'll define a FEM problem described in the chapter 25.3-4, * from the book, which can also be downloaded from * http://titan.colorado.edu/courses.d/IFEM.d/IFEM.Ch25.d/IFEM.Ch25.pdf */ /** * We start by creating four Node objects. One of them is of * class NodeXY. It has two displacements in two degrees of freedom. * 3 of them are of class NodeXYrotZ, which also includes the rotation * around Z axis. */ /** We'll need these pointers to create and initialize the objects. */ NodeXYrotZ::Pointer n1; NodeXY::Pointer n2; /** * We create the objects through the object factory to make everything * compatible when both smart and dumb pointers are used. Since we * want to cast the pointer to the NodeXYrotZ object, not the SmartPointer * class, we use both reference and de-reference operator (&*). This * has absolutely no effect on a compiled code when smart pointers are * not used. The resulting (dumb) pointer NodeXYrotZ* is then automatically * converted to SmartPointer if necessary and stored in n1. */ n1=static_cast<NodeXYrotZ*>( &*FEMOF::Create(NodeXYrotZ::OFID) ); /** * Additionally we could create the objects in the standard way... */ //n1=new NodeXYrotZ; /** * ... or using SmartPointers... */ //n1=NodeXYrotZ::New(); /** * Initialize the data members inside the node objects. Basically here * we only have to specify the X and Y coordinate of the node in global * coordinate system. */ n1->X=-4.0; n1->Y=3.0; /** * Convert the node pointer into a special pointer (FEMP) and add it to * the nodes array inside the solver class. The special pointer now * owns the object and we don't have to keep track of it anymore. * Here we again have to use both reference and de-reference operator (&*), * because we can't cast SmartPointer<NodeXYrotZ> to SmartPointer<Node>. * If smart pointers are not used, the operators have no effect on the * compiled code. */ S.node.push_back( FEMP<Node>(&*n1) ); /** * Special pointers (class FEMP) create a copy of the objects, * when a pointer object is copied. We can use that feature to quickly * create many similar objects without using the FEMObjectFactory, * New() function, or new operator. * * Operator[] on FEMPArray returns the special pointer (FEMP), while * the function operator () returns the actual pointer. */ S.node.push_back( S.node[0] ); S.node.push_back( S.node[0] ); /** * Now we have to update coordinates inside the newly created nodes. * Since we're getting back the pointers to base class, we need to * cast it to the proper class. dynamic_cast is used in this case. * Note that the Y coordinate of a node remains 3.0, so we don't have * to change it. */ dynamic_cast<NodeXYrotZ*>( &*S.node(1) )->X=0.0; dynamic_cast<NodeXYrotZ*>( &*S.node(2) )->X=4.0; /** * Note that we could also create new objects by always using the * FEMObjectFactory and not copying the objects inside arrays. * This is what we'll do for the final node. */ n2=static_cast<NodeXY*>( &*FEMOF::Create(NodeXY::OFID) ); n2->X=0.0; n2->Y=0.0; S.node.push_back( FEMP<Node>(&*n2) ); /** * Automatically assign the global numbers (IDs) to * all the objects in the array. (first object gets number 0, * second 1, and so on). We could have also specified the GN * member in all the created objects above, but this is easier. */ S.node.Renumber(); /** * Then we have to create the materials that will define * the elements. */ MaterialStandard::Pointer m; m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=0; /** Global number of the material */ m->E=30000.0; /** Young modulus */ m->A=0.02; /** Crossection area */ m->I=0.004; /** Momemt of inertia */ S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=1; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.001; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=2; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.003; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); /** * Next we create the finite elements that use the above * created nodes. We'll have 3 Bar elements ( a simple * spring in 2D space ) and 2 Beam elements that also * accounts for bending. */ Beam2D::Pointer e1; Bar2D::Pointer e2; e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); /** * Initialize the pointers to correct node objects. We use the * Find function of the FEMPArray to search for object (in this * case node) with given GN. Since the Beam2D element requires * nodes of class NodeXYrotZ, we have to make sure that we * have the right node object by using dynamic_cast. */ e1->GN=0; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(0) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); /** same for material */ e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** Create the other elements */ e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); e1->GN=1; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(2) ); e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** * Note that Bar2D requires nodes of class NodeXY. But since the * class NodeXYrotZ is derived from NodeXY, we can cast it * to NodeXY without loosing any information and seemlessly * connect these two elements together. Error checking is * guarantied by compiler either at compile time or by * dynamic_cast operator. */ e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=2; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(0) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=3; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(1) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(2) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=4; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(2) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); /** * Apply the boundary conditions and external forces (loads). */ /** * The first node is completely fixed i.e. both displacements * are fixed to 0. * * This is done by using the LoadBC class. */ LoadBC::Pointer l1; l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); /** * Here we're saying that the first degree of freedom at first node * is fixed to value m_value=0.0. See comments in class LoadBC declaration * for more information. Note that the m_value is a vector. This is useful * when having isotropic elements. This is not the case here, so we only * have a scalar. */ l1->m_element = &*S.el.Find(0); l1->m_dof = 0; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * In a same way we also fix the second DOF in a first node and the * second DOF in a third node (it's only fixed in Y direction). */ l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(0); l1->m_dof = 1; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(1); l1->m_dof = 4; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * Now we apply the external force on the fourth node. The force is specified * by a vector [20,-20] in global coordinate system. This is the second point * of the third element in a system. */ LoadNode::Pointer l2; l2=static_cast<LoadNode*>( &*FEMOF::Create(LoadNode::OFID) ); l2->m_element=S.el.Find(2); l2->m_pt=1; l2->F=vnl_vector<double>(2); l2->F[0]=20; l2->F[1]=-20; S.load.push_back( FEMP<Load>(&*l2) ); /** * The whole problem is now stored inside the Solver class. * Note that in the code above we don't use any of the * constructors that make creation of objects easier and with * less code. See declaration of classes for more info. */ /** * We can now solve for displacements. */ /** * Assign a unique id (global freedom number - GFN) * to every degree of freedom (DOF) in a system. */ S.GenerateGFN(); /** * Assemble the master stiffness matrix. In order to do this * the GFN's should already be assigned to every DOF. */ S.AssembleK(); /** * Invert the master stiffness matrix. */ S.DecomposeK(); /** * Assemble the master force vector (from the applied loads) */ S.AssembleF(); /** * Solve the system of equations for displacements (u=K^-1*F) */ S.Solve(); /** * Copy the displacemenets which are now stored inside * the solver class back to nodes, where they belong. */ S.UpdateDisplacements(); /** * Output displacements of all nodes in a system; */ std::cout<<"\nNodal displacements:\n"; for( ::itk::fem::Solver::NodeArray::iterator n = S.node.begin(); n!=S.node.end(); n++) { std::cout<<"Node#: "<<(*n)->GN<<": "; /** For each DOF in the node... */ for( unsigned int d=0, dof; (dof=(*n)->GetDegreeOfFreedom(d))!=::itk::fem::Element::InvalidDegreeOfFreedomID; d++ ) { std::cout<<S.GetSolution(dof); std::cout<<", "; } std::cout<<"\b\b\b \b\n"; } cout<<"\n"; return 0; } <|endoftext|>
<commit_before>//===--- IndexRecordWriter.cpp - Index record serialization ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Index/IndexRecordWriter.h" #include "IndexDataStoreUtils.h" #include "indexstore/indexstore.h" #include "clang/Index/IndexDataStoreSymbolUtils.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::index; using namespace clang::index::store; using namespace llvm; using writer::OpaqueDecl; namespace { struct DeclInfo { OpaqueDecl D; SymbolRoleSet Roles; SymbolRoleSet RelatedRoles; }; struct OccurrenceInfo { unsigned DeclID; OpaqueDecl D; SymbolRoleSet Roles; unsigned Line; unsigned Column; SmallVector<std::pair<writer::SymbolRelation, unsigned>, 4> Related; }; struct RecordState { std::string RecordPath; SmallString<512> Buffer; BitstreamWriter Stream; DenseMap<OpaqueDecl, unsigned> IndexForDecl; std::vector<DeclInfo> Decls; std::vector<OccurrenceInfo> Occurrences; RecordState(std::string &&RecordPath) : RecordPath(std::move(RecordPath)), Stream(Buffer) {} }; } // end anonymous namespace static void writeBlockInfo(BitstreamWriter &Stream) { RecordData Record; Stream.EnterBlockInfoBlock(); #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record) #define RECORD(X) emitRecordID(X, #X, Stream, Record) BLOCK(REC_VERSION_BLOCK); RECORD(REC_VERSION); BLOCK(REC_DECLS_BLOCK); RECORD(REC_DECLINFO); BLOCK(REC_DECLOFFSETS_BLOCK); RECORD(REC_DECLOFFSETS); BLOCK(REC_DECLOCCURRENCES_BLOCK); RECORD(REC_DECLOCCURRENCE); #undef RECORD #undef BLOCK Stream.ExitBlock(); } static void writeVersionInfo(BitstreamWriter &Stream) { using namespace llvm::sys; Stream.EnterSubblock(REC_VERSION_BLOCK_ID, 3); auto Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_VERSION)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Store format version unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); RecordData Record; Record.push_back(REC_VERSION); Record.push_back(STORE_FORMAT_VERSION); Stream.EmitRecordWithAbbrev(AbbrevCode, Record); Stream.ExitBlock(); } template <typename T, typename Allocator> static StringRef data(const std::vector<T, Allocator> &v) { if (v.empty()) return StringRef(); return StringRef(reinterpret_cast<const char *>(&v[0]), sizeof(T) * v.size()); } template <typename T> static StringRef data(const SmallVectorImpl<T> &v) { return StringRef(reinterpret_cast<const char *>(v.data()), sizeof(T) * v.size()); } static void writeDecls(BitstreamWriter &Stream, ArrayRef<DeclInfo> Decls, ArrayRef<OccurrenceInfo> Occurrences, writer::SymbolWriterCallback GetSymbolForDecl) { SmallVector<uint32_t, 32> DeclOffsets; DeclOffsets.reserve(Decls.size()); //===--------------------------------------------------------------------===// // DECLS_BLOCK_ID //===--------------------------------------------------------------------===// Stream.EnterSubblock(REC_DECLS_BLOCK_ID, 3); auto Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_DECLINFO)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 5)); // Kind Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 5)); // SubKind Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 5)); // Language Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolPropertyBitNum)); // Properties Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolRoleBitNum)); // Roles Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolRoleBitNum)); // Related Roles Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Length of name in block Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Length of USR in block Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name + USR + CodeGen symbol name unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); #ifndef NDEBUG StringSet<> USRSet; #endif RecordData Record; llvm::SmallString<256> Blob; llvm::SmallString<256> Scratch; for (auto &Info : Decls) { DeclOffsets.push_back(Stream.GetCurrentBitNo()); Blob.clear(); Scratch.clear(); writer::Symbol SymInfo = GetSymbolForDecl(Info.D, Scratch); assert(SymInfo.SymInfo.Kind != SymbolKind::Unknown); assert(!SymInfo.USR.empty() && "Recorded decl without USR!"); Blob += SymInfo.Name; Blob += SymInfo.USR; Blob += SymInfo.CodeGenName; #ifndef NDEBUG bool IsNew = USRSet.insert(SymInfo.USR).second; if (!IsNew) { llvm::errs() << "Index: Duplicate USR! " << SymInfo.USR << "\n"; // FIXME: print more information so it's easier to find the declaration. } #endif Record.clear(); Record.push_back(REC_DECLINFO); Record.push_back(getIndexStoreKind(SymInfo.SymInfo.Kind)); Record.push_back(getIndexStoreSubKind(SymInfo.SymInfo.SubKind)); Record.push_back(getIndexStoreLang(SymInfo.SymInfo.Lang)); Record.push_back(getIndexStoreProperties(SymInfo.SymInfo.Properties)); Record.push_back(getIndexStoreRoles(Info.Roles)); Record.push_back(getIndexStoreRoles(Info.RelatedRoles)); Record.push_back(SymInfo.Name.size()); Record.push_back(SymInfo.USR.size()); Stream.EmitRecordWithBlob(AbbrevCode, Record, Blob); } Stream.ExitBlock(); //===--------------------------------------------------------------------===// // DECLOFFSETS_BLOCK_ID //===--------------------------------------------------------------------===// Stream.EnterSubblock(REC_DECLOFFSETS_BLOCK_ID, 3); Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_DECLOFFSETS)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of Decls Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Offsets array AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); Record.clear(); Record.push_back(REC_DECLOFFSETS); Record.push_back(DeclOffsets.size()); Stream.EmitRecordWithBlob(AbbrevCode, Record, data(DeclOffsets)); Stream.ExitBlock(); //===--------------------------------------------------------------------===// // DECLOCCURRENCES_BLOCK_ID //===--------------------------------------------------------------------===// Stream.EnterSubblock(REC_DECLOCCURRENCES_BLOCK_ID, 3); Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_DECLOCCURRENCE)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Decl ID Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolRoleBitNum)); // Roles Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Line Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Column Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Num related Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // Related Roles/IDs Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Roles or ID AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); for (auto &Occur : Occurrences) { Record.clear(); Record.push_back(REC_DECLOCCURRENCE); Record.push_back(Occur.DeclID); Record.push_back(getIndexStoreRoles(Occur.Roles)); Record.push_back(Occur.Line); Record.push_back(Occur.Column); Record.push_back(Occur.Related.size()); for (auto &Rel : Occur.Related) { Record.push_back(getIndexStoreRoles(Rel.first.Roles)); Record.push_back(Rel.second); } Stream.EmitRecordWithAbbrev(AbbrevCode, Record); } Stream.ExitBlock(); } IndexRecordWriter::IndexRecordWriter(StringRef IndexPath) : RecordsPath(IndexPath) { store::appendRecordSubDir(RecordsPath); } IndexRecordWriter::Result IndexRecordWriter::beginRecord(StringRef Filename, hash_code RecordHash, std::string &Error, std::string *OutRecordFile) { using namespace llvm::sys; assert(!Record && "called beginRecord before calling endRecord on previous"); std::string RecordName; { llvm::raw_string_ostream RN(RecordName); RN << path::filename(Filename); RN << "-" << APInt(64, RecordHash).toString(36, /*Signed=*/false); } SmallString<256> RecordPath = RecordsPath.str(); appendInteriorRecordPath(RecordName, RecordPath); if (OutRecordFile) *OutRecordFile = RecordName; if (std::error_code EC = fs::access(RecordPath.c_str(), fs::AccessMode::Exist)) { if (EC != errc::no_such_file_or_directory) { llvm::raw_string_ostream Err(Error); Err << "could not access record '" << RecordPath << "': " << EC.message(); return Result::Failure; } } else { return Result::AlreadyExists; } // Write the record header. auto *State = new RecordState(RecordPath.str()); Record = State; llvm::BitstreamWriter &Stream = State->Stream; Stream.Emit('I', 8); Stream.Emit('D', 8); Stream.Emit('X', 8); Stream.Emit('R', 8); writeBlockInfo(Stream); writeVersionInfo(Stream); return Result::Success; } IndexRecordWriter::Result IndexRecordWriter::endRecord(std::string &Error, writer::SymbolWriterCallback GetSymbolForDecl) { assert(Record && "called endRecord without calling beginRecord"); auto &State = *static_cast<RecordState *>(Record); Record = nullptr; struct ScopedDelete { RecordState *S; ScopedDelete(RecordState *S) : S(S) {} ~ScopedDelete() { delete S; } } Deleter(&State); if (!State.Decls.empty()) { writeDecls(State.Stream, State.Decls, State.Occurrences, GetSymbolForDecl); } if (std::error_code EC = sys::fs::create_directory(sys::path::parent_path(State.RecordPath))) { llvm::raw_string_ostream Err(Error); Err << "failed to create directory '" << sys::path::parent_path(State.RecordPath) << "': " << EC.message(); return Result::Failure; } // Create a unique file to write to so that we can move the result into place // atomically. If this process crashes we don't want to interfere with any // other concurrent processes. SmallString<128> TempPath(State.RecordPath); TempPath += "-temp-%%%%%%%%"; int TempFD; if (sys::fs::createUniqueFile(TempPath.str(), TempFD, TempPath)) { llvm::raw_string_ostream Err(Error); Err << "failed to create temporary file: " << TempPath; return Result::Failure; } raw_fd_ostream OS(TempFD, /*shouldClose=*/true); OS.write(State.Buffer.data(), State.Buffer.size()); OS.close(); if (OS.has_error()) { llvm::raw_string_ostream Err(Error); Err << "failed to write '" << TempPath << "': " << OS.error().message(); OS.clear_error(); return Result::Failure; } // Atomically move the unique file into place. if (std::error_code EC = sys::fs::rename(TempPath.c_str(), State.RecordPath.c_str())) { llvm::raw_string_ostream Err(Error); Err << "failed to rename '" << TempPath << "' to '" << State.RecordPath << "': " << EC.message(); return Result::Failure; } return Result::Success; } void IndexRecordWriter::addOccurrence( OpaqueDecl D, SymbolRoleSet Roles, unsigned Line, unsigned Column, ArrayRef<writer::SymbolRelation> Related) { assert(Record && "called addOccurrence without calling beginRecord"); auto &State = *static_cast<RecordState *>(Record); auto insertDecl = [&](OpaqueDecl D, SymbolRoleSet Roles, SymbolRoleSet RelatedRoles) -> unsigned { auto Insert = State.IndexForDecl.insert(std::make_pair(D, State.Decls.size())); unsigned Index = Insert.first->second; if (Insert.second) { State.Decls.push_back(DeclInfo{D, Roles, RelatedRoles}); } else { State.Decls[Index].Roles |= Roles; State.Decls[Index].RelatedRoles |= RelatedRoles; } return Index + 1; }; unsigned DeclID = insertDecl(D, Roles, SymbolRoleSet()); decltype(OccurrenceInfo::Related) RelatedDecls; RelatedDecls.reserve(Related.size()); for (auto &Rel : Related) { unsigned ID = insertDecl(Rel.RelatedSymbol, SymbolRoleSet(), Rel.Roles); RelatedDecls.emplace_back(Rel, ID); } State.Occurrences.push_back( OccurrenceInfo{DeclID, D, Roles, Line, Column, std::move(RelatedDecls)}); } <commit_msg>[index/store] Put the USR validation checking logging behind an environment variable<commit_after>//===--- IndexRecordWriter.cpp - Index record serialization ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Index/IndexRecordWriter.h" #include "IndexDataStoreUtils.h" #include "indexstore/indexstore.h" #include "clang/Index/IndexDataStoreSymbolUtils.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Bitcode/BitstreamWriter.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace clang; using namespace clang::index; using namespace clang::index::store; using namespace llvm; using writer::OpaqueDecl; namespace { struct DeclInfo { OpaqueDecl D; SymbolRoleSet Roles; SymbolRoleSet RelatedRoles; }; struct OccurrenceInfo { unsigned DeclID; OpaqueDecl D; SymbolRoleSet Roles; unsigned Line; unsigned Column; SmallVector<std::pair<writer::SymbolRelation, unsigned>, 4> Related; }; struct RecordState { std::string RecordPath; SmallString<512> Buffer; BitstreamWriter Stream; DenseMap<OpaqueDecl, unsigned> IndexForDecl; std::vector<DeclInfo> Decls; std::vector<OccurrenceInfo> Occurrences; RecordState(std::string &&RecordPath) : RecordPath(std::move(RecordPath)), Stream(Buffer) {} }; } // end anonymous namespace static void writeBlockInfo(BitstreamWriter &Stream) { RecordData Record; Stream.EnterBlockInfoBlock(); #define BLOCK(X) emitBlockID(X ## _ID, #X, Stream, Record) #define RECORD(X) emitRecordID(X, #X, Stream, Record) BLOCK(REC_VERSION_BLOCK); RECORD(REC_VERSION); BLOCK(REC_DECLS_BLOCK); RECORD(REC_DECLINFO); BLOCK(REC_DECLOFFSETS_BLOCK); RECORD(REC_DECLOFFSETS); BLOCK(REC_DECLOCCURRENCES_BLOCK); RECORD(REC_DECLOCCURRENCE); #undef RECORD #undef BLOCK Stream.ExitBlock(); } static void writeVersionInfo(BitstreamWriter &Stream) { using namespace llvm::sys; Stream.EnterSubblock(REC_VERSION_BLOCK_ID, 3); auto Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_VERSION)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Store format version unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); RecordData Record; Record.push_back(REC_VERSION); Record.push_back(STORE_FORMAT_VERSION); Stream.EmitRecordWithAbbrev(AbbrevCode, Record); Stream.ExitBlock(); } template <typename T, typename Allocator> static StringRef data(const std::vector<T, Allocator> &v) { if (v.empty()) return StringRef(); return StringRef(reinterpret_cast<const char *>(&v[0]), sizeof(T) * v.size()); } template <typename T> static StringRef data(const SmallVectorImpl<T> &v) { return StringRef(reinterpret_cast<const char *>(v.data()), sizeof(T) * v.size()); } static void writeDecls(BitstreamWriter &Stream, ArrayRef<DeclInfo> Decls, ArrayRef<OccurrenceInfo> Occurrences, writer::SymbolWriterCallback GetSymbolForDecl) { SmallVector<uint32_t, 32> DeclOffsets; DeclOffsets.reserve(Decls.size()); //===--------------------------------------------------------------------===// // DECLS_BLOCK_ID //===--------------------------------------------------------------------===// Stream.EnterSubblock(REC_DECLS_BLOCK_ID, 3); auto Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_DECLINFO)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 5)); // Kind Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 5)); // SubKind Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 5)); // Language Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolPropertyBitNum)); // Properties Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolRoleBitNum)); // Roles Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolRoleBitNum)); // Related Roles Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Length of name in block Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Length of USR in block Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name + USR + CodeGen symbol name unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); #ifndef NDEBUG StringSet<> USRSet; bool enableValidation = getenv("CLANG_INDEX_VALIDATION_CHECKS") != nullptr; #endif RecordData Record; llvm::SmallString<256> Blob; llvm::SmallString<256> Scratch; for (auto &Info : Decls) { DeclOffsets.push_back(Stream.GetCurrentBitNo()); Blob.clear(); Scratch.clear(); writer::Symbol SymInfo = GetSymbolForDecl(Info.D, Scratch); assert(SymInfo.SymInfo.Kind != SymbolKind::Unknown); assert(!SymInfo.USR.empty() && "Recorded decl without USR!"); Blob += SymInfo.Name; Blob += SymInfo.USR; Blob += SymInfo.CodeGenName; #ifndef NDEBUG if (enableValidation) { bool IsNew = USRSet.insert(SymInfo.USR).second; if (!IsNew) { llvm::errs() << "Index: Duplicate USR! " << SymInfo.USR << "\n"; // FIXME: print more information so it's easier to find the declaration. } } #endif Record.clear(); Record.push_back(REC_DECLINFO); Record.push_back(getIndexStoreKind(SymInfo.SymInfo.Kind)); Record.push_back(getIndexStoreSubKind(SymInfo.SymInfo.SubKind)); Record.push_back(getIndexStoreLang(SymInfo.SymInfo.Lang)); Record.push_back(getIndexStoreProperties(SymInfo.SymInfo.Properties)); Record.push_back(getIndexStoreRoles(Info.Roles)); Record.push_back(getIndexStoreRoles(Info.RelatedRoles)); Record.push_back(SymInfo.Name.size()); Record.push_back(SymInfo.USR.size()); Stream.EmitRecordWithBlob(AbbrevCode, Record, Blob); } Stream.ExitBlock(); //===--------------------------------------------------------------------===// // DECLOFFSETS_BLOCK_ID //===--------------------------------------------------------------------===// Stream.EnterSubblock(REC_DECLOFFSETS_BLOCK_ID, 3); Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_DECLOFFSETS)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of Decls Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Offsets array AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); Record.clear(); Record.push_back(REC_DECLOFFSETS); Record.push_back(DeclOffsets.size()); Stream.EmitRecordWithBlob(AbbrevCode, Record, data(DeclOffsets)); Stream.ExitBlock(); //===--------------------------------------------------------------------===// // DECLOCCURRENCES_BLOCK_ID //===--------------------------------------------------------------------===// Stream.EnterSubblock(REC_DECLOCCURRENCES_BLOCK_ID, 3); Abbrev = std::make_shared<BitCodeAbbrev>(); Abbrev->Add(BitCodeAbbrevOp(REC_DECLOCCURRENCE)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Decl ID Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, SymbolRoleBitNum)); // Roles Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Line Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Column Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Num related Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // Related Roles/IDs Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // Roles or ID AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); for (auto &Occur : Occurrences) { Record.clear(); Record.push_back(REC_DECLOCCURRENCE); Record.push_back(Occur.DeclID); Record.push_back(getIndexStoreRoles(Occur.Roles)); Record.push_back(Occur.Line); Record.push_back(Occur.Column); Record.push_back(Occur.Related.size()); for (auto &Rel : Occur.Related) { Record.push_back(getIndexStoreRoles(Rel.first.Roles)); Record.push_back(Rel.second); } Stream.EmitRecordWithAbbrev(AbbrevCode, Record); } Stream.ExitBlock(); } IndexRecordWriter::IndexRecordWriter(StringRef IndexPath) : RecordsPath(IndexPath) { store::appendRecordSubDir(RecordsPath); } IndexRecordWriter::Result IndexRecordWriter::beginRecord(StringRef Filename, hash_code RecordHash, std::string &Error, std::string *OutRecordFile) { using namespace llvm::sys; assert(!Record && "called beginRecord before calling endRecord on previous"); std::string RecordName; { llvm::raw_string_ostream RN(RecordName); RN << path::filename(Filename); RN << "-" << APInt(64, RecordHash).toString(36, /*Signed=*/false); } SmallString<256> RecordPath = RecordsPath.str(); appendInteriorRecordPath(RecordName, RecordPath); if (OutRecordFile) *OutRecordFile = RecordName; if (std::error_code EC = fs::access(RecordPath.c_str(), fs::AccessMode::Exist)) { if (EC != errc::no_such_file_or_directory) { llvm::raw_string_ostream Err(Error); Err << "could not access record '" << RecordPath << "': " << EC.message(); return Result::Failure; } } else { return Result::AlreadyExists; } // Write the record header. auto *State = new RecordState(RecordPath.str()); Record = State; llvm::BitstreamWriter &Stream = State->Stream; Stream.Emit('I', 8); Stream.Emit('D', 8); Stream.Emit('X', 8); Stream.Emit('R', 8); writeBlockInfo(Stream); writeVersionInfo(Stream); return Result::Success; } IndexRecordWriter::Result IndexRecordWriter::endRecord(std::string &Error, writer::SymbolWriterCallback GetSymbolForDecl) { assert(Record && "called endRecord without calling beginRecord"); auto &State = *static_cast<RecordState *>(Record); Record = nullptr; struct ScopedDelete { RecordState *S; ScopedDelete(RecordState *S) : S(S) {} ~ScopedDelete() { delete S; } } Deleter(&State); if (!State.Decls.empty()) { writeDecls(State.Stream, State.Decls, State.Occurrences, GetSymbolForDecl); } if (std::error_code EC = sys::fs::create_directory(sys::path::parent_path(State.RecordPath))) { llvm::raw_string_ostream Err(Error); Err << "failed to create directory '" << sys::path::parent_path(State.RecordPath) << "': " << EC.message(); return Result::Failure; } // Create a unique file to write to so that we can move the result into place // atomically. If this process crashes we don't want to interfere with any // other concurrent processes. SmallString<128> TempPath(State.RecordPath); TempPath += "-temp-%%%%%%%%"; int TempFD; if (sys::fs::createUniqueFile(TempPath.str(), TempFD, TempPath)) { llvm::raw_string_ostream Err(Error); Err << "failed to create temporary file: " << TempPath; return Result::Failure; } raw_fd_ostream OS(TempFD, /*shouldClose=*/true); OS.write(State.Buffer.data(), State.Buffer.size()); OS.close(); if (OS.has_error()) { llvm::raw_string_ostream Err(Error); Err << "failed to write '" << TempPath << "': " << OS.error().message(); OS.clear_error(); return Result::Failure; } // Atomically move the unique file into place. if (std::error_code EC = sys::fs::rename(TempPath.c_str(), State.RecordPath.c_str())) { llvm::raw_string_ostream Err(Error); Err << "failed to rename '" << TempPath << "' to '" << State.RecordPath << "': " << EC.message(); return Result::Failure; } return Result::Success; } void IndexRecordWriter::addOccurrence( OpaqueDecl D, SymbolRoleSet Roles, unsigned Line, unsigned Column, ArrayRef<writer::SymbolRelation> Related) { assert(Record && "called addOccurrence without calling beginRecord"); auto &State = *static_cast<RecordState *>(Record); auto insertDecl = [&](OpaqueDecl D, SymbolRoleSet Roles, SymbolRoleSet RelatedRoles) -> unsigned { auto Insert = State.IndexForDecl.insert(std::make_pair(D, State.Decls.size())); unsigned Index = Insert.first->second; if (Insert.second) { State.Decls.push_back(DeclInfo{D, Roles, RelatedRoles}); } else { State.Decls[Index].Roles |= Roles; State.Decls[Index].RelatedRoles |= RelatedRoles; } return Index + 1; }; unsigned DeclID = insertDecl(D, Roles, SymbolRoleSet()); decltype(OccurrenceInfo::Related) RelatedDecls; RelatedDecls.reserve(Related.size()); for (auto &Rel : Related) { unsigned ID = insertDecl(Rel.RelatedSymbol, SymbolRoleSet(), Rel.Roles); RelatedDecls.emplace_back(Rel, ID); } State.Occurrences.push_back( OccurrenceInfo{DeclID, D, Roles, Line, Column, std::move(RelatedDecls)}); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" using namespace clang; namespace cling { Transaction::~Transaction() { if (hasNestedTransactions()) for (size_t i = 0; i < m_NestedTransactions->size(); ++i) delete (*m_NestedTransactions)[i]; } void Transaction::append(DelayCallInfo DCI) { if (!DCI.m_DGR.isNull() && getState() == kCommitting) { // We are committing and getting enw decls in. // Move them into a sub transaction that will be processed // recursively at the end of of commitTransaction. Transaction* subTransactionWhileCommitting = 0; if (hasNestedTransactions() && m_NestedTransactions->back()->getState() == kCollecting) subTransactionWhileCommitting = m_NestedTransactions->back(); else { // FIXME: is this correct (Axel says "yes") CompilationOptions Opts(getCompilationOpts()); Opts.DeclarationExtraction = 0; Opts.ValuePrinting = CompilationOptions::VPDisabled; Opts.ResultEvaluation = 0; Opts.DynamicScoping = 0; subTransactionWhileCommitting = new Transaction(Opts, getModule()); addNestedTransaction(subTransactionWhileCommitting); } subTransactionWhileCommitting->append(DCI); return; } assert(DCI.m_DGR.isNull() || (getState() == kCollecting || getState() == kCompleted) || "Cannot append declarations in current state."); bool checkForWrapper = !m_WrapperFD; assert(checkForWrapper = true && "Check for wrappers with asserts"); // register the wrapper if any. if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())) if (utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } } // Lazy create the container on first append. if (!m_DeclQueue) m_DeclQueue.reset(new DeclQueue()); m_DeclQueue->push_back(DCI); } void Transaction::append(clang::DeclGroupRef DGR) { append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl)); } void Transaction::append(Decl* D) { append(DeclGroupRef(D)); } void Transaction::dump() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); Policy.DumpSourceManager = &C.getSourceManager(); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; ASTContext* C = 0; if (m_WrapperFD) C = &(m_WrapperFD->getASTContext()); if (!getFirstDecl().isNull()) C = &(getFirstDecl().getSingleDecl()->getASTContext()); PrintingPolicy Policy(C->getLangOpts()); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->m_DGR.isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; (*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->m_DGR.begin(), L = I->m_DGR.end(); J != L; ++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } void Transaction::printStructure(size_t nindent) const { static const char* const stateNames[] = { "Collecting", "RolledBack", "RolledBackWithErrors", "Committing", "Committed" }; std::string indent(nindent, ' '); llvm::errs() << indent << "Transaction @" << this << ": \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { (*I)->printStructure(nindent + 1); } llvm::errs() << indent << " state: " << stateNames[getState()] << ", " << size() << " decl groups, " << m_NestedTransactions->size() << " nested transactions\n" << indent << " wrapper: " << m_WrapperFD << ", parent: " << m_Parent << ", next: " << m_Next << "\n"; } } // end namespace cling <commit_msg>80 cols.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" using namespace clang; namespace cling { Transaction::~Transaction() { if (hasNestedTransactions()) for (size_t i = 0; i < m_NestedTransactions->size(); ++i) delete (*m_NestedTransactions)[i]; } void Transaction::append(DelayCallInfo DCI) { if (!DCI.m_DGR.isNull() && getState() == kCommitting) { // We are committing and getting enw decls in. // Move them into a sub transaction that will be processed // recursively at the end of of commitTransaction. Transaction* subTransactionWhileCommitting = 0; if (hasNestedTransactions() && m_NestedTransactions->back()->getState() == kCollecting) subTransactionWhileCommitting = m_NestedTransactions->back(); else { // FIXME: is this correct (Axel says "yes") CompilationOptions Opts(getCompilationOpts()); Opts.DeclarationExtraction = 0; Opts.ValuePrinting = CompilationOptions::VPDisabled; Opts.ResultEvaluation = 0; Opts.DynamicScoping = 0; subTransactionWhileCommitting = new Transaction(Opts, getModule()); addNestedTransaction(subTransactionWhileCommitting); } subTransactionWhileCommitting->append(DCI); return; } assert(DCI.m_DGR.isNull() || (getState() == kCollecting || getState() == kCompleted) || "Cannot append declarations in current state."); bool checkForWrapper = !m_WrapperFD; assert(checkForWrapper = true && "Check for wrappers with asserts"); // register the wrapper if any. if (checkForWrapper && !DCI.m_DGR.isNull() && DCI.m_DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())) if (utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } } // Lazy create the container on first append. if (!m_DeclQueue) m_DeclQueue.reset(new DeclQueue()); m_DeclQueue->push_back(DCI); } void Transaction::append(clang::DeclGroupRef DGR) { append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl)); } void Transaction::append(Decl* D) { append(DeclGroupRef(D)); } void Transaction::dump() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); Policy.DumpSourceManager = &C.getSourceManager(); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; ASTContext* C = 0; if (m_WrapperFD) C = &(m_WrapperFD->getASTContext()); if (!getFirstDecl().isNull()) C = &(getFirstDecl().getSingleDecl()->getASTContext()); PrintingPolicy Policy(C->getLangOpts()); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->m_DGR.isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; (*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->m_DGR.begin(), L = I->m_DGR.end(); J != L; ++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } void Transaction::printStructure(size_t nindent) const { static const char* const stateNames[] = { "Collecting", "RolledBack", "RolledBackWithErrors", "Committing", "Committed" }; std::string indent(nindent, ' '); llvm::errs() << indent << "Transaction @" << this << ": \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { (*I)->printStructure(nindent + 1); } llvm::errs() << indent << " state: " << stateNames[getState()] << ", " << size() << " decl groups, " << m_NestedTransactions->size() << " nested transactions\n" << indent << " wrapper: " << m_WrapperFD << ", parent: " << m_Parent << ", next: " << m_Next << "\n"; } } // end namespace cling <|endoftext|>
<commit_before>/* openfx-arena - https://github.com/olear/openfx-arena Copyright (c) 2015, Ole-André Rodlie <olear@fxarena.net> Copyright (c) 2015, FxArena DA <mail@fxarena.net> 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. * Neither the name of FxArena DA nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * 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 "Polar.h" #include "ofxsMacros.h" #include <Magick++.h> #define kPluginName "Polar" #define kPluginGrouping "Filter" #define kPluginDescription "Swirl image" #define kPluginIdentifier "net.fxarena.openfx.Polar" #define kPluginVersionMajor 1 #define kPluginVersionMinor 0 //#define kParamSwirl "swirl" //#define kParamSwirlLabel "Swirl" //#define kParamSwirlHint "Swirl image by degree" //#define kParamSwirlDefault 90 #define kSupportsTiles 0 #define kSupportsMultiResolution 1 #define kSupportsRenderScale 1 #define kRenderThreadSafety eRenderInstanceSafe using namespace OFX; class PolarPlugin : public OFX::ImageEffect { public: PolarPlugin(OfxImageEffectHandle handle); virtual ~PolarPlugin(); virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL; virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL; private: OFX::Clip *dstClip_; OFX::Clip *srcClip_; //OFX::DoubleParam *swirlDegree_; }; PolarPlugin::PolarPlugin(OfxImageEffectHandle handle) : OFX::ImageEffect(handle) , dstClip_(0) , srcClip_(0) { Magick::InitializeMagick(""); dstClip_ = fetchClip(kOfxImageEffectOutputClipName); assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB)); srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName); assert(srcClip_ && (srcClip_->getPixelComponents() == OFX::ePixelComponentRGBA || srcClip_->getPixelComponents() == OFX::ePixelComponentRGB)); //swirlDegree_ = fetchDoubleParam(kParamSwirl); //assert(swirlDegree_); } PolarPlugin::~PolarPlugin() { } void PolarPlugin::render(const OFX::RenderArguments &args) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (!srcClip_) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } assert(srcClip_); std::auto_ptr<const OFX::Image> srcImg(srcClip_->fetchImage(args.time)); OfxRectI srcRod,srcBounds; OFX::BitDepthEnum bitDepth = eBitDepthNone; if (srcImg.get()) { srcRod = srcImg->getRegionOfDefinition(); srcBounds = srcImg->getBounds(); bitDepth = srcImg->getPixelDepth(); if (srcImg->getRenderScale().x != args.renderScale.x || srcImg->getRenderScale().y != args.renderScale.y || srcImg->getField() != args.fieldToRender) { setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); OFX::throwSuiteStatusException(kOfxStatFailed); return; } } if (!dstClip_) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } assert(dstClip_); std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time)); if (!dstImg.get()) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (dstImg->getRenderScale().x != args.renderScale.x || dstImg->getRenderScale().y != args.renderScale.y || dstImg->getField() != args.fieldToRender) { setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); OFX::throwSuiteStatusException(kOfxStatFailed); return; } OfxRectI dstRod = dstImg->getRegionOfDefinition(); // get bit depth OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth(); if (dstBitDepth != OFX::eBitDepthFloat || (srcImg.get() && dstBitDepth != srcImg->getPixelDepth())) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } // get pixel component OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents(); if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha) || (srcImg.get() && (dstComponents != srcImg->getPixelComponents()))) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } std::string channels; switch (dstComponents) { case ePixelComponentRGBA: channels = "RGBA"; break; case ePixelComponentRGB: channels = "RGB"; break; case ePixelComponentAlpha: channels = "A"; break; } // are we in the image bounds OfxRectI dstBounds = dstImg->getBounds(); if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 || args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) { OFX::throwSuiteStatusException(kOfxStatErrValue); return; } // get param //double swirl; //swirlDegree_->getValueAtTime(args.time, swirl); // read image Magick::Image image(srcRod.x2-srcRod.x1,srcRod.y2-srcRod.y1,channels,Magick::FloatPixel,(float*)srcImg->getPixelData()); // proc image //image.swirl(swirl); image.virtualPixelMethod(Magick::BlackVirtualPixelMethod); const double polarArgs[4] = {0, 0, 0, 0}; image.distort(Magick::PolarDistortion, 1, polarArgs, Magick::MagickTrue); // return image switch (dstBitDepth) { case eBitDepthUByte: if (image.depth()>8) image.depth(8); image.write(0,0,dstRod.x2-dstRod.x1,dstRod.y2-dstRod.y1,channels,Magick::CharPixel,(float*)dstImg->getPixelData()); break; case eBitDepthUShort: if (image.depth()>16) image.depth(16); image.write(0,0,dstRod.x2-dstRod.x1,dstRod.y2-dstRod.y1,channels,Magick::ShortPixel,(float*)dstImg->getPixelData()); break; case eBitDepthFloat: image.write(0,0,dstRod.x2-dstRod.x1,dstRod.y2-dstRod.y1,channels,Magick::FloatPixel,(float*)dstImg->getPixelData()); break; } } bool PolarPlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return false; } if (srcClip_ && srcClip_->isConnected()) { rod = srcClip_->getRegionOfDefinition(args.time); } else { rod.x1 = rod.y1 = kOfxFlagInfiniteMin; rod.x2 = rod.y2 = kOfxFlagInfiniteMax; } return true; } mDeclarePluginFactory(PolarPluginFactory, {}, {}); /** @brief The basic describe function, passed a plugin descriptor */ void PolarPluginFactory::describe(OFX::ImageEffectDescriptor &desc) { // basic labels desc.setLabel(kPluginName); desc.setPluginGrouping(kPluginGrouping); desc.setPluginDescription(kPluginDescription); // add the supported contexts desc.addSupportedContext(eContextGeneral); desc.addSupportedContext(eContextFilter); // add supported pixel depths desc.addSupportedBitDepth(eBitDepthUByte); desc.addSupportedBitDepth(eBitDepthUShort); desc.addSupportedBitDepth(eBitDepthFloat); desc.setSupportsTiles(kSupportsTiles); desc.setSupportsMultiResolution(kSupportsMultiResolution); desc.setRenderThreadSafety(kRenderThreadSafety); } /** @brief The describe in context function, passed a plugin descriptor and a context */ void PolarPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/) { // create the mandated source clip ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName); srcClip->addSupportedComponent(ePixelComponentRGBA); srcClip->addSupportedComponent(ePixelComponentRGB); //srcClip->addSupportedComponent(ePixelComponentAlpha); // should work, not tested srcClip->setTemporalClipAccess(false); srcClip->setSupportsTiles(kSupportsTiles); srcClip->setIsMask(false); // create the mandated output clip ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName); dstClip->addSupportedComponent(ePixelComponentRGBA); dstClip->addSupportedComponent(ePixelComponentRGB); //dstClip->addSupportedComponent(ePixelComponentAlpha); // should work, not tested dstClip->setSupportsTiles(kSupportsTiles); // make some pages and to things in PageParamDescriptor *page = desc.definePageParam(kPluginName); /*{ DoubleParamDescriptor *param = desc.defineDoubleParam(kParamSwirl); param->setLabel(kParamSwirlLabel); param->setHint(kParamSwirlHint); param->setRange(-360, 360); param->setDisplayRange(-360, 360); param->setDefault(kParamSwirlDefault); page->addChild(*param); }*/ } /** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */ ImageEffect* PolarPluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/) { return new PolarPlugin(handle); } void getPolarPluginID(OFX::PluginFactoryArray &ids) { static PolarPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor); ids.push_back(&p); } <commit_msg>Polar: add some params<commit_after>/* openfx-arena - https://github.com/olear/openfx-arena Copyright (c) 2015, Ole-André Rodlie <olear@fxarena.net> Copyright (c) 2015, FxArena DA <mail@fxarena.net> 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. * Neither the name of FxArena DA nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * 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 "Polar.h" #include "ofxsMacros.h" #include <Magick++.h> #define kPluginName "Polar" #define kPluginGrouping "Filter" #define kPluginDescription "Polar Distort Image" #define kPluginIdentifier "net.fxarena.openfx.Polar" #define kPluginVersionMajor 0 #define kPluginVersionMinor 1 #define kParamVPixel "virtualPixelMethod" #define kParamVPixelLabel "Virtual Pixel" #define kParamVPixelHint "Virtual Pixel Method" #define kParamVPixelDefault 7 #define kParamDistort "distort" #define kParamDistortLabel "Distort" #define kParamDistortHint "Distort type" #define kParamDistortDefault 0 /*#define kParamRadius "radius" #define kParamRadiusLabel "Radius" #define kParamRadiusHint "Radius amount" #define kParamRadiusDefault 0*/ #define kSupportsTiles 0 #define kSupportsMultiResolution 1 #define kSupportsRenderScale 1 #define kRenderThreadSafety eRenderInstanceSafe using namespace OFX; class PolarPlugin : public OFX::ImageEffect { public: PolarPlugin(OfxImageEffectHandle handle); virtual ~PolarPlugin(); virtual void render(const OFX::RenderArguments &args) OVERRIDE FINAL; virtual bool getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL; private: OFX::Clip *dstClip_; OFX::Clip *srcClip_; OFX::ChoiceParam *vpixel_; OFX::ChoiceParam *distort_; //OFX::IntParam *radius_; }; PolarPlugin::PolarPlugin(OfxImageEffectHandle handle) : OFX::ImageEffect(handle) , dstClip_(0) , srcClip_(0) { Magick::InitializeMagick(""); dstClip_ = fetchClip(kOfxImageEffectOutputClipName); assert(dstClip_ && (dstClip_->getPixelComponents() == OFX::ePixelComponentRGBA || dstClip_->getPixelComponents() == OFX::ePixelComponentRGB)); srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName); assert(srcClip_ && (srcClip_->getPixelComponents() == OFX::ePixelComponentRGBA || srcClip_->getPixelComponents() == OFX::ePixelComponentRGB)); vpixel_ = fetchChoiceParam(kParamVPixel); distort_ = fetchChoiceParam(kParamDistort); //radius_ = fetchIntParam(kParamRadius); assert(vpixel_ && distort_ /*&& radius_*/); } PolarPlugin::~PolarPlugin() { } void PolarPlugin::render(const OFX::RenderArguments &args) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (!srcClip_) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } assert(srcClip_); std::auto_ptr<const OFX::Image> srcImg(srcClip_->fetchImage(args.time)); OfxRectI srcRod,srcBounds; OFX::BitDepthEnum bitDepth = eBitDepthNone; if (srcImg.get()) { srcRod = srcImg->getRegionOfDefinition(); srcBounds = srcImg->getBounds(); bitDepth = srcImg->getPixelDepth(); if (srcImg->getRenderScale().x != args.renderScale.x || srcImg->getRenderScale().y != args.renderScale.y || srcImg->getField() != args.fieldToRender) { setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); OFX::throwSuiteStatusException(kOfxStatFailed); return; } } if (!dstClip_) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } assert(dstClip_); std::auto_ptr<OFX::Image> dstImg(dstClip_->fetchImage(args.time)); if (!dstImg.get()) { OFX::throwSuiteStatusException(kOfxStatFailed); return; } if (dstImg->getRenderScale().x != args.renderScale.x || dstImg->getRenderScale().y != args.renderScale.y || dstImg->getField() != args.fieldToRender) { setPersistentMessage(OFX::Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); OFX::throwSuiteStatusException(kOfxStatFailed); return; } OfxRectI dstRod = dstImg->getRegionOfDefinition(); // get bit depth OFX::BitDepthEnum dstBitDepth = dstImg->getPixelDepth(); if (dstBitDepth != OFX::eBitDepthFloat || (srcImg.get() && dstBitDepth != srcImg->getPixelDepth())) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } // get pixel component OFX::PixelComponentEnum dstComponents = dstImg->getPixelComponents(); if ((dstComponents != OFX::ePixelComponentRGBA && dstComponents != OFX::ePixelComponentRGB && dstComponents != OFX::ePixelComponentAlpha) || (srcImg.get() && (dstComponents != srcImg->getPixelComponents()))) { OFX::throwSuiteStatusException(kOfxStatErrFormat); return; } std::string channels; switch (dstComponents) { case ePixelComponentRGBA: channels = "RGBA"; break; case ePixelComponentRGB: channels = "RGB"; break; case ePixelComponentAlpha: channels = "A"; break; } // are we in the image bounds OfxRectI dstBounds = dstImg->getBounds(); if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 || args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) { OFX::throwSuiteStatusException(kOfxStatErrValue); return; } // get params int vpixel,distort,radius; vpixel_->getValueAtTime(args.time, vpixel); distort_->getValueAtTime(args.time, distort); //radius_->getValueAtTime(args.time, radius); radius = 0; // read image Magick::Image image(srcRod.x2-srcRod.x1,srcRod.y2-srcRod.y1,channels,Magick::FloatPixel,(float*)srcImg->getPixelData()); Magick::Image wrapper(Magick::Geometry(srcRod.x2-srcRod.x1,srcRod.y2-srcRod.y1),Magick::Color("rgba(0,0,0,0)")); // flip it! image.flip(); // set virtual pixel switch (vpixel) { case 0: image.virtualPixelMethod(Magick::UndefinedVirtualPixelMethod); break; case 1: image.virtualPixelMethod(Magick::BackgroundVirtualPixelMethod); break; case 2: image.virtualPixelMethod(Magick::BlackVirtualPixelMethod); break; case 3: image.virtualPixelMethod(Magick::CheckerTileVirtualPixelMethod); break; case 4: image.virtualPixelMethod(Magick::DitherVirtualPixelMethod); break; case 5: image.virtualPixelMethod(Magick::EdgeVirtualPixelMethod); break; case 6: image.virtualPixelMethod(Magick::GrayVirtualPixelMethod); break; case 7: image.virtualPixelMethod(Magick::HorizontalTileVirtualPixelMethod); break; case 8: image.virtualPixelMethod(Magick::HorizontalTileEdgeVirtualPixelMethod); break; case 9: image.virtualPixelMethod(Magick::MirrorVirtualPixelMethod); break; case 10: image.virtualPixelMethod(Magick::RandomVirtualPixelMethod); break; case 11: image.virtualPixelMethod(Magick::TileVirtualPixelMethod); break; case 12: image.virtualPixelMethod(Magick::TransparentVirtualPixelMethod); break; case 13: image.virtualPixelMethod(Magick::VerticalTileVirtualPixelMethod); break; case 14: image.virtualPixelMethod(Magick::VerticalTileEdgeVirtualPixelMethod); break; case 15: image.virtualPixelMethod(Magick::WhiteVirtualPixelMethod); break; } // set bg image.backgroundColor(Magick::Color("black")); wrapper.backgroundColor(Magick::Color("black")); // set args const double polarArgs[4] = {0, 0, 0, 0}; // TODO! add params // distort switch (distort) { case 0: image.distort(Magick::PolarDistortion, radius, NULL, Magick::MagickTrue); break; case 1: image.distort(Magick::DePolarDistortion, radius, NULL, Magick::MagickTrue); break; } // flip and comp image.flip(); wrapper.composite(image,0,0,Magick::OverCompositeOp); // return image switch (dstBitDepth) { case eBitDepthUByte: if (image.depth()>8) image.depth(8); wrapper.write(0,0,dstRod.x2-dstRod.x1,dstRod.y2-dstRod.y1,channels,Magick::CharPixel,(float*)dstImg->getPixelData()); break; case eBitDepthUShort: if (image.depth()>16) image.depth(16); wrapper.write(0,0,dstRod.x2-dstRod.x1,dstRod.y2-dstRod.y1,channels,Magick::ShortPixel,(float*)dstImg->getPixelData()); break; case eBitDepthFloat: wrapper.write(0,0,dstRod.x2-dstRod.x1,dstRod.y2-dstRod.y1,channels,Magick::FloatPixel,(float*)dstImg->getPixelData()); break; } } bool PolarPlugin::getRegionOfDefinition(const OFX::RegionOfDefinitionArguments &args, OfxRectD &rod) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { OFX::throwSuiteStatusException(kOfxStatFailed); return false; } if (srcClip_ && srcClip_->isConnected()) { rod = srcClip_->getRegionOfDefinition(args.time); } else { rod.x1 = rod.y1 = kOfxFlagInfiniteMin; rod.x2 = rod.y2 = kOfxFlagInfiniteMax; } return true; } mDeclarePluginFactory(PolarPluginFactory, {}, {}); /** @brief The basic describe function, passed a plugin descriptor */ void PolarPluginFactory::describe(OFX::ImageEffectDescriptor &desc) { // basic labels desc.setLabel(kPluginName); desc.setPluginGrouping(kPluginGrouping); desc.setPluginDescription(kPluginDescription); // add the supported contexts desc.addSupportedContext(eContextGeneral); desc.addSupportedContext(eContextFilter); // add supported pixel depths desc.addSupportedBitDepth(eBitDepthUByte); desc.addSupportedBitDepth(eBitDepthUShort); desc.addSupportedBitDepth(eBitDepthFloat); desc.setSupportsTiles(kSupportsTiles); desc.setSupportsMultiResolution(kSupportsMultiResolution); desc.setRenderThreadSafety(kRenderThreadSafety); } /** @brief The describe in context function, passed a plugin descriptor and a context */ void PolarPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum /*context*/) { // create the mandated source clip ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName); srcClip->addSupportedComponent(ePixelComponentRGBA); srcClip->addSupportedComponent(ePixelComponentRGB); //srcClip->addSupportedComponent(ePixelComponentAlpha); // should work, not tested srcClip->setTemporalClipAccess(false); srcClip->setSupportsTiles(kSupportsTiles); srcClip->setIsMask(false); // create the mandated output clip ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName); dstClip->addSupportedComponent(ePixelComponentRGBA); dstClip->addSupportedComponent(ePixelComponentRGB); //dstClip->addSupportedComponent(ePixelComponentAlpha); // should work, not tested dstClip->setSupportsTiles(kSupportsTiles); // make some pages and to things in PageParamDescriptor *page = desc.definePageParam(kPluginName); { ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamVPixel); param->setLabel(kParamVPixelLabel); param->setHint(kParamVPixelHint); param->appendOption("Undefined"); param->appendOption("Background"); param->appendOption("Black"); param->appendOption("CheckerTile"); param->appendOption("Dither"); param->appendOption("Edge"); param->appendOption("Gray"); param->appendOption("HorizontalTile"); param->appendOption("HorizontalTileEdge"); param->appendOption("Mirror"); param->appendOption("Random"); param->appendOption("Tile"); param->appendOption("Transparent"); param->appendOption("VerticalTile"); param->appendOption("VerticalTileEdge"); param->appendOption("White"); param->setDefault(kParamVPixelDefault); param->setAnimates(true); page->addChild(*param); } { ChoiceParamDescriptor *param = desc.defineChoiceParam(kParamDistort); param->setLabel(kParamDistortLabel); param->setHint(kParamDistortHint); param->appendOption("Polar"); param->appendOption("DePolar"); param->setDefault(kParamDistortDefault); param->setAnimates(true); page->addChild(*param); } /*{ IntParamDescriptor *param = desc.defineIntParam(kParamRadius); param->setLabel(kParamRadiusLabel); param->setHint(kParamRadiusHint); param->setRange(0, 10); param->setDisplayRange(0, 10); param->setDefault(kParamRadiusDefault); page->addChild(*param); }*/ } /** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */ ImageEffect* PolarPluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/) { return new PolarPlugin(handle); } void getPolarPluginID(OFX::PluginFactoryArray &ids) { static PolarPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor); ids.push_back(&p); } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2012-2013 Danny Y., Rapptz // 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. #ifndef GEARS_CONCEPTS_BASIC_HPP #define GEARS_CONCEPTS_BASIC_HPP #include "alias.hpp" #include <utility> namespace gears { namespace basic_detail { struct is_lvalue_swappable { template<typename T, typename U> static auto test(int) -> decltype(std::swap(std::declval<LRef<T>>(), std::declval<LRef<U>>()), std::true_type{}) {} template<typename...> static std::false_type test(...); }; struct is_rvalue_swappable { template<typename T, typename U> static auto test(int) -> decltype(std::swap(std::declval<RRef<T>>(), std::declval<RRef<U>>()), std::true_type{}) {} template<typename...> static std::false_type test(...); }; } // basic_detail template<typename T> struct DefaultConstructible : std::is_default_constructible<NoRef<T>> {}; template<typename T> struct MoveConstructible : std::is_move_constructible<NoRef<T>> {}; template<typename T> struct CopyConstructible : std::is_copy_constructible<NoRef<T>> {}; template<typename T> struct MoveAssignable : std::is_move_assignable<NoRef<T>> {}; template<typename T> struct CopyAssignable : std::is_copy_assignable<NoRef<T>> {}; template<typename T> struct Movable : And<MoveAssignable<T>, MoveConstructible<T>> {}; template<typename T> struct Copyable : And<CopyAssignable<T>, CopyConstructible<T>> {}; template<typename T> struct Assignable : And<MoveAssignable<T>, CopyAssignable<T>> {}; template<typename T> struct Destructible : std::is_destructible<NoRef<T>> {}; template<typename T> struct Constructible : std::is_constructible<NoRef<T>> {}; template<typename T> struct StandardLayout : std::is_standard_layout<NoRef<T>> {}; template<typename T> struct POD : std::is_pod<NoRef<T>> {}; template<typename T, typename U = T> struct LValueSwappable : TraitOf<basic_detail::is_lvalue_swappable, T, U> {}; template<typename T, typename U = T> struct RValueSwappable : TraitOf<basic_detail::is_rvalue_swappable, T, U> {}; template<typename T, typename U = T> struct Swappable : And<LValueSwappable<T, U>, RValueSwappable<T, U>> {}; template<typename T> struct ContextualBool : std::is_constructible<bool, T> {}; template<typename T> struct Integral : std::is_integral<T> {}; template<typename T> struct FloatingPoint : std::is_floating_point<T> {}; template<typename T> struct Signed : std::is_signed<T> {}; template<typename T> struct Unsigned : std::is_unsigned<T> {}; template<typename T> struct Arithmetic : std::is_arithmetic<T> {}; template<typename T> struct Fundamental : std::is_fundamental<T> {}; template<typename T> struct Compound : std::is_compound<T> {}; template<typename T> struct Pointer : std::is_pointer<T> {}; template<typename T> struct LValueReference : std::is_lvalue_reference<T> {}; template<typename T> struct RValueReference : std::is_rvalue_reference<T> {}; template<typename T> struct Reference : std::is_reference<T> {}; namespace basic_detail { struct is_less_than_comparable { template<typename T, typename U, typename LT = decltype(std::declval<T&>() < std::declval<U&>()), TrueIf<ContextualBool<LT>>...> static std::true_type test(int); template<typename...> static std::false_type test(...); }; struct is_equality_comparable { template<typename T, typename U, typename EQ = decltype(std::declval<T&>() == std::declval<U&>()), typename NE = decltype(std::declval<T&>() != std::declval<U&>()), TrueIf<ContextualBool<EQ>, ContextualBool<NE>>...> static std::true_type test(int); template<typename...> static std::false_type test(...); }; struct is_comparable { template<typename T, typename U, typename LT = decltype(std::declval<T&>() < std::declval<U&>()), typename LE = decltype(std::declval<T&>() <= std::declval<U&>()), typename GT = decltype(std::declval<T&>() > std::declval<U&>()), typename GE = decltype(std::declval<T&>() >= std::declval<U&>()), TrueIf<ContextualBool<LT>, ContextualBool<LE>, ContextualBool<GT>, ContextualBool<GE>>...> static std::true_type test(int); template<typename...> static std::false_type test(...); }; template<typename Pointer> struct is_np_assignable_impl { private: Pointer a; std::nullptr_t np = nullptr; const std::nullptr_t npc = nullptr; public: static const bool one = std::is_same<Pointer&, decltype(a = np)>(); static const bool two = std::is_same<Pointer&, decltype(a = npc)>(); static const bool three = std::is_constructible<Pointer, std::nullptr_t>(); static const bool four = std::is_constructible<Pointer, const std::nullptr_t>(); static const bool value = one && two && three && four; }; template<typename T> struct is_np_assign : std::integral_constant<bool, is_np_assignable_impl<T>::value> {}; } // basic_detail template<typename T, typename U = T> struct LessThanComparable : TraitOf<basic_detail::is_less_than_comparable, T, U> {}; template<typename T, typename U = T> struct EqualityComparable : TraitOf<basic_detail::is_equality_comparable, T, U> {}; template<typename T, typename U = T> struct Comparable : TraitOf<basic_detail::is_comparable, T, U> {}; template<typename T> struct NullablePointer : And<DefaultConstructible<T>, CopyConstructible<T>, CopyAssignable<T>, Destructible<T>, EqualityComparable<T, std::nullptr_t>, EqualityComparable<std::nullptr_t, T>, basic_detail::is_np_assign<T>> {}; } // gears #endif // GEARS_CONCEPTS_BASIC_HPP<commit_msg>Fix issue with Constructible concept (Issue #9)<commit_after>// The MIT License (MIT) // Copyright (c) 2012-2013 Danny Y., Rapptz // 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. #ifndef GEARS_CONCEPTS_BASIC_HPP #define GEARS_CONCEPTS_BASIC_HPP #include "alias.hpp" #include <utility> namespace gears { namespace basic_detail { struct is_lvalue_swappable { template<typename T, typename U> static auto test(int) -> decltype(std::swap(std::declval<LRef<T>>(), std::declval<LRef<U>>()), std::true_type{}) {} template<typename...> static std::false_type test(...); }; struct is_rvalue_swappable { template<typename T, typename U> static auto test(int) -> decltype(std::swap(std::declval<RRef<T>>(), std::declval<RRef<U>>()), std::true_type{}) {} template<typename...> static std::false_type test(...); }; } // basic_detail template<typename T> struct DefaultConstructible : std::is_default_constructible<NoRef<T>> {}; template<typename T> struct MoveConstructible : std::is_move_constructible<NoRef<T>> {}; template<typename T> struct CopyConstructible : std::is_copy_constructible<NoRef<T>> {}; template<typename T> struct MoveAssignable : std::is_move_assignable<NoRef<T>> {}; template<typename T> struct CopyAssignable : std::is_copy_assignable<NoRef<T>> {}; template<typename T> struct Movable : And<MoveAssignable<T>, MoveConstructible<T>> {}; template<typename T> struct Copyable : And<CopyAssignable<T>, CopyConstructible<T>> {}; template<typename T> struct Assignable : And<MoveAssignable<T>, CopyAssignable<T>> {}; template<typename T> struct Destructible : std::is_destructible<NoRef<T>> {}; template<typename T, typename... Args> struct Constructible : std::is_constructible<NoRef<T>, Args...> {}; template<typename T> struct StandardLayout : std::is_standard_layout<NoRef<T>> {}; template<typename T> struct POD : std::is_pod<NoRef<T>> {}; template<typename T, typename U = T> struct LValueSwappable : TraitOf<basic_detail::is_lvalue_swappable, T, U> {}; template<typename T, typename U = T> struct RValueSwappable : TraitOf<basic_detail::is_rvalue_swappable, T, U> {}; template<typename T, typename U = T> struct Swappable : And<LValueSwappable<T, U>, RValueSwappable<T, U>> {}; template<typename T> struct ContextualBool : std::is_constructible<bool, T> {}; template<typename T> struct Integral : std::is_integral<T> {}; template<typename T> struct FloatingPoint : std::is_floating_point<T> {}; template<typename T> struct Signed : std::is_signed<T> {}; template<typename T> struct Unsigned : std::is_unsigned<T> {}; template<typename T> struct Arithmetic : std::is_arithmetic<T> {}; template<typename T> struct Fundamental : std::is_fundamental<T> {}; template<typename T> struct Compound : std::is_compound<T> {}; template<typename T> struct Pointer : std::is_pointer<T> {}; template<typename T> struct LValueReference : std::is_lvalue_reference<T> {}; template<typename T> struct RValueReference : std::is_rvalue_reference<T> {}; template<typename T> struct Reference : std::is_reference<T> {}; namespace basic_detail { struct is_less_than_comparable { template<typename T, typename U, typename LT = decltype(std::declval<T&>() < std::declval<U&>()), TrueIf<ContextualBool<LT>>...> static std::true_type test(int); template<typename...> static std::false_type test(...); }; struct is_equality_comparable { template<typename T, typename U, typename EQ = decltype(std::declval<T&>() == std::declval<U&>()), typename NE = decltype(std::declval<T&>() != std::declval<U&>()), TrueIf<ContextualBool<EQ>, ContextualBool<NE>>...> static std::true_type test(int); template<typename...> static std::false_type test(...); }; struct is_comparable { template<typename T, typename U, typename LT = decltype(std::declval<T&>() < std::declval<U&>()), typename LE = decltype(std::declval<T&>() <= std::declval<U&>()), typename GT = decltype(std::declval<T&>() > std::declval<U&>()), typename GE = decltype(std::declval<T&>() >= std::declval<U&>()), TrueIf<ContextualBool<LT>, ContextualBool<LE>, ContextualBool<GT>, ContextualBool<GE>>...> static std::true_type test(int); template<typename...> static std::false_type test(...); }; template<typename Pointer> struct is_np_assignable_impl { private: Pointer a; std::nullptr_t np = nullptr; const std::nullptr_t npc = nullptr; public: static const bool one = std::is_same<Pointer&, decltype(a = np)>(); static const bool two = std::is_same<Pointer&, decltype(a = npc)>(); static const bool three = Constructible<Pointer, std::nullptr_t>(); static const bool four = Constructible<Pointer, const std::nullptr_t>(); static const bool value = one && two && three && four; }; template<typename T> struct is_np_assign : std::integral_constant<bool, is_np_assignable_impl<T>::value> {}; } // basic_detail template<typename T, typename U = T> struct LessThanComparable : TraitOf<basic_detail::is_less_than_comparable, T, U> {}; template<typename T, typename U = T> struct EqualityComparable : TraitOf<basic_detail::is_equality_comparable, T, U> {}; template<typename T, typename U = T> struct Comparable : TraitOf<basic_detail::is_comparable, T, U> {}; template<typename T> struct NullablePointer : And<DefaultConstructible<T>, CopyConstructible<T>, CopyAssignable<T>, Destructible<T>, EqualityComparable<T, std::nullptr_t>, EqualityComparable<std::nullptr_t, T>, basic_detail::is_np_assign<T>> {}; } // gears #endif // GEARS_CONCEPTS_BASIC_HPP<|endoftext|>
<commit_before>/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2003 - 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ #include "event/Listener.h" #include "base/globalsdef.h" USE_NAMESPACE Listener::Listener() { } <commit_msg>Removed Listener.cpp<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> #include <map> // Loriano: let's try Armadillo quick code #include <armadillo> #include <cassert> #include <getopt.h> #include <unistd.h> #include <alloca.h> #include <pcafitter_private.hpp> // lstorchi: basi code to fit tracks, using the PCA constants generated // by the related generatepca void build_and_compare (arma::mat & paramslt, arma::mat & coordslt, arma::mat & cmtx, arma::rowvec & q, bool verbose) { double * oneoverptcmp, * phicmp, * etacmp, * z0cmp, * d0cmp; oneoverptcmp = new double [(int)coordslt.n_rows]; phicmp = new double [(int)coordslt.n_rows]; etacmp = new double [(int)coordslt.n_rows]; z0cmp = new double [(int)coordslt.n_rows]; d0cmp = new double [(int)coordslt.n_rows]; pcafitter::computeparameters (cmtx, q, coordslt, oneoverptcmp, phicmp, etacmp, z0cmp, d0cmp); arma::running_stat<double> pc[PARAMDIM]; for (int i=0; i<(int)coordslt.n_rows; ++i) { pc[PTIDX](fabs(oneoverptcmp[i] - paramslt(i, PTIDX))/ (fabs(oneoverptcmp[i] + paramslt(i, PTIDX))/2.0)); pc[PHIIDX](fabs(phicmp[i] - paramslt(i, PHIIDX))/ (fabs(phicmp[i] + paramslt(i, PHIIDX))/2.0)); pc[TETHAIDX](fabs(etacmp[i] - paramslt(i, TETHAIDX))/ (fabs(etacmp[i] + paramslt(i, TETHAIDX))/2.0)); pc[D0IDX](fabs(d0cmp[i] - paramslt(i, D0IDX))/ (fabs(d0cmp[i] + paramslt(i, D0IDX))/2.0)); pc[Z0IDX](fabs(z0cmp[i] - paramslt(i, Z0IDX))/ (fabs(z0cmp[i] + paramslt(i, Z0IDX))/2.0)); if (verbose) { std::cout << "For track : " << i+1 << std::endl; std::cout << " 1/pt cmpt " << oneoverptcmp[i] << std::endl; std::cout << " 1/pt calc " << paramslt(i, PTIDX) << std::endl; std::cout << " phi cmpt " << phicmp[i] << std::endl; std::cout << " phi calc " << paramslt(i, PHIIDX) << std::endl; std::cout << " cot(tetha/2) cmpt " << etacmp[i] << std::endl; std::cout << " cot(tetha/2) calc " << paramslt(i, TETHAIDX) << std::endl; std::cout << " d0 cmpt " << d0cmp[i] << std::endl; std::cout << " d0 calc " << paramslt(i, D0IDX) << std::endl; std::cout << " z0 cmpt " << z0cmp[i] << std::endl; std::cout << " z0 calc " << paramslt(i, Z0IDX) << std::endl; } } for (int i=0; i<PARAMDIM; ++i) std::cout << "For " << pcafitter::paramidxtostring(i) << " error " << 100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl; delete [] oneoverptcmp; delete [] phicmp; delete [] etacmp; delete [] z0cmp; delete [] d0cmp; } void usage (char * name) { std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl; std::cerr << std::endl; std::cerr << " -h, --help : display this help and exit" << std::endl; std::cerr << " -V, --verbose : verbose option on" << std::endl; std::cerr << " -v, --version : print version and exit" << std::endl; std::cerr << " -c, --cmtx=[fillename] : CMTX filename [default is c.bin]" << std::endl; std::cerr << " -q, --qvct=[fillename] : QVCT filename [default is q.bin]" << std::endl; std::cerr << " -s, --subsector=[subsec] : by default use values of the bigger subsector" << std::endl; std::cerr << " with this option you can speficy to perform " << std::endl; std::cerr << " prediction for subsector subsec " << std::endl; std::cerr << " -l, --subladder=[subld] : by default use values of the bigger subladder " << std::endl; std::cerr << " with this option you can speficy to perform " << std::endl; std::cerr << " prediction for subladder subld " << std::endl; exit(1); } int main (int argc, char ** argv) { std::string qfname = "q.bin"; std::string cfname = "c.bin"; std::string subsec = ""; std::string sublad = ""; bool verbose = false; while (1) { int c, option_index; static struct option long_options[] = { {"help", 0, NULL, 'h'}, {"cmtx", 1, NULL, 'c'}, {"qvct", 1, NULL, 'q'}, {"subsector", 1, NULL, 's'}, {"subladder", 1, NULL, 'l'}, {"verbose", 0, NULL, 'V'}, {"version", 0, NULL, 'v'}, {0, 0, 0, 0} }; c = getopt_long (argc, argv, "vhVc:q:s:l:", long_options, &option_index); if (c == -1) break; switch (c) { case 'V': verbose = true; break; case 'v': std::cout << "Version: " << pcafitter::get_version_string() << std::endl; exit(1); break; case 'h': usage (argv[0]); break; case 's': subsec = optarg; break; case 'l': sublad = optarg; break; case'c': cfname = optarg; break; case 'q': qfname = optarg; break; default: usage (argv[0]); break; } } if (optind >= argc) usage (argv[0]); char * filename = (char *) alloca (strlen(argv[optind]) + 1); strcpy (filename, argv[optind]); // leggere file coordinate tracce e file costanti PCA // N righe di 9 double sono le coordinate // matrice C e vettore q sono le costanti arma::mat cmtx; arma::rowvec q; std::cout << "Read constant from files (" << cfname << " and " << qfname << ")" << std::endl; pcafitter::readarmmat(cfname.c_str(), cmtx); pcafitter::readarmvct(qfname.c_str(), q); std::cout << "Reading data from " << filename << " file " << std::endl; int num_of_line = pcafitter::numofline(filename); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << "file has " << num_of_ent << " entries " << std::endl; arma::mat layer, ladder, module, coord, param; layer.set_size(num_of_ent,COORDIM); ladder.set_size(num_of_ent,COORDIM); module.set_size(num_of_ent,COORDIM); coord.set_size(num_of_ent,DIMPERCOORD*COORDIM); param.set_size(num_of_ent,PARAMDIM); std::map<std::string, int> subsectors, subladders; std::vector<std::string> subladderslist, subsectorslist; // leggere file coordinate tracce simulate plus parametri pcafitter::readingfromfile (filename, param, coord, layer, ladder, module, subsectors, subladders, subsectorslist, subladderslist, num_of_ent); if ((subsec == "") && (sublad == "")) { int maxnumber; std::cout << "Looking for bigger subsector" << std::endl; std::cout << "We found " << subsectors.size() << " subsectors " << std::endl; pcafitter::select_bigger_sub (subsectors, verbose, maxnumber, subsec); std::cout << "Selected subsector " << subsec << " numevt: " << maxnumber << std::endl; std::cout << "Looking for bigger subladder" << std::endl; std::cout << "We found " << subladders.size() << " subladders " << std::endl; pcafitter::select_bigger_sub (subladders, verbose, maxnumber, sublad); std::cout << "Selected subladder " << sublad << " numevt: " << maxnumber << std::endl; } if (subsec != "") { arma::mat paramslt, coordslt; std::cout << "Using subsector " << subsec << std::endl; pcafitter::extract_sub (subsectorslist, subsec, param, coord, paramslt, coordslt); build_and_compare (paramslt, coordslt, cmtx, q, verbose); } if (sublad != "") { arma::mat paramslt, coordslt; std::cout << "Using subladder " << sublad << std::endl; pcafitter::extract_sub (subladderslist, sublad, param, coord, paramslt, coordslt); build_and_compare (paramslt, coordslt, cmtx, q, verbose); } return 0; } <commit_msg>adding use all subtower and subladder also to the fitter<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> #include <map> #include <set> // Loriano: let's try Armadillo quick code #include <armadillo> #include <cassert> #include <sys/stat.h> #include <getopt.h> #include <unistd.h> #include <alloca.h> #include <pcafitter_private.hpp> // lstorchi: basi code to fit tracks, using the PCA constants generated // by the related generatepca namespace { bool file_exists(const std::string& filename) { struct stat buf; if (stat(filename.c_str(), &buf) != -1) return true; return false; } } void build_and_compare (arma::mat & paramslt, arma::mat & coordslt, arma::mat & cmtx, arma::rowvec & q, bool verbose) { double * oneoverptcmp, * phicmp, * etacmp, * z0cmp, * d0cmp; oneoverptcmp = new double [(int)coordslt.n_rows]; phicmp = new double [(int)coordslt.n_rows]; etacmp = new double [(int)coordslt.n_rows]; z0cmp = new double [(int)coordslt.n_rows]; d0cmp = new double [(int)coordslt.n_rows]; pcafitter::computeparameters (cmtx, q, coordslt, oneoverptcmp, phicmp, etacmp, z0cmp, d0cmp); arma::running_stat<double> pc[PARAMDIM]; for (int i=0; i<(int)coordslt.n_rows; ++i) { pc[PTIDX](fabs(oneoverptcmp[i] - paramslt(i, PTIDX))/ (fabs(oneoverptcmp[i] + paramslt(i, PTIDX))/2.0)); pc[PHIIDX](fabs(phicmp[i] - paramslt(i, PHIIDX))/ (fabs(phicmp[i] + paramslt(i, PHIIDX))/2.0)); pc[TETHAIDX](fabs(etacmp[i] - paramslt(i, TETHAIDX))/ (fabs(etacmp[i] + paramslt(i, TETHAIDX))/2.0)); pc[D0IDX](fabs(d0cmp[i] - paramslt(i, D0IDX))/ (fabs(d0cmp[i] + paramslt(i, D0IDX))/2.0)); pc[Z0IDX](fabs(z0cmp[i] - paramslt(i, Z0IDX))/ (fabs(z0cmp[i] + paramslt(i, Z0IDX))/2.0)); if (verbose) { std::cout << "For track : " << i+1 << std::endl; std::cout << " 1/pt cmpt " << oneoverptcmp[i] << std::endl; std::cout << " 1/pt calc " << paramslt(i, PTIDX) << std::endl; std::cout << " phi cmpt " << phicmp[i] << std::endl; std::cout << " phi calc " << paramslt(i, PHIIDX) << std::endl; std::cout << " cot(tetha/2) cmpt " << etacmp[i] << std::endl; std::cout << " cot(tetha/2) calc " << paramslt(i, TETHAIDX) << std::endl; std::cout << " d0 cmpt " << d0cmp[i] << std::endl; std::cout << " d0 calc " << paramslt(i, D0IDX) << std::endl; std::cout << " z0 cmpt " << z0cmp[i] << std::endl; std::cout << " z0 calc " << paramslt(i, Z0IDX) << std::endl; } } for (int i=0; i<PARAMDIM; ++i) std::cout << "For " << pcafitter::paramidxtostring(i) << " error " << 100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl; delete [] oneoverptcmp; delete [] phicmp; delete [] etacmp; delete [] z0cmp; delete [] d0cmp; } void usage (char * name) { std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl; std::cerr << std::endl; std::cerr << " -h, --help : display this help and exit" << std::endl; std::cerr << " -V, --verbose : verbose option on" << std::endl; std::cerr << " -v, --version : print version and exit" << std::endl; std::cerr << " -c, --cmtx=[fillename] : CMTX filename [default is c.bin]" << std::endl; std::cerr << " -q, --qvct=[fillename] : QVCT filename [default is q.bin]" << std::endl; std::cerr << " -s, --subsector=[subsec] : by default use values of the bigger subsector" << std::endl; std::cerr << " with this option you can speficy to perform " << std::endl; std::cerr << " prediction for subsector subsec " << std::endl; std::cerr << " -l, --subladder=[subld] : by default use values of the bigger subladder " << std::endl; std::cerr << " with this option you can speficy to perform " << std::endl; std::cerr << " prediction for subladder subld " << std::endl; std::cerr << " -a, --all-subsectors : perform the fitting for all subsectors" << std::endl; std::cerr << " -r, --all-subladders : perform the fitting for all subladders" << std::endl; exit(1); } int main (int argc, char ** argv) { std::string qfname = "q.bin"; std::string cfname = "c.bin"; std::string subsec = ""; std::string sublad = ""; bool verbose = false; bool useallsubsectors = false; bool useallsubladders = false; while (1) { int c, option_index; static struct option long_options[] = { {"help", 0, NULL, 'h'}, {"cmtx", 1, NULL, 'c'}, {"qvct", 1, NULL, 'q'}, {"subsector", 1, NULL, 's'}, {"subladder", 1, NULL, 'l'}, {"verbose", 0, NULL, 'V'}, {"version", 0, NULL, 'v'}, {"all-subsectors", 0, NULL, 'a'}, {"all-subladders", 0, NULL, 'r'}, {0, 0, 0, 0} }; c = getopt_long (argc, argv, "arvhVc:q:s:l:", long_options, &option_index); if (c == -1) break; switch (c) { case 'a': useallsubsectors = true; break; case 'r': useallsubladders = true; break; case 'V': verbose = true; break; case 'v': std::cout << "Version: " << pcafitter::get_version_string() << std::endl; exit(1); break; case 'h': usage (argv[0]); break; case 's': subsec = optarg; break; case 'l': sublad = optarg; break; case'c': cfname = optarg; break; case 'q': qfname = optarg; break; default: usage (argv[0]); break; } } if (optind >= argc) usage (argv[0]); if (useallsubladders && useallsubsectors) usage (argv[0]); char * filename = (char *) alloca (strlen(argv[optind]) + 1); strcpy (filename, argv[optind]); // leggere file coordinate tracce e file costanti PCA // N righe di 9 double sono le coordinate // matrice C e vettore q sono le costanti arma::mat cmtx; arma::rowvec q; std::cout << "Reading data from " << filename << " file " << std::endl; int num_of_line = pcafitter::numofline(filename); std::cout << "file has " << num_of_line << " line " << std::endl; int num_of_ent = (num_of_line-1)/ENTDIM; std::cout << "file has " << num_of_ent << " entries " << std::endl; arma::mat layer, ladder, module, coord, param; layer.set_size(num_of_ent,COORDIM); ladder.set_size(num_of_ent,COORDIM); module.set_size(num_of_ent,COORDIM); coord.set_size(num_of_ent,DIMPERCOORD*COORDIM); param.set_size(num_of_ent,PARAMDIM); std::map<std::string, int> subsectors, subladders; std::vector<std::string> subladderslist, subsectorslist; // leggere file coordinate tracce simulate plus parametri if (!file_exists(filename)) { std::cerr << "Inout file does not exist" << std::endl; return 1; } pcafitter::readingfromfile (filename, param, coord, layer, ladder, module, subsectors, subladders, subsectorslist, subladderslist, num_of_ent); if (!useallsubsectors && !useallsubladders) { std::cout << "Read constant from files (" << cfname << " and " << qfname << ")" << std::endl; if (!file_exists(cfname) || !file_exists(qfname)) { std::cerr << "Constants file does not exist" << std::endl; return 1; } pcafitter::readarmmat(cfname.c_str(), cmtx); pcafitter::readarmvct(qfname.c_str(), q); if ((subsec == "") && (sublad == "")) { int maxnumber; std::cout << "Looking for bigger subsector" << std::endl; std::cout << "We found " << subsectors.size() << " subsectors " << std::endl; pcafitter::select_bigger_sub (subsectors, verbose, maxnumber, subsec); std::cout << "Selected subsector " << subsec << " numevt: " << maxnumber << std::endl; std::cout << "Looking for bigger subladder" << std::endl; std::cout << "We found " << subladders.size() << " subladders " << std::endl; pcafitter::select_bigger_sub (subladders, verbose, maxnumber, sublad); std::cout << "Selected subladder " << sublad << " numevt: " << maxnumber << std::endl; } if (subsec != "") { arma::mat paramslt, coordslt; std::cout << "Using subsector " << subsec << std::endl; pcafitter::extract_sub (subsectorslist, subsec, param, coord, paramslt, coordslt); build_and_compare (paramslt, coordslt, cmtx, q, verbose); } if (sublad != "") { arma::mat paramslt, coordslt; std::cout << "Using subladder " << sublad << std::endl; pcafitter::extract_sub (subladderslist, sublad, param, coord, paramslt, coordslt); build_and_compare (paramslt, coordslt, cmtx, q, verbose); } } else { assert(useallsubladders != useallsubsectors); std::set<std::string> sectrorset; std::vector<std::string> * listtouse = NULL; if (useallsubsectors) { std::vector<std::string>::const_iterator selecteds = subsectorslist.begin(); for (; selecteds != subsectorslist.end(); ++selecteds) sectrorset.insert(*selecteds); listtouse = &subsectorslist; } else if (useallsubladders) { std::vector<std::string>::const_iterator selecteds = subladderslist.begin(); for (; selecteds != subladderslist.end(); ++selecteds) sectrorset.insert(*selecteds); listtouse = &subladderslist; } else usage(argv[0]); std::set<std::string>::const_iterator selected = sectrorset.begin(); for (; selected != sectrorset.end(); ++selected) { std::ostringstream cfname, qfname; cfname << "c." << *selected << ".bin"; qfname << "q." << *selected << ".bin"; if (file_exists(cfname.str()) && file_exists(qfname.str())) { std::cout << "Perfom fitting for " << *selected << std::endl; } } // TODO } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "tone_filter.hpp" #include "aligned_alloc.hpp" #include "pole_zero_filter_design.hpp" #include "dsp.hpp" #include "util.hpp" #include <complex> #include <cmath> #include <assert.h> #ifdef TONE_DEBUG #include "audio_events.hpp" #endif namespace Granite { namespace Audio { namespace DSP { static const double TwoPI = 2.0 * 3.141592653589793; struct ToneFilter::Impl : Util::AlignedAllocation<ToneFilter::Impl> { alignas(64) float fir_history[FilterTaps][ToneCount] = {}; alignas(64) float iir_history[FilterTaps][ToneCount] = {}; alignas(64) float fir_coeff[FilterTaps + 1][ToneCount] = {}; alignas(64) float iir_coeff[FilterTaps][ToneCount] = {}; alignas(64) float running_power[ToneCount] = {}; alignas(64) float running_total_power = {}; unsigned index = 0; unsigned iir_filter_taps = 0; unsigned fir_filter_taps = 0; float tone_power_lerp = 0.002f; float total_tone_power_lerp = 0.0005f; float final_history = 0.0f; void filter(float *out_samples, const float *in_samples, unsigned count); #ifdef TONE_DEBUG std::vector<float> tone_buffers[ToneCount]; #endif }; #ifdef TONE_DEBUG void ToneFilter::flush_debug_info(Util::LockFreeMessageQueue &queue, StreamID id) { for (int i = 0; i < ToneCount; i++) { emplace_padded_audio_event_on_queue<ToneFilterWave>(queue, impl->tone_buffers[i].size() * sizeof(float), id, i, impl->running_power[i] / (impl->running_total_power + 0.000001f), impl->tone_buffers[i].data(), impl->tone_buffers[i].size()); impl->tone_buffers[i].clear(); } } #endif void ToneFilter::init(float sample_rate, float tuning_freq) { PoleZeroFilterDesigner designer; for (int i = 0; i < ToneCount; i++) { designer.reset(); double freq = tuning_freq * std::exp2(double(i - 12) / 12.0); double angular_freq = freq * TwoPI / sample_rate; // Ad-hoc sloppy IIR filter design, wooo. // Add some zeroes to balance out the filter. designer.add_zero_dc(1.0); designer.add_zero_nyquist(1.0); // We're going to create a resonator around the desired tone we're looking for. designer.add_pole(0.9999, angular_freq); // Look ma', a biquad! impl->fir_filter_taps = designer.get_numerator_count() - 1; impl->iir_filter_taps = designer.get_denominator_count() - 1; assert(impl->fir_filter_taps <= FilterTaps); assert(impl->iir_filter_taps <= FilterTaps); // Normalize the FIR part. double inv_response = 1.0 / std::abs(designer.evaluate_response(angular_freq)); for (unsigned coeff = 0; coeff < impl->fir_filter_taps + 1; coeff++) impl->fir_coeff[coeff][i] = float(designer.get_numerator()[coeff] * inv_response); // IIR part. To apply the filter, we need to negate the Z-form coeffs. for (unsigned coeff = 0; coeff < impl->iir_filter_taps; coeff++) impl->iir_coeff[coeff][i] = float(-designer.get_denominator()[coeff + 1]); #ifdef TONE_DEBUG impl->tone_buffers[i].reserve(1024); #endif } } ToneFilter::ToneFilter() { impl = new Impl; } ToneFilter::~ToneFilter() { delete impl; } static float distort(float v) { float abs_v = std::abs(v); return std::copysign(1.0f, v) * (1.0f - std::exp(-abs_v)); } void ToneFilter::Impl::filter(float *out_samples, const float *in_samples, unsigned count) { for (unsigned samp = 0; samp < count; samp++) { float final_sample = 0.0f; float in_sample = in_samples[samp]; running_total_power = running_total_power * (1.0f - total_tone_power_lerp) + total_tone_power_lerp * in_sample * in_sample; float low_threshold = 0.01f * running_total_power; float high_threshold = 0.10f * running_total_power; for (int tone = 0; tone < ToneCount; tone++) { float ret = fir_coeff[0][tone] * in_sample; for (unsigned x = 0; x < fir_filter_taps; x++) ret += fir_coeff[x + 1][tone] * fir_history[(index + x) & (FilterTaps - 1)][tone]; for (unsigned x = 0; x < iir_filter_taps; x++) ret += iir_coeff[x][tone] * iir_history[(index + x) & (FilterTaps - 1)][tone]; fir_history[(index - 1) & (FilterTaps - 1)][tone] = in_sample; iir_history[(index - 1) & (FilterTaps - 1)][tone] = ret; float new_power = ret * ret; if (new_power < low_threshold) new_power = new_power * new_power * new_power / (low_threshold * low_threshold + 0.00001f); if (new_power > high_threshold) new_power = high_threshold; new_power = (1.0f - tone_power_lerp) * running_power[tone] + tone_power_lerp * new_power; running_power[tone] = new_power; float rms = std::sqrt(new_power); float final = rms * distort(ret * 40.0f / (rms + 0.001f)); final_sample += final; #ifdef TONE_DEBUG tone_buffers[tone].push_back(final); #endif } // Trivial 1-pole IIR filter to serve as a slight low-pass to dampen the worst high-end. final_sample = 0.5f * final_history + 0.5f * final_sample; final_history = final_sample; #if 0 static float max_final = 0.0f; if (std::abs(final_sample) > max_final) { max_final = std::abs(final_sample); LOGI("New max final sample: %f.\n", max_final); } #endif out_samples[samp] = distort(2.0f * final_sample); index = (index - 1) & (FilterTaps - 1); } } void ToneFilter::filter(float *out_samples, const float *in_samples, unsigned count) { impl->filter(out_samples, in_samples, count); } } } } <commit_msg>Use quadric falloff.<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "tone_filter.hpp" #include "aligned_alloc.hpp" #include "pole_zero_filter_design.hpp" #include "dsp.hpp" #include "util.hpp" #include <complex> #include <cmath> #include <assert.h> #ifdef TONE_DEBUG #include "audio_events.hpp" #endif namespace Granite { namespace Audio { namespace DSP { static const double TwoPI = 2.0 * 3.141592653589793; struct ToneFilter::Impl : Util::AlignedAllocation<ToneFilter::Impl> { alignas(64) float fir_history[FilterTaps][ToneCount] = {}; alignas(64) float iir_history[FilterTaps][ToneCount] = {}; alignas(64) float fir_coeff[FilterTaps + 1][ToneCount] = {}; alignas(64) float iir_coeff[FilterTaps][ToneCount] = {}; alignas(64) float running_power[ToneCount] = {}; alignas(64) float running_total_power = {}; unsigned index = 0; unsigned iir_filter_taps = 0; unsigned fir_filter_taps = 0; float tone_power_lerp = 0.002f; float total_tone_power_lerp = 0.0005f; float final_history = 0.0f; void filter(float *out_samples, const float *in_samples, unsigned count); #ifdef TONE_DEBUG std::vector<float> tone_buffers[ToneCount]; #endif }; #ifdef TONE_DEBUG void ToneFilter::flush_debug_info(Util::LockFreeMessageQueue &queue, StreamID id) { for (int i = 0; i < ToneCount; i++) { emplace_padded_audio_event_on_queue<ToneFilterWave>(queue, impl->tone_buffers[i].size() * sizeof(float), id, i, impl->running_power[i] / (impl->running_total_power + 0.000001f), impl->tone_buffers[i].data(), impl->tone_buffers[i].size()); impl->tone_buffers[i].clear(); } } #endif void ToneFilter::init(float sample_rate, float tuning_freq) { PoleZeroFilterDesigner designer; for (int i = 0; i < ToneCount; i++) { designer.reset(); double freq = tuning_freq * std::exp2(double(i - 12) / 12.0); double angular_freq = freq * TwoPI / sample_rate; // Ad-hoc sloppy IIR filter design, wooo. // Add some zeroes to balance out the filter. designer.add_zero_dc(1.0); designer.add_zero_nyquist(1.0); // We're going to create a resonator around the desired tone we're looking for. designer.add_pole(0.9999, angular_freq); // Look ma', a biquad! impl->fir_filter_taps = designer.get_numerator_count() - 1; impl->iir_filter_taps = designer.get_denominator_count() - 1; assert(impl->fir_filter_taps <= FilterTaps); assert(impl->iir_filter_taps <= FilterTaps); // Normalize the FIR part. double inv_response = 1.0 / std::abs(designer.evaluate_response(angular_freq)); for (unsigned coeff = 0; coeff < impl->fir_filter_taps + 1; coeff++) impl->fir_coeff[coeff][i] = float(designer.get_numerator()[coeff] * inv_response); // IIR part. To apply the filter, we need to negate the Z-form coeffs. for (unsigned coeff = 0; coeff < impl->iir_filter_taps; coeff++) impl->iir_coeff[coeff][i] = float(-designer.get_denominator()[coeff + 1]); #ifdef TONE_DEBUG impl->tone_buffers[i].reserve(1024); #endif } } ToneFilter::ToneFilter() { impl = new Impl; } ToneFilter::~ToneFilter() { delete impl; } static float distort(float v) { float abs_v = std::abs(v); return std::copysign(1.0f, v) * (1.0f - std::exp(-abs_v)); } void ToneFilter::Impl::filter(float *out_samples, const float *in_samples, unsigned count) { for (unsigned samp = 0; samp < count; samp++) { float final_sample = 0.0f; float in_sample = in_samples[samp]; running_total_power = running_total_power * (1.0f - total_tone_power_lerp) + total_tone_power_lerp * in_sample * in_sample; float low_threshold = 0.01f * running_total_power; float high_threshold = 0.10f * running_total_power; float low_threshold_divider = 1.0f / (low_threshold * low_threshold * low_threshold + 0.00000001f); for (int tone = 0; tone < ToneCount; tone++) { float ret = fir_coeff[0][tone] * in_sample; for (unsigned x = 0; x < fir_filter_taps; x++) ret += fir_coeff[x + 1][tone] * fir_history[(index + x) & (FilterTaps - 1)][tone]; for (unsigned x = 0; x < iir_filter_taps; x++) ret += iir_coeff[x][tone] * iir_history[(index + x) & (FilterTaps - 1)][tone]; fir_history[(index - 1) & (FilterTaps - 1)][tone] = in_sample; iir_history[(index - 1) & (FilterTaps - 1)][tone] = ret; float new_power = ret * ret; if (new_power < low_threshold) new_power = new_power * new_power * new_power * new_power * low_threshold_divider; if (new_power > high_threshold) new_power = high_threshold; new_power = (1.0f - tone_power_lerp) * running_power[tone] + tone_power_lerp * new_power; running_power[tone] = new_power; float rms = std::sqrt(new_power); float final = rms * distort(ret * 40.0f / (rms + 0.001f)); final_sample += final; #ifdef TONE_DEBUG tone_buffers[tone].push_back(final); #endif } // Trivial 1-pole IIR filter to serve as a slight low-pass to dampen the worst high-end. final_sample = 0.5f * final_history + 0.5f * final_sample; final_history = final_sample; #if 0 static float max_final = 0.0f; if (std::abs(final_sample) > max_final) { max_final = std::abs(final_sample); LOGI("New max final sample: %f.\n", max_final); } #endif out_samples[samp] = distort(2.0f * final_sample); index = (index - 1) & (FilterTaps - 1); } } void ToneFilter::filter(float *out_samples, const float *in_samples, unsigned count) { impl->filter(out_samples, in_samples, count); } } } } <|endoftext|>
<commit_before>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Nate Begeman and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "llvm/Module.h" #include "X86GenSubtarget.inc" using namespace llvm; /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. static bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("pushl\t%%ebx\n\t" "cpuid\n\t" "movl\t%%ebx, %%esi\n\t" "popl\t%%ebx" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; // Bits 8 - 11 unsigned Model = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; // Bits 4 - 7 GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = EDX & (1 << 29); union { unsigned u[3]; char c[12]; } text; GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: this poorly matches the generated SubtargetFeatureKV table. There // appears to be no way to generate the wide variety of AMD-specific targets // from the information returned from CPUID. switch (Family) { case 4: return "i486"; case 5: switch (Model) { case 6: case 7: return "k6"; case 8: return "k6-2"; case 9: case 13: return "k6-3"; default: return "pentium"; } case 6: switch (Model) { case 4: return "athlon-tbird"; case 6: case 7: case 8: return "athlon-mp"; case 10: return "athlon-xp"; default: return "athlon"; } case 15: switch (Model) { case 5: return "athlon-fx"; // also opteron default: return "athlon64"; } default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS) { stackAlignment = 8; indirectExternAndWeakGlobals = false; X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; Is64Bit = false; // Determine default and user specified characteristics std::string CPU = GetCurrentX86CPU(); // Parse features string. ParseSubtargetFeatures(FS, CPU); // Default to ELF unless otherwise specified. TargetType = isELF; X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { if (TT.find("cygwin") != std::string::npos || TT.find("mingw") != std::string::npos) TargetType = isCygwin; else if (TT.find("darwin") != std::string::npos) TargetType = isDarwin; else if (TT.find("win32") != std::string::npos) TargetType = isWindows; } else if (TT.empty()) { #if defined(__CYGWIN__) || defined(__MINGW32__) TargetType = isCygwin; #elif defined(__APPLE__) TargetType = isDarwin; #elif defined(_WIN32) TargetType = isWindows; #endif } if (TargetType == isDarwin) { stackAlignment = 16; indirectExternAndWeakGlobals = true; } } <commit_msg>Duh<commit_after>//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by Nate Begeman and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "llvm/Module.h" #include "X86GenSubtarget.inc" using namespace llvm; /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. static bool GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("pushl\t%%ebx\n\t" "cpuid\n\t" "movl\t%%ebx, %%esi\n\t" "popl\t%%ebx" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX & (0xffffffff >> (32 - 4)) << 8) >> 8; // Bits 8 - 11 unsigned Model = (EAX & (0xffffffff >> (32 - 4)) << 4) >> 4; // Bits 4 - 7 GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = EDX & (1 << 29); union { unsigned u[3]; char c[12]; } text; GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: this poorly matches the generated SubtargetFeatureKV table. There // appears to be no way to generate the wide variety of AMD-specific targets // from the information returned from CPUID. switch (Family) { case 4: return "i486"; case 5: switch (Model) { case 6: case 7: return "k6"; case 8: return "k6-2"; case 9: case 13: return "k6-3"; default: return "pentium"; } case 6: switch (Model) { case 4: return "athlon-tbird"; case 6: case 7: case 8: return "athlon-mp"; case 10: return "athlon-xp"; default: return "athlon"; } case 15: switch (Model) { case 5: return "athlon-fx"; // also opteron default: return "athlon64"; } default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS) { stackAlignment = 8; indirectExternAndWeakGlobals = false; X86SSELevel = NoMMXSSE; X863DNowLevel = NoThreeDNow; Is64Bit = false; // Determine default and user specified characteristics std::string CPU = GetCurrentX86CPU(); // Parse features string. ParseSubtargetFeatures(FS, CPU); // Default to ELF unless otherwise specified. TargetType = isELF; // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { if (TT.find("cygwin") != std::string::npos || TT.find("mingw") != std::string::npos) TargetType = isCygwin; else if (TT.find("darwin") != std::string::npos) TargetType = isDarwin; else if (TT.find("win32") != std::string::npos) TargetType = isWindows; } else if (TT.empty()) { #if defined(__CYGWIN__) || defined(__MINGW32__) TargetType = isCygwin; #elif defined(__APPLE__) TargetType = isDarwin; #elif defined(_WIN32) TargetType = isWindows; #endif } if (TargetType == isDarwin) { stackAlignment = 16; indirectExternAndWeakGlobals = true; } } <|endoftext|>
<commit_before>#include <tnt/tntnet.h> #include <string> #include "./models/Config.h" int main ( int argc, char* argv[] ) { Config config; int port = atoi(config.get( "APP-PORT" ).c_str()); std::string ip_addr = config.get( "APP-IP" ); try { tnt::Tntnet app; // Configurator configurator( app ); app.listen( ip_addr, port ); app.mapUrl( "^/login", "login" ).setPathInfo( "login" ); app.mapUrl( "^/$", "home" ).setPathInfo( "home" ); // ruft bei /keyword-detail/keyword die Komponente keyword-detail // auf und übergibt den Parameter "keywordp". // Mit 'request.getArg(0)' läst sich der Wert auslesen. app.mapUrl("^/keyword-detail/(.*)", "keyword-detail").pushArg("$1"); app.mapUrl( "^/(.*)$", "$1" ); std::cout << "peruschim cpp is started and run on http://" << ip_addr \ << ":" << port << "/" << std::endl; app.run(); } catch ( const std::exception& e ) { std::cerr << e.what() << std::endl; } } <commit_msg>Remove unused function pushArg().<commit_after>#include <tnt/tntnet.h> #include <string> #include "./models/Config.h" int main ( int argc, char* argv[] ) { Config config; int port = atoi(config.get( "APP-PORT" ).c_str()); std::string ip_addr = config.get( "APP-IP" ); try { tnt::Tntnet app; // Configurator configurator( app ); app.listen( ip_addr, port ); app.mapUrl( "^/login", "login" ).setPathInfo( "login" ); app.mapUrl( "^/$", "home" ).setPathInfo( "home" ); // ruft bei /keyword-detail/keyword die Komponente keyword-detail // auf und übergibt den Parameter "keywordp". // Mit 'request.getArg(0)' läst sich der Wert auslesen. // app.mapUrl("^/keyword-detail/(.*)", "keyword-detail").pushArg("$1"); app.mapUrl( "^/(.*)$", "$1" ); std::cout << "peruschim cpp is started and run on http://" << ip_addr \ << ":" << port << "/" << std::endl; app.run(); } catch ( const std::exception& e ) { std::cerr << e.what() << std::endl; } } <|endoftext|>
<commit_before>#ifndef LIB_DRAW_RENDERSTATES_HPP #define LIB_DRAW_RENDERSTATES_HPP #include <SFML/Graphics/BlendMode.hpp> #include "transformation.hpp" namespace sf { class Shader; class Texture; } namespace lib { namespace core { class RenderTarget; } namespace draw { class RenderStates { public: RenderStates(); RenderStates(const sf::BlendMode &theBlendMode); RenderStates(const Transformation &transformation); RenderStates(const sf::Texture* theTexture); RenderStates(const sf::Shader* theShader); RenderStates(const sf::BlendMode &theBlendMode, const Transformation &transformation, const sf::Texture *theTexture, const sf::Shader *theShader); RenderStates(const RenderStates&) = delete; RenderStates &operator=(const RenderStates&) = delete; void nextFrame(); void reset(); //static const RenderStates Default; sf::BlendMode blendMode; Transformation transform; const sf::Texture *texture; const sf::Shader *shader; sptr<core::RenderTarget> currentTarget; }; } } #endif <commit_msg>Alignment<commit_after>#ifndef LIB_DRAW_RENDERSTATES_HPP #define LIB_DRAW_RENDERSTATES_HPP #include <SFML/Graphics/BlendMode.hpp> #include "transformation.hpp" namespace sf { class Shader; class Texture; } namespace lib { namespace core { class RenderTarget; } namespace draw { class RenderStates { public: RenderStates(); RenderStates(const sf::BlendMode &theBlendMode); RenderStates(const Transformation &transformation); RenderStates(const sf::Texture* theTexture); RenderStates(const sf::Shader* theShader); RenderStates(const sf::BlendMode &theBlendMode, const Transformation &transformation, const sf::Texture *theTexture, const sf::Shader *theShader); RenderStates(const RenderStates&) = delete; RenderStates &operator=(const RenderStates&) = delete; void nextFrame(); void reset(); Transformation transform; sf::BlendMode blendMode; const sf::Texture *texture; const sf::Shader *shader; sptr<core::RenderTarget> currentTarget; }; } } #endif <|endoftext|>
<commit_before>#include <iostream> #include <cstdint> #include <random> #include <chrono> #include <vector> #include <boost/dynamic_bitset.hpp> #include <numeric> /** * Lessons learned so far: * - SIMD registers are used as soon as we compile with -03 * - If we want to get the real speed up (and use all SIMD registers by unfolding both loops, * we have to know both, input-size and number of comparisons, at compile time. * - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to * code optimized with 02. * - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd * - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp */ typedef std::mt19937 Engine; typedef std::uniform_int_distribution<unsigned> Intdistr; template <typename T, typename U> void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) { for (unsigned i = 0; i < array_size; ++i) { for (unsigned m = 0; m < comparisons; ++m) { outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]); } } } template <typename T> void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") { std::cout << s << ":" << std::endl; for (auto r = arr; r < arr+size; ++r ) { std::cout << *r << std::endl; } } template <typename T> void compute_stats(const std::vector<T> stats, double &mean, double &stdev) { double sum = std::accumulate(stats.begin(), stats.end(), 0.0); mean = sum / stats.size(); std::vector<double> diff(stats.size()); std::transform(stats.begin(), stats.end(), diff.begin(), std::bind2nd(std::minus<double>(), mean)); double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); stdev = std::sqrt(sq_sum / stats.size()); } template <typename T> void fill (T *arr, unsigned size) { Engine engine (0); Intdistr distr (0, 100000); for (auto r = arr; r < arr+size; ++r ) { *r = distr(engine); } } int main (int argc, char *argv[]) { //**** PARAMS ****/ typedef unsigned TestType; static constexpr unsigned repetitions = 10000; // constexpr unsigned input_size = 500000; constexpr unsigned comparisons = 1; // if (argc != 3) // { // std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl; // return -1; // } unsigned long input_size = std::stoi(argv[1]); // unsigned comparisons = std::stoi(argv[2]); std::cout << "input size: " << input_size << std::endl; std::cout << "comparisons: " << comparisons<< std::endl; //**** INPUT ****/ TestType test_input [input_size]; fill(test_input, input_size); // pretty_print(test_input, input_size, "Input"); TestType comparison_values [comparisons]; for (unsigned c = 0; c < comparisons; ++c) { comparison_values[c] = test_input[c]; } // pretty_print(comparison_values, comparisons, "Comparison values"); //**** COMPUTE ****/ std::vector<unsigned long> stats (repetitions); bool results [comparisons * input_size]; // std::vector<bool> results (comparisons * input_size); // boost::dynamic_bitset<> results(comparisons * input_size); for (unsigned i = 0; i < repetitions; ++i) { auto start = std::chrono::high_resolution_clock::now(); smaller(test_input, results, comparison_values, input_size, comparisons); auto end = std::chrono::high_resolution_clock::now(); stats [i] = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count(); } //**** REPORT ****/ double mean, stdev; compute_stats(stats, mean, stdev); std::cout // << "Avg Time [microsecs]: " << mean << "\t" // << "(+/- " << stdev // << ")" << std::endl; // pretty_print(stats.data(), repetitions, "Stats"); // for (unsigned c = 0; c < comparisons; ++c) { // pretty_print(&results[c*input_size], input_size, "Result"); // } return 0; } <commit_msg>finished simd experiments for all-same-operator (smaller)<commit_after>#include <iostream> #include <cstdint> #include <random> #include <chrono> #include <vector> #include <boost/dynamic_bitset.hpp> #include <numeric> /** * Lessons learned so far: * - SIMD registers are used as soon as we compile with -03 * - If we want to get the real speed up (and use all SIMD registers by unfolding both loops, * we have to know both, input-size and number of comparisons, at compile time. * - Otherwise, only some of the SIMD registers are used, and speedup is 0, compared to * code optimized with 02. * - Example compile command: g++ -std=c++11 -march=native -O3 simd.cpp -o simd * - Command for getting assembly code: g++ -std=c++11 -march=native -O3 -S simd.cpp */ typedef std::mt19937 Engine; typedef std::uniform_int_distribution<unsigned> Intdistr; template <typename T, typename U> void smaller (const T *input, U outputs, const T *comparison_values, const unsigned array_size, const unsigned comparisons) { for (unsigned i = 0; i < array_size; ++i) { for (unsigned m = 0; m < comparisons; ++m) { outputs[m*array_size+i] = (float) (input[i] < comparison_values[m]); } } } template <typename T> void pretty_print (T *arr, unsigned size, std::string s = "Pretty Print") { std::cout << s << ":" << std::endl; for (auto r = arr; r < arr+size; ++r ) { std::cout << *r << std::endl; } } template <typename T> void compute_stats(const std::vector<T> stats, double &mean, double &stdev) { double sum = std::accumulate(stats.begin(), stats.end(), 0.0); mean = sum / stats.size(); std::vector<double> diff(stats.size()); std::transform(stats.begin(), stats.end(), diff.begin(), std::bind2nd(std::minus<double>(), mean)); double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0); stdev = std::sqrt(sq_sum / stats.size()); } template <typename T> void fill (T *arr, unsigned size) { Engine engine (0); Intdistr distr (0, 100000); for (auto r = arr; r < arr+size; ++r ) { *r = distr(engine); } } int main (int argc, char *argv[]) { //**** PARAMS ****/ typedef unsigned TestType; static constexpr unsigned repetitions = 10000; constexpr unsigned input_size = 500000; constexpr unsigned comparisons = 1; // if (argc != 3) // { // std::cout << "Usage: ./simd <input-size> <comparisons>" << std::endl; // return -1; // } unsigned long input_size = std::stoi(argv[1]); unsigned comparisons = std::stoi(argv[2]); std::cout << "input size: " << input_size << std::endl; std::cout << "comparisons: " << comparisons<< std::endl; //**** INPUT ****/ TestType test_input [input_size]; fill(test_input, input_size); // pretty_print(test_input, input_size, "Input"); TestType comparison_values [comparisons]; for (unsigned c = 0; c < comparisons; ++c) { comparison_values[c] = test_input[c]; } // pretty_print(comparison_values, comparisons, "Comparison values"); //**** COMPUTE ****/ std::vector<unsigned long> stats (repetitions); bool results [comparisons * input_size]; // std::vector<bool> results (comparisons * input_size); // boost::dynamic_bitset<> results(comparisons * input_size); for (unsigned i = 0; i < repetitions; ++i) { auto start = std::chrono::high_resolution_clock::now(); smaller(test_input, results, comparison_values, input_size, comparisons); auto end = std::chrono::high_resolution_clock::now(); stats [i] = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count(); } //**** REPORT ****/ double mean, stdev; compute_stats(stats, mean, stdev); std::cout // << "Avg Time [microsecs]: " << mean << "\t" // << "(+/- " << stdev // << ")" << std::endl; // pretty_print(stats.data(), repetitions, "Stats"); // for (unsigned c = 0; c < comparisons; ++c) { // pretty_print(&results[c*input_size], input_size, "Result"); // } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <fb/fbjni/CoreClasses.h> #include <fb/assert.h> #include <fb/log.h> #include <alloca.h> #include <cstdlib> #include <ios> #include <stdexcept> #include <stdio.h> #include <string> #include <system_error> #include <jni.h> namespace facebook { namespace jni { namespace { class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;"; static local_ref<JRuntimeException> create(const char* str) { return newInstance(make_jstring(str)); } static local_ref<JRuntimeException> create() { return newInstance(); } }; class JIOException : public JavaClass<JIOException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/io/IOException;"; static local_ref<JIOException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;"; static local_ref<JOutOfMemoryError> create(const char* str) { return newInstance(make_jstring(str)); } }; class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;"; static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;"; static local_ref<JUnknownCppException> create() { return newInstance(); } static local_ref<JUnknownCppException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;"; static local_ref<JCppSystemErrorException> create(const std::system_error& e) { return newInstance(make_jstring(e.what()), e.code().value()); } }; // Exception throwing & translating functions ////////////////////////////////////////////////////// // Functions that throw Java exceptions void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) { auto env = Environment::current(); if (throwable) { env->Throw(throwable.get()); } if (env->ExceptionCheck() != JNI_TRUE) { std::abort(); } } } // Functions that throw C++ exceptions // TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated void throwPendingJniExceptionAsCppException() { JNIEnv* env = Environment::current(); if (env->ExceptionCheck() == JNI_FALSE) { return; } auto throwable = adopt_local(env->ExceptionOccurred()); if (!throwable) { throw std::runtime_error("Unable to get pending JNI exception."); } env->ExceptionClear(); throw JniException(throwable); } void throwCppExceptionIf(bool condition) { if (!condition) { return; } auto env = Environment::current(); if (env->ExceptionCheck() == JNI_TRUE) { throwPendingJniExceptionAsCppException(); return; } throw JniException(); } void throwNewJavaException(jthrowable throwable) { throw JniException(wrap_alias(throwable)); } void throwNewJavaException(const char* throwableName, const char* msg) { // If anything of the fbjni calls fail, an exception of a suitable // form will be thrown, which is what we want. auto throwableClass = findClassLocal(throwableName); auto throwable = throwableClass->newObject( throwableClass->getConstructor<jthrowable(jstring)>(), make_jstring(msg).release()); throwNewJavaException(throwable.get()); } // Translate C++ to Java Exception namespace { // The implementation std::rethrow_if_nested uses a dynamic_cast to determine // if the exception is a nested_exception. If the exception is from a library // built with -fno-rtti, then that will crash. This avoids that. void rethrow_if_nested() { try { throw; } catch (const std::nested_exception& e) { e.rethrow_nested(); } catch (...) { } } // For each exception in the chain of the currently handled exception, func // will be called with that exception as the currently handled exception (in // reverse order, i.e. innermost first). void denest(std::function<void()> func) { try { throw; } catch (const std::exception& e) { try { rethrow_if_nested(); } catch (...) { denest(func); } func(); } catch (...) { func(); } } } void translatePendingCppExceptionToJavaException() noexcept { local_ref<JThrowable> previous; auto func = [&previous] () { local_ref<JThrowable> current; try { throw; } catch(const JniException& ex) { current = ex.getThrowable(); } catch(const std::ios_base::failure& ex) { current = JIOException::create(ex.what()); } catch(const std::bad_alloc& ex) { current = JOutOfMemoryError::create(ex.what()); } catch(const std::out_of_range& ex) { current = JArrayIndexOutOfBoundsException::create(ex.what()); } catch(const std::system_error& ex) { current = JCppSystemErrorException::create(ex); } catch(const std::runtime_error& ex) { current = JRuntimeException::create(ex.what()); } catch(const std::exception& ex) { current = JCppException::create(ex.what()); } catch(const char* msg) { current = JUnknownCppException::create(msg); } catch(...) { current = JUnknownCppException::create(); } if (previous) { current->initCause(previous); } previous = current; }; try { denest(func); setJavaExceptionAndAbortOnFailure(previous); } catch (std::exception& e) { FBLOGE("unexpected exception in translatePendingCppExceptionToJavaException: %s", e.what()); // rethrow the exception and let the noexcept handling abort. throw; } catch (...) { FBLOGE("unexpected exception in translatePendingCppExceptionToJavaException"); throw; } } // JniException //////////////////////////////////////////////////////////////////////////////////// const std::string JniException::kExceptionMessageFailure_ = "Unable to get exception message."; JniException::JniException() : JniException(JRuntimeException::create()) { } JniException::JniException(alias_ref<jthrowable> throwable) : isMessageExtracted_(false) { throwable_ = make_global(throwable); <commit_msg>Lines authored by ritzau<commit_after>/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include <fb/fbjni/CoreClasses.h> #include <fb/assert.h> #include <fb/log.h> #include <alloca.h> #include <cstdlib> #include <ios> #include <stdexcept> #include <stdio.h> #include <string> #include <system_error> #include <jni.h> namespace facebook { namespace jni { namespace { class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;"; static local_ref<JRuntimeException> create(const char* str) { return newInstance(make_jstring(str)); } static local_ref<JRuntimeException> create() { return newInstance(); } }; class JIOException : public JavaClass<JIOException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/io/IOException;"; static local_ref<JIOException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;"; static local_ref<JOutOfMemoryError> create(const char* str) { return newInstance(make_jstring(str)); } }; class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;"; static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;"; static local_ref<JUnknownCppException> create() { return newInstance(); } static local_ref<JUnknownCppException> create(const char* str) { return newInstance(make_jstring(str)); } }; class JCppSystemErrorException : public JavaClass<JCppSystemErrorException, JThrowable> { public: static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/CppSystemErrorException;"; static local_ref<JCppSystemErrorException> create(const std::system_error& e) { return newInstance(make_jstring(e.what()), e.code().value()); } }; // Exception throwing & translating functions ////////////////////////////////////////////////////// // Functions that throw Java exceptions void setJavaExceptionAndAbortOnFailure(alias_ref<JThrowable> throwable) { auto env = Environment::current(); if (throwable) { env->Throw(throwable.get()); } if (env->ExceptionCheck() != JNI_TRUE) { std::abort(); } } } // Functions that throw C++ exceptions // TODO(T6618159) Take a stack dump here to save context if it results in a crash when propagated void throwPendingJniExceptionAsCppException() { JNIEnv* env = Environment::current(); if (env->ExceptionCheck() == JNI_FALSE) { return; } auto throwable = adopt_local(env->ExceptionOccurred()); if (!throwable) { throw std::runtime_error("Unable to get pending JNI exception."); } env->ExceptionClear(); throw JniException(throwable); } void throwCppExceptionIf(bool condition) { if (!condition) { return; } auto env = Environment::current(); if (env->ExceptionCheck() == JNI_TRUE) { throwPendingJniExceptionAsCppException(); return; } throw JniException(); } void throwNewJavaException(jthrowable throwable) { throw JniException(wrap_alias(throwable)); } void throwNewJavaException(const char* throwableName, const char* msg) { // If anything of the fbjni calls fail, an exception of a suitable // form will be thrown, which is what we want. auto throwableClass = findClassLocal(throwableName); auto throwable = throwableClass->newObject( throwableClass->getConstructor<jthrowable(jstring)>(), make_jstring(msg).release()); throwNewJavaException(throwable.get()); } // Translate C++ to Java Exception namespace { // The implementation std::rethrow_if_nested uses a dynamic_cast to determine // if the exception is a nested_exception. If the exception is from a library // built with -fno-rtti, then that will crash. This avoids that. void rethrow_if_nested() { try { throw; } catch (const std::nested_exception& e) { e.rethrow_nested(); } catch (...) { } } // For each exception in the chain of the currently handled exception, func // will be called with that exception as the currently handled exception (in // reverse order, i.e. innermost first). void denest(std::function<void()> func) { try { throw; } catch (const std::exception& e) { try { rethrow_if_nested(); } catch (...) { denest(func); } func(); } catch (...) { func(); } } } void translatePendingCppExceptionToJavaException() noexcept { local_ref<JThrowable> previous; auto func = [&previous] () { local_ref<JThrowable> current; try { throw; } catch(const JniException& ex) { current = ex.getThrowable(); } catch(const std::ios_base::failure& ex) { current = JIOException::create(ex.what()); } catch(const std::bad_alloc& ex) { current = JOutOfMemoryError::create(ex.what()); } catch(const std::out_of_range& ex) { current = JArrayIndexOutOfBoundsException::create(ex.what()); } catch(const std::system_error& ex) { current = JCppSystemErrorException::create(ex); } catch(const std::runtime_error& ex) { current = JRuntimeException::create(ex.what()); } catch(const std::exception& ex) { current = JCppException::create(ex.what()); } catch(const char* msg) { current = JUnknownCppException::create(msg); } catch(...) { current = JUnknownCppException::create(); } if (previous) { current->initCause(previous); } previous = current; }; try { denest(func); setJavaExceptionAndAbortOnFailure(previous); } catch (std::exception& e) { FBLOGE("unexpected exception in translatePendingCppExceptionToJavaException: %s", e.what()); // rethrow the exception and let the noexcept handling abort. throw; } catch (...) { FBLOGE("unexpected exception in translatePendingCppExceptionToJavaException"); throw; } } // JniException //////////////////////////////////////////////////////////////////////////////////// const std::string JniException::kExceptionMessageFailure_ = "Unable to get exception message."; JniException::JniException() : JniException(JRuntimeException::create()) { } JniException::JniException(alias_ref<jthrowable> throwable) : isMessageExtracted_(false) { throwable_ = make_global(throwable); } JniException::JniException(JniException &&rhs) <|endoftext|>
<commit_before>#include <collector.pb.h> #include <lightstep/tracer.h> #include <opentracing/noop.h> #include <opentracing/stringref.h> #include <atomic> #include <cstdint> #include <iostream> #include <memory> #include <mutex> #include <random> #include <tuple> #include <vector> #include "propagation.h" #include "recorder.h" using namespace opentracing; namespace lightstep { collector::KeyValue to_key_value(StringRef key, const Value& value); std::unique_ptr<Recorder> make_lightstep_recorder( const TracerOptions& options) noexcept; uint64_t generate_id(); //------------------------------------------------------------------------------ // to_timestamp //------------------------------------------------------------------------------ google::protobuf::Timestamp to_timestamp(SystemTime t) { using namespace std::chrono; auto nanos = duration_cast<nanoseconds>(t.time_since_epoch()).count(); google::protobuf::Timestamp ts; const uint64_t nanosPerSec = 1000000000; ts.set_seconds(nanos / nanosPerSec); ts.set_nanos(nanos % nanosPerSec); return ts; } //------------------------------------------------------------------------------ // LightStepSpanContext //------------------------------------------------------------------------------ namespace { class LightStepSpanContext : public SpanContext { public: LightStepSpanContext() noexcept : trace_id(0), span_id(0) {} LightStepSpanContext( uint64_t trace_id, uint64_t span_id, std::unordered_map<std::string, std::string>&& baggage) noexcept : trace_id(trace_id), span_id(span_id), baggage_(std::move(baggage)) {} void setBaggageItem(StringRef key, StringRef value) noexcept try { std::lock_guard<std::mutex> l(baggage_mutex_); baggage_.emplace(key, value); } catch (const std::bad_alloc&) { } std::string baggageItem(const std::string& key) const { std::lock_guard<std::mutex> l(baggage_mutex_); auto lookup = baggage_.find(key); if (lookup != baggage_.end()) { return lookup->second; } return {}; } void ForeachBaggageItem( std::function<bool(const std::string& key, const std::string& value)> f) const override { std::lock_guard<std::mutex> l(baggage_mutex_); for (const auto& bi : baggage_) { if (!f(bi.first, bi.second)) { return; } } } LightStepSpanContext& operator=(LightStepSpanContext&& other) noexcept { std::lock_guard<std::mutex> l(baggage_mutex_); trace_id = other.trace_id; span_id = other.span_id; baggage_ = std::move(other.baggage_); return *this; } Expected<void> Inject(CarrierFormat format, const CarrierWriter& writer) const { std::lock_guard<std::mutex> l(baggage_mutex_); switch (format) { case CarrierFormat::OpenTracingBinary: return make_unexpected(unsupported_format_error); case CarrierFormat::HTTPHeaders: { auto http_headers_writer = dynamic_cast<const HTTPHeadersWriter*>(&writer); if (!http_headers_writer) return make_unexpected(invalid_carrier_error); return inject_span_context(*http_headers_writer, trace_id, span_id, baggage_); } case CarrierFormat::TextMap: { auto text_map_writer = dynamic_cast<const TextMapWriter*>(&writer); if (!text_map_writer) return make_unexpected(invalid_carrier_error); return inject_span_context(*text_map_writer, trace_id, span_id, baggage_); } } } Expected<bool> Extract(CarrierFormat format, const CarrierReader& reader) { std::lock_guard<std::mutex> l(baggage_mutex_); switch (format) { case CarrierFormat::OpenTracingBinary: return make_unexpected(unsupported_format_error); case CarrierFormat::HTTPHeaders: { auto http_headers_reader = dynamic_cast<const HTTPHeadersReader*>(&reader); if (!http_headers_reader) return make_unexpected(invalid_carrier_error); return extract_span_context(*http_headers_reader, trace_id, span_id, baggage_); } case CarrierFormat::TextMap: { auto text_map_reader = dynamic_cast<const TextMapReader*>(&reader); if (!text_map_reader) return make_unexpected(invalid_carrier_error); return extract_span_context(*text_map_reader, trace_id, span_id, baggage_); } } } // These are modified during constructors (StartSpan and Extract), // but would require extra work/copying to make them const. uint64_t trace_id; uint64_t span_id; private: mutable std::mutex baggage_mutex_; std::unordered_map<std::string, std::string> baggage_; }; } // anonymous namespace //------------------------------------------------------------------------------ // set_span_reference //------------------------------------------------------------------------------ static bool set_span_reference( const std::pair<SpanReferenceType, const SpanContext*>& reference, std::unordered_map<std::string, std::string>& baggage, collector::Reference& collector_reference) { switch (reference.first) { case SpanReferenceType::ChildOfRef: collector_reference.set_relationship(collector::Reference::CHILD_OF); break; case SpanReferenceType::FollowsFromRef: collector_reference.set_relationship(collector::Reference::FOLLOWS_FROM); break; } if (!reference.second) { std::cerr << "LightStep: passed in null span reference.\n"; return false; } auto referenced_context = dynamic_cast<const LightStepSpanContext*>(reference.second); if (!referenced_context) { std::cerr << "LightStep: passed in span reference of unexpected type.\n"; return false; } collector_reference.mutable_span_context()->set_trace_id( referenced_context->trace_id); collector_reference.mutable_span_context()->set_span_id( referenced_context->span_id); referenced_context->ForeachBaggageItem( [&baggage](const std::string& key, const std::string& value) { baggage[key] = value; return true; }); return true; } //------------------------------------------------------------------------------ // compute_start_timestamps //------------------------------------------------------------------------------ std::tuple<SystemTime, SteadyTime> compute_start_timestamps( const SystemTime& start_system_timestamp, const SteadyTime& start_steady_timestamp) { // If neither the system nor steady timestamps are set, get the tme from the // respective clocks; otherwise, use the set timestamp to initialize the // other. if (start_system_timestamp == SystemTime() && start_steady_timestamp == SteadyTime()) return {SystemClock::now(), SteadyClock::now()}; else if (start_system_timestamp == SystemTime()) return {convert_time_point<SystemClock>(start_steady_timestamp), start_steady_timestamp}; else if (start_steady_timestamp == SteadyTime()) return {start_system_timestamp, convert_time_point<SteadyClock>(start_system_timestamp)}; else return {start_system_timestamp, start_steady_timestamp}; } //------------------------------------------------------------------------------ // LightStepSpan //------------------------------------------------------------------------------ namespace { class LightStepSpan : public Span { public: LightStepSpan(std::shared_ptr<const Tracer>&& tracer, Recorder& recorder, StringRef operation_name, const StartSpanOptions& options) : tracer_(std::move(tracer)), recorder_(recorder), operation_name_(operation_name) { // Set the start timestamps. std::tie(start_timestamp_, start_steady_) = compute_start_timestamps( options.start_system_timestamp, options.start_steady_timestamp); // Set any span references. std::unordered_map<std::string, std::string> baggage; references_.reserve(options.references.size()); collector::Reference collector_reference; for (auto& reference : options.references) { auto span_reference_type = reference.first; if (!set_span_reference(reference, baggage, collector_reference)) continue; references_.push_back(collector_reference); } // Set tags. for (auto& tag : options.tags) tags_[tag.first] = tag.second; // Set SpanContext. auto trace_id = references_.empty() ? generate_id() : references_[0].span_context().trace_id(); auto span_id = generate_id(); span_context_ = LightStepSpanContext(trace_id, span_id, std::move(baggage)); } void FinishWithOptions(const FinishSpanOptions& options) noexcept override try { // Ensure the span is only finished once. if (is_finished_.exchange(true)) return; auto finish_timestamp = options.finish_steady_timestamp; if (finish_timestamp == SteadyTime()) finish_timestamp = SteadyClock::now(); collector::Span span; // Set timing information. auto duration = finish_timestamp - start_steady_; span.set_duration_micros( std::chrono::duration_cast<std::chrono::microseconds>(duration) .count()); *span.mutable_start_timestamp() = to_timestamp(start_timestamp_); // Set references. auto references = span.mutable_references(); references->Reserve(references_.size()); for (const auto& reference : references_) *references->Add() = reference; // Set tags, logs, and operation name. { std::lock_guard<std::mutex> lock(mutex_); span.set_operation_name(std::move(operation_name_)); auto tags = span.mutable_tags(); tags->Reserve(tags_.size()); for (const auto& tag : tags_) *tags->Add() = to_key_value(tag.first, tag.second); auto logs = span.mutable_logs(); for (auto& log : logs_) *logs->Add() = std::move(log); } // Set the span context. auto span_context = span.mutable_span_context(); span_context->set_trace_id(span_context_.trace_id); span_context->set_span_id(span_context_.span_id); auto baggage = span_context->mutable_baggage(); span_context_.ForeachBaggageItem( [baggage](const std::string& key, const std::string& value) { using StringMap = google::protobuf::Map<std::string, std::string>; baggage->insert(StringMap::value_type(key, value)); return true; }); // Record the span recorder_.RecordSpan(std::move(span)); } catch (const std::bad_alloc&) { // Do nothing if memory allocation fails. } void SetOperationName(StringRef name) noexcept override try { std::lock_guard<std::mutex> l(mutex_); operation_name_ = name; } catch (const std::bad_alloc&) { // Don't change operation name if memory can't be allocated for it. } void SetTag(StringRef key, const Value& value) noexcept override try { std::lock_guard<std::mutex> l(mutex_); tags_[key] = value; } catch (const std::bad_alloc&) { // Don't add the tag if memory can't be allocated for it. } void SetBaggageItem(StringRef restricted_key, StringRef value) noexcept override { span_context_.setBaggageItem(restricted_key, value); } std::string BaggageItem(StringRef restricted_key) const noexcept override try { return span_context_.baggageItem(restricted_key); } catch (const std::bad_alloc&) { return {}; } void Log(std::initializer_list<std::pair<StringRef, Value>> fields) noexcept override try { auto timestamp = SystemClock::now(); collector::Log log; *log.mutable_timestamp() = to_timestamp(timestamp); auto key_values = log.mutable_keyvalues(); for (const auto& field : fields) *key_values->Add() = to_key_value(field.first, field.second); logs_.emplace_back(std::move(log)); } catch (const std::bad_alloc&) { // Do nothing if memory can't be allocted for log records. } const SpanContext& context() const noexcept override { return span_context_; } const Tracer& tracer() const noexcept override { return *tracer_; } private: // Fields set in StartSpan() are not protected by a mutex. std::shared_ptr<const Tracer> tracer_; Recorder& recorder_; std::vector<collector::Reference> references_; SystemTime start_timestamp_; SteadyTime start_steady_; LightStepSpanContext span_context_; // Mutex protects tags_ and operation_name_. std::atomic<bool> is_finished_{false}; std::mutex mutex_; std::string operation_name_; std::unordered_map<std::string, Value> tags_; std::vector<collector::Log> logs_; }; } // namespace anonymous //------------------------------------------------------------------------------ // LightStepTracer //------------------------------------------------------------------------------ namespace { class LightStepTracer : public Tracer, public std::enable_shared_from_this<LightStepTracer> { public: LightStepTracer(std::unique_ptr<Recorder>&& recorder) : recorder_(std::move(recorder)) {} std::unique_ptr<Span> StartSpanWithOptions( StringRef operation_name, const StartSpanOptions& options) const noexcept override try { return std::unique_ptr<Span>(new LightStepSpan( shared_from_this(), *recorder_, operation_name, options)); } catch (const std::bad_alloc&) { // Don't create a span if std::bad_alloc is thrown. return nullptr; } Expected<void> Inject(const SpanContext& sc, CarrierFormat format, const CarrierWriter& writer) const override { auto lightstep_span_context = dynamic_cast<const LightStepSpanContext*>(&sc); if (!lightstep_span_context) return make_unexpected(invalid_span_context_error); return lightstep_span_context->Inject(format, writer); } Expected<std::unique_ptr<SpanContext>> Extract( CarrierFormat format, const CarrierReader& reader) const override { auto lightstep_span_context = new (std::nothrow) LightStepSpanContext(); std::unique_ptr<SpanContext> span_context(lightstep_span_context); if (!span_context) return make_unexpected(make_error_code(std::errc::not_enough_memory)); auto result = lightstep_span_context->Extract(format, reader); if (!result) return make_unexpected(result.error()); else if (!*result) span_context.reset(); return span_context; } void Close() noexcept override { recorder_->FlushWithTimeout(std::chrono::hours(24)); } private: std::unique_ptr<Recorder> recorder_; }; } // anonymous namespace //------------------------------------------------------------------------------ // make_lightstep_tracer //------------------------------------------------------------------------------ std::shared_ptr<opentracing::Tracer> make_lightstep_tracer( std::unique_ptr<Recorder>&& recorder) { if (!recorder) return make_noop_tracer(); else return std::shared_ptr<opentracing::Tracer>( new (std::nothrow) LightStepTracer(std::move(recorder))); } std::shared_ptr<opentracing::Tracer> make_lightstep_tracer( const TracerOptions& options) { return make_lightstep_tracer(make_lightstep_recorder(options)); } } // namespace lightstep <commit_msg>Finish a span in destuctor if not already done.<commit_after>#include <collector.pb.h> #include <lightstep/tracer.h> #include <opentracing/noop.h> #include <opentracing/stringref.h> #include <atomic> #include <cstdint> #include <iostream> #include <memory> #include <mutex> #include <random> #include <tuple> #include <vector> #include "propagation.h" #include "recorder.h" using namespace opentracing; namespace lightstep { collector::KeyValue to_key_value(StringRef key, const Value& value); std::unique_ptr<Recorder> make_lightstep_recorder( const TracerOptions& options) noexcept; uint64_t generate_id(); //------------------------------------------------------------------------------ // to_timestamp //------------------------------------------------------------------------------ google::protobuf::Timestamp to_timestamp(SystemTime t) { using namespace std::chrono; auto nanos = duration_cast<nanoseconds>(t.time_since_epoch()).count(); google::protobuf::Timestamp ts; const uint64_t nanosPerSec = 1000000000; ts.set_seconds(nanos / nanosPerSec); ts.set_nanos(nanos % nanosPerSec); return ts; } //------------------------------------------------------------------------------ // LightStepSpanContext //------------------------------------------------------------------------------ namespace { class LightStepSpanContext : public SpanContext { public: LightStepSpanContext() noexcept : trace_id(0), span_id(0) {} LightStepSpanContext( uint64_t trace_id, uint64_t span_id, std::unordered_map<std::string, std::string>&& baggage) noexcept : trace_id(trace_id), span_id(span_id), baggage_(std::move(baggage)) {} void setBaggageItem(StringRef key, StringRef value) noexcept try { std::lock_guard<std::mutex> l(baggage_mutex_); baggage_.emplace(key, value); } catch (const std::bad_alloc&) { } std::string baggageItem(const std::string& key) const { std::lock_guard<std::mutex> l(baggage_mutex_); auto lookup = baggage_.find(key); if (lookup != baggage_.end()) { return lookup->second; } return {}; } void ForeachBaggageItem( std::function<bool(const std::string& key, const std::string& value)> f) const override { std::lock_guard<std::mutex> l(baggage_mutex_); for (const auto& bi : baggage_) { if (!f(bi.first, bi.second)) { return; } } } LightStepSpanContext& operator=(LightStepSpanContext&& other) noexcept { std::lock_guard<std::mutex> l(baggage_mutex_); trace_id = other.trace_id; span_id = other.span_id; baggage_ = std::move(other.baggage_); return *this; } Expected<void> Inject(CarrierFormat format, const CarrierWriter& writer) const { std::lock_guard<std::mutex> l(baggage_mutex_); switch (format) { case CarrierFormat::OpenTracingBinary: return make_unexpected(unsupported_format_error); case CarrierFormat::HTTPHeaders: { auto http_headers_writer = dynamic_cast<const HTTPHeadersWriter*>(&writer); if (!http_headers_writer) return make_unexpected(invalid_carrier_error); return inject_span_context(*http_headers_writer, trace_id, span_id, baggage_); } case CarrierFormat::TextMap: { auto text_map_writer = dynamic_cast<const TextMapWriter*>(&writer); if (!text_map_writer) return make_unexpected(invalid_carrier_error); return inject_span_context(*text_map_writer, trace_id, span_id, baggage_); } } } Expected<bool> Extract(CarrierFormat format, const CarrierReader& reader) { std::lock_guard<std::mutex> l(baggage_mutex_); switch (format) { case CarrierFormat::OpenTracingBinary: return make_unexpected(unsupported_format_error); case CarrierFormat::HTTPHeaders: { auto http_headers_reader = dynamic_cast<const HTTPHeadersReader*>(&reader); if (!http_headers_reader) return make_unexpected(invalid_carrier_error); return extract_span_context(*http_headers_reader, trace_id, span_id, baggage_); } case CarrierFormat::TextMap: { auto text_map_reader = dynamic_cast<const TextMapReader*>(&reader); if (!text_map_reader) return make_unexpected(invalid_carrier_error); return extract_span_context(*text_map_reader, trace_id, span_id, baggage_); } } } // These are modified during constructors (StartSpan and Extract), // but would require extra work/copying to make them const. uint64_t trace_id; uint64_t span_id; private: mutable std::mutex baggage_mutex_; std::unordered_map<std::string, std::string> baggage_; }; } // anonymous namespace //------------------------------------------------------------------------------ // set_span_reference //------------------------------------------------------------------------------ static bool set_span_reference( const std::pair<SpanReferenceType, const SpanContext*>& reference, std::unordered_map<std::string, std::string>& baggage, collector::Reference& collector_reference) { switch (reference.first) { case SpanReferenceType::ChildOfRef: collector_reference.set_relationship(collector::Reference::CHILD_OF); break; case SpanReferenceType::FollowsFromRef: collector_reference.set_relationship(collector::Reference::FOLLOWS_FROM); break; } if (!reference.second) { std::cerr << "LightStep: passed in null span reference.\n"; return false; } auto referenced_context = dynamic_cast<const LightStepSpanContext*>(reference.second); if (!referenced_context) { std::cerr << "LightStep: passed in span reference of unexpected type.\n"; return false; } collector_reference.mutable_span_context()->set_trace_id( referenced_context->trace_id); collector_reference.mutable_span_context()->set_span_id( referenced_context->span_id); referenced_context->ForeachBaggageItem( [&baggage](const std::string& key, const std::string& value) { baggage[key] = value; return true; }); return true; } //------------------------------------------------------------------------------ // compute_start_timestamps //------------------------------------------------------------------------------ std::tuple<SystemTime, SteadyTime> compute_start_timestamps( const SystemTime& start_system_timestamp, const SteadyTime& start_steady_timestamp) { // If neither the system nor steady timestamps are set, get the tme from the // respective clocks; otherwise, use the set timestamp to initialize the // other. if (start_system_timestamp == SystemTime() && start_steady_timestamp == SteadyTime()) return {SystemClock::now(), SteadyClock::now()}; else if (start_system_timestamp == SystemTime()) return {convert_time_point<SystemClock>(start_steady_timestamp), start_steady_timestamp}; else if (start_steady_timestamp == SteadyTime()) return {start_system_timestamp, convert_time_point<SteadyClock>(start_system_timestamp)}; else return {start_system_timestamp, start_steady_timestamp}; } //------------------------------------------------------------------------------ // LightStepSpan //------------------------------------------------------------------------------ namespace { class LightStepSpan : public Span { public: LightStepSpan(std::shared_ptr<const Tracer>&& tracer, Recorder& recorder, StringRef operation_name, const StartSpanOptions& options) : tracer_(std::move(tracer)), recorder_(recorder), operation_name_(operation_name) { // Set the start timestamps. std::tie(start_timestamp_, start_steady_) = compute_start_timestamps( options.start_system_timestamp, options.start_steady_timestamp); // Set any span references. std::unordered_map<std::string, std::string> baggage; references_.reserve(options.references.size()); collector::Reference collector_reference; for (auto& reference : options.references) { auto span_reference_type = reference.first; if (!set_span_reference(reference, baggage, collector_reference)) continue; references_.push_back(collector_reference); } // Set tags. for (auto& tag : options.tags) tags_[tag.first] = tag.second; // Set SpanContext. auto trace_id = references_.empty() ? generate_id() : references_[0].span_context().trace_id(); auto span_id = generate_id(); span_context_ = LightStepSpanContext(trace_id, span_id, std::move(baggage)); } ~LightStepSpan() { if (!is_finished_) Finish(); } void FinishWithOptions(const FinishSpanOptions& options) noexcept override try { // Ensure the span is only finished once. if (is_finished_.exchange(true)) return; auto finish_timestamp = options.finish_steady_timestamp; if (finish_timestamp == SteadyTime()) finish_timestamp = SteadyClock::now(); collector::Span span; // Set timing information. auto duration = finish_timestamp - start_steady_; span.set_duration_micros( std::chrono::duration_cast<std::chrono::microseconds>(duration) .count()); *span.mutable_start_timestamp() = to_timestamp(start_timestamp_); // Set references. auto references = span.mutable_references(); references->Reserve(references_.size()); for (const auto& reference : references_) *references->Add() = reference; // Set tags, logs, and operation name. { std::lock_guard<std::mutex> lock(mutex_); span.set_operation_name(std::move(operation_name_)); auto tags = span.mutable_tags(); tags->Reserve(tags_.size()); for (const auto& tag : tags_) *tags->Add() = to_key_value(tag.first, tag.second); auto logs = span.mutable_logs(); for (auto& log : logs_) *logs->Add() = std::move(log); } // Set the span context. auto span_context = span.mutable_span_context(); span_context->set_trace_id(span_context_.trace_id); span_context->set_span_id(span_context_.span_id); auto baggage = span_context->mutable_baggage(); span_context_.ForeachBaggageItem( [baggage](const std::string& key, const std::string& value) { using StringMap = google::protobuf::Map<std::string, std::string>; baggage->insert(StringMap::value_type(key, value)); return true; }); // Record the span recorder_.RecordSpan(std::move(span)); } catch (const std::bad_alloc&) { // Do nothing if memory allocation fails. } void SetOperationName(StringRef name) noexcept override try { std::lock_guard<std::mutex> l(mutex_); operation_name_ = name; } catch (const std::bad_alloc&) { // Don't change operation name if memory can't be allocated for it. } void SetTag(StringRef key, const Value& value) noexcept override try { std::lock_guard<std::mutex> l(mutex_); tags_[key] = value; } catch (const std::bad_alloc&) { // Don't add the tag if memory can't be allocated for it. } void SetBaggageItem(StringRef restricted_key, StringRef value) noexcept override { span_context_.setBaggageItem(restricted_key, value); } std::string BaggageItem(StringRef restricted_key) const noexcept override try { return span_context_.baggageItem(restricted_key); } catch (const std::bad_alloc&) { return {}; } void Log(std::initializer_list<std::pair<StringRef, Value>> fields) noexcept override try { auto timestamp = SystemClock::now(); collector::Log log; *log.mutable_timestamp() = to_timestamp(timestamp); auto key_values = log.mutable_keyvalues(); for (const auto& field : fields) *key_values->Add() = to_key_value(field.first, field.second); logs_.emplace_back(std::move(log)); } catch (const std::bad_alloc&) { // Do nothing if memory can't be allocted for log records. } const SpanContext& context() const noexcept override { return span_context_; } const Tracer& tracer() const noexcept override { return *tracer_; } private: // Fields set in StartSpan() are not protected by a mutex. std::shared_ptr<const Tracer> tracer_; Recorder& recorder_; std::vector<collector::Reference> references_; SystemTime start_timestamp_; SteadyTime start_steady_; LightStepSpanContext span_context_; // Mutex protects tags_ and operation_name_. std::atomic<bool> is_finished_{false}; std::mutex mutex_; std::string operation_name_; std::unordered_map<std::string, Value> tags_; std::vector<collector::Log> logs_; }; } // namespace anonymous //------------------------------------------------------------------------------ // LightStepTracer //------------------------------------------------------------------------------ namespace { class LightStepTracer : public Tracer, public std::enable_shared_from_this<LightStepTracer> { public: LightStepTracer(std::unique_ptr<Recorder>&& recorder) : recorder_(std::move(recorder)) {} std::unique_ptr<Span> StartSpanWithOptions( StringRef operation_name, const StartSpanOptions& options) const noexcept override try { return std::unique_ptr<Span>(new LightStepSpan( shared_from_this(), *recorder_, operation_name, options)); } catch (const std::bad_alloc&) { // Don't create a span if std::bad_alloc is thrown. return nullptr; } Expected<void> Inject(const SpanContext& sc, CarrierFormat format, const CarrierWriter& writer) const override { auto lightstep_span_context = dynamic_cast<const LightStepSpanContext*>(&sc); if (!lightstep_span_context) return make_unexpected(invalid_span_context_error); return lightstep_span_context->Inject(format, writer); } Expected<std::unique_ptr<SpanContext>> Extract( CarrierFormat format, const CarrierReader& reader) const override { auto lightstep_span_context = new (std::nothrow) LightStepSpanContext(); std::unique_ptr<SpanContext> span_context(lightstep_span_context); if (!span_context) return make_unexpected(make_error_code(std::errc::not_enough_memory)); auto result = lightstep_span_context->Extract(format, reader); if (!result) return make_unexpected(result.error()); else if (!*result) span_context.reset(); return span_context; } void Close() noexcept override { recorder_->FlushWithTimeout(std::chrono::hours(24)); } private: std::unique_ptr<Recorder> recorder_; }; } // anonymous namespace //------------------------------------------------------------------------------ // make_lightstep_tracer //------------------------------------------------------------------------------ std::shared_ptr<opentracing::Tracer> make_lightstep_tracer( std::unique_ptr<Recorder>&& recorder) { if (!recorder) return make_noop_tracer(); else return std::shared_ptr<opentracing::Tracer>( new (std::nothrow) LightStepTracer(std::move(recorder))); } std::shared_ptr<opentracing::Tracer> make_lightstep_tracer( const TracerOptions& options) { return make_lightstep_tracer(make_lightstep_recorder(options)); } } // namespace lightstep <|endoftext|>
<commit_before>// Catch #define CATCH_CONFIG_RUNNER #include <catch.hpp> // C++ Standard Library #include <string> #include <stdexcept> #include <iostream> // Boost #include <boost/filesystem.hpp> // Mantella #include <mantella> boost::filesystem::path testDirectory; int main(const int argc, const char* argv[]) { try { if (argc != 2) { throw std::invalid_argument("The location of the test data directory need to be added to the command line."); } testDirectory = boost::filesystem::path(argv[1]); if (!boost::filesystem::exists(testDirectory)) { throw std::invalid_argument("The speficied test data directory (" + testDirectory.string() + ") does not exists."); } mant::Rng::setSeed(1234567890); return Catch::Session().run(); } catch(const std::exception& exception) { std::cout << exception.what(); } } <commit_msg>devel: Even better error messages<commit_after>// Catch #define CATCH_CONFIG_RUNNER #include <catch.hpp> // C++ Standard Library #include <string> #include <stdexcept> #include <iostream> // Boost #include <boost/filesystem.hpp> // Mantella #include <mantella> boost::filesystem::path testDirectory; int main(const int argc, const char* argv[]) { try { if (argc != 2) { throw std::invalid_argument("The location of the test directory must be added to the command line."); } testDirectory = boost::filesystem::path(argv[1]); if (!boost::filesystem::exists(testDirectory)) { throw std::invalid_argument("The speficied test directory (" + testDirectory.string() + ") does not exists."); } mant::Rng::setSeed(1234567890); return Catch::Session().run(); } catch(const std::exception& exception) { std::cout << exception.what(); } } <|endoftext|>
<commit_before>/* Simple test for MIPSim * run mipsim and gdb sim in parallel * load the same target program in both simulators * run the program step by step * check for disparity in the effect of each instruction * report issues */ #include <QDir> #include <QDebug> #include <QString> #include <QProcess> enum { GDB, MIPSim, TARGET_COUNT }; enum Regnames { // cpu GPR ZERO, AT, V0, V1, A0, A1, A2, A3, T0, T1, T2, T3, T4, T5, T6, T7, S0, S1, S2, S3, S4, S5, S6, S7, T8, T9, K0, K1, GP, SP, FP, RA, // cpu SPR PC, IR, HI, LO, NONE = -1 }; struct RegisterFile { quint32 pc; quint32 hi, lo; quint32 gpr[32]; }; static RegisterFile regs[TARGET_COUNT]; void print_register_file_diff(int t1, int t2) { if ( regs[t1].pc != regs[t2].pc ) qDebug("pc : 0x%08x != 0x%08x", regs[t1].pc, regs[t2].pc); for ( int i = 0; i < 32; ++i ) if ( regs[t1].gpr[i] != regs[t2].gpr[i] ) qDebug("r%i : 0x%08x != 0x%08x", i, regs[t1].gpr[i], regs[t2].gpr[i]); if ( regs[t1].hi != regs[t2].hi ) qDebug("hi : 0x%08x != 0x%08x", regs[t1].hi, regs[t2].hi); if ( regs[t1].lo != regs[t2].lo ) qDebug("lo : 0x%08x != 0x%08x", regs[t1].lo, regs[t2].lo); } static QProcess* sim[TARGET_COUNT]; static const QByteArray prompts[TARGET_COUNT] = { "(gdb) ", "mipsim> " }; bool at_prompt[TARGET_COUNT]; QByteArray command(int target, const QByteArray& command) { QByteArray tmp; QProcess *p = sim[target]; const QByteArray& prompt = prompts[target]; while ( !at_prompt[target] ) { p->waitForReadyRead(-1); tmp += p->readAll(); at_prompt[target] = tmp.endsWith(prompt); } //qDebug("%d> %s", target, qPrintable(command)); p->write(command); QByteArray ans; at_prompt[target] = false; while ( !at_prompt[target] && (p->state() == QProcess::Running) ) { p->waitForReadyRead(200); ans += p->readAll(); if ( ans.endsWith(prompt) ) { ans.chop(prompt.length()); at_prompt[target] = true; } } return ans; } static const QByteArray reg_dump_cmd[TARGET_COUNT] = { "info registers\n", "d\n" }; static const QByteArray reg_dump_skip[TARGET_COUNT] = { "The program has no registers now.\n", "dummy!" }; static const QList<int> reg_dump_mapping[TARGET_COUNT] = { QList<int>() << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 26 << 27 << 28 << 29 << 30 << 31 << 32 << 33 << 43 << 44 << 45 << 46 << 47 << 48 << 49 << 50 << 60 << 61 << 62 << 63 << 64 << 65 << 66 << 67 << 79 << -1 << 76 << 75 , QList<int>() << 11 << 14 << 17 << 20 << 23 << 26 << 29 << 32 << 35 << 38 << 41 << 44 << 47 << 50 << 53 << 56 << 59 << 62 << 65 << 68 << 71 << 74 << 77 << 80 << 83 << 86 << 89 << 92 << 95 << 98 << 101<< 104 << 2 << -1 << 5 << 8 }; typedef QVector<int> QRangeList; void split_ws(QByteArray s, QRangeList& l) { int idx, last; idx = last = 0; const int len = s.length(); const char *d = s.constData(); while ( idx < len ) { if ( d[idx] > ' ' ) { ++idx; } else { if ( last != idx ) l << last << (idx - last); last = ++idx; } } if ( last != idx ) l << last << (idx - last); } quint32 hex_value(const char *d, int length, bool *ok) { quint32 n = 0; if ( ok ) *ok = false; if ( length > 2 && d[0] == '0' && d[1] == 'x' ) { length -= 2; d += 2; } do { unsigned char c = *d - '0'; if ( c > 9 ) { c &= ~('a' - 'A'); c -= ('A' - '0'); c += 10; if ( c > 15 ) return 0; } n <<= 4; n += c; ++d; } while ( --length ); if ( ok ) *ok = true; return n; } QRangeList ranges[TARGET_COUNT]; void update_register_file(int target) { QByteArray ans = command(target, reg_dump_cmd[target]); if ( ans == reg_dump_skip[target] ) return; int n = 0; split_ws(ans, ranges[target]); for ( int i = 0; i < reg_dump_mapping[target].count(); ++i ) { int idx = reg_dump_mapping[target].at(i); if ( idx >= 0 ) { if ( (2*idx+1) < ranges[target].count() ) { bool ok = false; int r_f = ranges[target].at(2*idx); int r_s = ranges[target].at(2*idx+1); quint32 val = hex_value(ans.constData() + r_f, r_s, &ok); if ( !ok ) { qWarning("(%i) borked reg dump : %i = %s", target, i, ans.mid(r_f, r_s).constData()); } else { ++n; if ( i >= 0 && i < 32 ) regs[target].gpr[i] = val; else if ( i == PC ) regs[target].pc = val; else if ( i == HI ) regs[target].hi = val; else if ( i == LO ) regs[target].lo = val; else --n; } } else { qDebug("doh!"); } } } //qDebug("dumped %d registers from target %d", n, target); } int main(int argc, char **argv) { QString target, ans; QProcess mipsim, gdb; sim[GDB] = &gdb; sim[MIPSim] = &mipsim; at_prompt[GDB] = at_prompt[MIPSim] = false; target = QString::fromLocal8Bit(argv[1]); mipsim.setProcessChannelMode(QProcess::MergedChannels); mipsim.start("./mipsim", QStringList() << target); gdb.setProcessChannelMode(QProcess::MergedChannels); gdb.start("mips-elf-gdb", QStringList() << target << "--silent"); if ( !gdb.waitForStarted() ) { qDebug("Unable to start gdb"); return 1; } // get gdb simulator ready for single stepping... command(GDB, "target sim\n"); command(GDB, "load\n"); command(GDB, "b _start\n"); command(GDB, "r\n"); qDebug("Initial register dump"); memset(regs, 0, sizeof(RegisterFile) * TARGET_COUNT); update_register_file(GDB); update_register_file(MIPSim); while ( regs[GDB].pc < regs[MIPSim].pc ) { command(GDB, "si\n"); update_register_file(GDB); } while ( regs[MIPSim].pc < regs[GDB].pc ) { command(MIPSim, "s\n"); update_register_file(MIPSim); } qDebug("Starting @ 0x%08x, 0x%08x", regs[GDB].pc, regs[MIPSim].pc); int n = 0, diff_seq = 0; const int max_diff_seq = QString::fromLocal8Bit(argv[2]).toUInt(); forever { if ( command(GDB, "info program\n") == "The program being debugged is not being run.\n" ) { qDebug("sim target stopped"); break; } if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) ) { if ( !diff_seq ) { // account for GDB maybe lagging one instruction behind quint32 pc = regs[GDB].pc; if ( regs[MIPSim].pc - pc == 4 ) { command(GDB, "si\n"); update_register_file(GDB); if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) ) { qDebug("Simulations differ after %i instruction : ", n); qDebug(" @ 0x%08x, 0x%08x", pc, regs[MIPSim].pc); print_register_file_diff(GDB, MIPSim); ++n; ++diff_seq; command(MIPSim, "s\n"); update_register_file(MIPSim); continue; } else { //qDebug("Corrected delay slot GDB lag @ 0x%08x", pc); continue; } } qDebug("Simulations differ after %i instruction : ", n); qDebug(" @ 0x%08x, 0x%08x", pc, regs[MIPSim].pc); print_register_file_diff(GDB, MIPSim); } if ( ++diff_seq >= max_diff_seq ) { qDebug("simulations not merged after %i steps : aborting...", diff_seq); print_register_file_diff(GDB, MIPSim); break; } } else if ( diff_seq ) { qDebug("simulations merge back after %i steps", diff_seq); diff_seq = 0; } command(MIPSim, "s\n"); update_register_file(MIPSim); command(GDB, "si\n"); update_register_file(GDB); ++n; } command(GDB, "q\ny\n"); command(MIPSim, "q\n"); } <commit_msg>Updated autotester to take name change into account.<commit_after>/* Simple test for MIPSim * run mipsim and gdb sim in parallel * load the same target program in both simulators * run the program step by step * check for disparity in the effect of each instruction * report issues */ #include <QDir> #include <QDebug> #include <QString> #include <QProcess> enum { GDB, MIPSim, TARGET_COUNT }; enum Regnames { // cpu GPR ZERO, AT, V0, V1, A0, A1, A2, A3, T0, T1, T2, T3, T4, T5, T6, T7, S0, S1, S2, S3, S4, S5, S6, S7, T8, T9, K0, K1, GP, SP, FP, RA, // cpu SPR PC, IR, HI, LO, NONE = -1 }; struct RegisterFile { quint32 pc; quint32 hi, lo; quint32 gpr[32]; }; static RegisterFile regs[TARGET_COUNT]; void print_register_file_diff(int t1, int t2) { if ( regs[t1].pc != regs[t2].pc ) qDebug("pc : 0x%08x != 0x%08x", regs[t1].pc, regs[t2].pc); for ( int i = 0; i < 32; ++i ) if ( regs[t1].gpr[i] != regs[t2].gpr[i] ) qDebug("r%i : 0x%08x != 0x%08x", i, regs[t1].gpr[i], regs[t2].gpr[i]); if ( regs[t1].hi != regs[t2].hi ) qDebug("hi : 0x%08x != 0x%08x", regs[t1].hi, regs[t2].hi); if ( regs[t1].lo != regs[t2].lo ) qDebug("lo : 0x%08x != 0x%08x", regs[t1].lo, regs[t2].lo); } static QProcess* sim[TARGET_COUNT]; static const QByteArray prompts[TARGET_COUNT] = { "(gdb) ", "mipsim> " }; bool at_prompt[TARGET_COUNT]; QByteArray command(int target, const QByteArray& command) { QByteArray tmp; QProcess *p = sim[target]; const QByteArray& prompt = prompts[target]; while ( !at_prompt[target] ) { p->waitForReadyRead(-1); tmp += p->readAll(); at_prompt[target] = tmp.endsWith(prompt); } //qDebug("%d> %s", target, qPrintable(command)); p->write(command); QByteArray ans; at_prompt[target] = false; while ( !at_prompt[target] && (p->state() == QProcess::Running) ) { p->waitForReadyRead(200); ans += p->readAll(); if ( ans.endsWith(prompt) ) { ans.chop(prompt.length()); at_prompt[target] = true; } } return ans; } static const QByteArray reg_dump_cmd[TARGET_COUNT] = { "info registers\n", "d\n" }; static const QByteArray reg_dump_skip[TARGET_COUNT] = { "The program has no registers now.\n", "dummy!" }; static const QList<int> reg_dump_mapping[TARGET_COUNT] = { QList<int>() << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16 << 26 << 27 << 28 << 29 << 30 << 31 << 32 << 33 << 43 << 44 << 45 << 46 << 47 << 48 << 49 << 50 << 60 << 61 << 62 << 63 << 64 << 65 << 66 << 67 << 79 << -1 << 76 << 75 , QList<int>() << 11 << 14 << 17 << 20 << 23 << 26 << 29 << 32 << 35 << 38 << 41 << 44 << 47 << 50 << 53 << 56 << 59 << 62 << 65 << 68 << 71 << 74 << 77 << 80 << 83 << 86 << 89 << 92 << 95 << 98 << 101<< 104 << 2 << -1 << 5 << 8 }; typedef QVector<int> QRangeList; void split_ws(QByteArray s, QRangeList& l) { int idx, last; idx = last = 0; const int len = s.length(); const char *d = s.constData(); while ( idx < len ) { if ( d[idx] > ' ' ) { ++idx; } else { if ( last != idx ) l << last << (idx - last); last = ++idx; } } if ( last != idx ) l << last << (idx - last); } quint32 hex_value(const char *d, int length, bool *ok) { quint32 n = 0; if ( ok ) *ok = false; if ( length > 2 && d[0] == '0' && d[1] == 'x' ) { length -= 2; d += 2; } do { unsigned char c = *d - '0'; if ( c > 9 ) { c &= ~('a' - 'A'); c -= ('A' - '0'); c += 10; if ( c > 15 ) return 0; } n <<= 4; n += c; ++d; } while ( --length ); if ( ok ) *ok = true; return n; } QRangeList ranges[TARGET_COUNT]; void update_register_file(int target) { QByteArray ans = command(target, reg_dump_cmd[target]); if ( ans == reg_dump_skip[target] ) return; int n = 0; split_ws(ans, ranges[target]); for ( int i = 0; i < reg_dump_mapping[target].count(); ++i ) { int idx = reg_dump_mapping[target].at(i); if ( idx >= 0 ) { if ( (2*idx+1) < ranges[target].count() ) { bool ok = false; int r_f = ranges[target].at(2*idx); int r_s = ranges[target].at(2*idx+1); quint32 val = hex_value(ans.constData() + r_f, r_s, &ok); if ( !ok ) { qWarning("(%i) borked reg dump : %i = %s", target, i, ans.mid(r_f, r_s).constData()); } else { ++n; if ( i >= 0 && i < 32 ) regs[target].gpr[i] = val; else if ( i == PC ) regs[target].pc = val; else if ( i == HI ) regs[target].hi = val; else if ( i == LO ) regs[target].lo = val; else --n; } } else { qDebug("doh!"); } } } //qDebug("dumped %d registers from target %d", n, target); } int main(int argc, char **argv) { QString target, ans; QProcess mipsim, gdb; sim[GDB] = &gdb; sim[MIPSim] = &mipsim; at_prompt[GDB] = at_prompt[MIPSim] = false; target = QString::fromLocal8Bit(argv[1]); mipsim.setProcessChannelMode(QProcess::MergedChannels); mipsim.start("./simips", QStringList() << target); gdb.setProcessChannelMode(QProcess::MergedChannels); gdb.start("mips-elf-gdb", QStringList() << target << "--silent"); if ( !gdb.waitForStarted() ) { qDebug("Unable to start gdb"); return 1; } // get gdb simulator ready for single stepping... command(GDB, "target sim\n"); command(GDB, "load\n"); command(GDB, "b _start\n"); command(GDB, "r\n"); qDebug("Initial register dump"); memset(regs, 0, sizeof(RegisterFile) * TARGET_COUNT); update_register_file(GDB); update_register_file(MIPSim); while ( regs[GDB].pc < regs[MIPSim].pc ) { command(GDB, "si\n"); update_register_file(GDB); } while ( regs[MIPSim].pc < regs[GDB].pc ) { command(MIPSim, "s\n"); update_register_file(MIPSim); } qDebug("Starting @ 0x%08x, 0x%08x", regs[GDB].pc, regs[MIPSim].pc); int n = 0, diff_seq = 0; const int max_diff_seq = QString::fromLocal8Bit(argv[2]).toUInt(); forever { if ( command(GDB, "info program\n") == "The program being debugged is not being run.\n" ) { qDebug("sim target stopped"); break; } if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) ) { if ( !diff_seq ) { // account for GDB maybe lagging one instruction behind quint32 pc = regs[GDB].pc; if ( regs[MIPSim].pc - pc == 4 ) { command(GDB, "si\n"); update_register_file(GDB); if ( memcmp(&regs[GDB], &regs[MIPSim], sizeof(RegisterFile)) ) { qDebug("Simulations differ after %i instruction : ", n); qDebug(" @ 0x%08x, 0x%08x", pc, regs[MIPSim].pc); print_register_file_diff(GDB, MIPSim); ++n; ++diff_seq; command(MIPSim, "s\n"); update_register_file(MIPSim); continue; } else { //qDebug("Corrected delay slot GDB lag @ 0x%08x", pc); continue; } } qDebug("Simulations differ after %i instruction : ", n); qDebug(" @ 0x%08x, 0x%08x", pc, regs[MIPSim].pc); print_register_file_diff(GDB, MIPSim); } if ( ++diff_seq >= max_diff_seq ) { qDebug("simulations not merged after %i steps : aborting...", diff_seq); print_register_file_diff(GDB, MIPSim); break; } } else if ( diff_seq ) { qDebug("simulations merge back after %i steps", diff_seq); diff_seq = 0; } command(MIPSim, "s\n"); update_register_file(MIPSim); command(GDB, "si\n"); update_register_file(GDB); ++n; } command(GDB, "q\ny\n"); command(MIPSim, "q\n"); } <|endoftext|>
<commit_before>/* Copyright (c) 2008, 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 <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <commit_msg>initialize random number generator for tests<commit_after>/* Copyright (c) 2008, 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 <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, 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 <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure #include "dht_server.hpp" // for stop_dht #include "peer_server.hpp" // for stop_peer int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif // just in case of premature exits // make sure we try to clean up some stop_tracker(); stop_all_proxies(); stop_web_server(); stop_peer(); stop_dht(); fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <commit_msg>SetErrorMode at the start of unit tests (on windows)<commit_after>/* Copyright (c) 2008, 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 <iostream> #include <boost/config.hpp> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> // for exit() #include "setup_transfer.hpp" // for tests_failure #include "dht_server.hpp" // for stop_dht #include "peer_server.hpp" // for stop_peer int test_main(); #include "libtorrent/assert.hpp" #include "libtorrent/file.hpp" #include <signal.h> #ifdef WIN32 #include <windows.h> // fot SetErrorMode #endif void sig_handler(int sig) { char stack_text[10000]; #if (defined TORRENT_DEBUG && !TORRENT_NO_ASSERTS) || TORRENT_RELEASE_ASSERTS print_backtrace(stack_text, sizeof(stack_text), 30); #elif defined __FUNCTION__ strcat(stack_text, __FUNCTION__); #else stack_text[0] = 0; #endif char const* sig_name = 0; switch (sig) { #define SIG(x) case x: sig_name = #x; break SIG(SIGSEGV); #ifdef SIGBUS SIG(SIGBUS); #endif SIG(SIGILL); SIG(SIGABRT); SIG(SIGFPE); #ifdef SIGSYS SIG(SIGSYS); #endif #undef SIG }; fprintf(stderr, "signal: %s caught:\n%s\n", sig_name, stack_text); exit(138); } using namespace libtorrent; int main() { #ifdef WIN32 // try to suppress hanging the process by windows displaying // modal dialogs. SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #endif srand(total_microseconds(time_now_hires() - min_time())); #ifdef O_NONBLOCK // on darwin, stdout is set to non-blocking mode by default // which sometimes causes tests to fail with EAGAIN just // by printing logs int flags = fcntl(fileno(stdout), F_GETFL, 0); fcntl(fileno(stdout), F_SETFL, flags & ~O_NONBLOCK); flags = fcntl(fileno(stderr), F_GETFL, 0); fcntl(fileno(stderr), F_SETFL, flags & ~O_NONBLOCK); #endif signal(SIGSEGV, &sig_handler); #ifdef SIGBUS signal(SIGBUS, &sig_handler); #endif signal(SIGILL, &sig_handler); signal(SIGABRT, &sig_handler); signal(SIGFPE, &sig_handler); #ifdef SIGSYS signal(SIGSYS, &sig_handler); #endif char dir[40]; snprintf(dir, sizeof(dir), "test_tmp_%u", rand()); std::string test_dir = complete(dir); error_code ec; create_directory(test_dir, ec); if (ec) { fprintf(stderr, "Failed to create test directory: %s\n", ec.message().c_str()); return 1; } #ifdef TORRENT_WINDOWS SetCurrentDirectoryA(dir); #else chdir(dir); #endif #ifndef BOOST_NO_EXCEPTIONS try { #endif test_main(); #ifndef BOOST_NO_EXCEPTIONS } catch (std::exception const& e) { std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"; tests_failure = true; } catch (...) { std::cerr << "Terminated with unknown exception\n"; tests_failure = true; } #endif // just in case of premature exits // make sure we try to clean up some stop_tracker(); stop_all_proxies(); stop_web_server(); stop_peer(); stop_dht(); fflush(stdout); fflush(stderr); remove_all(test_dir, ec); if (ec) fprintf(stderr, "failed to remove test dir: %s\n", ec.message().c_str()); return tests_failure ? 1 : 0; } <|endoftext|>
<commit_before>#include "gmock/gmock.h" #include "gtest/gtest.h" int main(int argc, char ** argv) { ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>remove redudant include to gtest<commit_after>#include "gmock/gmock.h" int main(int argc, char ** argv) { ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "domain.h" #include "person.h" //#include <iostream> #include <algorithm> #include <vector> #include "data.h" #include "console.h" //using namespace std; Domain::Domain() { } int Domain::findAge(Person& sciAge) const { int x; int y; int resultDead; int resultAlive; const int currentYear = 2016; x = sciAge.getDeath(); y = sciAge.getBirth(); if(x == 0) { resultAlive = currentYear - y; return resultAlive; } else { resultDead = x - y; return resultDead; } } vector<Person> Domain::search(vector<Person>& p, string name) { vector<Person> results; //Search function, we search from out vector and then put the results in another vector so it shows us all results for(unsigned int i = 0; i < p.size(); i++) { string nameFind; string genderFind; int birthFind; int deathFind; nameFind = p[i].getName(); std::size_t found = nameFind.find(name); if (found!=std::string::npos) { p[i].getName(); genderFind = p[i].getGender(); birthFind = p[i].getBirth(); deathFind = p[i].getDeath(); Person p2(nameFind, genderFind, birthFind, deathFind); results.push_back(p2); } } return results; } vector<Person> Domain::searchName(QString &name) { return _dat.searchName(name); } vector<Computer> Domain::searchComputer(QString &computerName) { return _dat.searchComputer(computerName); } /* vector<Person> Domain::readData() { return _dat.readData(); } */ vector<Computer> Domain::readCompData(int sortedBy) { if(sortedBy == 1) return _dat.readCompDataNameAsc(); else if(sortedBy == 2) return _dat.readCompDataNameDesc(); else if(sortedBy == 3) return _dat.readCompDataYearAsc(); else if(sortedBy == 4) return _dat.readCompDataYearDesc(); else if(sortedBy == 5) return _dat.readCompDataTypeAsc(); else if(sortedBy == 6) return _dat.readCompDataTypeDesc(); else if(sortedBy == 7) return _dat.readCompDataBuiltAsc(); else if(sortedBy == 8) return _dat.readCompDataBuiltDesc(); } vector<Person> Domain::readData(int sortedBy) { if(sortedBy == 1) return _dat.readDataNameAsc(); else if(sortedBy == 2) return _dat.readDataNameDesc(); else if(sortedBy == 3) return _dat.readDataGenderAsc(); else if(sortedBy == 4) return _dat.readDataGenderDesc(); else if(sortedBy == 5) return _dat.readDataBirthAsc(); else if(sortedBy == 6) return _dat.readDataBirthDesc(); else if(sortedBy == 7) return _dat.readDataDeathAsc(); else if(sortedBy == 8) return _dat.readDataDeathDesc(); } bool Domain::addPerson(Person p) { return _dat.addPerson(p); } bool Domain::addComputer(Computer c) { return _dat.addComputer(c); } void Domain::open() { _dat.open(); } void Domain::close() { _dat.close(); } int Domain::sortBy() { Console _con; return _con.sortBy(); } bool Domain::removeAllPersons() { return _dat.removeAllPersons(); } bool Domain::removeAllComputers() { return _dat.removeAllComputers(); } <commit_msg>return in a non void function lagað<commit_after>#include "domain.h" #include "person.h" //#include <iostream> #include <algorithm> #include <vector> #include "data.h" #include "console.h" //using namespace std; Domain::Domain() { } int Domain::findAge(Person& sciAge) const { int x; int y; int resultDead; int resultAlive; const int currentYear = 2016; x = sciAge.getDeath(); y = sciAge.getBirth(); if(x == 0) { resultAlive = currentYear - y; return resultAlive; } else { resultDead = x - y; return resultDead; } } vector<Person> Domain::search(vector<Person>& p, string name) { vector<Person> results; //Search function, we search from out vector and then put the results in another vector so it shows us all results for(unsigned int i = 0; i < p.size(); i++) { string nameFind; string genderFind; int birthFind; int deathFind; nameFind = p[i].getName(); std::size_t found = nameFind.find(name); if (found!=std::string::npos) { p[i].getName(); genderFind = p[i].getGender(); birthFind = p[i].getBirth(); deathFind = p[i].getDeath(); Person p2(nameFind, genderFind, birthFind, deathFind); results.push_back(p2); } } return results; } vector<Person> Domain::searchName(QString &name) { return _dat.searchName(name); } vector<Computer> Domain::searchComputer(QString &computerName) { return _dat.searchComputer(computerName); } /* vector<Person> Domain::readData() { return _dat.readData(); } */ vector<Computer> Domain::readCompData(int sortedBy) { if(sortedBy == 1) return _dat.readCompDataNameAsc(); else if(sortedBy == 2) return _dat.readCompDataNameDesc(); else if(sortedBy == 3) return _dat.readCompDataYearAsc(); else if(sortedBy == 4) return _dat.readCompDataYearDesc(); else if(sortedBy == 5) return _dat.readCompDataTypeAsc(); else if(sortedBy == 6) return _dat.readCompDataTypeDesc(); else if(sortedBy == 7) return _dat.readCompDataBuiltAsc(); else return _dat.readCompDataBuiltDesc(); } vector<Person> Domain::readData(int sortedBy) { if(sortedBy == 1) return _dat.readDataNameAsc(); else if(sortedBy == 2) return _dat.readDataNameDesc(); else if(sortedBy == 3) return _dat.readDataGenderAsc(); else if(sortedBy == 4) return _dat.readDataGenderDesc(); else if(sortedBy == 5) return _dat.readDataBirthAsc(); else if(sortedBy == 6) return _dat.readDataBirthDesc(); else if(sortedBy == 7) return _dat.readDataDeathAsc(); else return _dat.readDataDeathDesc(); } bool Domain::addPerson(Person p) { return _dat.addPerson(p); } bool Domain::addComputer(Computer c) { return _dat.addComputer(c); } void Domain::open() { _dat.open(); } void Domain::close() { _dat.close(); } int Domain::sortBy() { Console _con; return _con.sortBy(); } bool Domain::removeAllPersons() { return _dat.removeAllPersons(); } bool Domain::removeAllComputers() { return _dat.removeAllComputers(); } <|endoftext|>
<commit_before>/************************************************************ cvfont.cpp - $Author: lsxi $ Copyright (C) 2005-2006 Masakazu Yonekura ************************************************************/ #include "cvfont.h" /* * Document-class: OpenCV::CvFont * * Font structure that can be passed to text rendering functions. * see CvMat#put_text, CvMat#put_text! */ __NAMESPACE_BEGIN_OPENCV __NAMESPACE_BEGIN_CVFONT VALUE rb_klass; int rb_font_option_line_type(VALUE font_option) { VALUE line_type = LOOKUP_CVMETHOD(font_option, "line_type"); if (FIXNUM_P(line_type)) { return FIX2INT(line_type); } else if (line_type == ID2SYM(rb_intern("aa"))) { return CV_AA; } return 0; } VALUE rb_class() { return rb_klass; } void define_ruby_class() { if (rb_klass) return; /* * opencv = rb_define_module("OpenCV"); * * note: this comment is used by rdoc. */ VALUE opencv = rb_module_opencv(); rb_klass = rb_define_class_under(opencv, "CvFont", rb_cObject); rb_define_alloc_func(rb_klass, rb_allocate); VALUE face = rb_hash_new(); rb_define_const(rb_klass, "FACE", face); rb_hash_aset(face, ID2SYM(rb_intern("simplex")), INT2FIX(CV_FONT_HERSHEY_SIMPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("plain")), INT2FIX(CV_FONT_HERSHEY_PLAIN)); rb_hash_aset(face, ID2SYM(rb_intern("duplex")), INT2FIX(CV_FONT_HERSHEY_DUPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("triplex")), INT2FIX(CV_FONT_HERSHEY_TRIPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("complex_small")), INT2FIX(CV_FONT_HERSHEY_COMPLEX_SMALL)); rb_hash_aset(face, ID2SYM(rb_intern("script_simplex")), INT2FIX(CV_FONT_HERSHEY_SCRIPT_SIMPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("script_complex")), INT2FIX(CV_FONT_HERSHEY_SCRIPT_COMPLEX)); VALUE default_option = rb_hash_new(); rb_define_const(rb_klass, "FONT_OPTION", default_option); rb_hash_aset(default_option, ID2SYM(rb_intern("hscale")), rb_float_new(1.0)); rb_hash_aset(default_option, ID2SYM(rb_intern("vscale")), rb_float_new(1.0)); rb_hash_aset(default_option, ID2SYM(rb_intern("shear")), INT2FIX(0)); rb_hash_aset(default_option, ID2SYM(rb_intern("thickness")), INT2FIX(1)); rb_hash_aset(default_option, ID2SYM(rb_intern("line_type")), INT2FIX(8)); rb_define_private_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), -1); rb_define_method(rb_klass, "face", RUBY_METHOD_FUNC(rb_face), 0); rb_define_method(rb_klass, "hscale", RUBY_METHOD_FUNC(rb_hscale), 0); rb_define_method(rb_klass, "vscale", RUBY_METHOD_FUNC(rb_vscale), 0); rb_define_method(rb_klass, "shear", RUBY_METHOD_FUNC(rb_shear), 0); rb_define_method(rb_klass, "thickness", RUBY_METHOD_FUNC(rb_thickness), 0); rb_define_method(rb_klass, "line_type", RUBY_METHOD_FUNC(rb_line_type), 0); rb_define_method(rb_klass, "italic", RUBY_METHOD_FUNC(rb_italic), 0); } VALUE rb_allocate(VALUE klass) { CvFont *ptr; return Data_Make_Struct(klass, CvFont, 0, -1, ptr); } /* * call-seq: * CvFont.new(<i>face[,font_option]</i>) -> font * * Create font object. * <i>face</i> is font name identifier. * * Only a subset of Hershey fonts (http://sources.isc.org/utils/misc/hershey-font.txt) are supported now: * * :simplex - normal size sans-serif font * * :plain - small size sans-serif font * * :duplex - normal size sans-serif font (more complex than :simplex) * * :complex - normal size serif font * * :triplex - normal size serif font (more complex than :complex) * * :complex_small - smaller version of :complex * * :script_simplex - hand-writing style font * * :script_complex - more complex variant of :script_simplex * * <i>font_option</i> should be Hash include these keys. * :hscale * Horizontal scale. If equal to 1.0, the characters have the original width depending on the font type. * If equal to 0.5, the characters are of half the original width. * :vscale * Vertical scale. If equal to 1.0, the characters have the original height depending on the font type. * If equal to 0.5, the characters are of half the original height. * :shear * Approximate tangent of the character slope relative to the vertical line. * Zero value means a non-italic font, 1.0f means ~45degree slope, etc. * :thickness * Thickness of the text strokes. * :line_type * Type of the strokes, see CvMat#Line description. * :italic * If value is not nil or false that means italic or oblique font. * * note: <i>font_option</i>'s default value is CvFont::FONT_OPTION. * * e.g. Create Font * OpenCV::CvFont.new(:simplex, :hscale => 2, :vslace => 2, :italic => true) * # create 2x bigger than normal, italic type font. */ VALUE rb_initialize(int argc, VALUE *argv, VALUE self) { VALUE face, font_option; rb_scan_args(argc, argv, "11", &face, &font_option); Check_Type(face, T_SYMBOL); face = rb_hash_aref(rb_const_get(cCvFont::rb_class(), rb_intern("FACE")), face); if (NIL_P(face)) { rb_raise(rb_eArgError, "undefined face."); } font_option = FONT_OPTION(font_option); try { cvInitFont(CVFONT(self), (FIX2INT(face) | FO_ITALIC(font_option)), FO_HSCALE(font_option), FO_VSCALE(font_option), FO_SHEAR(font_option), FO_THICKNESS(font_option), FO_LINE_TYPE(font_option)); } catch (cv::Exception& e) { raise_cverror(e); } return self; } VALUE rb_face(VALUE self) { return INT2FIX(CVFONT(self)->font_face); } VALUE rb_hscale(VALUE self) { return rb_float_new(CVFONT(self)->hscale); } VALUE rb_vscale(VALUE self) { return rb_float_new(CVFONT(self)->vscale); } VALUE rb_shear(VALUE self) { return rb_float_new(CVFONT(self)->shear); } VALUE rb_thickness(VALUE self) { return INT2FIX(CVFONT(self)->thickness); } VALUE rb_line_type(VALUE self) { return INT2FIX(CVFONT(self)->line_type); } VALUE rb_italic(VALUE self) { return ((CVFONT(self)->font_face & CV_FONT_ITALIC) > 0) ? Qtrue : Qfalse; } __NAMESPACE_END_CVFONT __NAMESPACE_END_OPENCV <commit_msg>fix italic option of CvFont#initialize<commit_after>/************************************************************ cvfont.cpp - $Author: lsxi $ Copyright (C) 2005-2006 Masakazu Yonekura ************************************************************/ #include "cvfont.h" /* * Document-class: OpenCV::CvFont * * Font structure that can be passed to text rendering functions. * see CvMat#put_text, CvMat#put_text! */ __NAMESPACE_BEGIN_OPENCV __NAMESPACE_BEGIN_CVFONT VALUE rb_klass; int rb_font_option_line_type(VALUE font_option) { VALUE line_type = LOOKUP_CVMETHOD(font_option, "line_type"); if (FIXNUM_P(line_type)) { return FIX2INT(line_type); } else if (line_type == ID2SYM(rb_intern("aa"))) { return CV_AA; } return 0; } VALUE rb_class() { return rb_klass; } void define_ruby_class() { if (rb_klass) return; /* * opencv = rb_define_module("OpenCV"); * * note: this comment is used by rdoc. */ VALUE opencv = rb_module_opencv(); rb_klass = rb_define_class_under(opencv, "CvFont", rb_cObject); rb_define_alloc_func(rb_klass, rb_allocate); VALUE face = rb_hash_new(); rb_define_const(rb_klass, "FACE", face); rb_hash_aset(face, ID2SYM(rb_intern("simplex")), INT2FIX(CV_FONT_HERSHEY_SIMPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("plain")), INT2FIX(CV_FONT_HERSHEY_PLAIN)); rb_hash_aset(face, ID2SYM(rb_intern("duplex")), INT2FIX(CV_FONT_HERSHEY_DUPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("triplex")), INT2FIX(CV_FONT_HERSHEY_TRIPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("complex_small")), INT2FIX(CV_FONT_HERSHEY_COMPLEX_SMALL)); rb_hash_aset(face, ID2SYM(rb_intern("script_simplex")), INT2FIX(CV_FONT_HERSHEY_SCRIPT_SIMPLEX)); rb_hash_aset(face, ID2SYM(rb_intern("script_complex")), INT2FIX(CV_FONT_HERSHEY_SCRIPT_COMPLEX)); VALUE default_option = rb_hash_new(); rb_define_const(rb_klass, "FONT_OPTION", default_option); rb_hash_aset(default_option, ID2SYM(rb_intern("hscale")), rb_float_new(1.0)); rb_hash_aset(default_option, ID2SYM(rb_intern("vscale")), rb_float_new(1.0)); rb_hash_aset(default_option, ID2SYM(rb_intern("shear")), INT2FIX(0)); rb_hash_aset(default_option, ID2SYM(rb_intern("thickness")), INT2FIX(1)); rb_hash_aset(default_option, ID2SYM(rb_intern("line_type")), INT2FIX(8)); rb_define_private_method(rb_klass, "initialize", RUBY_METHOD_FUNC(rb_initialize), -1); rb_define_method(rb_klass, "face", RUBY_METHOD_FUNC(rb_face), 0); rb_define_method(rb_klass, "hscale", RUBY_METHOD_FUNC(rb_hscale), 0); rb_define_method(rb_klass, "vscale", RUBY_METHOD_FUNC(rb_vscale), 0); rb_define_method(rb_klass, "shear", RUBY_METHOD_FUNC(rb_shear), 0); rb_define_method(rb_klass, "thickness", RUBY_METHOD_FUNC(rb_thickness), 0); rb_define_method(rb_klass, "line_type", RUBY_METHOD_FUNC(rb_line_type), 0); rb_define_method(rb_klass, "italic", RUBY_METHOD_FUNC(rb_italic), 0); } VALUE rb_allocate(VALUE klass) { CvFont *ptr; return Data_Make_Struct(klass, CvFont, 0, -1, ptr); } /* * call-seq: * CvFont.new(<i>face[,font_option]</i>) -> font * * Create font object. * <i>face</i> is font name identifier. * * Only a subset of Hershey fonts (http://sources.isc.org/utils/misc/hershey-font.txt) are supported now: * * :simplex - normal size sans-serif font * * :plain - small size sans-serif font * * :duplex - normal size sans-serif font (more complex than :simplex) * * :complex - normal size serif font * * :triplex - normal size serif font (more complex than :complex) * * :complex_small - smaller version of :complex * * :script_simplex - hand-writing style font * * :script_complex - more complex variant of :script_simplex * * <i>font_option</i> should be Hash include these keys. * :hscale * Horizontal scale. If equal to 1.0, the characters have the original width depending on the font type. * If equal to 0.5, the characters are of half the original width. * :vscale * Vertical scale. If equal to 1.0, the characters have the original height depending on the font type. * If equal to 0.5, the characters are of half the original height. * :shear * Approximate tangent of the character slope relative to the vertical line. * Zero value means a non-italic font, 1.0f means ~45degree slope, etc. * :thickness * Thickness of the text strokes. * :line_type * Type of the strokes, see CvMat#Line description. * :italic * If value is not nil or false that means italic or oblique font. * * note: <i>font_option</i>'s default value is CvFont::FONT_OPTION. * * e.g. Create Font * OpenCV::CvFont.new(:simplex, :hscale => 2, :vslace => 2, :italic => true) * # create 2x bigger than normal, italic type font. */ VALUE rb_initialize(int argc, VALUE *argv, VALUE self) { VALUE face, font_option; rb_scan_args(argc, argv, "11", &face, &font_option); Check_Type(face, T_SYMBOL); face = rb_hash_aref(rb_const_get(cCvFont::rb_class(), rb_intern("FACE")), face); if (NIL_P(face)) { rb_raise(rb_eArgError, "undefined face."); } font_option = FONT_OPTION(font_option); int font_face = NUM2INT(face); if (FO_ITALIC(font_option)) { font_face |= CV_FONT_ITALIC; } try { cvInitFont(CVFONT(self), font_face, FO_HSCALE(font_option), FO_VSCALE(font_option), FO_SHEAR(font_option), FO_THICKNESS(font_option), FO_LINE_TYPE(font_option)); } catch (cv::Exception& e) { raise_cverror(e); } return self; } VALUE rb_face(VALUE self) { return INT2FIX(CVFONT(self)->font_face); } VALUE rb_hscale(VALUE self) { return rb_float_new(CVFONT(self)->hscale); } VALUE rb_vscale(VALUE self) { return rb_float_new(CVFONT(self)->vscale); } VALUE rb_shear(VALUE self) { return rb_float_new(CVFONT(self)->shear); } VALUE rb_thickness(VALUE self) { return INT2FIX(CVFONT(self)->thickness); } VALUE rb_line_type(VALUE self) { return INT2FIX(CVFONT(self)->line_type); } VALUE rb_italic(VALUE self) { return ((CVFONT(self)->font_face & CV_FONT_ITALIC) > 0) ? Qtrue : Qfalse; } __NAMESPACE_END_CVFONT __NAMESPACE_END_OPENCV <|endoftext|>
<commit_before>#include <Windows.h> #include <iostream> #include "..\breakpoint.h" // globals int g_val = 0; HANDLE g_hEvent1, g_hEvent2; void tryWrite() { std::cout << "thread " << std::hex << ::GetCurrentThreadId() << " trying to write..."; __try { g_val = 1; } __except (EXCEPTION_EXECUTE_HANDLER) { std::cout << "\tcatch write attempt [ok]" << std::endl << std::endl; } } DWORD WINAPI ThreadWriteFunc() { // inform main thread to set breakpoint ::SetEvent(g_hEvent2); // wait for main thread to finish setting the BP ::WaitForSingleObject(g_hEvent1, INFINITE); tryWrite(); return 0; } int main() { HANDLE hTrd; DWORD threadId; g_hEvent1 = ::CreateEvent(NULL, TRUE, FALSE, NULL); g_hEvent2 = ::CreateEvent(NULL, TRUE, FALSE, NULL); // multi-thread testing: std::cout << std::endl << std::endl << "test 1: existing thread before the BP has setting" << std::endl; std::cout << "=============================================================================" << std::endl; hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId); // wait for new thread creation ::WaitForSingleObject(g_hEvent2, INFINITE); // print out the new thread id std::cout << "thread " << std::hex << threadId << " has created" << std::endl; // set the BP HWBreakpoint::Set(&g_val, sizeof(int), HWBreakpoint::Write); // signal the thread to continue exection (try to write) ::SetEvent(g_hEvent1); // wait for thread completion ::WaitForSingleObject(hTrd, INFINITE); ::CloseHandle(hTrd); std::cout << std::endl << std::endl << "test 2: new thread after setting the BP" << std::endl; std::cout << "=============================================================================" << std::endl; hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId); // wait for new thread creation ::WaitForSingleObject(g_hEvent2, INFINITE); // print out the new thread id std::cout << "thread " << std::hex << threadId << " has created" << std::endl; // signal the thread to continue execution ::SetEvent(g_hEvent1); // wait for thread completion ::WaitForSingleObject(hTrd, INFINITE); ::CloseHandle(hTrd); // reset the BP HWBreakpoint::Clear(&g_val); // wait for user input std::cin.ignore(); } <commit_msg>reset events<commit_after>#include <Windows.h> #include <iostream> #include "..\breakpoint.h" // globals int g_val = 0; HANDLE g_hEvent1, g_hEvent2; void tryWrite() { std::cout << "thread " << std::hex << ::GetCurrentThreadId() << " trying to write..."; __try { g_val = 1; } __except (EXCEPTION_EXECUTE_HANDLER) { std::cout << "\tcatch write attempt [ok]" << std::endl << std::endl; } } DWORD WINAPI ThreadWriteFunc() { // inform main thread to set breakpoint ::SetEvent(g_hEvent2); // wait for main thread to finish setting the BP ::WaitForSingleObject(g_hEvent1, INFINITE); tryWrite(); return 0; } int main() { HANDLE hTrd; DWORD threadId; g_hEvent1 = ::CreateEvent(NULL, TRUE, FALSE, NULL); g_hEvent2 = ::CreateEvent(NULL, TRUE, FALSE, NULL); // multi-thread testing: std::cout << std::endl << std::endl << "test 1: existing thread before the BP has setting" << std::endl; std::cout << "=============================================================================" << std::endl; hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId); // wait for new thread creation ::WaitForSingleObject(g_hEvent2, INFINITE); // print out the new thread id std::cout << "thread " << std::hex << threadId << " has created" << std::endl; // set the BP HWBreakpoint::Set(&g_val, sizeof(int), HWBreakpoint::Write); // signal the thread to continue exection (try to write) ::SetEvent(g_hEvent1); // wait for thread completion ::WaitForSingleObject(hTrd, INFINITE); // cleanup and reset events ::CloseHandle(hTrd); ::ResetEvent(g_hEvent1); ::ResetEvent(g_hEvent2); std::cout << std::endl << std::endl << "test 2: new thread after setting the BP" << std::endl; std::cout << "=============================================================================" << std::endl; hTrd = ::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadWriteFunc, NULL, 0, &threadId); // wait for new thread creation ::WaitForSingleObject(g_hEvent2, INFINITE); // print out the new thread id std::cout << "thread " << std::hex << threadId << " has created" << std::endl; // signal the thread to continue execution ::SetEvent(g_hEvent1); // wait for thread completion ::WaitForSingleObject(hTrd, INFINITE); ::CloseHandle(hTrd); // reset the BP HWBreakpoint::Clear(&g_val); // wait for user input std::cin.ignore(); } <|endoftext|>
<commit_before>#include <cmath> #include <cstdio> int main() { // double sqrt2 = sqrt(2.0); const int max_y = 127; // 127 const int half_x = 32; for (int y = 0; y < 128; ++y) { for (int z = 0; z < 16; ++z) { for (int x = 0; x < 16; ++x) { double dz; int cx, cy; cx = 2 * x - 2 * z; cy = x + 2 * (max_y-y) + z; // cz = sqrt2 * x - sqrt2 * (max_y-y) + sqrt2 * z; cy += 2; cx += half_x; fprintf(stderr, "%d %d %d: %d %d\n", z, x, y, cy, cx); } } } return 0; } <commit_msg>isometric projection work<commit_after>#include <cmath> #include <cstdio> #include <vector> int main() { // double sqrt2 = sqrt(2.0); const int max_y = 127; // 127 const int half_x = 32; std::vector<std::vector<int> > mask(288, std::vector<int>(64, -1)); std::vector<std::vector<std::vector<int > > > to3D(288, std::vector<std::vector<int> >(64, std::vector<int>(3,-1))); for (int y = 0; y < 128; ++y) { for (int z = 15; z >= 0; --z) { for (int x = 15; x >= 0; --x) { double dz; int px = 15-x; int pz = 15-z; int cx, cy; cx = 2 * px - 2 * pz; cy = px + 2 * (max_y-y) + pz; // cz = sqrt2 * x - sqrt2 * (max_y-y) + sqrt2 * z; cy += 2; cx += half_x; // fprintf(stdout, "%d %d %d: %d %d\n", z, x, y, cy, cx); int index = 0; for (int i = -2; i < 2; ++i) { for (int j = -2; j < 2; ++j) { mask[cy+i][cx+j] = index++; to3D[cy+i][cx+j][0] = x; to3D[cy+i][cx+j][1] = y; to3D[cy+i][cx+j][2] = z; } } } } } for (int i = 0; i < 288; ++i) { for (int j = 0; j < 64; ++j) { // printf("%d %d: %d %d %d\n", i, j, to3D[i][j][0], to3D[i][j][0], to3D[i][j][0]); if (mask[i][j] == -1) { printf("-"); } else { printf("%x", mask[i][j]); } } printf("\n"); } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, 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. */ #ifndef TEST_HPP #define TEST_HPP #include <boost/config.hpp> #include <exception> #include <sstream> #include "libtorrent/config.hpp" #ifdef TORRENT_BUILDING_TEST_SHARED #define EXPORT BOOST_SYMBOL_EXPORT #else #define EXPORT BOOST_SYMBOL_IMPORT #endif // the unit tests need access to these. // they are built into the unit test library as well. // not exported from libtorrent itself extern "C" { int EXPORT ed25519_create_seed(unsigned char *seed); void EXPORT ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed); void EXPORT ed25519_sign(unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key); int EXPORT ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key); void EXPORT ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar); void EXPORT ed25519_key_exchange(unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key); } void EXPORT report_failure(char const* err, char const* file, int line); #if defined(_MSC_VER) #define COUNTER_GUARD(x) #else #define COUNTER_GUARD(type) \ struct BOOST_PP_CAT(type, _counter_guard) \ { \ ~BOOST_PP_CAT(type, _counter_guard()) \ { \ TEST_CHECK(counted_type<type>::count == 0); \ } \ } BOOST_PP_CAT(type, _guard) #endif #define TEST_REPORT_AUX(x, line, file) \ report_failure(x, line, file) #ifdef BOOST_NO_EXCEPTIONS #define TEST_CHECK(x) \ if (!(x)) \ TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); #define TEST_EQUAL(x, y) \ if (x != y) { \ std::stringstream s__; \ s__ << "TEST_EQUAL_ERROR:\n" #x ": " << x << "\nexpected: " << y << std::endl; \ TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \ } #else #define TEST_CHECK(x) \ try \ { \ if (!(x)) \ TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \ } \ catch (std::exception& e) \ { \ TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } #define TEST_EQUAL(x, y) \ try { \ if (x != y) { \ std::stringstream s__; \ s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \ TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \ } \ } \ catch (std::exception& e) \ { \ TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } #endif #define TEST_ERROR(x) \ TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__) #define TEST_NOTHROW(x) \ try \ { \ x; \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } #endif // TEST_HPP <commit_msg>one more attempt at fixing windows linking of test<commit_after>/* Copyright (c) 2008, 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. */ #ifndef TEST_HPP #define TEST_HPP #include <boost/config.hpp> #include <exception> #include <sstream> #include "libtorrent/config.hpp" #ifdef TORRENT_BUILDING_TEST_SHARED #define EXPORT BOOST_SYMBOL_EXPORT #else #define EXPORT BOOST_SYMBOL_IMPORT #endif // the unit tests need access to these. // they are built into the unit test library as well. // not exported from libtorrent itself extern "C" { int EXPORT ed25519_create_seed(unsigned char *seed); void EXPORT ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed); void EXPORT ed25519_sign(unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key, const unsigned char *private_key); int EXPORT ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *private_key); void EXPORT ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key, const unsigned char *scalar); void EXPORT ed25519_key_exchange(unsigned char *shared_secret, const unsigned char *public_key, const unsigned char *private_key); } void EXPORT report_failure(char const* err, char const* file, int line); int EXPORT print_failures(); #if defined(_MSC_VER) #define COUNTER_GUARD(x) #else #define COUNTER_GUARD(type) \ struct BOOST_PP_CAT(type, _counter_guard) \ { \ ~BOOST_PP_CAT(type, _counter_guard()) \ { \ TEST_CHECK(counted_type<type>::count == 0); \ } \ } BOOST_PP_CAT(type, _guard) #endif #define TEST_REPORT_AUX(x, line, file) \ report_failure(x, line, file) #ifdef BOOST_NO_EXCEPTIONS #define TEST_CHECK(x) \ if (!(x)) \ TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); #define TEST_EQUAL(x, y) \ if (x != y) { \ std::stringstream s__; \ s__ << "TEST_EQUAL_ERROR:\n" #x ": " << x << "\nexpected: " << y << std::endl; \ TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \ } #else #define TEST_CHECK(x) \ try \ { \ if (!(x)) \ TEST_REPORT_AUX("TEST_CHECK failed: \"" #x "\"", __FILE__, __LINE__); \ } \ catch (std::exception& e) \ { \ TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } #define TEST_EQUAL(x, y) \ try { \ if (x != y) { \ std::stringstream s__; \ s__ << "TEST_EQUAL_ERROR: " #x ": " << x << " expected: " << y << std::endl; \ TEST_REPORT_AUX(s__.str().c_str(), __FILE__, __LINE__); \ } \ } \ catch (std::exception& e) \ { \ TEST_ERROR("Exception thrown: " #x " :" + std::string(e.what())); \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } #endif #define TEST_ERROR(x) \ TEST_REPORT_AUX((std::string("ERROR: \"") + x + "\"").c_str(), __FILE__, __LINE__) #define TEST_NOTHROW(x) \ try \ { \ x; \ } \ catch (...) \ { \ TEST_ERROR("Exception thrown: " #x); \ } #endif // TEST_HPP <|endoftext|>
<commit_before> #include "AConfig.h" #if(HAS_STD_PILOT) #include "Device.h" #include "Pin.h" #include "Pilot.h" #include "Timer.h" Timer pilotTimer; bool _headingHoldEnabled = false; int _headingHoldTarget = 0; int hdg = 0; int hdg_Error; int raw_Left, raw_Right; int left, right; // motor outputs in microseconds, +/-500 int loop_Gain = 1; int integral_Divisor = 100; long hdg_Error_Integral = 0; int tgt_Hdg = 0; bool _depthHoldEnabled = false; int _depthHoldTarget = 0; int depth = 0; int depth_Error = 0; int raw_lift =0; int lift = 0; int target_depth; int raw_yaw, yaw; void Pilot::device_setup(){ pilotTimer.reset(); Serial.println(F("log:pilot setup complete;")); } void Pilot::device_loop(Command command){ //intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth); if( command.cmp("holdHeading_toggle")){ if (_headingHoldEnabled) { _headingHoldEnabled = false; raw_Left = 0; raw_Right = 0; hdg_Error_Integral = 0; // Reset error integrator tgt_Hdg = -500; // -500 = system not in hdg hold int argsToSend[] = {1,00}; //include number of parms as last parm command.pushCommand("yaw",argsToSend); Serial.println(F("log:heading_hold_disabled;")); } else { _headingHoldEnabled = true; if(command.args[0]==0){ _headingHoldTarget = navdata::HDGD; } else { _headingHoldTarget = command.args[1]; } tgt_Hdg = _headingHoldTarget; Serial.print(F("log:heading_hold_enabled on=")); Serial.print(tgt_Hdg); Serial.println(';'); } Serial.print(F("targetHeading:")); if (_headingHoldEnabled) { Serial.print(tgt_Hdg); } else { Serial.print(DISABLED); } Serial.println(';'); } if( command.cmp("holdDepth_toggle")){ if (_depthHoldEnabled) { _depthHoldEnabled = false; raw_lift = 0; target_depth = 0; int argsToSend[] = {1,0}; //include number of parms as last parm command.pushCommand("lift",argsToSend); Serial.println(F("log:depth_hold_disabled;")); } else { _depthHoldEnabled = true; if(command.args[0]==0){ _depthHoldTarget = navdata::DEAP*100; //casting to cm } else { _depthHoldTarget = command.args[1]; } target_depth = _depthHoldTarget; Serial.print(F("log:depth_hold_enabled on=")); Serial.print(target_depth); Serial.println(';'); } Serial.print(F("targetDepth:")); if (_depthHoldEnabled) { Serial.print(target_depth); } else { Serial.pitnt(DISABLED); } Serial.println(';'); } if (pilotTimer.elapsed (50)) { // Autopilot Test #3 6 Jan 2014 // Hold vehicle at arbitrary heading // Integer math; proportional control plus basic integrator // No hysteresis around 180 degree error // Check whether hold mode is on if (_depthHoldEnabled) { depth = navdata::DEAP*100; depth_Error = target_depth-depth; //positive error = positive lift = go deaper. raw_lift = depth_Error * loop_Gain; lift = constrain(raw_lift, -50, 50); Serial.println(F("log:dhold pushing command;")); Serial.print(F("dp_er:")); Serial.print(depth_Error); Serial.println(';'); int argsToSend[] = {1,lift}; //include number of parms as last parm command.pushCommand("lift",argsToSend); } if (_headingHoldEnabled) { // Code for hold mode here hdg = navdata::HDGD; // Calculate heading error hdg_Error = hdg - tgt_Hdg; if (hdg_Error > 180) { hdg_Error = hdg_Error - 360; } if (hdg_Error < -179) { hdg_Error = hdg_Error + 360; } // Run error accumulator (integrator) hdg_Error_Integral = hdg_Error_Integral + hdg_Error; // Calculator motor outputs raw_yaw = -1 * hdg_Error * loop_Gain; // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor); // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor); // Constrain and output to motors yaw = constrain(raw_yaw, -50, 50); Serial.println(F("log:hold pushing command;")); Serial.print(F("p_er:")); Serial.print(hdg_Error); Serial.println(';'); int argsToSend[] = {1,yaw}; //include number of parms as last parm command.pushCommand("yaw",argsToSend); } } } #endif <commit_msg>Revert "Fix spelling in Arduino"<commit_after> #include "AConfig.h" #if(HAS_STD_PILOT) #include "Device.h" #include "Pin.h" #include "Pilot.h" #include "Timer.h" Timer pilotTimer; bool _headingHoldEnabled = false; int _headingHoldTarget = 0; int hdg = 0; int hdg_Error; int raw_Left, raw_Right; int left, right; // motor outputs in microseconds, +/-500 int loop_Gain = 1; int integral_Divisor = 100; long hdg_Error_Integral = 0; int tgt_Hdg = 0; bool _depthHoldEnabled = false; int _depthHoldTarget = 0; int depth = 0; int depth_Error = 0; int raw_lift =0; int lift = 0; int target_depth; int raw_yaw, yaw; void Pilot::device_setup(){ pilotTimer.reset(); Serial.println(F("log:pilot setup complete;")); } void Pilot::device_loop(Command command){ //intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth); if( command.cmp("holdHeading_toggle")){ if (_headingHoldEnabled) { _headingHoldEnabled = false; raw_Left = 0; raw_Right = 0; hdg_Error_Integral = 0; // Reset error integrator tgt_Hdg = -500; // -500 = system not in hdg hold int argsToSend[] = {1,00}; //include number of parms as last parm command.pushCommand("yaw",argsToSend); Serial.println(F("log:heading_hold_disabled;")); } else { _headingHoldEnabled = true; if(command.args[0]==0){ _headingHoldTarget = navdata::HDGD; } else { _headingHoldTarget = command.args[1]; } tgt_Hdg = _headingHoldTarget; Serial.print(F("log:heading_hold_enabled on=")); Serial.print(tgt_Hdg); Serial.println(';'); } Serial.print(F("targetHeading:")); if (_headingHoldEnabled) { Serial.print(tgt_Hdg); } else { Serial.print(DISAABLED); } Serial.println(';'); } if( command.cmp("holdDepth_toggle")){ if (_depthHoldEnabled) { _depthHoldEnabled = false; raw_lift = 0; target_depth = 0; int argsToSend[] = {1,0}; //include number of parms as last parm command.pushCommand("lift",argsToSend); Serial.println(F("log:depth_hold_disabled;")); } else { _depthHoldEnabled = true; if(command.args[0]==0){ _depthHoldTarget = navdata::DEAP*100; //casting to cm } else { _depthHoldTarget = command.args[1]; } target_depth = _depthHoldTarget; Serial.print(F("log:depth_hold_enabled on=")); Serial.print(target_depth); Serial.println(';'); } Serial.print(F("targetDepth:")); if (_depthHoldEnabled) { Serial.print(target_depth); } else { Serial.pitnt(DISABLED); } Serial.println(';'); } if (pilotTimer.elapsed (50)) { // Autopilot Test #3 6 Jan 2014 // Hold vehicle at arbitrary heading // Integer math; proportional control plus basic integrator // No hysteresis around 180 degree error // Check whether hold mode is on if (_depthHoldEnabled) { depth = navdata::DEAP*100; depth_Error = target_depth-depth; //positive error = positive lift = go deaper. raw_lift = depth_Error * loop_Gain; lift = constrain(raw_lift, -50, 50); Serial.println(F("log:dhold pushing command;")); Serial.print(F("dp_er:")); Serial.print(depth_Error); Serial.println(';'); int argsToSend[] = {1,lift}; //include number of parms as last parm command.pushCommand("lift",argsToSend); } if (_headingHoldEnabled) { // Code for hold mode here hdg = navdata::HDGD; // Calculate heading error hdg_Error = hdg - tgt_Hdg; if (hdg_Error > 180) { hdg_Error = hdg_Error - 360; } if (hdg_Error < -179) { hdg_Error = hdg_Error + 360; } // Run error accumulator (integrator) hdg_Error_Integral = hdg_Error_Integral + hdg_Error; // Calculator motor outputs raw_yaw = -1 * hdg_Error * loop_Gain; // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor); // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor); // Constrain and output to motors yaw = constrain(raw_yaw, -50, 50); Serial.println(F("log:hold pushing command;")); Serial.print(F("p_er:")); Serial.print(hdg_Error); Serial.println(';'); int argsToSend[] = {1,yaw}; //include number of parms as last parm command.pushCommand("yaw",argsToSend); } } } #endif <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: vcs.cpp // Purpose: Implementation of wxExVCS class // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <map> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/xml/xml.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/filename.h> #include <wx/extension/util.h> // The vcs id's here can be set using the config dialog, and are not // present in the vcs.xml. enum { VCS_NONE = -2, // no version control VCS_AUTO = -1, // uses the VCS appropriate for current file VCS_START = 0 // no where fixed VCS start (index in vector) }; std::vector<wxExVCSEntry> wxExVCS::m_Entries; wxFileName wxExVCS::m_FileName; wxExVCS::wxExVCS() { } wxExVCS::wxExVCS(const wxArrayString& files, int menu_id) : m_Files(files) { m_Entry = FindEntry(GetFile()); if (!m_Entry.GetName().empty()) { m_Entry.SetCommand(menu_id); m_Caption = m_Entry.GetName() + " " + m_Entry.GetCommand().GetCommand(); if (!m_Entry.GetCommand().IsHelp() && m_Files.size() == 1) { m_Caption += " " + wxFileName(m_Files[0]).GetFullName(); } } else { m_Caption = "VCS"; } } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title, bool modal) const { if (m_Entries.empty()) { return wxID_CANCEL; } std::map<long, const wxString> choices; choices.insert(std::make_pair((long)VCS_NONE, _("None"))); // Using auto vcs is not useful if we only have one vcs. if (m_Entries.size() != 1) { choices.insert(std::make_pair((long)VCS_AUTO, "Auto")); } long i = VCS_START; for ( #ifdef wxExUSE_CPP0X auto it = m_Entries.begin(); #else std::vector<wxExVCSEntry>::const_iterator it = m_Entries.begin(); #endif it != m_Entries.end(); ++it) { choices.insert(std::make_pair(i, it->GetName())); i++; } // Estimate number of columns used by the radiobox. int cols = 5; switch (choices.size()) { case 6: case 11: cols = 3; break; case 7: case 8: case 12: case 16: cols = 4; break; } std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem( "VCS", choices, true, // use a radiobox wxEmptyString, cols)); for ( #ifdef wxExUSE_CPP0X auto it2 = m_Entries.begin(); #else std::vector<wxExVCSEntry>::const_iterator it2 = m_Entries.begin(); #endif it2 != m_Entries.end(); ++it2) { v.push_back(wxExConfigItem(it2->GetName(), CONFIG_FILEPICKERCTRL)); } if (modal) { return wxExConfigDialog(parent, v, title).ShowModal(); } else { wxExConfigDialog* dlg = new wxExConfigDialog(parent, v, title); return dlg->Show(); } } #endif bool wxExVCS::DirExists(const wxFileName& filename) { const wxExVCSEntry entry(FindEntry(filename)); if ( entry.AdminDirIsTopLevel() && IsAdminDirTopLevel(entry.GetAdminDir(), filename)) { return true; } else { return IsAdminDir(entry.GetAdminDir(), filename); } } bool wxExVCS::Execute() { const wxExFileName filename(GetFile()); if (!filename.IsOk()) { wxString args; if (m_Entry.GetCommand().IsAdd()) { args = wxExConfigFirstOf(_("Path")); } return m_Entry.Execute( args, wxExLexer(), wxExConfigFirstOf(_("Base folder"))); } else { wxString args; wxString wd; if (m_Files.size() > 1) { // File should not be surrounded by double quotes. for ( #ifdef wxExUSE_CPP0X auto it = m_Files.begin(); #else wxArrayString::iterator it = m_Files.begin(); #endif it != m_Files.end(); ++it) { args += *it + " "; } } else if (m_Entry.GetName().Lower() == "git") { const wxString admin_dir(FindEntry(filename).GetAdminDir()); wd = GetTopLevelDir(admin_dir, filename); if (!filename.GetFullName().empty()) { args = GetRelativeFile( admin_dir, filename); } } else if (m_Entry.GetName().Lower() == "sccs") { args = "\"" + // sccs for windows does not handle windows paths, // so convert them to UNIX, and add volume as well. #ifdef __WXMSW__ filename.GetVolume() + filename.GetVolumeSeparator() + #endif filename.GetFullPath(wxPATH_UNIX) + "\""; } else { args = "\"" + filename.GetFullPath() + "\""; } return m_Entry.Execute(args, filename.GetLexer(), wd); } } const wxExVCSEntry wxExVCS::FindEntry(const wxFileName& filename) { const int vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO); if (vcs == VCS_AUTO) { if (filename.IsOk()) { for ( #ifdef wxExUSE_CPP0X auto it = m_Entries.begin(); #else std::vector<wxExVCSEntry>::iterator it = m_Entries.begin(); #endif it != m_Entries.end(); ++it) { const bool toplevel = it->AdminDirIsTopLevel(); const wxString admin_dir = it->GetAdminDir(); if (toplevel && IsAdminDirTopLevel(admin_dir, filename)) { return *it; } else if (IsAdminDir(admin_dir, filename)) { return *it; } } } } else if (vcs >= VCS_START && vcs < m_Entries.size()) { return m_Entries[vcs]; } return wxExVCSEntry(); } bool wxExVCS::GetDir(wxWindow* parent) { if (!Use()) { return false; } const wxString message = _("Select VCS Folder"); std::vector<wxExConfigItem> v; // See also vcsentry, same item is used there. v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true, 1005)); if (wxExConfigFirstOf(_("Base folder")).empty()) { if ( parent != NULL && wxExConfigDialog(parent, v, message).ShowModal() == wxID_CANCEL) { return false; } } else { m_Entry = FindEntry(wxExConfigFirstOf(_("Base folder"))); if (m_Entry.GetName().empty()) { if ( parent != NULL && wxExConfigDialog(parent, v, message).ShowModal() == wxID_CANCEL) { return false; } } } m_Entry = FindEntry(wxExConfigFirstOf(_("Base folder"))); return !m_Entry.GetName().empty(); } const wxString wxExVCS::GetFile() const { if (m_Files.empty()) { return wxExConfigFirstOf(_("Base folder")); } else { return m_Files[0]; } } const wxString wxExVCS::GetName() const { if (!Use()) { return wxEmptyString; } else if (wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO) == VCS_AUTO) { return "Auto"; } else { return m_Entry.GetName(); } } // See IsAdminDirTopLevel const wxString wxExVCS::GetRelativeFile( const wxString& admin_dir, const wxFileName& fn) const { // The .git dir only exists in the root, so check all components. wxFileName root(fn); wxArrayString as; while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(admin_dir); if (path.DirExists() && !path.FileExists()) { wxString relative_file; for (int i = as.GetCount() - 1; i >= 0; i--) { relative_file += as[i] + "/"; } return relative_file + fn.GetFullName(); } as.Add(root.GetDirs().Last()); root.RemoveLastDir(); } return wxEmptyString; } // See IsAdminDirTopLevel const wxString wxExVCS::GetTopLevelDir( const wxString& admin_dir, const wxFileName& fn) const { if (!fn.IsOk() || admin_dir.empty()) { return wxEmptyString; } // The .git dir only exists in the root, so check all components. wxFileName root(fn); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(admin_dir); if (path.DirExists() && !path.FileExists()) { return root.GetPath(); } root.RemoveLastDir(); } return wxEmptyString; } bool wxExVCS::IsAdminDir( const wxString& admin_dir, const wxFileName& fn) { if (admin_dir.empty() || !fn.IsOk()) { return false; } // these cannot be combined, as AppendDir is a void (2.9.1). wxFileName path(fn); path.AppendDir(admin_dir); return path.DirExists() && !path.FileExists(); } bool wxExVCS::IsAdminDirTopLevel( const wxString& admin_dir, const wxFileName& fn) { if (!fn.IsOk() || admin_dir.empty()) { return false; } // The .git dir only exists in the root, so check all components. wxFileName root(fn); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(admin_dir); if (path.DirExists() && !path.FileExists()) { return true; } root.RemoveLastDir(); } return false; } bool wxExVCS::Read() { // This test is to prevent showing an error if the vcs file does not exist, // as this is not required. if (!m_FileName.FileExists()) { return false; } wxXmlDocument doc; if (!doc.Load(m_FileName.GetFullPath())) { return false; } // Initialize members. const int old_entries = m_Entries.size(); m_Entries.clear(); wxXmlNode* child = doc.GetRoot()->GetChildren(); while (child) { if (child->GetName() == "vcs") { m_Entries.push_back(wxExVCSEntry(child)); } child = child->GetNext(); } if (old_entries == 0) { // Add default VCS. if (!wxConfigBase::Get()->Exists("VCS")) { wxConfigBase::Get()->Write("VCS", (long)VCS_AUTO); } } else if (old_entries != m_Entries.size()) { // If current number of entries differs from old one, // we added or removed an entry. That might give problems // with the vcs id stored in the config, so reset it. wxConfigBase::Get()->Write("VCS", (long)VCS_AUTO); } return true; } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (!Execute()) { return wxID_CANCEL; } m_Entry.ShowOutput(m_Caption); return wxID_OK; } #endif bool wxExVCS::Use() const { return wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO) != VCS_NONE; } <commit_msg>use quotes for multiple files<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: vcs.cpp // Purpose: Implementation of wxExVCS class // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <map> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/xml/xml.h> #include <wx/extension/vcs.h> #include <wx/extension/configdlg.h> #include <wx/extension/filename.h> #include <wx/extension/util.h> // The vcs id's here can be set using the config dialog, and are not // present in the vcs.xml. enum { VCS_NONE = -2, // no version control VCS_AUTO = -1, // uses the VCS appropriate for current file VCS_START = 0 // no where fixed VCS start (index in vector) }; std::vector<wxExVCSEntry> wxExVCS::m_Entries; wxFileName wxExVCS::m_FileName; wxExVCS::wxExVCS() { } wxExVCS::wxExVCS(const wxArrayString& files, int menu_id) : m_Files(files) { m_Entry = FindEntry(GetFile()); if (!m_Entry.GetName().empty()) { m_Entry.SetCommand(menu_id); m_Caption = m_Entry.GetName() + " " + m_Entry.GetCommand().GetCommand(); if (!m_Entry.GetCommand().IsHelp() && m_Files.size() == 1) { m_Caption += " " + wxFileName(m_Files[0]).GetFullName(); } } else { m_Caption = "VCS"; } } #if wxUSE_GUI int wxExVCS::ConfigDialog( wxWindow* parent, const wxString& title, bool modal) const { if (m_Entries.empty()) { return wxID_CANCEL; } std::map<long, const wxString> choices; choices.insert(std::make_pair((long)VCS_NONE, _("None"))); // Using auto vcs is not useful if we only have one vcs. if (m_Entries.size() != 1) { choices.insert(std::make_pair((long)VCS_AUTO, "Auto")); } long i = VCS_START; for ( auto it = m_Entries.begin(); it != m_Entries.end(); ++it) { choices.insert(std::make_pair(i, it->GetName())); i++; } // Estimate number of columns used by the radiobox. int cols = 5; switch (choices.size()) { case 6: case 11: cols = 3; break; case 7: case 8: case 12: case 16: cols = 4; break; } std::vector<wxExConfigItem> v; v.push_back(wxExConfigItem( "VCS", choices, true, // use a radiobox wxEmptyString, cols)); for ( auto it2 = m_Entries.begin(); it2 != m_Entries.end(); ++it2) { v.push_back(wxExConfigItem(it2->GetName(), CONFIG_FILEPICKERCTRL)); } if (modal) { return wxExConfigDialog(parent, v, title).ShowModal(); } else { wxExConfigDialog* dlg = new wxExConfigDialog(parent, v, title); return dlg->Show(); } } #endif bool wxExVCS::DirExists(const wxFileName& filename) { const wxExVCSEntry entry(FindEntry(filename)); if ( entry.AdminDirIsTopLevel() && IsAdminDirTopLevel(entry.GetAdminDir(), filename)) { return true; } else { return IsAdminDir(entry.GetAdminDir(), filename); } } bool wxExVCS::Execute() { const wxExFileName filename(GetFile()); if (!filename.IsOk()) { wxString args; if (m_Entry.GetCommand().IsAdd()) { args = wxExConfigFirstOf(_("Path")); } return m_Entry.Execute( args, wxExLexer(), wxExConfigFirstOf(_("Base folder"))); } else { wxString args; wxString wd; if (m_Files.size() > 1) { for ( auto it = m_Files.begin(); it != m_Files.end(); ++it) { args += "\"" + *it + "\" "; } } else if (m_Entry.GetName().Lower() == "git") { const wxString admin_dir(FindEntry(filename).GetAdminDir()); wd = GetTopLevelDir(admin_dir, filename); if (!filename.GetFullName().empty()) { args = GetRelativeFile( admin_dir, filename); } } else if (m_Entry.GetName().Lower() == "sccs") { args = "\"" + // sccs for windows does not handle windows paths, // so convert them to UNIX, and add volume as well. #ifdef __WXMSW__ filename.GetVolume() + filename.GetVolumeSeparator() + #endif filename.GetFullPath(wxPATH_UNIX) + "\""; } else { args = "\"" + filename.GetFullPath() + "\""; } return m_Entry.Execute(args, filename.GetLexer(), wd); } } const wxExVCSEntry wxExVCS::FindEntry(const wxFileName& filename) { const int vcs = wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO); if (vcs == VCS_AUTO) { if (filename.IsOk()) { for ( auto it = m_Entries.begin(); it != m_Entries.end(); ++it) { const bool toplevel = it->AdminDirIsTopLevel(); const wxString admin_dir = it->GetAdminDir(); if (toplevel && IsAdminDirTopLevel(admin_dir, filename)) { return *it; } else if (IsAdminDir(admin_dir, filename)) { return *it; } } } } else if (vcs >= VCS_START && vcs < m_Entries.size()) { return m_Entries[vcs]; } return wxExVCSEntry(); } bool wxExVCS::GetDir(wxWindow* parent) { if (!Use()) { return false; } const wxString message = _("Select VCS Folder"); std::vector<wxExConfigItem> v; // See also vcsentry, same item is used there. v.push_back(wxExConfigItem( _("Base folder"), CONFIG_COMBOBOXDIR, wxEmptyString, true, 1005)); if (wxExConfigFirstOf(_("Base folder")).empty()) { if ( parent != NULL && wxExConfigDialog(parent, v, message).ShowModal() == wxID_CANCEL) { return false; } } else { m_Entry = FindEntry(wxExConfigFirstOf(_("Base folder"))); if (m_Entry.GetName().empty()) { if ( parent != NULL && wxExConfigDialog(parent, v, message).ShowModal() == wxID_CANCEL) { return false; } } } m_Entry = FindEntry(wxExConfigFirstOf(_("Base folder"))); return !m_Entry.GetName().empty(); } const wxString wxExVCS::GetFile() const { if (m_Files.empty()) { return wxExConfigFirstOf(_("Base folder")); } else { return m_Files[0]; } } const wxString wxExVCS::GetName() const { if (!Use()) { return wxEmptyString; } else if (wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO) == VCS_AUTO) { return "Auto"; } else { return m_Entry.GetName(); } } // See IsAdminDirTopLevel const wxString wxExVCS::GetRelativeFile( const wxString& admin_dir, const wxFileName& fn) const { // The .git dir only exists in the root, so check all components. wxFileName root(fn); wxArrayString as; while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(admin_dir); if (path.DirExists() && !path.FileExists()) { wxString relative_file; for (int i = as.GetCount() - 1; i >= 0; i--) { relative_file += as[i] + "/"; } return relative_file + fn.GetFullName(); } as.Add(root.GetDirs().Last()); root.RemoveLastDir(); } return wxEmptyString; } // See IsAdminDirTopLevel const wxString wxExVCS::GetTopLevelDir( const wxString& admin_dir, const wxFileName& fn) const { if (!fn.IsOk() || admin_dir.empty()) { return wxEmptyString; } // The .git dir only exists in the root, so check all components. wxFileName root(fn); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(admin_dir); if (path.DirExists() && !path.FileExists()) { return root.GetPath(); } root.RemoveLastDir(); } return wxEmptyString; } bool wxExVCS::IsAdminDir( const wxString& admin_dir, const wxFileName& fn) { if (admin_dir.empty() || !fn.IsOk()) { return false; } // these cannot be combined, as AppendDir is a void (2.9.1). wxFileName path(fn); path.AppendDir(admin_dir); return path.DirExists() && !path.FileExists(); } bool wxExVCS::IsAdminDirTopLevel( const wxString& admin_dir, const wxFileName& fn) { if (!fn.IsOk() || admin_dir.empty()) { return false; } // The .git dir only exists in the root, so check all components. wxFileName root(fn); while (root.DirExists() && root.GetDirCount() > 0) { wxFileName path(root); path.AppendDir(admin_dir); if (path.DirExists() && !path.FileExists()) { return true; } root.RemoveLastDir(); } return false; } bool wxExVCS::Read() { // This test is to prevent showing an error if the vcs file does not exist, // as this is not required. if (!m_FileName.FileExists()) { return false; } wxXmlDocument doc; if (!doc.Load(m_FileName.GetFullPath())) { return false; } // Initialize members. const int old_entries = m_Entries.size(); m_Entries.clear(); wxXmlNode* child = doc.GetRoot()->GetChildren(); while (child) { if (child->GetName() == "vcs") { m_Entries.push_back(wxExVCSEntry(child)); } child = child->GetNext(); } if (old_entries == 0) { // Add default VCS. if (!wxConfigBase::Get()->Exists("VCS")) { wxConfigBase::Get()->Write("VCS", (long)VCS_AUTO); } } else if (old_entries != m_Entries.size()) { // If current number of entries differs from old one, // we added or removed an entry. That might give problems // with the vcs id stored in the config, so reset it. wxConfigBase::Get()->Write("VCS", (long)VCS_AUTO); } return true; } #if wxUSE_GUI wxStandardID wxExVCS::Request(wxWindow* parent) { if (ShowDialog(parent) == wxID_CANCEL) { return wxID_CANCEL; } if (!Execute()) { return wxID_CANCEL; } m_Entry.ShowOutput(m_Caption); return wxID_OK; } #endif bool wxExVCS::Use() const { return wxConfigBase::Get()->ReadLong("VCS", VCS_AUTO) != VCS_NONE; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file vdev_posix.cpp * * POSIX-like API for virtual character device */ #include <px4_log.h> #include <px4_posix.h> #include <px4_time.h> #include "device.h" #include "vfile.h" #include <hrt_work.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> using namespace device; pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER; px4_sem_t lockstep_sem; bool sim_lockstep = false; volatile bool sim_delay = false; extern "C" { #define PX4_MAX_FD 300 static device::file_t *filemap[PX4_MAX_FD] = {}; int px4_errno; inline bool valid_fd(int fd) { pthread_mutex_lock(&filemutex); bool ret = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != nullptr); pthread_mutex_unlock(&filemutex); return ret; } inline CDev *get_vdev(int fd) { pthread_mutex_lock(&filemutex); bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != nullptr); CDev *dev; if (valid) { dev = (CDev *)(filemap[fd]->vdev); } else { dev = nullptr; } pthread_mutex_unlock(&filemutex); return dev; } int px4_open(const char *path, int flags, ...) { PX4_DEBUG("px4_open"); CDev *dev = CDev::getDev(path); int ret = 0; int i; mode_t mode; if (!dev && (flags & (PX4_F_WRONLY | PX4_F_CREAT)) != 0 && strncmp(path, "/obj/", 5) != 0 && strncmp(path, "/dev/", 5) != 0) { va_list p; va_start(p, flags); mode = va_arg(p, int); va_end(p); // Create the file PX4_DEBUG("Creating virtual file %s", path); dev = VFile::createFile(path, mode); } if (dev) { pthread_mutex_lock(&filemutex); for (i = 0; i < PX4_MAX_FD; ++i) { if (filemap[i] == nullptr) { filemap[i] = new device::file_t(flags, dev, i); break; } } pthread_mutex_unlock(&filemutex); if (i < PX4_MAX_FD) { ret = dev->open(filemap[i]); } else { const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } PX4_BACKTRACE(); #endif PX4_WARN("%s: exceeded maximum number of file descriptors, accessing %s", thread_name, path); ret = -ENOENT; } } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; return -1; } PX4_DEBUG("px4_open fd = %d", filemap[i]->fd); return filemap[i]->fd; } int px4_close(int fd) { int ret; CDev *dev = get_vdev(fd); if (dev) { pthread_mutex_lock(&filemutex); ret = dev->close(filemap[fd]); if (filemap[fd] != nullptr) { delete filemap[fd]; } filemap[fd] = nullptr; pthread_mutex_unlock(&filemutex); PX4_DEBUG("px4_close fd = %d", fd); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_read(int fd, void *buffer, size_t buflen) { int ret; CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_read fd = %d", fd); ret = dev->read(filemap[fd], (char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_write(int fd, const void *buffer, size_t buflen) { int ret; CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_write fd = %d", fd); ret = dev->write(filemap[fd], (const char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } int px4_ioctl(int fd, int cmd, unsigned long arg) { PX4_DEBUG("px4_ioctl fd = %d", fd); int ret = 0; CDev *dev = get_vdev(fd); if (dev) { ret = dev->ioctl(filemap[fd], cmd, arg); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; } return ret; } int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout) { if (nfds == 0) { PX4_WARN("px4_poll with no fds"); return -1; } px4_sem_t sem; int count = 0; int ret = -1; unsigned int i; const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } #endif while (sim_delay) { usleep(100); } PX4_DEBUG("Called px4_poll timeout = %d", timeout); px4_sem_init(&sem, 0, 0); // sem use case is a signal px4_sem_setprotocol(&sem, SEM_PRIO_NONE); // Go through all fds and check them for a pollable state bool fd_pollable = false; for (i = 0; i < nfds; ++i) { fds[i].sem = &sem; fds[i].revents = 0; fds[i].priv = nullptr; CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(setup) %d", thread_name, fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], true); if (ret < 0) { PX4_WARN("%s: px4_poll() error: %s", thread_name, strerror(errno)); break; } if (ret >= 0) { fd_pollable = true; } } } // If any FD can be polled, lock the semaphore and // check for new data if (fd_pollable) { if (timeout > 0) { // Get the current time struct timespec ts; // FIXME: check if QURT should probably be using CLOCK_MONOTONIC px4_clock_gettime(CLOCK_REALTIME, &ts); // Calculate an absolute time in the future const unsigned billion = (1000 * 1000 * 1000); unsigned tdiff = timeout; uint64_t nsecs = ts.tv_nsec + (tdiff * 1000 * 1000); ts.tv_sec += nsecs / billion; nsecs -= (nsecs / billion) * billion; ts.tv_nsec = nsecs; // Execute a blocking wait for that time in the future errno = 0; ret = px4_sem_timedwait(&sem, &ts); #ifndef __PX4_DARWIN ret = errno; #endif // Ensure ret is negative on failure if (ret > 0) { ret = -ret; } if (ret && ret != -ETIMEDOUT) { PX4_WARN("%s: px4_poll() sem error", thread_name); } } else if (timeout < 0) { px4_sem_wait(&sem); } // We have waited now (or not, depending on timeout), // go through all fds and count how many have data for (i = 0; i < nfds; ++i) { CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(teardown) %d", thread_name, fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], false); if (ret < 0) { PX4_WARN("%s: px4_poll() 2nd poll fail", thread_name); break; } if (fds[i].revents) { count += 1; } } } } px4_sem_destroy(&sem); // Return the positive count if present, // return the negative error number if failed return (count) ? count : ret; } int px4_fsync(int fd) { return 0; } int px4_access(const char *pathname, int mode) { if (mode != F_OK) { errno = EINVAL; return -1; } CDev *dev = CDev::getDev(pathname); return (dev != nullptr) ? 0 : -1; } void px4_show_devices() { CDev::showDevices(); } void px4_show_topics() { CDev::showTopics(); } void px4_show_files() { CDev::showFiles(); } void px4_enable_sim_lockstep() { px4_sem_init(&lockstep_sem, 0, 0); // lockstep_sem use case is a signal px4_sem_setprotocol(&lockstep_sem, SEM_PRIO_NONE); sim_lockstep = true; sim_delay = false; } void px4_sim_start_delay() { sim_delay = true; } void px4_sim_stop_delay() { sim_delay = false; } bool px4_sim_delay_enabled() { return sim_delay; } } <commit_msg>driver: vdev_posix, increase PX4_MAX_FD (#7905)<commit_after>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file vdev_posix.cpp * * POSIX-like API for virtual character device */ #include <px4_log.h> #include <px4_posix.h> #include <px4_time.h> #include "device.h" #include "vfile.h" #include <hrt_work.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> using namespace device; pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER; px4_sem_t lockstep_sem; bool sim_lockstep = false; volatile bool sim_delay = false; extern "C" { #define PX4_MAX_FD 350 static device::file_t *filemap[PX4_MAX_FD] = {}; int px4_errno; inline bool valid_fd(int fd) { pthread_mutex_lock(&filemutex); bool ret = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != nullptr); pthread_mutex_unlock(&filemutex); return ret; } inline CDev *get_vdev(int fd) { pthread_mutex_lock(&filemutex); bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != nullptr); CDev *dev; if (valid) { dev = (CDev *)(filemap[fd]->vdev); } else { dev = nullptr; } pthread_mutex_unlock(&filemutex); return dev; } int px4_open(const char *path, int flags, ...) { PX4_DEBUG("px4_open"); CDev *dev = CDev::getDev(path); int ret = 0; int i; mode_t mode; if (!dev && (flags & (PX4_F_WRONLY | PX4_F_CREAT)) != 0 && strncmp(path, "/obj/", 5) != 0 && strncmp(path, "/dev/", 5) != 0) { va_list p; va_start(p, flags); mode = va_arg(p, int); va_end(p); // Create the file PX4_DEBUG("Creating virtual file %s", path); dev = VFile::createFile(path, mode); } if (dev) { pthread_mutex_lock(&filemutex); for (i = 0; i < PX4_MAX_FD; ++i) { if (filemap[i] == nullptr) { filemap[i] = new device::file_t(flags, dev, i); break; } } pthread_mutex_unlock(&filemutex); if (i < PX4_MAX_FD) { ret = dev->open(filemap[i]); } else { const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } PX4_BACKTRACE(); #endif PX4_WARN("%s: exceeded maximum number of file descriptors, accessing %s", thread_name, path); ret = -ENOENT; } } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; return -1; } PX4_DEBUG("px4_open fd = %d", filemap[i]->fd); return filemap[i]->fd; } int px4_close(int fd) { int ret; CDev *dev = get_vdev(fd); if (dev) { pthread_mutex_lock(&filemutex); ret = dev->close(filemap[fd]); if (filemap[fd] != nullptr) { delete filemap[fd]; } filemap[fd] = nullptr; pthread_mutex_unlock(&filemutex); PX4_DEBUG("px4_close fd = %d", fd); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_read(int fd, void *buffer, size_t buflen) { int ret; CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_read fd = %d", fd); ret = dev->read(filemap[fd], (char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_write(int fd, const void *buffer, size_t buflen) { int ret; CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_write fd = %d", fd); ret = dev->write(filemap[fd], (const char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } int px4_ioctl(int fd, int cmd, unsigned long arg) { PX4_DEBUG("px4_ioctl fd = %d", fd); int ret = 0; CDev *dev = get_vdev(fd); if (dev) { ret = dev->ioctl(filemap[fd], cmd, arg); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; } return ret; } int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout) { if (nfds == 0) { PX4_WARN("px4_poll with no fds"); return -1; } px4_sem_t sem; int count = 0; int ret = -1; unsigned int i; const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } #endif while (sim_delay) { usleep(100); } PX4_DEBUG("Called px4_poll timeout = %d", timeout); px4_sem_init(&sem, 0, 0); // sem use case is a signal px4_sem_setprotocol(&sem, SEM_PRIO_NONE); // Go through all fds and check them for a pollable state bool fd_pollable = false; for (i = 0; i < nfds; ++i) { fds[i].sem = &sem; fds[i].revents = 0; fds[i].priv = nullptr; CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(setup) %d", thread_name, fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], true); if (ret < 0) { PX4_WARN("%s: px4_poll() error: %s", thread_name, strerror(errno)); break; } if (ret >= 0) { fd_pollable = true; } } } // If any FD can be polled, lock the semaphore and // check for new data if (fd_pollable) { if (timeout > 0) { // Get the current time struct timespec ts; // FIXME: check if QURT should probably be using CLOCK_MONOTONIC px4_clock_gettime(CLOCK_REALTIME, &ts); // Calculate an absolute time in the future const unsigned billion = (1000 * 1000 * 1000); unsigned tdiff = timeout; uint64_t nsecs = ts.tv_nsec + (tdiff * 1000 * 1000); ts.tv_sec += nsecs / billion; nsecs -= (nsecs / billion) * billion; ts.tv_nsec = nsecs; // Execute a blocking wait for that time in the future errno = 0; ret = px4_sem_timedwait(&sem, &ts); #ifndef __PX4_DARWIN ret = errno; #endif // Ensure ret is negative on failure if (ret > 0) { ret = -ret; } if (ret && ret != -ETIMEDOUT) { PX4_WARN("%s: px4_poll() sem error", thread_name); } } else if (timeout < 0) { px4_sem_wait(&sem); } // We have waited now (or not, depending on timeout), // go through all fds and count how many have data for (i = 0; i < nfds; ++i) { CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(teardown) %d", thread_name, fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], false); if (ret < 0) { PX4_WARN("%s: px4_poll() 2nd poll fail", thread_name); break; } if (fds[i].revents) { count += 1; } } } } px4_sem_destroy(&sem); // Return the positive count if present, // return the negative error number if failed return (count) ? count : ret; } int px4_fsync(int fd) { return 0; } int px4_access(const char *pathname, int mode) { if (mode != F_OK) { errno = EINVAL; return -1; } CDev *dev = CDev::getDev(pathname); return (dev != nullptr) ? 0 : -1; } void px4_show_devices() { CDev::showDevices(); } void px4_show_topics() { CDev::showTopics(); } void px4_show_files() { CDev::showFiles(); } void px4_enable_sim_lockstep() { px4_sem_init(&lockstep_sem, 0, 0); // lockstep_sem use case is a signal px4_sem_setprotocol(&lockstep_sem, SEM_PRIO_NONE); sim_lockstep = true; sim_delay = false; } void px4_sim_start_delay() { sim_delay = true; } void px4_sim_stop_delay() { sim_delay = false; } bool px4_sim_delay_enabled() { return sim_delay; } } <|endoftext|>
<commit_before>// Support for Python plugin // // proof-of-concept for access to Interp and canon // // NB: all this is executed at readahead time // // Michael Haberler 4/2011 // // if you get a segfault like described // here: https://bugs.launchpad.net/ubuntu/+source/mesa/+bug/259219 // or here: https://www.libavg.de/wiki/LinuxInstallIssues#glibc_invalid_pointer : // // try this before starting milltask and axis in emc: // LD_PRELOAD=/usr/lib/libstdc++.so.6 $EMCTASK ... // LD_PRELOAD=/usr/lib/libstdc++.so.6 $EMCDISPLAY ... // // this is actually a bug in libgl1-mesa-dri and it looks // it has been fixed in mesa - 7.10.1-0ubuntu2 #include <boost/python.hpp> #include <boost/make_shared.hpp> #include <boost/python/object.hpp> #include <boost/python/raw_function.hpp> #include <boost/python/call.hpp> namespace bp = boost::python; #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <exception> #include "rs274ngc.hh" #include "interp_return.hh" #include "interp_internal.hh" #include "rs274ngc_interp.hh" #include "units.h" #include "interpmodule.hh" static bool useGIL = false; // not sure if this is needed extern "C" void initCanonMod(); extern "C" void initInterpMod(); #define PYCHK(bad, fmt, ...) \ do { \ if (bad) { \ logPy(fmt, ## __VA_ARGS__); \ ERS(fmt, ## __VA_ARGS__); \ goto error; \ } \ } while(0) // accessing the private data of Interp is kind of kludgy because // technically the Python module does not run in a member context // but 'outside' // option 1 is making all member data public // option 2 is this: // we store references to private data during call setup and // use it to reference it in the python module // NB: this is likely not thread-safe setup_pointer current_setup; // the Interp instance, set on call before handing to Python Interp *current_interp; // http://hafizpariabi.blogspot.com/2008/01/using-custom-deallocator-in.html // reason: avoid segfaults by del(interp_instance) on program exit // make delete(interp_instance) a noop wrt Interp static void interpDeallocFunc(Interp *interp) {} #define IS_STRING(x) (PyObject_IsInstance(x.ptr(), (PyObject*)&PyString_Type)) #define IS_INT(x) (PyObject_IsInstance(x.ptr(), (PyObject*)&PyInt_Type)) // decode a Python exception into a string. std::string handle_pyerror() { using namespace boost::python; using namespace boost; PyObject *exc,*val,*tb; object formatted_list, formatted; PyErr_Fetch(&exc,&val,&tb); handle<> hexc(exc),hval(val),htb(allow_null(tb)); object traceback(import("traceback")); if (!tb) { object format_exception_only(traceback.attr("format_exception_only")); formatted_list = format_exception_only(hexc,hval); } else { object format_exception(traceback.attr("format_exception")); formatted_list = format_exception(hexc,hval,htb); } formatted = str("\n").join(formatted_list); return extract<std::string>(formatted); } int Interp::init_python(setup_pointer settings, bool reload) { char path[PATH_MAX]; std::string msg; bool py_exception = false; PyGILState_STATE gstate; if ((settings->py_module_stat != PYMOD_NONE) && !reload) { logPy("init_python RE-INIT %d pid=%d",settings->py_module_stat,getpid()); return INTERP_OK; // already done, or failed } current_setup = get_setup(this); // &this->_setup; current_interp = this; logPy("init_python(this=%lx pid=%d py_module_stat=%d PyInited=%d reload=%d", (unsigned long)this, getpid(), settings->py_module_stat, Py_IsInitialized(),reload); PYCHK((settings->py_module == NULL), "init_python: no module defined"); PYCHK(((realpath(settings->py_module, path)) == NULL), "init_python: cant resolve path to '%s'", settings->py_module); // record timestamp first time around if (settings->module_mtime == 0) { struct stat sub_stat; if (stat(path, &sub_stat)) { logPy("init_python(): stat(%s) returns %s", settings->py_module, sys_errlist[errno]); } else settings->module_mtime = sub_stat.st_mtime; } if (!reload) { Py_SetProgramName(path); PyImport_AppendInittab( (char *) "CanonMod", &initCanonMod); PyImport_AppendInittab( (char *) "InterpMod", &initInterpMod); Py_Initialize(); } if (useGIL) gstate = PyGILState_Ensure(); try { settings->module = bp::import("__main__"); settings->module_namespace = settings->module.attr("__dict__"); if (!reload) { bp::object interp_module = bp::import("InterpMod"); bp::object canon_module = bp::import("CanonMod"); settings->module_namespace["InterpMod"] = interp_module; settings->module_namespace["CanonMod"] = canon_module; // the null deallocator avoids destroying the Interp instance on // leaving scope (or shutdown) bp::scope(interp_module).attr("interp") = interp_ptr(this, interpDeallocFunc); } bp::object result = bp::exec_file(path, settings->module_namespace, settings->module_namespace); settings->py_module_stat = PYMOD_OK; } catch (bp::error_already_set) { if (PyErr_Occurred()) { msg = handle_pyerror(); py_exception = true; } bp::handle_exception(); settings->py_module_stat = PYMOD_FAILED; PyErr_Clear(); } if (py_exception) { logPy("init_python: module '%s' init failed: \n%s",path,msg.c_str()); if (useGIL) PyGILState_Release(gstate); ERS("init_python: %s",msg.c_str()); } if (useGIL) PyGILState_Release(gstate); return INTERP_OK; error: // come here if PYCHK() macro fails if (useGIL) PyGILState_Release(gstate); return INTERP_ERROR; } int Interp::py_reload_on_change(setup_pointer settings) { struct stat current_stat; if (!settings->py_module) return INTERP_OK; if (stat(settings->py_module, &current_stat)) { logPy("py_iscallable: stat(%s) returned %s", settings->py_module, sys_errlist[errno]); return INTERP_ERROR; } if (current_stat.st_mtime > settings->module_mtime) { int status; if ((status = init_python(settings,true)) != INTERP_OK) { // init_python() set the error text already char err_msg[LINELEN+1]; error_text(status, err_msg, sizeof(err_msg)); logPy("init_python(%s): %s", settings->py_module, err_msg); return INTERP_ERROR; } else logPy("init_python(): module %s reloaded", settings->py_module); } return INTERP_OK; } bool Interp::is_pycallable(setup_pointer settings, const char *funcname) { bool result = false; bool py_unexpected = false; std::string msg; if (settings->py_reload_on_change) py_reload_on_change(settings); if ((settings->py_module_stat != PYMOD_OK) || (funcname == NULL)) { return false; } try { bp::object function = settings->module_namespace[funcname]; result = PyCallable_Check(function.ptr()); } catch (bp::error_already_set) { // KeyError expected if not a callable if (!PyErr_ExceptionMatches(PyExc_KeyError)) { // something else, strange msg = handle_pyerror(); py_unexpected = true; } result = false; PyErr_Clear(); } if (py_unexpected) logPy("is_pycallable: %s",msg.c_str()); if (_setup.loggingLevel > 5) logPy("py_iscallable(%s) = %s",funcname,result ? "TRUE":"FALSE"); return result; } int Interp::pycall(setup_pointer settings, block_pointer block, const char *funcname) { bp::object retval, function; PyGILState_STATE gstate; std::string msg; bool py_exception = false; if (_setup.loggingLevel > 2) logPy("pycall %s \n", funcname); if (settings->py_reload_on_change) py_reload_on_change(settings); // &this->_setup wont work, _setup is currently private current_setup = get_setup(this); current_interp = this; block->returned = 0; if (settings->py_module_stat != PYMOD_OK) { ERS("function '%s.%s' : module %s", settings->py_module,funcname, (settings->py_module_stat == PYMOD_FAILED) ? "initialization failed" : " not initialized"); return INTERP_OK; } if (useGIL) gstate = PyGILState_Ensure(); try { function = settings->module_namespace[funcname]; retval = function(*block->tupleargs,**block->kwargs); } catch (bp::error_already_set) { if (PyErr_Occurred()) { msg = handle_pyerror(); } py_exception = true; bp::handle_exception(); PyErr_Clear(); } if (useGIL) PyGILState_Release(gstate); if (py_exception) { fprintf(stderr,"-->%s\n",msg.c_str()); ERS("pycall: %s", msg.c_str()); return INTERP_ERROR; } if (retval.ptr() != Py_None) { if (PyFloat_Check(retval.ptr())) { block->py_returned_value = bp::extract<double>(retval); block->returned[RET_DOUBLE] = 1; logPy("pycall: '%s' returned %f", funcname, block->py_returned_value); return INTERP_OK; } if (PyTuple_Check(retval.ptr())) { bp::tuple tret = bp::extract<bp::tuple>(retval); int len = bp::len(tret); if (!len) { logPy("pycall: empty tuple detected"); block->returned[RET_NONE] = 1; return INTERP_OK; } bp::object item0 = tret[0]; if (PyInt_Check(item0.ptr())) { block->returned[RET_STATUS] = 1; block->py_returned_status = bp::extract<int>(item0); logPy("pycall: tuple item 0 - int: (%s)", interp_status(block->py_returned_status)); } if (len > 1) { bp::object item1 = tret[1]; if (PyInt_Check(item1.ptr())) { block->py_returned_userdata = bp::extract<int>(item1); block->returned[RET_USERDATA] = 1; logPy("pycall: tuple item 1: int userdata=%d", block->py_returned_userdata); } } if (block->returned[RET_STATUS]) ERP(block->py_returned_status); return INTERP_OK; } PyObject *res_str = PyObject_Str(retval.ptr()); ERS("function '%s.%s' returned '%s' - expected float or tuple, got %s", settings->py_module,funcname, PyString_AsString(res_str), retval.ptr()->ob_type->tp_name); Py_XDECREF(res_str); return INTERP_OK; } else { block->returned[RET_NONE] = 1; logPy("pycall: '%s' returned no value",funcname); } return INTERP_OK; } // called by (py, ....) comments int Interp::py_execute(const char *cmd) { std::string msg; PyGILState_STATE gstate; bool py_exception = false; bp::object main_module = bp::import("__main__"); bp::object main_namespace = main_module.attr("__dict__"); logPy("py_execute(%s)",cmd); if (_setup.py_reload_on_change) py_reload_on_change(&_setup); if (useGIL) gstate = PyGILState_Ensure(); bp::object retval; try { retval = bp::exec(cmd, _setup.module_namespace, _setup.module_namespace); } catch (bp::error_already_set) { if (PyErr_Occurred()) { py_exception = true; msg = handle_pyerror(); } bp::handle_exception(); PyErr_Clear(); } if (useGIL) PyGILState_Release(gstate); if (py_exception) logPy("py_execute(%s): %s", cmd, msg.c_str()); // msg.erase(std::remove(msg.begin(), msg.end(), '\n'), msg.end()); // msg.erase(std::remove(msg.begin(), msg.end(), '\r'), msg.end()); // if (msg.length()) // MESSAGE((char *) msg.c_str()); ERP(INTERP_OK); } <commit_msg>interp_python: cleanup, clarify error message<commit_after>// Support for Python plugin // // proof-of-concept for access to Interp and canon // // NB: all this is executed at readahead time // // Michael Haberler 4/2011 // // if you get a segfault like described // here: https://bugs.launchpad.net/ubuntu/+source/mesa/+bug/259219 // or here: https://www.libavg.de/wiki/LinuxInstallIssues#glibc_invalid_pointer : // // try this before starting milltask and axis in emc: // LD_PRELOAD=/usr/lib/libstdc++.so.6 $EMCTASK ... // LD_PRELOAD=/usr/lib/libstdc++.so.6 $EMCDISPLAY ... // // this is actually a bug in libgl1-mesa-dri and it looks // it has been fixed in mesa - 7.10.1-0ubuntu2 #include <boost/python.hpp> #include <boost/make_shared.hpp> #include <boost/python/object.hpp> #include <boost/python/raw_function.hpp> #include <boost/python/call.hpp> namespace bp = boost::python; #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <exception> #include "rs274ngc.hh" #include "interp_return.hh" #include "interp_internal.hh" #include "rs274ngc_interp.hh" #include "units.h" #include "interpmodule.hh" static bool useGIL = false; // not sure if this is needed extern "C" void initCanonMod(); extern "C" void initInterpMod(); #define PYCHK(bad, fmt, ...) \ do { \ if (bad) { \ logPy(fmt, ## __VA_ARGS__); \ ERS(fmt, ## __VA_ARGS__); \ goto error; \ } \ } while(0) // accessing the private data of Interp is kind of kludgy because // technically the Python module does not run in a member context // but 'outside' // option 1 is making all member data public // option 2 is this: // we store references to private data during call setup and // use it to reference it in the python module // NB: this is likely not thread-safe setup_pointer current_setup; // the Interp instance, set on call before handing to Python Interp *current_interp; // http://hafizpariabi.blogspot.com/2008/01/using-custom-deallocator-in.html // reason: avoid segfaults by del(interp_instance) on program exit // make delete(interp_instance) a noop wrt Interp static void interpDeallocFunc(Interp *interp) {} #define IS_STRING(x) (PyObject_IsInstance(x.ptr(), (PyObject*)&PyString_Type)) #define IS_INT(x) (PyObject_IsInstance(x.ptr(), (PyObject*)&PyInt_Type)) // decode a Python exception into a string. std::string handle_pyerror() { using namespace boost::python; using namespace boost; PyObject *exc,*val,*tb; object formatted_list, formatted; PyErr_Fetch(&exc,&val,&tb); handle<> hexc(exc),hval(val),htb(allow_null(tb)); object traceback(import("traceback")); if (!tb) { object format_exception_only(traceback.attr("format_exception_only")); formatted_list = format_exception_only(hexc,hval); } else { object format_exception(traceback.attr("format_exception")); formatted_list = format_exception(hexc,hval,htb); } formatted = str("\n").join(formatted_list); return extract<std::string>(formatted); } int Interp::init_python(setup_pointer settings, bool reload) { char path[PATH_MAX]; std::string msg; bool py_exception = false; PyGILState_STATE gstate; if ((settings->py_module_stat != PYMOD_NONE) && !reload) { logPy("init_python RE-INIT %d pid=%d",settings->py_module_stat,getpid()); return INTERP_OK; // already done, or failed } // this crap has to go. current_setup = get_setup(this); current_interp = this; logPy("init_python(this=%lx pid=%d py_module_stat=%d PyInited=%d reload=%d", (unsigned long)this, getpid(), settings->py_module_stat, Py_IsInitialized(),reload); PYCHK((settings->py_module == NULL), "init_python: no module defined"); PYCHK(((realpath(settings->py_module, path)) == NULL), "init_python: cant resolve path to '%s'", settings->py_module); // record timestamp first time around if (settings->module_mtime == 0) { struct stat sub_stat; if (stat(path, &sub_stat)) { logPy("init_python(): stat(%s) returns %s", settings->py_module, sys_errlist[errno]); } else settings->module_mtime = sub_stat.st_mtime; } if (!reload) { Py_SetProgramName(path); PyImport_AppendInittab( (char *) "CanonMod", &initCanonMod); PyImport_AppendInittab( (char *) "InterpMod", &initInterpMod); Py_Initialize(); } if (useGIL) gstate = PyGILState_Ensure(); try { settings->module = bp::import("__main__"); settings->module_namespace = settings->module.attr("__dict__"); if (!reload) { bp::object interp_module = bp::import("InterpMod"); bp::object canon_module = bp::import("CanonMod"); settings->module_namespace["InterpMod"] = interp_module; settings->module_namespace["CanonMod"] = canon_module; // the null deallocator avoids destroying the Interp instance on // leaving scope (or shutdown) bp::scope(interp_module).attr("interp") = interp_ptr(this, interpDeallocFunc); } bp::object result = bp::exec_file(path, settings->module_namespace, settings->module_namespace); settings->py_module_stat = PYMOD_OK; } catch (bp::error_already_set) { if (PyErr_Occurred()) { msg = handle_pyerror(); py_exception = true; } bp::handle_exception(); settings->py_module_stat = PYMOD_FAILED; PyErr_Clear(); } if (py_exception) { logPy("init_python: module '%s' init failed: \n%s",path,msg.c_str()); if (useGIL) PyGILState_Release(gstate); ERS("init_python: %s",msg.c_str()); } if (useGIL) PyGILState_Release(gstate); return INTERP_OK; error: // come here if PYCHK() macro fails if (useGIL) PyGILState_Release(gstate); return INTERP_ERROR; } int Interp::py_reload_on_change(setup_pointer settings) { struct stat current_stat; if (!settings->py_module) return INTERP_OK; if (stat(settings->py_module, &current_stat)) { logPy("py_iscallable: stat(%s) returned %s", settings->py_module, sys_errlist[errno]); return INTERP_ERROR; } if (current_stat.st_mtime > settings->module_mtime) { int status; if ((status = init_python(settings,true)) != INTERP_OK) { // init_python() set the error text already char err_msg[LINELEN+1]; error_text(status, err_msg, sizeof(err_msg)); logPy("init_python(%s): %s", settings->py_module, err_msg); return INTERP_ERROR; } else logPy("init_python(): module %s reloaded", settings->py_module); } return INTERP_OK; } bool Interp::is_pycallable(setup_pointer settings, const char *funcname) { bool result = false; bool py_unexpected = false; std::string msg; if (settings->py_reload_on_change) py_reload_on_change(settings); if ((settings->py_module_stat != PYMOD_OK) || (funcname == NULL)) { return false; } try { bp::object function = settings->module_namespace[funcname]; result = PyCallable_Check(function.ptr()); } catch (bp::error_already_set) { // KeyError expected if not a callable if (!PyErr_ExceptionMatches(PyExc_KeyError)) { // something else, strange msg = handle_pyerror(); py_unexpected = true; } result = false; PyErr_Clear(); } if (py_unexpected) logPy("is_pycallable: %s",msg.c_str()); if (_setup.loggingLevel > 5) logPy("py_iscallable(%s) = %s",funcname,result ? "TRUE":"FALSE"); return result; } int Interp::pycall(setup_pointer settings, block_pointer block, const char *funcname) { bp::object retval, function; PyGILState_STATE gstate; std::string msg; bool py_exception = false; if (_setup.loggingLevel > 2) logPy("pycall %s \n", funcname); if (settings->py_reload_on_change) py_reload_on_change(settings); // &this->_setup wont work, _setup is currently private current_setup = get_setup(this); current_interp = this; block->returned = 0; if (settings->py_module_stat != PYMOD_OK) { ERS("function '%s.%s' : module %s", settings->py_module,funcname, (settings->py_module_stat == PYMOD_FAILED) ? "initialization failed" : " not initialized"); return INTERP_OK; } if (useGIL) gstate = PyGILState_Ensure(); try { function = settings->module_namespace[funcname]; retval = function(*block->tupleargs,**block->kwargs); } catch (bp::error_already_set) { if (PyErr_Occurred()) { msg = handle_pyerror(); } py_exception = true; bp::handle_exception(); PyErr_Clear(); } if (useGIL) PyGILState_Release(gstate); if (py_exception) { fprintf(stderr,"-->%s\n",msg.c_str()); ERS("pycall: %s", msg.c_str()); return INTERP_ERROR; } if (retval.ptr() != Py_None) { if (PyFloat_Check(retval.ptr())) { block->py_returned_value = bp::extract<double>(retval); block->returned[RET_DOUBLE] = 1; logPy("pycall: '%s' returned %f", funcname, block->py_returned_value); return INTERP_OK; } if (PyTuple_Check(retval.ptr())) { bp::tuple tret = bp::extract<bp::tuple>(retval); int len = bp::len(tret); if (!len) { logPy("pycall: empty tuple detected"); block->returned[RET_NONE] = 1; return INTERP_OK; } bp::object item0 = tret[0]; if (PyInt_Check(item0.ptr())) { block->returned[RET_STATUS] = 1; block->py_returned_status = bp::extract<int>(item0); logPy("pycall: tuple item 0 - int: (%s)", interp_status(block->py_returned_status)); } if (len > 1) { bp::object item1 = tret[1]; if (PyInt_Check(item1.ptr())) { block->py_returned_userdata = bp::extract<int>(item1); block->returned[RET_USERDATA] = 1; logPy("pycall: tuple item 1: int userdata=%d", block->py_returned_userdata); } } if (block->returned[RET_STATUS]) ERP(block->py_returned_status); return INTERP_OK; } PyObject *res_str = PyObject_Str(retval.ptr()); ERS("function '%s.%s' returned '%s' - expected float or tuple, got %s", settings->py_module,funcname, PyString_AsString(res_str), retval.ptr()->ob_type->tp_name); Py_XDECREF(res_str); return INTERP_OK; } else { block->returned[RET_NONE] = 1; logPy("pycall: '%s' returned no value",funcname); } return INTERP_OK; } // called by (py, ....) comments int Interp::py_execute(const char *cmd) { std::string msg; PyGILState_STATE gstate; bool py_exception = false; bp::object main_module = bp::import("__main__"); bp::object main_namespace = main_module.attr("__dict__"); logPy("py_execute(%s)",cmd); if (_setup.py_reload_on_change) py_reload_on_change(&_setup); if (useGIL) gstate = PyGILState_Ensure(); bp::object retval; try { retval = bp::exec(cmd, _setup.module_namespace, _setup.module_namespace); } catch (bp::error_already_set) { if (PyErr_Occurred()) { py_exception = true; msg = handle_pyerror(); } bp::handle_exception(); PyErr_Clear(); } if (useGIL) PyGILState_Release(gstate); if (py_exception) logPy("py_execute(%s): %s", cmd, msg.c_str()); // msg.erase(std::remove(msg.begin(), msg.end(), '\n'), msg.end()); // msg.erase(std::remove(msg.begin(), msg.end(), '\r'), msg.end()); // if (msg.length()) // MESSAGE((char *) msg.c_str()); ERP(INTERP_OK); } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "factory/FileSystemFactory.h" #include "medialibrary/filesystem/IDirectory.h" #include "medialibrary/filesystem/IFile.h" #include "logging/Logger.h" #include "utils/Filename.h" #include "utils/Directory.h" #include "utils/Url.h" #if defined(__linux__) || defined(__APPLE__) # include "filesystem/unix/Directory.h" # include "filesystem/unix/File.h" # include "filesystem/unix/Device.h" #elif defined(_WIN32) # include "filesystem/win32/Directory.h" # include "filesystem/win32/File.h" # include "filesystem/win32/Device.h" #else # error No filesystem implementation for this architecture #endif #include "medialibrary/IDeviceLister.h" #include "compat/Mutex.h" #include <algorithm> #include <cassert> namespace medialibrary { namespace factory { FileSystemFactory::FileSystemFactory( DeviceListerPtr lister ) : m_deviceLister( std::move( lister ) ) { } std::shared_ptr<fs::IDirectory> FileSystemFactory::createDirectory( const std::string& mrl ) { return std::make_shared<fs::Directory>( mrl, *this ); } std::shared_ptr<fs::IFile> FileSystemFactory::createFile( const std::string& mrl ) { auto fsDir = createDirectory( utils::file::directory( mrl ) ); assert( fsDir != nullptr ); return fsDir->file( mrl ); } std::shared_ptr<fs::IDevice> FileSystemFactory::createDevice( const std::string& uuid ) { auto it = m_deviceCache.find( uuid ); if ( it != end( m_deviceCache ) ) return it->second; return nullptr; } std::shared_ptr<fs::IDevice> FileSystemFactory::createDeviceFromMrl( const std::string& mrl ) { std::string canonicalMrl; try { auto canonicalPath = utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ); canonicalMrl = utils::file::toMrl( canonicalPath ); } catch ( const std::system_error& ex ) { LOG_WARN( "Failed to canonicalize mountpoint ", mrl, ": ", ex.what() ); return nullptr; } std::shared_ptr<fs::IDevice> res; std::string mountpoint; for ( const auto& p : m_deviceCache ) { auto match = p.second->matchesMountpoint( canonicalMrl ); if ( std::get<0>( match ) == true ) { const auto& newMountpoint = std::get<1>( match ); if ( res == nullptr || mountpoint.length() < newMountpoint.length() ) { res = p.second; mountpoint = newMountpoint; } } } return res; } void FileSystemFactory::refreshDevices() { LOG_INFO( "Refreshing devices from IDeviceLister" ); auto devices = m_deviceLister->devices(); for ( auto& devicePair : m_deviceCache ) { auto it = std::find_if( begin( devices ), end( devices ), [&devicePair]( decltype(devices)::value_type& deviceTuple ) { return std::get<0>( deviceTuple ) == devicePair.first; }); if ( it != end( devices ) ) devices.erase( it ); } // And now insert all new devices, if any for ( const auto& d : devices ) { const auto& uuid = std::get<0>( d ); const auto& mountpoint = std::get<1>( d ); const auto removable = std::get<2>( d ); auto it = m_deviceCache.find( uuid ); if ( it == end( m_deviceCache ) ) { LOG_INFO( "Caching device ", uuid, " mounted on ", mountpoint, ". Removable: ", removable ? "true" : "false" ); m_deviceCache.emplace( uuid, std::make_shared<fs::Device>( uuid, mountpoint, removable ) ); } else { LOG_INFO( "Adding mountpoint to device ", uuid, ": ", mountpoint ); it->second->addMountpoint( mountpoint ); } } LOG_INFO( "Done refreshing devices from IDeviceLister" ); } bool FileSystemFactory::isMrlSupported( const std::string& path ) const { return path.compare( 0, 7, "file://" ) == 0; } bool FileSystemFactory::isNetworkFileSystem() const { return false; } const std::string& FileSystemFactory::scheme() const { static const std::string s = "file://"; return s; } bool FileSystemFactory::start( fs::IFileSystemFactoryCb* ) { return true; } void FileSystemFactory::stop() { } } } <commit_msg>Revert "fs: factory: Remove superfluous device refresh"<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "factory/FileSystemFactory.h" #include "medialibrary/filesystem/IDirectory.h" #include "medialibrary/filesystem/IFile.h" #include "logging/Logger.h" #include "utils/Filename.h" #include "utils/Directory.h" #include "utils/Url.h" #if defined(__linux__) || defined(__APPLE__) # include "filesystem/unix/Directory.h" # include "filesystem/unix/File.h" # include "filesystem/unix/Device.h" #elif defined(_WIN32) # include "filesystem/win32/Directory.h" # include "filesystem/win32/File.h" # include "filesystem/win32/Device.h" #else # error No filesystem implementation for this architecture #endif #include "medialibrary/IDeviceLister.h" #include "compat/Mutex.h" #include <algorithm> #include <cassert> namespace medialibrary { namespace factory { FileSystemFactory::FileSystemFactory( DeviceListerPtr lister ) : m_deviceLister( std::move( lister ) ) { refreshDevices(); } std::shared_ptr<fs::IDirectory> FileSystemFactory::createDirectory( const std::string& mrl ) { return std::make_shared<fs::Directory>( mrl, *this ); } std::shared_ptr<fs::IFile> FileSystemFactory::createFile( const std::string& mrl ) { auto fsDir = createDirectory( utils::file::directory( mrl ) ); assert( fsDir != nullptr ); return fsDir->file( mrl ); } std::shared_ptr<fs::IDevice> FileSystemFactory::createDevice( const std::string& uuid ) { auto it = m_deviceCache.find( uuid ); if ( it != end( m_deviceCache ) ) return it->second; return nullptr; } std::shared_ptr<fs::IDevice> FileSystemFactory::createDeviceFromMrl( const std::string& mrl ) { std::string canonicalMrl; try { auto canonicalPath = utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ); canonicalMrl = utils::file::toMrl( canonicalPath ); } catch ( const std::system_error& ex ) { LOG_WARN( "Failed to canonicalize mountpoint ", mrl, ": ", ex.what() ); return nullptr; } std::shared_ptr<fs::IDevice> res; std::string mountpoint; for ( const auto& p : m_deviceCache ) { auto match = p.second->matchesMountpoint( canonicalMrl ); if ( std::get<0>( match ) == true ) { const auto& newMountpoint = std::get<1>( match ); if ( res == nullptr || mountpoint.length() < newMountpoint.length() ) { res = p.second; mountpoint = newMountpoint; } } } return res; } void FileSystemFactory::refreshDevices() { LOG_INFO( "Refreshing devices from IDeviceLister" ); auto devices = m_deviceLister->devices(); for ( auto& devicePair : m_deviceCache ) { auto it = std::find_if( begin( devices ), end( devices ), [&devicePair]( decltype(devices)::value_type& deviceTuple ) { return std::get<0>( deviceTuple ) == devicePair.first; }); if ( it != end( devices ) ) devices.erase( it ); } // And now insert all new devices, if any for ( const auto& d : devices ) { const auto& uuid = std::get<0>( d ); const auto& mountpoint = std::get<1>( d ); const auto removable = std::get<2>( d ); auto it = m_deviceCache.find( uuid ); if ( it == end( m_deviceCache ) ) { LOG_INFO( "Caching device ", uuid, " mounted on ", mountpoint, ". Removable: ", removable ? "true" : "false" ); m_deviceCache.emplace( uuid, std::make_shared<fs::Device>( uuid, mountpoint, removable ) ); } else { LOG_INFO( "Adding mountpoint to device ", uuid, ": ", mountpoint ); it->second->addMountpoint( mountpoint ); } } LOG_INFO( "Done refreshing devices from IDeviceLister" ); } bool FileSystemFactory::isMrlSupported( const std::string& path ) const { return path.compare( 0, 7, "file://" ) == 0; } bool FileSystemFactory::isNetworkFileSystem() const { return false; } const std::string& FileSystemFactory::scheme() const { static const std::string s = "file://"; return s; } bool FileSystemFactory::start( fs::IFileSystemFactoryCb* ) { return true; } void FileSystemFactory::stop() { } } } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #include "Directory.h" #include "Media.h" #include <cstring> #include <cstdlib> #include <dirent.h> #include <limits.h> #include <sys/stat.h> #include <unistd.h> namespace fs { Directory::Directory( const std::string& path ) : m_path( toAbsolute( path ) ) { struct stat s; lstat( path.c_str(), &s ); m_lastModificationDate = s.st_mtim.tv_sec; read(); } const std::string&Directory::path() const { return m_path; } const std::vector<std::string>& Directory::files() const { return m_files; } const std::vector<std::string>&Directory::dirs() const { return m_dirs; } unsigned int Directory::lastModificationDate() const { return m_lastModificationDate; } bool Directory::isRemovable() const { //FIXME return false; } std::string Directory::toAbsolute(const std::string& path) { auto abs = std::unique_ptr<char[]>( new char[PATH_MAX] ); if ( realpath( path.c_str(), abs.get() ) == nullptr ) { std::string err( "Failed to convert to absolute path" ); err += "(" + path + "): "; err += strerror(errno); throw std::runtime_error( err ); } return std::string{ abs.get() }; } void Directory::read() { auto dir = std::unique_ptr<DIR, int(*)(DIR*)>( opendir( m_path.c_str() ), closedir ); if ( dir == nullptr ) { std::string err( "Failed to open directory " ); err += m_path; err += strerror(errno); throw std::runtime_error( err ); } dirent* result = nullptr; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } std::string path = m_path + "/" + result->d_name; #if defined(_DIRENT_HAVE_D_TYPE) && defined(_BSD_SOURCE) if ( result->d_type == DT_DIR ) { #else struct stat s; if ( lstat( result->d_name, &s ) != 0 ) { std::string err( "Failed to get file info " ); err += m_path; err += strerror(errno); throw std::runtime_error( err ); } if ( S_ISDIR( s.st_mode ) ) { #endif m_dirs.emplace_back( toAbsolute( path ) ); } else { m_files.emplace_back( toAbsolute( path ) ); } } } } <commit_msg>fs: Directory: Ensure we're handling a directory<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #include "Directory.h" #include "Media.h" #include <cstring> #include <cstdlib> #include <dirent.h> #include <limits.h> #include <sys/stat.h> #include <unistd.h> namespace fs { Directory::Directory( const std::string& path ) : m_path( toAbsolute( path ) ) { struct stat s; lstat( path.c_str(), &s ); if ( S_ISDIR( s.st_mode ) == false ) throw std::runtime_error( "The provided path isn't a directory" ); m_lastModificationDate = s.st_mtim.tv_sec; read(); } const std::string&Directory::path() const { return m_path; } const std::vector<std::string>& Directory::files() const { return m_files; } const std::vector<std::string>&Directory::dirs() const { return m_dirs; } unsigned int Directory::lastModificationDate() const { return m_lastModificationDate; } bool Directory::isRemovable() const { //FIXME return false; } std::string Directory::toAbsolute(const std::string& path) { auto abs = std::unique_ptr<char[]>( new char[PATH_MAX] ); if ( realpath( path.c_str(), abs.get() ) == nullptr ) { std::string err( "Failed to convert to absolute path" ); err += "(" + path + "): "; err += strerror(errno); throw std::runtime_error( err ); } return std::string{ abs.get() }; } void Directory::read() { auto dir = std::unique_ptr<DIR, int(*)(DIR*)>( opendir( m_path.c_str() ), closedir ); if ( dir == nullptr ) { std::string err( "Failed to open directory " ); err += m_path; err += strerror(errno); throw std::runtime_error( err ); } dirent* result = nullptr; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } std::string path = m_path + "/" + result->d_name; #if defined(_DIRENT_HAVE_D_TYPE) && defined(_BSD_SOURCE) if ( result->d_type == DT_DIR ) { #else struct stat s; if ( lstat( result->d_name, &s ) != 0 ) { std::string err( "Failed to get file info " ); err += m_path; err += strerror(errno); throw std::runtime_error( err ); } if ( S_ISDIR( s.st_mode ) ) { #endif m_dirs.emplace_back( toAbsolute( path ) ); } else { m_files.emplace_back( toAbsolute( path ) ); } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient> * * 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 "otmlparser.h" #include "otmldocument.h" #include "otmlexception.h" OTMLParser::OTMLParser(OTMLDocumentPtr doc, std::istream& in) : currentDepth(0), currentLine(0), doc(doc), currentParent(doc), previousNode(0), in(in) { } void OTMLParser::parse() { if(!in.good()) throw OTMLException(doc, "cannot read from input stream"); while(!in.eof()) parseLine(getNextLine()); } std::string OTMLParser::getNextLine() { currentLine++; std::string line; std::getline(in, line); return line; } int OTMLParser::getLineDepth(const std::string& line, bool multilining) { // count number of spaces at the line beginning std::size_t spaces = 0; while(line[spaces] == ' ') spaces++; // pre calculate depth int depth = spaces / 2; if(!multilining || depth <= currentDepth) { // check the next character is a tab if(line[spaces] == '\t') throw OTMLException(doc, "indentation with tabs are not allowed", currentLine); // must indent every 2 spaces if(spaces % 2 != 0) throw OTMLException(doc, "must indent every 2 spaces", currentLine); } return depth; } void OTMLParser::parseLine(std::string line) { int depth = getLineDepth(line); if(depth == -1) return; // remove line sides spaces boost::trim(line); // skip empty lines if(line.empty()) return; // skip comments if(boost::starts_with(line, "//")) return; // a depth above, change current parent to the previous added node if(depth == currentDepth+1) { currentParent = previousNode; // a depth below, change parent to previous parent } else if(depth < currentDepth) { for(int i=0;i<currentDepth-depth;++i) currentParent = currentParent->parent(); // if it isn't the current depth, it's a syntax error } else if(depth != currentDepth) throw OTMLException(doc, "invalid indentation depth, are you indenting correctly?", currentLine); // sets current depth currentDepth = depth; // alright, new depth is set, the line is not empty and it isn't a comment // then it must be a node, so we parse it parseNode(line); } void OTMLParser::parseNode(const std::string& data) { std::string tag; std::string value; std::size_t dotsPos = data.find_first_of(':'); int nodeLine = currentLine; // node that has no tag and may have a value if(!data.empty() && data[0] == '-') { value = data.substr(1); boost::trim(value); // node that has tag and possible a value } else if(dotsPos != std::string::npos) { tag = data.substr(0, dotsPos); if(data.size() > dotsPos+1) value = data.substr(dotsPos+1); // node that has only a tag } else { tag = data; } boost::trim(tag); boost::trim(value); // process multitine values if(value == "|" || value == "|-" || value == "|+") { // reads next lines until we can a value below the same depth std::string multiLineData; do { size_t lastPos = in.tellg(); std::string line = getNextLine(); int depth = getLineDepth(line, true); // depth above current depth, add the text to the multiline if(depth > currentDepth) { multiLineData += line.substr((currentDepth+1)*2); // it has contents below the current depth } else { // if not empty, its a node boost::trim(line); if(!line.empty()) { // rewind and break in.seekg(lastPos, std::ios::beg); currentLine--; break; } } multiLineData += "\n"; } while(!in.eof()); /* determine how to treat new lines at the end * | strip all new lines at the end and add just a new one * |- strip all new lines at the end * |+ keep all the new lines at the end (the new lines until next node) */ if(value == "|" || value == "|-") { // remove all new lines at the end int lastPos = multiLineData.length(); while(multiLineData[--lastPos] == '\n') multiLineData.erase(lastPos, 1); if(value == "|") multiLineData.append("\n"); } // else it's |+ value = multiLineData; } // create the node OTMLNodePtr node = OTMLNode::create(tag); node->setUnique(dotsPos != std::string::npos); node->setTag(tag); node->setSource(doc->source() + ":" + stdext::unsafe_cast<std::string>(nodeLine)); // ~ is considered the null value if(value == "~") node->setNull(true); else node->setValue(value); currentParent->addChild(node); previousNode = node; } <commit_msg>Support for OTML inline sequences<commit_after>/* * Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient> * * 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 "otmlparser.h" #include "otmldocument.h" #include "otmlexception.h" #include <boost/tokenizer.hpp> OTMLParser::OTMLParser(OTMLDocumentPtr doc, std::istream& in) : currentDepth(0), currentLine(0), doc(doc), currentParent(doc), previousNode(0), in(in) { } void OTMLParser::parse() { if(!in.good()) throw OTMLException(doc, "cannot read from input stream"); while(!in.eof()) parseLine(getNextLine()); } std::string OTMLParser::getNextLine() { currentLine++; std::string line; std::getline(in, line); return line; } int OTMLParser::getLineDepth(const std::string& line, bool multilining) { // count number of spaces at the line beginning std::size_t spaces = 0; while(line[spaces] == ' ') spaces++; // pre calculate depth int depth = spaces / 2; if(!multilining || depth <= currentDepth) { // check the next character is a tab if(line[spaces] == '\t') throw OTMLException(doc, "indentation with tabs are not allowed", currentLine); // must indent every 2 spaces if(spaces % 2 != 0) throw OTMLException(doc, "must indent every 2 spaces", currentLine); } return depth; } void OTMLParser::parseLine(std::string line) { int depth = getLineDepth(line); if(depth == -1) return; // remove line sides spaces boost::trim(line); // skip empty lines if(line.empty()) return; // skip comments if(boost::starts_with(line, "//")) return; // a depth above, change current parent to the previous added node if(depth == currentDepth+1) { currentParent = previousNode; // a depth below, change parent to previous parent } else if(depth < currentDepth) { for(int i=0;i<currentDepth-depth;++i) currentParent = currentParent->parent(); // if it isn't the current depth, it's a syntax error } else if(depth != currentDepth) throw OTMLException(doc, "invalid indentation depth, are you indenting correctly?", currentLine); // sets current depth currentDepth = depth; // alright, new depth is set, the line is not empty and it isn't a comment // then it must be a node, so we parse it parseNode(line); } void OTMLParser::parseNode(const std::string& data) { std::string tag; std::string value; std::size_t dotsPos = data.find_first_of(':'); int nodeLine = currentLine; // node that has no tag and may have a value if(!data.empty() && data[0] == '-') { value = data.substr(1); boost::trim(value); // node that has tag and possible a value } else if(dotsPos != std::string::npos) { tag = data.substr(0, dotsPos); if(data.size() > dotsPos+1) value = data.substr(dotsPos+1); // node that has only a tag } else { tag = data; } boost::trim(tag); boost::trim(value); // process multitine values if(value == "|" || value == "|-" || value == "|+") { // reads next lines until we can a value below the same depth std::string multiLineData; do { size_t lastPos = in.tellg(); std::string line = getNextLine(); int depth = getLineDepth(line, true); // depth above current depth, add the text to the multiline if(depth > currentDepth) { multiLineData += line.substr((currentDepth+1)*2); // it has contents below the current depth } else { // if not empty, its a node boost::trim(line); if(!line.empty()) { // rewind and break in.seekg(lastPos, std::ios::beg); currentLine--; break; } } multiLineData += "\n"; } while(!in.eof()); /* determine how to treat new lines at the end * | strip all new lines at the end and add just a new one * |- strip all new lines at the end * |+ keep all the new lines at the end (the new lines until next node) */ if(value == "|" || value == "|-") { // remove all new lines at the end int lastPos = multiLineData.length(); while(multiLineData[--lastPos] == '\n') multiLineData.erase(lastPos, 1); if(value == "|") multiLineData.append("\n"); } // else it's |+ value = multiLineData; } // create the node OTMLNodePtr node = OTMLNode::create(tag); node->setUnique(dotsPos != std::string::npos); node->setTag(tag); node->setSource(doc->source() + ":" + stdext::unsafe_cast<std::string>(nodeLine)); // ~ is considered the null value if(value == "~") node->setNull(true); else { if(boost::starts_with(value, "[") && boost::ends_with(value, "]")) { std::string tmp = value.substr(1, value.length()-2); boost::tokenizer<boost::escaped_list_separator<char>> tokens(tmp); for(std::string v : tokens) { stdext::trim(v); node->writeIn(v); } } else node->setValue(value); } currentParent->addChild(node); previousNode = node; } <|endoftext|>
<commit_before> #if !BOOST_PP_IS_ITERATING #if !defined(PLANE_H_) || INCLUDE_PLANE_LEVEL >= 1 #define PLANE_H_ #include <tuple> // 要求された定義レベルを実体化 #ifndef INCLUDE_PLANE_LEVEL #define INCLUDE_PLANE_LEVEL 0 #endif #define BOOST_PP_ITERATION_PARAMS_1 (4, (0,1, "plane.hpp", INCLUDE_PLANE_LEVEL)) #include BOOST_PP_ITERATE() #undef INCLUDE_PLANE_LEVEL #endif #elif BOOST_PP_ITERATION_DEPTH() == 1 #define ALIGN BOOST_PP_ITERATION() #define ALIGNA AFLAG(ALIGN) #define ALIGNB BOOLNIZE(ALIGN) #define ALIGN16 BOOST_PP_IF(ALIGN, alignas(16), NOTHING) #define VEC3 VecT<3,ALIGNB> #define PT PlaneT<ALIGNB> #define DIM 4 #include "local_macro.hpp" namespace spn { #if BOOST_PP_ITERATION_FLAGS() == 0 template <> struct ALIGN16 PlaneT<ALIGNB> { using APlane = PlaneT<true>; using UPlane = PlaneT<false>; union { struct { float a,b,c,d; }; float m[4]; }; PlaneT() = default; PlaneT(const UPlane& p); PlaneT(const APlane& p); PlaneT(float fa, float fb, float fc, float fd); PlaneT(const VEC3& orig, float dist); static PT FromPtDir(const VEC3& pos, const VEC3& dir); static PT FromPts(const VEC3& p0, const VEC3& p1, const VEC3& p2); static std::tuple<VEC3,bool> ChokePoint(const UPlane& p0, const UPlane& p1, const UPlane& p2); static std::tuple<VEC3,VEC3,bool> CrossLine(const UPlane& p0, const UPlane& p1); float dot(const VEC3& p) const; void move(float d); const VEC3& getNormal() const; PlaneT operator * (const MatT<4,3,ALIGNB>& m) const; PlaneT& operator *= (const MatT<4,3,ALIGNB>& m); }; using BOOST_PP_CAT(ALIGNA, Plane) = PlaneT<ALIGNB>; #else PT::PlaneT(const UPlane& p) { STORETHIS(LOADPSU(p.m)); } PT::PlaneT(const APlane& p) { STORETHIS(LOADPS(p.m)); } PT::PlaneT(float fa, float fb, float fc, float fd) { a = fa; b = fb; c = fc; d = fd; } PT::PlaneT(const VEC3& orig, float dist) { STORETHIS(LOADTHISPS(orig.m)); d = dist; } const VEC3& PT::getNormal() const { return *reinterpret_cast<const VEC3*>(this); } float PT::dot(const VEC3& p) const { reg128 xm = reg_mul_ps(LOADTHIS(), LOADPS_I3(p.m, 3)); SUMVEC(xm) float ret; reg_store_ss(&ret, xm); return ret; } void PT::move(float fd) { d += fd; } PT PT::FromPtDir(const VEC3& pos, const VEC3& dir) { return PlaneT(dir, -dir.dot(pos)); } PT PT::FromPts(const VEC3& p0, const VEC3& p1, const VEC3& p2) { VEC3 nml = (p1 - p0).cross(p2 - p0); nml.normalize(); return PlaneT(nml, -p0.dot(nml)); } //! 3つの平面が交差する座標を調べる std::tuple<VEC3,bool> PT::ChokePoint(const UPlane& p0, const UPlane& p1, const UPlane& p2) { AMat33 m, mInv; m.getRow(0) = p0.getNormal(); m.getRow(1) = p1.getNormal(); m.getRow(2) = p2.getNormal(); m.transpose(); if(!m.inversion(mInv)) return std::make_tuple(VEC3(), false); VEC3 v(-p0.d, -p1.d, -p2.d); v *= mInv; return std::make_tuple(v, true); } //! 2つの平面が交差する直線を調べる std::tuple<VEC3,VEC3,bool> PT::CrossLine(const UPlane& p0, const UPlane& p1) { const auto &nml0 = p0.getNormal(), &nml1 = p1.getNormal(); AVec3 nml = nml0 % nml1; if(std::fabs(nml.len_sq()) < FLOAT_EPSILON) return std::make_tuple(VEC3(),VEC3(), false); nml.normalize(); AMat33 m, mInv; m.getRow(0) = nml0; m.getRow(1) = nml1; m.getRow(2) = nml; m.transpose(); if(!m.inversion(mInv)) return std::make_tuple(VEC3(),VEC3(),false); AVec3 v(-p0.d, -p1.d, 0); v *= mInv; return std::make_tuple(v, nml, true); } PT PT::operator * (const MatT<4,3,ALIGNB>& m) const { auto& nml = getNormal(); VEC3 tmp(nml * -d); return PT::FromPtDir(tmp.asVec4(1)*m, nml.asVec4(0)*m); } PT& PT::operator *= (const MatT<4,3,ALIGNB>& m) { return *this = (*this * m); } #endif } #include "local_unmacro.hpp" #undef ALIGN #undef ALIGNA #undef ALIGNB #undef ALIGN16 #undef VEC3 #undef PT #undef DIM #endif <commit_msg>Plane: 行列との積算 (Alignment両対応)<commit_after> #if !BOOST_PP_IS_ITERATING #if !defined(PLANE_H_) || INCLUDE_PLANE_LEVEL >= 1 #define PLANE_H_ #include <tuple> // 要求された定義レベルを実体化 #ifndef INCLUDE_PLANE_LEVEL #define INCLUDE_PLANE_LEVEL 0 #endif #define BOOST_PP_ITERATION_PARAMS_1 (4, (0,1, "plane.hpp", INCLUDE_PLANE_LEVEL)) #include BOOST_PP_ITERATE() #undef INCLUDE_PLANE_LEVEL #endif #elif BOOST_PP_ITERATION_DEPTH() == 1 #define ALIGN BOOST_PP_ITERATION() #define ALIGNA AFLAG(ALIGN) #define ALIGNB BOOLNIZE(ALIGN) #define ALIGN16 BOOST_PP_IF(ALIGN, alignas(16), NOTHING) #define VEC3 VecT<3,ALIGNB> #define PT PlaneT<ALIGNB> #define DIM 4 #include "local_macro.hpp" namespace spn { #if BOOST_PP_ITERATION_FLAGS() == 0 template <> struct ALIGN16 PlaneT<ALIGNB> { using APlane = PlaneT<true>; using UPlane = PlaneT<false>; union { struct { float a,b,c,d; }; float m[4]; }; PlaneT() = default; PlaneT(const UPlane& p); PlaneT(const APlane& p); PlaneT(float fa, float fb, float fc, float fd); PlaneT(const VEC3& orig, float dist); static PT FromPtDir(const VEC3& pos, const VEC3& dir); static PT FromPts(const VEC3& p0, const VEC3& p1, const VEC3& p2); static std::tuple<VEC3,bool> ChokePoint(const UPlane& p0, const UPlane& p1, const UPlane& p2); static std::tuple<VEC3,VEC3,bool> CrossLine(const UPlane& p0, const UPlane& p1); float dot(const VEC3& p) const; void move(float d); const VEC3& getNormal() const; template <bool A> PlaneT operator * (const MatT<4,3,A>& m) const; template <bool A> PlaneT& operator *= (const MatT<4,3,A>& m); }; using BOOST_PP_CAT(ALIGNA, Plane) = PlaneT<ALIGNB>; #else PT::PlaneT(const UPlane& p) { STORETHIS(LOADPSU(p.m)); } PT::PlaneT(const APlane& p) { STORETHIS(LOADPS(p.m)); } PT::PlaneT(float fa, float fb, float fc, float fd) { a = fa; b = fb; c = fc; d = fd; } PT::PlaneT(const VEC3& orig, float dist) { STORETHIS(LOADTHISPS(orig.m)); d = dist; } const VEC3& PT::getNormal() const { return *reinterpret_cast<const VEC3*>(this); } float PT::dot(const VEC3& p) const { reg128 xm = reg_mul_ps(LOADTHIS(), LOADPS_I3(p.m, 3)); SUMVEC(xm) float ret; reg_store_ss(&ret, xm); return ret; } void PT::move(float fd) { d += fd; } PT PT::FromPtDir(const VEC3& pos, const VEC3& dir) { return PlaneT(dir, -dir.dot(pos)); } PT PT::FromPts(const VEC3& p0, const VEC3& p1, const VEC3& p2) { VEC3 nml = (p1 - p0).cross(p2 - p0); nml.normalize(); return PlaneT(nml, -p0.dot(nml)); } //! 3つの平面が交差する座標を調べる std::tuple<VEC3,bool> PT::ChokePoint(const UPlane& p0, const UPlane& p1, const UPlane& p2) { AMat33 m, mInv; m.getRow(0) = p0.getNormal(); m.getRow(1) = p1.getNormal(); m.getRow(2) = p2.getNormal(); m.transpose(); if(!m.inversion(mInv)) return std::make_tuple(VEC3(), false); VEC3 v(-p0.d, -p1.d, -p2.d); v *= mInv; return std::make_tuple(v, true); } //! 2つの平面が交差する直線を調べる std::tuple<VEC3,VEC3,bool> PT::CrossLine(const UPlane& p0, const UPlane& p1) { const auto &nml0 = p0.getNormal(), &nml1 = p1.getNormal(); AVec3 nml = nml0 % nml1; if(std::fabs(nml.len_sq()) < FLOAT_EPSILON) return std::make_tuple(VEC3(),VEC3(), false); nml.normalize(); AMat33 m, mInv; m.getRow(0) = nml0; m.getRow(1) = nml1; m.getRow(2) = nml; m.transpose(); if(!m.inversion(mInv)) return std::make_tuple(VEC3(),VEC3(),false); AVec3 v(-p0.d, -p1.d, 0); v *= mInv; return std::make_tuple(v, nml, true); } template <bool A> PT PT::operator * (const MatT<4,3,A>& m) const { auto& nml = getNormal(); VEC3 tmp(nml * -d); return PT::FromPtDir(tmp.asVec4(1)*m, nml.asVec4(0)*m); } template <bool A> PT& PT::operator *= (const MatT<4,3,A>& m) { return *this = (*this * m); } template PT PT::operator * (const MatT<4,3,false>&) const; template PT PT::operator * (const MatT<4,3,true>& m) const; template PT& PT::operator *= (const MatT<4,3,false>& m); template PT& PT::operator *= (const MatT<4,3,true>& m); #endif } #include "local_unmacro.hpp" #undef ALIGN #undef ALIGNA #undef ALIGNB #undef ALIGN16 #undef VEC3 #undef PT #undef DIM #endif <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <DataFileReaderPField.h> #include <Ougens.h> // for Oonepole DataFileReaderPField::DataFileReaderPField(const char *fileName, const double lag, const int controlRate, const int defaultFileRate, const int defaultFormat, const bool defaultSwap) : RTNumberPField(0) { _datafile = new DataFile(fileName, controlRate); if (_datafile) { if (_datafile->openFileRead() == 0) _datafile->readHeader(defaultFileRate, defaultFormat, defaultSwap); else { delete _datafile; _datafile = NULL; } } _filter = new Oonepole(controlRate); _filter->setlag(lag); } DataFileReaderPField::~DataFileReaderPField() { delete _datafile; delete _filter; } double DataFileReaderPField::doubleValue(double) const { return _datafile ? _filter->next(_datafile->readOne()) : 0.0; } <commit_msg>Track changes to DataFile class.<commit_after>/* RTcmix - Copyright (C) 2005 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <DataFileReaderPField.h> #include <Ougens.h> // for Oonepole DataFileReaderPField::DataFileReaderPField(const char *fileName, const double lag, const int controlRate, const int defaultFileRate, const int defaultFormat, const bool defaultSwap) : RTNumberPField(0) { _datafile = new DataFile(fileName, controlRate); if (_datafile) { long status = _datafile->openFileRead(); if (status == 0) status = _datafile->readHeader(defaultFileRate, defaultFormat, defaultSwap); if (status == -1) { delete _datafile; _datafile = NULL; } } _filter = new Oonepole(controlRate); _filter->setlag(lag); } DataFileReaderPField::~DataFileReaderPField() { delete _datafile; delete _filter; } double DataFileReaderPField::doubleValue(double) const { return _datafile ? _filter->next(_datafile->readOne()) : 0.0; } <|endoftext|>
<commit_before>#include "core/meta/MetaPopulationApportionment.hpp" #include "core/meta/BlanketResolver.hpp" MetaPopulationApportionment::MetaPopulationApportionment( PopulationNode * metaNode, ApportionmentFunction * apportionment, AggregationFunction * aggregation ) : Apportionment(metaNode, apportionment, aggregation) {} Genome * MetaPopulationApportionment::getOperableGenome(Genome * genome) { Genome resolved = BlanketResolver::resolveBlanket(genome); return new Genome(&resolved); } std::vector<unsigned int> MetaPopulationApportionment::getComponentIndices( Genome * upper, Genome * target ) { Genome * head = upper->getIndex<Genome*>( BlanketResolver::findHeadIndex(upper) ); return (head == target) ? std::vector<unsigned int>(1, 0) : head->getFlattenedSpeciesIndices(target); } std::vector<unsigned int> MetaPopulationApportionment::getRelevantIndices( Genome * target, unsigned int targetIndex ) { std::vector<Locus*> targetLoci = target->getLoci(); std::vector<unsigned int> indices; unsigned int currentIndex = 0; for (unsigned int i = 0; i < targetLoci.size(); i++) if (!targetLoci[i]->isConstructive()) { indices.push_back(targetIndex + currentIndex); } else { currentIndex += target->getIndex<Genome*>(i) ->flattenedGenomeLength(); } return indices; } <commit_msg>[MetaPopApportionment]: Fixed index-finding bug<commit_after>#include "core/meta/MetaPopulationApportionment.hpp" #include "core/meta/BlanketResolver.hpp" MetaPopulationApportionment::MetaPopulationApportionment( PopulationNode * metaNode, ApportionmentFunction * apportionment, AggregationFunction * aggregation ) : Apportionment(metaNode, apportionment, aggregation) {} Genome * MetaPopulationApportionment::getOperableGenome(Genome * genome) { Genome resolved = BlanketResolver::resolveBlanket(genome); return new Genome(&resolved); } std::vector<unsigned int> MetaPopulationApportionment::getComponentIndices( Genome * upper, Genome * target ) { Genome * head = upper->getIndex<Genome*>( BlanketResolver::findHeadIndex(upper) ); return (head == target) ? std::vector<unsigned int>(1, 0) : head->getFlattenedSpeciesIndices(target); } std::vector<unsigned int> MetaPopulationApportionment::getRelevantIndices( Genome * target, unsigned int targetIndex ) { std::vector<Locus*> targetLoci = target->getLoci(); std::vector<unsigned int> indices; unsigned int currentIndex = 0; for (unsigned int i = 0; i < targetLoci.size(); i++) if (!targetLoci[i]->isConstructive()) { indices.push_back(targetIndex + currentIndex++); } else { currentIndex += target->getIndex<Genome*>(i) ->flattenedGenomeLength(); } return indices; } <|endoftext|>
<commit_before>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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. */ // $Id$ // $URL$ #include "ExecutionConfiguration.h" #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #ifdef USE_CUDA #include <cuda_runtime.h> #endif #ifdef USE_PYTHON #include <boost/python.hpp> using namespace boost::python; #endif #include <boost/foreach.hpp> #define foreach BOOST_FOREACH #include <stdexcept> #include <iostream> using namespace std; using namespace boost; /*! \file ExecutionConfiguration.cc \brief Defines ExecutionConfiguration and related classes */ /*! Code previous to the creation of ExecutionConfiguration always used CUDA device 0 by default. To maintain continuity, a default constructed ExecutionConfiguration will do the same. When the full multi-gpu code is written, ExecutionConfiguration will by default use all of the GPUs found in the device. This will provide the user with the default fastest performance with no need for command line options. */ ExecutionConfiguration::ExecutionConfiguration() { #ifdef USE_CUDA int dev_count; cudaError_t error = cudaGetDeviceCount(&dev_count); if (error != cudaSuccess) { cerr << "***Warning! Error getting CUDA capable device count! Continuing with 0 GPUs." << endl; exec_mode = CPU; return; } else { if (dev_count > 0) { gpu.push_back(shared_ptr<GPUWorker>(new GPUWorker(0))); exec_mode = GPU; } else exec_mode = CPU; } #else exec_mode=CPU; #endif } /*! \param mode Execution mode to set (cpu or gpu) \param gpu_id GPU to execute on No GPU is initialized if mode==cpu */ ExecutionConfiguration::ExecutionConfiguration(executionMode mode, unsigned int gpu_id) { exec_mode = mode; #ifdef USE_CUDA if (exec_mode == GPU) { int dev_count; cudaError_t error = cudaGetDeviceCount(&dev_count); if (error != cudaSuccess) { cerr << endl << "***Error! Error getting CUDA capable device count!" << endl << endl; throw runtime_error("Error initializing execution configuration"); return; } else { if ((unsigned int)dev_count > gpu_id) gpu.push_back(shared_ptr<GPUWorker>(new GPUWorker(gpu_id))); else { cerr << endl << "***Error! GPU " << gpu_id << " was requested, but only " << dev_count << " was/were found" << endl << endl; throw runtime_error("Error initializing execution configuration"); } } } #endif } /*! \param mode Execution mode to set (cpu or gpu) \param gpu_ids List of GPUs to execute on No GPU is initialized if mode==cpu */ ExecutionConfiguration::ExecutionConfiguration(executionMode mode, const std::vector<unsigned int>& gpu_ids) { exec_mode = mode; #ifdef USE_CUDA if (exec_mode == GPU) { int dev_count; cudaError_t error = cudaGetDeviceCount(&dev_count); if (error != cudaSuccess) { cerr << endl << "***Error! Error getting CUDA capable device count!" << endl << endl; throw runtime_error("Error initializing execution configuration"); return; } else { if (gpu_ids.size() == 0) { cerr << endl << "***Error! GPU configuration requested with no GPU ids!" << endl << endl; throw runtime_error("Error initializing execution configuration"); return; } for (unsigned int i = 0; i < gpu_ids.size(); i++) { if ((unsigned int)dev_count > gpu_ids[i]) gpu.push_back(shared_ptr<GPUWorker>(new GPUWorker(gpu_ids[i]))); else { cerr << endl << "***Error! GPU " << gpu_ids[i] << " was requested, but only " << dev_count << " was/were found" << endl << endl; throw runtime_error("Error initializing execution configuration"); } } } } #endif } #ifdef USE_CUDA /*! \param file Passed to GPUWorker::setTag \param line Passed to GPUWorker::setTag */ void ExecutionConfiguration::tagAll(const std::string &file, unsigned int line) const { foreach (shared_ptr<GPUWorker> cur_gpu, gpu) cur_gpu->setTag(file, line); } /*! Calls GPUWorker::sync() for all GPUs in the configuration */ void ExecutionConfiguration::syncAll() const { foreach (shared_ptr<GPUWorker> cur_gpu, gpu) cur_gpu->sync(); } /*! \param func Passed to GPUWorker::call */ void ExecutionConfiguration::callAll(const boost::function< cudaError_t (void) > &func) const { foreach (shared_ptr<GPUWorker> cur_gpu, gpu) cur_gpu->call(func); } #endif #ifdef USE_PYTHON void export_ExecutionConfiguration() { scope in_exec_conf = class_<ExecutionConfiguration, boost::shared_ptr<ExecutionConfiguration>, boost::noncopyable > ("ExecutionConfiguration", init< >()) .def(init<ExecutionConfiguration::executionMode, unsigned int>()) .def(init<ExecutionConfiguration::executionMode, vector<unsigned int> >()) .def_readonly("exec_mode", &ExecutionConfiguration::exec_mode) ; enum_<ExecutionConfiguration::executionMode>("executionMode") .value("GPU", ExecutionConfiguration::GPU) .value("CPU", ExecutionConfiguration::CPU) ; } #endif #ifdef WIN32 #pragma warning( pop ) #endif <commit_msg>Stopped using boost foreach since it isn't supported pre boost 1.34<commit_after>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, in source and binary forms, with or without modification, are permitted, provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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. */ // $Id$ // $URL$ #include "ExecutionConfiguration.h" #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #ifdef USE_CUDA #include <cuda_runtime.h> #endif #ifdef USE_PYTHON #include <boost/python.hpp> using namespace boost::python; #endif #include <stdexcept> #include <iostream> using namespace std; using namespace boost; /*! \file ExecutionConfiguration.cc \brief Defines ExecutionConfiguration and related classes */ /*! Code previous to the creation of ExecutionConfiguration always used CUDA device 0 by default. To maintain continuity, a default constructed ExecutionConfiguration will do the same. When the full multi-gpu code is written, ExecutionConfiguration will by default use all of the GPUs found in the device. This will provide the user with the default fastest performance with no need for command line options. */ ExecutionConfiguration::ExecutionConfiguration() { #ifdef USE_CUDA int dev_count; cudaError_t error = cudaGetDeviceCount(&dev_count); if (error != cudaSuccess) { cerr << "***Warning! Error getting CUDA capable device count! Continuing with 0 GPUs." << endl; exec_mode = CPU; return; } else { if (dev_count > 0) { gpu.push_back(shared_ptr<GPUWorker>(new GPUWorker(0))); exec_mode = GPU; } else exec_mode = CPU; } #else exec_mode=CPU; #endif } /*! \param mode Execution mode to set (cpu or gpu) \param gpu_id GPU to execute on No GPU is initialized if mode==cpu */ ExecutionConfiguration::ExecutionConfiguration(executionMode mode, unsigned int gpu_id) { exec_mode = mode; #ifdef USE_CUDA if (exec_mode == GPU) { int dev_count; cudaError_t error = cudaGetDeviceCount(&dev_count); if (error != cudaSuccess) { cerr << endl << "***Error! Error getting CUDA capable device count!" << endl << endl; throw runtime_error("Error initializing execution configuration"); return; } else { if ((unsigned int)dev_count > gpu_id) gpu.push_back(shared_ptr<GPUWorker>(new GPUWorker(gpu_id))); else { cerr << endl << "***Error! GPU " << gpu_id << " was requested, but only " << dev_count << " was/were found" << endl << endl; throw runtime_error("Error initializing execution configuration"); } } } #endif } /*! \param mode Execution mode to set (cpu or gpu) \param gpu_ids List of GPUs to execute on No GPU is initialized if mode==cpu */ ExecutionConfiguration::ExecutionConfiguration(executionMode mode, const std::vector<unsigned int>& gpu_ids) { exec_mode = mode; #ifdef USE_CUDA if (exec_mode == GPU) { int dev_count; cudaError_t error = cudaGetDeviceCount(&dev_count); if (error != cudaSuccess) { cerr << endl << "***Error! Error getting CUDA capable device count!" << endl << endl; throw runtime_error("Error initializing execution configuration"); return; } else { if (gpu_ids.size() == 0) { cerr << endl << "***Error! GPU configuration requested with no GPU ids!" << endl << endl; throw runtime_error("Error initializing execution configuration"); return; } for (unsigned int i = 0; i < gpu_ids.size(); i++) { if ((unsigned int)dev_count > gpu_ids[i]) gpu.push_back(shared_ptr<GPUWorker>(new GPUWorker(gpu_ids[i]))); else { cerr << endl << "***Error! GPU " << gpu_ids[i] << " was requested, but only " << dev_count << " was/were found" << endl << endl; throw runtime_error("Error initializing execution configuration"); } } } } #endif } #ifdef USE_CUDA /*! \param file Passed to GPUWorker::setTag \param line Passed to GPUWorker::setTag */ void ExecutionConfiguration::tagAll(const std::string &file, unsigned int line) const { for (unsigned int i = 0; i < gpu.size(); i++) gpu[i]->setTag(file, line); } /*! Calls GPUWorker::sync() for all GPUs in the configuration */ void ExecutionConfiguration::syncAll() const { for (unsigned int i = 0; i < gpu.size(); i++) gpu[i]->sync(); } /*! \param func Passed to GPUWorker::call */ void ExecutionConfiguration::callAll(const boost::function< cudaError_t (void) > &func) const { for (unsigned int i = 0; i < gpu.size(); i++) gpu[i]->call(func); } #endif #ifdef USE_PYTHON void export_ExecutionConfiguration() { scope in_exec_conf = class_<ExecutionConfiguration, boost::shared_ptr<ExecutionConfiguration>, boost::noncopyable > ("ExecutionConfiguration", init< >()) .def(init<ExecutionConfiguration::executionMode, unsigned int>()) .def(init<ExecutionConfiguration::executionMode, vector<unsigned int> >()) .def_readonly("exec_mode", &ExecutionConfiguration::exec_mode) ; enum_<ExecutionConfiguration::executionMode>("executionMode") .value("GPU", ExecutionConfiguration::GPU) .value("CPU", ExecutionConfiguration::CPU) ; } #endif #ifdef WIN32 #pragma warning( pop ) #endif <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2017 Axel Waggershauser Copyright (C) 2017 Roman Lebedev 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "parsers/FiffParser.h" #include "common/Common.h" // for make_unique, uint32, uchar8 #include "io/Buffer.h" // for Buffer #include "io/ByteStream.h" // for ByteStream #include "io/Endianness.h" // for getU32BE, getHostEndianness #include "parsers/FiffParserException.h" // for ThrowFPE #include "parsers/TiffParser.h" // for TiffParser::parse, TiffParser::makeDecoder #include "parsers/TiffParserException.h" // for TiffParserException #include "tiff/TiffEntry.h" // for TiffEntry, TiffDataType::TI... #include "tiff/TiffIFD.h" // for TiffIFD, TiffRootIFD, TiffI... #include "tiff/TiffTag.h" // for TiffTag, TiffTag::FUJIOLDWB #include <algorithm> // for move #include <limits> // for numeric_limits #include <memory> // for default_delete, unique_ptr using namespace std; namespace RawSpeed { class RawDecoder; FiffParser::FiffParser(Buffer* inputData) : RawParser(inputData) {} RawDecoder* FiffParser::getDecoder() { const uchar8* data = mInput->getData(0, 104); uint32 first_ifd = getU32BE(data + 0x54); if (first_ifd >= numeric_limits<uint32>::max() - 12) ThrowFPE("Not Fiff. First IFD too far away"); first_ifd += 12; uint32 second_ifd = getU32BE(data + 0x64); uint32 third_ifd = getU32BE(data + 0x5C); try { TiffRootIFDOwner rootIFD = TiffParser::parse(mInput->getSubView(first_ifd)); TiffIFDOwner subIFD = make_unique<TiffIFD>(); if (mInput->isValid(second_ifd)) { // RAW Tiff on newer models, pointer to raw data on older models // -> so we try parsing as Tiff first and add it as data if parsing fails try { rootIFD->add(TiffParser::parse(mInput->getSubView(second_ifd))); } catch (TiffParserException&) { // the offset will be interpreted relative to the rootIFD where this // subIFD gets inserted uint32 rawOffset = second_ifd - first_ifd; subIFD->add( make_unique<TiffEntry>(subIFD.get(), FUJI_STRIPOFFSETS, TIFF_OFFSET, 1, ByteStream::createCopy(&rawOffset, 4))); uint32 max_size = mInput->getSize() - second_ifd; subIFD->add(make_unique<TiffEntry>( subIFD.get(), FUJI_STRIPBYTECOUNTS, TIFF_LONG, 1, ByteStream::createCopy(&max_size, 4))); } } if (mInput->isValid(third_ifd)) { // RAW information IFD on older // This Fuji directory structure is similar to a Tiff IFD but with two // differences: // a) no type info and b) data is always stored in place. // 4b: # of entries, for each entry: 2b tag, 2b len, xb data ByteStream bytes(mInput, third_ifd, getHostEndianness() == big); uint32 entries = bytes.getU32(); if (entries > 255) ThrowFPE("Too many entries"); for (uint32 i = 0; i < entries; i++) { ushort16 tag = bytes.getU16(); ushort16 length = bytes.getU16(); TiffDataType type = TIFF_UNDEFINED; if (tag == IMAGEWIDTH || tag == FUJIOLDWB) // also 0x121? type = TIFF_SHORT; uint32 count = type == TIFF_SHORT ? length / 2 : length; subIFD->add(make_unique<TiffEntry>( subIFD.get(), (TiffTag)tag, type, count, bytes.getSubStream(bytes.getPosition(), length))); bytes.skipBytes(length); } } rootIFD->add(move(subIFD)); return TiffParser::makeDecoder(move(rootIFD), *mInput); } catch (TiffParserException&) { ThrowFPE("No decoder found. Sorry."); } } } // namespace RawSpeed <commit_msg>FiffParser::getDecoder(): do check IFD order first.<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2017 Axel Waggershauser Copyright (C) 2017 Roman Lebedev 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 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "parsers/FiffParser.h" #include "common/Common.h" // for make_unique, uint32, uchar8 #include "io/Buffer.h" // for Buffer #include "io/ByteStream.h" // for ByteStream #include "io/Endianness.h" // for getU32BE, getHostEndianness #include "parsers/FiffParserException.h" // for ThrowFPE #include "parsers/TiffParser.h" // for TiffParser::parse, TiffParser::makeDecoder #include "parsers/TiffParserException.h" // for TiffParserException #include "tiff/TiffEntry.h" // for TiffEntry, TiffDataType::TI... #include "tiff/TiffIFD.h" // for TiffIFD, TiffRootIFD, TiffI... #include "tiff/TiffTag.h" // for TiffTag, TiffTag::FUJIOLDWB #include <algorithm> // for move #include <limits> // for numeric_limits #include <memory> // for default_delete, unique_ptr using namespace std; namespace RawSpeed { class RawDecoder; FiffParser::FiffParser(Buffer* inputData) : RawParser(inputData) {} RawDecoder* FiffParser::getDecoder() { const uchar8* data = mInput->getData(0, 104); uint32 first_ifd = getU32BE(data + 0x54); if (first_ifd >= numeric_limits<uint32>::max() - 12) ThrowFPE("Not Fiff. First IFD too far away"); first_ifd += 12; uint32 second_ifd = getU32BE(data + 0x64); uint32 third_ifd = getU32BE(data + 0x5C); try { TiffRootIFDOwner rootIFD = TiffParser::parse(mInput->getSubView(first_ifd)); TiffIFDOwner subIFD = make_unique<TiffIFD>(); if (mInput->isValid(second_ifd)) { // RAW Tiff on newer models, pointer to raw data on older models // -> so we try parsing as Tiff first and add it as data if parsing fails try { rootIFD->add(TiffParser::parse(mInput->getSubView(second_ifd))); } catch (TiffParserException&) { // the offset will be interpreted relative to the rootIFD where this // subIFD gets inserted if (second_ifd <= first_ifd) ThrowFPE("Fiff is corrupted: second IFD is not after the first IFD"); uint32 rawOffset = second_ifd - first_ifd; subIFD->add( make_unique<TiffEntry>(subIFD.get(), FUJI_STRIPOFFSETS, TIFF_OFFSET, 1, ByteStream::createCopy(&rawOffset, 4))); uint32 max_size = mInput->getSize() - second_ifd; subIFD->add(make_unique<TiffEntry>( subIFD.get(), FUJI_STRIPBYTECOUNTS, TIFF_LONG, 1, ByteStream::createCopy(&max_size, 4))); } } if (mInput->isValid(third_ifd)) { // RAW information IFD on older // This Fuji directory structure is similar to a Tiff IFD but with two // differences: // a) no type info and b) data is always stored in place. // 4b: # of entries, for each entry: 2b tag, 2b len, xb data ByteStream bytes(mInput, third_ifd, getHostEndianness() == big); uint32 entries = bytes.getU32(); if (entries > 255) ThrowFPE("Too many entries"); for (uint32 i = 0; i < entries; i++) { ushort16 tag = bytes.getU16(); ushort16 length = bytes.getU16(); TiffDataType type = TIFF_UNDEFINED; if (tag == IMAGEWIDTH || tag == FUJIOLDWB) // also 0x121? type = TIFF_SHORT; uint32 count = type == TIFF_SHORT ? length / 2 : length; subIFD->add(make_unique<TiffEntry>( subIFD.get(), (TiffTag)tag, type, count, bytes.getSubStream(bytes.getPosition(), length))); bytes.skipBytes(length); } } rootIFD->add(move(subIFD)); return TiffParser::makeDecoder(move(rootIFD), *mInput); } catch (TiffParserException&) { ThrowFPE("No decoder found. Sorry."); } } } // namespace RawSpeed <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** $TROLLTECH_DUAL_EMBEDDED_LICENSE$ ** ****************************************************************************/ #include "qmenu.h" #include "qapplication.h" #include "qmainwindow.h" #include "qtoolbar.h" #include "qevent.h" #include "qstyle.h" #include "qdebug.h" #include "qwidgetaction.h" #include <eikmenub.h> #include <eikmenup.h> #include <private/qapplication_p.h> #include <private/qmenu_p.h> #include <private/qmenubar_p.h> #include <qt_s60_p.h> #include <eikaufty.h> #include <eikbtgpc.h> #include <QtCore/qlibrary.h> #include <avkon.rsg> #ifndef QT_NO_MENUBAR QT_BEGIN_NAMESPACE // ### FIX/Document this, we need some safe range of menu id's for Qt that don't clash with AIW ones #define QT_FIRST_MENU_ITEM 32000 static QList<QMenuBarPrivate *> s60_menubars; struct SymbianMenuItem { int id; CEikMenuPaneItem::SData menuItemData; QList<SymbianMenuItem*> children; QAction* action; }; static QList<SymbianMenuItem*> symbianMenus; static QList<QMenuBar*> nativeMenuBars; static uint qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM; // ### FIX THIS, copy/paste of original (faulty) stripped text implementation. // Implementation should be removed from QAction implementation to some generic place static QString qt_strippedText_copy_from_qaction(QString s) { s.remove(QString::fromLatin1("...")); int i = 0; while (i < s.size()) { ++i; if (s.at(i-1) != QLatin1Char('&')) continue; if (i < s.size() && s.at(i) == QLatin1Char('&')) ++i; s.remove(i-1,1); } return s.trimmed(); }; static SymbianMenuItem* qt_symbian_find_menu(int id, const QList<SymbianMenuItem*> &parent) { int index=0; while (index < parent.count()) { SymbianMenuItem* temp = parent[index]; if (temp->menuItemData.iCascadeId == id) return temp; else if (temp->menuItemData.iCascadeId != 0) { SymbianMenuItem* result = qt_symbian_find_menu( id, temp->children); if (result) return result; } index++; } return 0; } static SymbianMenuItem* qt_symbian_find_menu_item(int id, const QList<SymbianMenuItem*> &parent) { int index=0; while (index < parent.count()) { SymbianMenuItem* temp = parent[index]; if (temp->menuItemData.iCascadeId != 0) { SymbianMenuItem* result = qt_symbian_find_menu_item( id, temp->children); if (result) return result; } else if (temp->menuItemData.iCommandId == id) return temp; index++; } return 0; } static void qt_symbian_insert_action(QSymbianMenuAction* action, QList<SymbianMenuItem*>* parent) { if (action->action->isVisible()) { if (action->action->isSeparator()) return; // ### FIX THIS, the qt_strippedText2 doesn't work perfectly for stripping & marks. Same bug is in QAction // New really working method is needed in a place where the implementation isn't copy/pasted QString text = qt_strippedText_copy_from_qaction(action->action->text()); HBufC* menuItemText = qt_QString2HBufCNewL(text); if (action->action->menu()) { SymbianMenuItem* menuItem = new SymbianMenuItem(); menuItem->menuItemData.iCascadeId = action->command; menuItem->menuItemData.iCommandId = action->command; menuItem->menuItemData.iFlags = 0; menuItem->menuItemData.iText = *menuItemText; menuItem->action = action->action; if (action->action->menu()->actions().size() == 0 || !action->action->isEnabled() ) menuItem->menuItemData.iFlags |= EEikMenuItemDimmed; parent->append(menuItem); if (action->action->menu()->actions().size() > 0) { for (int c2= 0; c2 < action->action->menu()->actions().size(); ++c2) { QSymbianMenuAction *symbianAction2 = new QSymbianMenuAction; symbianAction2->action = action->action->menu()->actions().at(c2); QMenu * menu = symbianAction2->action->menu(); symbianAction2->command = qt_symbian_menu_static_cmd_id++; qt_symbian_insert_action(symbianAction2, &(menuItem->children)); } } } else { SymbianMenuItem* menuItem = new SymbianMenuItem(); menuItem->menuItemData.iCascadeId = 0; menuItem->menuItemData.iCommandId = action->command; menuItem->menuItemData.iFlags = 0; menuItem->menuItemData.iText = *menuItemText; menuItem->action = action->action; if (!action->action->isEnabled()){ menuItem->menuItemData.iFlags += EEikMenuItemDimmed; } if (action->action->isCheckable()) { if (action->action->isChecked()) menuItem->menuItemData.iFlags += EEikMenuItemCheckBox | EEikMenuItemSymbolOn; else menuItem->menuItemData.iFlags += EEikMenuItemCheckBox; } parent->append(menuItem); } delete menuItemText; } } void deleteAll(QList<SymbianMenuItem*> *items) { while (!items->isEmpty()) { SymbianMenuItem* temp = items->takeFirst(); deleteAll(&temp->children); delete temp; } } static void setSoftkeys() { CEikButtonGroupContainer* cba = CEikonEnv::Static()->AppUiFactory()->Cba(); if (cba){ if (s60_menubars.count()>0) cba->SetCommandSetL(R_AVKON_SOFTKEYS_OPTIONS_EXIT); else cba->SetCommandSetL(R_AVKON_SOFTKEYS_EXIT); } } static void rebuildMenu() { qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM; deleteAll( &symbianMenus ); if (s60_menubars.count()==0) return; for (int i = 0; i < s60_menubars.last()->actions.size(); ++i) { QSymbianMenuAction *symbianActionTopLevel = new QSymbianMenuAction; symbianActionTopLevel->action = s60_menubars.last()->actions.at(i); symbianActionTopLevel->parent = 0; symbianActionTopLevel->command = qt_symbian_menu_static_cmd_id++; qt_symbian_insert_action(symbianActionTopLevel, &symbianMenus); } return; } Q_GUI_EXPORT void qt_symbian_show_toplevel( CEikMenuPane* menuPane) { if (s60_menubars.count()==0) return; rebuildMenu(); for (int i = 0; i < symbianMenus.count(); ++i) menuPane->AddMenuItemL(symbianMenus.at(i)->menuItemData); } Q_GUI_EXPORT void qt_symbian_show_submenu( CEikMenuPane* menuPane, int id) { SymbianMenuItem* menu = qt_symbian_find_menu(id, symbianMenus); if (menu) { for (int i = 0; i < menu->children.count(); ++i) menuPane->AddMenuItemL(menu->children.at(i)->menuItemData); } } void QMenu::symbianCommands(int command) { Q_D(QMenu); d->symbianCommands(command); } void QMenuBar::symbianCommands(int command) { int size = nativeMenuBars.size(); for (int i = 0; i < nativeMenuBars.size(); ++i) { bool result = nativeMenuBars.at(i)->d_func()->symbianCommands(command); if (result) return; } } bool QMenuBarPrivate::symbianCommands(int command) { SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus); if (!menu) return false; emit q_func()->triggered(menu->action); menu->action->activate(QAction::Trigger); return true; } bool QMenuPrivate::symbianCommands(int command) { SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus); if (!menu) return false; emit q_func()->triggered(menu->action); menu->action->activate(QAction::Trigger); return true; } void QMenuBarPrivate::symbianCreateMenuBar(QWidget *parent) { Q_Q(QMenuBar); if (parent && parent->isWindow()){ symbian_menubar = new QSymbianMenuBarPrivate(this); nativeMenuBars.append(q); } } void QMenuBarPrivate::symbianDestroyMenuBar() { Q_Q(QMenuBar); int index = nativeMenuBars.indexOf(q); nativeMenuBars.removeAt(index); s60_menubars.removeLast(); rebuildMenu(); if (symbian_menubar) delete symbian_menubar; symbian_menubar = 0; } QMenuBarPrivate::QSymbianMenuBarPrivate::QSymbianMenuBarPrivate(QMenuBarPrivate *menubar) { d = menubar; s60_menubars.append(menubar); } QMenuBarPrivate::QSymbianMenuBarPrivate::~QSymbianMenuBarPrivate() { deleteAll( &symbianMenus ); symbianMenus.clear(); d = 0; rebuild(); } QMenuPrivate::QSymbianMenuPrivate::QSymbianMenuPrivate() { } QMenuPrivate::QSymbianMenuPrivate::~QSymbianMenuPrivate() { } void QMenuPrivate::QSymbianMenuPrivate::addAction(QAction *a, QSymbianMenuAction *before) { QSymbianMenuAction *action = new QSymbianMenuAction; action->action = a; action->command = qt_symbian_menu_static_cmd_id++; addAction(action, before); } void QMenuPrivate::QSymbianMenuPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before) { if (!action) return; int before_index = actionItems.indexOf(before); if (before_index < 0) { before = 0; before_index = actionItems.size(); } actionItems.insert(before_index, action); } void QMenuPrivate::QSymbianMenuPrivate::syncAction(QSymbianMenuAction *) { rebuild(); } void QMenuPrivate::QSymbianMenuPrivate::removeAction(QSymbianMenuAction *action) { actionItems.removeAll(action); delete action; action = 0; rebuild(); } void QMenuPrivate::QSymbianMenuPrivate::rebuild(bool) { } void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QAction *a, QSymbianMenuAction *before) { QSymbianMenuAction *action = new QSymbianMenuAction; action->action = a; action->command = qt_symbian_menu_static_cmd_id++; addAction(action, before); } void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before) { if (!action) return; int before_index = actionItems.indexOf(before); if (before_index < 0) { before = 0; before_index = actionItems.size(); } actionItems.insert(before_index, action); } void QMenuBarPrivate::QSymbianMenuBarPrivate::syncAction(QSymbianMenuAction*) { rebuild(); } void QMenuBarPrivate::QSymbianMenuBarPrivate::removeAction(QSymbianMenuAction *action) { actionItems.removeAll(action); delete action; rebuild(); } void QMenuBarPrivate::QSymbianMenuBarPrivate::rebuild() { setSoftkeys(); if (s60_menubars.count()==0) return; rebuildMenu(); } #endif //QT_NO_MENUBAR <commit_msg>Refactored implementation so that it works with multiple QMainWindows<commit_after>/**************************************************************************** ** ** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** ** $TROLLTECH_DUAL_EMBEDDED_LICENSE$ ** ****************************************************************************/ #include "qmenu.h" #include "qapplication.h" #include "qmainwindow.h" #include "qtoolbar.h" #include "qevent.h" #include "qstyle.h" #include "qdebug.h" #include "qwidgetaction.h" #include <eikmenub.h> #include <eikmenup.h> #include <private/qapplication_p.h> #include <private/qmenu_p.h> #include <private/qmenubar_p.h> #include <qt_s60_p.h> #include <eikaufty.h> #include <eikbtgpc.h> #include <QtCore/qlibrary.h> #include <avkon.rsg> #ifndef QT_NO_MENUBAR QT_BEGIN_NAMESPACE // ### FIX/Document this, we need some safe range of menu id's for Qt that don't clash with AIW ones typedef QHash<QWidget *, QMenuBarPrivate *> MenuBarHash; Q_GLOBAL_STATIC(MenuBarHash, menubars) #define QT_FIRST_MENU_ITEM 32000 struct SymbianMenuItem { int id; CEikMenuPaneItem::SData menuItemData; QList<SymbianMenuItem*> children; QAction* action; }; static QList<SymbianMenuItem*> symbianMenus; static QList<QMenuBar*> nativeMenuBars; static uint qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM; bool menuExists() { QWidget *w = qApp->activeWindow(); QMenuBarPrivate *mb = menubars()->value(w); if (!mb) return false; return true; } // ### FIX THIS, copy/paste of original (faulty) stripped text implementation. // Implementation should be removed from QAction implementation to some generic place static QString qt_strippedText_copy_from_qaction(QString s) { s.remove(QString::fromLatin1("...")); int i = 0; while (i < s.size()) { ++i; if (s.at(i-1) != QLatin1Char('&')) continue; if (i < s.size() && s.at(i) == QLatin1Char('&')) ++i; s.remove(i-1,1); } return s.trimmed(); }; static SymbianMenuItem* qt_symbian_find_menu(int id, const QList<SymbianMenuItem*> &parent) { int index=0; while (index < parent.count()) { SymbianMenuItem* temp = parent[index]; if (temp->menuItemData.iCascadeId == id) return temp; else if (temp->menuItemData.iCascadeId != 0) { SymbianMenuItem* result = qt_symbian_find_menu( id, temp->children); if (result) return result; } index++; } return 0; } static SymbianMenuItem* qt_symbian_find_menu_item(int id, const QList<SymbianMenuItem*> &parent) { int index=0; while (index < parent.count()) { SymbianMenuItem* temp = parent[index]; if (temp->menuItemData.iCascadeId != 0) { SymbianMenuItem* result = qt_symbian_find_menu_item( id, temp->children); if (result) return result; } else if (temp->menuItemData.iCommandId == id) return temp; index++; } return 0; } static void qt_symbian_insert_action(QSymbianMenuAction* action, QList<SymbianMenuItem*>* parent) { if (action->action->isVisible()) { if (action->action->isSeparator()) return; // ### FIX THIS, the qt_strippedText2 doesn't work perfectly for stripping & marks. Same bug is in QAction // New really working method is needed in a place where the implementation isn't copy/pasted QString text = qt_strippedText_copy_from_qaction(action->action->text()); HBufC* menuItemText = qt_QString2HBufCNewL(text); if (action->action->menu()) { SymbianMenuItem* menuItem = new SymbianMenuItem(); menuItem->menuItemData.iCascadeId = action->command; menuItem->menuItemData.iCommandId = action->command; menuItem->menuItemData.iFlags = 0; menuItem->menuItemData.iText = *menuItemText; menuItem->action = action->action; if (action->action->menu()->actions().size() == 0 || !action->action->isEnabled() ) menuItem->menuItemData.iFlags |= EEikMenuItemDimmed; parent->append(menuItem); if (action->action->menu()->actions().size() > 0) { for (int c2= 0; c2 < action->action->menu()->actions().size(); ++c2) { QSymbianMenuAction *symbianAction2 = new QSymbianMenuAction; symbianAction2->action = action->action->menu()->actions().at(c2); QMenu * menu = symbianAction2->action->menu(); symbianAction2->command = qt_symbian_menu_static_cmd_id++; qt_symbian_insert_action(symbianAction2, &(menuItem->children)); } } } else { SymbianMenuItem* menuItem = new SymbianMenuItem(); menuItem->menuItemData.iCascadeId = 0; menuItem->menuItemData.iCommandId = action->command; menuItem->menuItemData.iFlags = 0; menuItem->menuItemData.iText = *menuItemText; menuItem->action = action->action; if (!action->action->isEnabled()){ menuItem->menuItemData.iFlags += EEikMenuItemDimmed; } if (action->action->isCheckable()) { if (action->action->isChecked()) menuItem->menuItemData.iFlags += EEikMenuItemCheckBox | EEikMenuItemSymbolOn; else menuItem->menuItemData.iFlags += EEikMenuItemCheckBox; } parent->append(menuItem); } delete menuItemText; } } void deleteAll(QList<SymbianMenuItem*> *items) { while (!items->isEmpty()) { SymbianMenuItem* temp = items->takeFirst(); deleteAll(&temp->children); delete temp; } } static void setSoftkeys() { CEikButtonGroupContainer* cba = CEikonEnv::Static()->AppUiFactory()->Cba(); if (cba){ if (menuExists()) cba->SetCommandSetL(R_AVKON_SOFTKEYS_OPTIONS_EXIT); else cba->SetCommandSetL(R_AVKON_SOFTKEYS_EXIT); } } static void rebuildMenu() { QMenuBarPrivate *mb = 0; setSoftkeys(); QWidget *w = qApp->activeWindow(); if (w) { mb = menubars()->value(w); qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM; deleteAll( &symbianMenus ); if (!mb) return; mb->symbian_menubar->rebuild(); } } Q_GUI_EXPORT void qt_symbian_show_toplevel( CEikMenuPane* menuPane) { if (!menuExists()) return; rebuildMenu(); for (int i = 0; i < symbianMenus.count(); ++i) menuPane->AddMenuItemL(symbianMenus.at(i)->menuItemData); } Q_GUI_EXPORT void qt_symbian_show_submenu( CEikMenuPane* menuPane, int id) { SymbianMenuItem* menu = qt_symbian_find_menu(id, symbianMenus); if (menu) { for (int i = 0; i < menu->children.count(); ++i) menuPane->AddMenuItemL(menu->children.at(i)->menuItemData); } } void QMenu::symbianCommands(int command) { Q_D(QMenu); d->symbianCommands(command); } void QMenuBar::symbianCommands(int command) { int size = nativeMenuBars.size(); for (int i = 0; i < nativeMenuBars.size(); ++i) { bool result = nativeMenuBars.at(i)->d_func()->symbianCommands(command); if (result) return; } } bool QMenuBarPrivate::symbianCommands(int command) { SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus); if (!menu) return false; emit q_func()->triggered(menu->action); menu->action->activate(QAction::Trigger); return true; } bool QMenuPrivate::symbianCommands(int command) { SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus); if (!menu) return false; emit q_func()->triggered(menu->action); menu->action->activate(QAction::Trigger); return true; } void QMenuBarPrivate::symbianCreateMenuBar(QWidget *parent) { Q_Q(QMenuBar); if (parent && parent->isWindow()){ menubars()->insert(q->window(), this); symbian_menubar = new QSymbianMenuBarPrivate(this); nativeMenuBars.append(q); } } void QMenuBarPrivate::symbianDestroyMenuBar() { Q_Q(QMenuBar); int index = nativeMenuBars.indexOf(q); nativeMenuBars.removeAt(index); menubars()->remove(q->window()); rebuildMenu(); if (symbian_menubar) delete symbian_menubar; symbian_menubar = 0; } QMenuBarPrivate::QSymbianMenuBarPrivate::QSymbianMenuBarPrivate(QMenuBarPrivate *menubar) { d = menubar; } QMenuBarPrivate::QSymbianMenuBarPrivate::~QSymbianMenuBarPrivate() { deleteAll( &symbianMenus ); symbianMenus.clear(); d = 0; rebuild(); } QMenuPrivate::QSymbianMenuPrivate::QSymbianMenuPrivate() { } QMenuPrivate::QSymbianMenuPrivate::~QSymbianMenuPrivate() { } void QMenuPrivate::QSymbianMenuPrivate::addAction(QAction *a, QSymbianMenuAction *before) { QSymbianMenuAction *action = new QSymbianMenuAction; action->action = a; action->command = qt_symbian_menu_static_cmd_id++; addAction(action, before); } void QMenuPrivate::QSymbianMenuPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before) { if (!action) return; int before_index = actionItems.indexOf(before); if (before_index < 0) { before = 0; before_index = actionItems.size(); } actionItems.insert(before_index, action); } void QMenuPrivate::QSymbianMenuPrivate::syncAction(QSymbianMenuAction *) { rebuild(); } void QMenuPrivate::QSymbianMenuPrivate::removeAction(QSymbianMenuAction *action) { actionItems.removeAll(action); delete action; action = 0; rebuild(); } void QMenuPrivate::QSymbianMenuPrivate::rebuild(bool) { } void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QAction *a, QSymbianMenuAction *before) { QSymbianMenuAction *action = new QSymbianMenuAction; action->action = a; action->command = qt_symbian_menu_static_cmd_id++; addAction(action, before); } void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before) { if (!action) return; int before_index = actionItems.indexOf(before); if (before_index < 0) { before = 0; before_index = actionItems.size(); } actionItems.insert(before_index, action); } void QMenuBarPrivate::QSymbianMenuBarPrivate::syncAction(QSymbianMenuAction*) { rebuild(); } void QMenuBarPrivate::QSymbianMenuBarPrivate::removeAction(QSymbianMenuAction *action) { actionItems.removeAll(action); delete action; rebuild(); } void QMenuBarPrivate::QSymbianMenuBarPrivate::rebuild() { setSoftkeys(); qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM; deleteAll( &symbianMenus ); if (!d) return; for (int i = 0; i < d->actions.size(); ++i) { QSymbianMenuAction *symbianActionTopLevel = new QSymbianMenuAction; symbianActionTopLevel->action = d->actions.at(i); symbianActionTopLevel->parent = 0; symbianActionTopLevel->command = qt_symbian_menu_static_cmd_id++; qt_symbian_insert_action(symbianActionTopLevel, &symbianMenus); } } #endif //QT_NO_MENUBAR <|endoftext|>
<commit_before>/* This file is part of qjson * * Copyright (C) 2009 Till Adam <adam@kde.org> * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "qobjecthelper.h" #include <QtCore/QMetaObject> #include <QtCore/QMetaProperty> #include <QtCore/QObject> using namespace QJson; class QObjectHelper::QObjectHelperPrivate { }; QObjectHelper::QObjectHelper() : d (new QObjectHelperPrivate) { } QObjectHelper::~QObjectHelper() { delete d; } QVariantMap QObjectHelper::qobject2qvariant( const QObject* object, const QStringList& ignoredProperties) { QVariantMap result; const QMetaObject *metaobject = object->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); if (ignoredProperties.contains(QLatin1String(name)) || (!metaproperty.isReadable())) continue; QVariant value = object->property(name); result[QLatin1String(name)] = value; } return result; } void QObjectHelper::qvariant2qobject(const QVariantMap& variant, QObject* object) { const QMetaObject *metaobject = object->metaObject(); QVariantMap::const_iterator iter; for (iter = variant.constBegin(); iter != variant.constEnd(); iter++) { int pIdx = metaobject->indexOfProperty( iter.key().toAscii() ); if ( pIdx < 0 ) { continue; } QMetaProperty metaproperty = metaobject->property( pIdx ); QVariant::Type type = metaproperty.type(); QVariant v( iter.value() ); if ( v.canConvert( type ) ) { v.convert( type ); metaproperty.write( object, v ); } } } <commit_msg>Use prefix increment for faster processing<commit_after>/* This file is part of qjson * * Copyright (C) 2009 Till Adam <adam@kde.org> * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "qobjecthelper.h" #include <QtCore/QMetaObject> #include <QtCore/QMetaProperty> #include <QtCore/QObject> using namespace QJson; class QObjectHelper::QObjectHelperPrivate { }; QObjectHelper::QObjectHelper() : d (new QObjectHelperPrivate) { } QObjectHelper::~QObjectHelper() { delete d; } QVariantMap QObjectHelper::qobject2qvariant( const QObject* object, const QStringList& ignoredProperties) { QVariantMap result; const QMetaObject *metaobject = object->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); if (ignoredProperties.contains(QLatin1String(name)) || (!metaproperty.isReadable())) continue; QVariant value = object->property(name); result[QLatin1String(name)] = value; } return result; } void QObjectHelper::qvariant2qobject(const QVariantMap& variant, QObject* object) { const QMetaObject *metaobject = object->metaObject(); QVariantMap::const_iterator iter; for (iter = variant.constBegin(); iter != variant.constEnd(); ++iter) { int pIdx = metaobject->indexOfProperty( iter.key().toAscii() ); if ( pIdx < 0 ) { continue; } QMetaProperty metaproperty = metaobject->property( pIdx ); QVariant::Type type = metaproperty.type(); QVariant v( iter.value() ); if ( v.canConvert( type ) ) { v.convert( type ); metaproperty.write( object, v ); } } } <|endoftext|>
<commit_before>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5cpp. // // 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 ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Author: Eugen Wintersberger <eugen.wintersberger@desy.de> // Created on: Sep 14, 2017 // #pragma once #include <h5cpp/datatype/datatype.hpp> #include <h5cpp/dataspace/dataspace.hpp> #include <h5cpp/datatype/factory.hpp> #include <h5cpp/dataspace/type_trait.hpp> #include <h5cpp/property/dataset_transfer.hpp> #include <h5cpp/core/object_handle.hpp> #include <h5cpp/core/windows.hpp> #include <h5cpp/core/types.hpp> #include <h5cpp/node/link.hpp> #include <h5cpp/error/error.hpp> #include <initializer_list> namespace hdf5 { namespace attribute { class DLL_EXPORT Attribute { public: //! //! \brief constructor //! //! \param handle rvalue reference to the attributes handle //! Attribute(ObjectHandle &&handle,const node::Link &parent_link); //! //! \brief default constructor //! //! Uses default compiler implementation. //! Attribute() = default; //! //! \brief copy assignment operator //! //! Uses default compiler implementation. //! Attribute(const Attribute &) = default; //! //! \brief return the data type of the attribute //! //! Returns a copy of the datatype used to create the attribute. //! datatype::Datatype datatype() const; //! //! \brief return the dataspace of the attribute //! //! Returns the dataspace used to create the attribute. //! dataspace::Dataspace dataspace() const; //! //! \brief return the name of the attribute //! std::string name() const; //! //! \brief check if object is valid //! bool is_valid() const; //! //! @brief close the attribute //! //! This method will close the attribute and leave it in an invalid state. //! A subsequent call to is_valid should return false. The parent //! link remains valid though. //! void close(); //! //! @brief conversion operator to hid_t //! operator hid_t() const { return static_cast<hid_t>(handle_); } //! //! @brief get the parent ndoe //! //! Return a reference to the node to which the attribute is attached. //! const node::Link &parent_link() const noexcept; //! //! \brief write data to attribute //! //! Write data to disk. This is the simplest form of writting //! datat to disk. Its only argument is a reference to the object //! holding the data which should be written. //! //! \throws std::runtime_error in case of a failure //! //! \tparam T data type to write to disk //! \param data reference to the datas instance //! template<typename T> void write(const T& data) const; //! //! \brief write string literal to disk //! //! This is used whenever a string literal must be //! written to disk. //! //! \code //! attribute::Attribute a = dataset.attributes.create<std::string>("note"); //! a.write("a short text"); //! \endcode //! //! You should be aware that this currently only works if the //! string type used for the attribute is a variable length string. //! //! \throws std::runtime_error in case of a failure //! void write(const char *data) const; //! //! \brief write from initializer list //! //! This method is used if the data to write is provided via //! an initializer list. //! //! \code //! Attribute a = dataset.attributes.create<int>("index_list",{4}); //! a.write({56,23,4,12}); //! \endcode //! //! Internaly this method stores the content of the list to an instance //! of std::vector<T> which is then written to the attribute. //! //! \tparam T type of the list elements //! \param list reference to the initializer list //! template<typename T> void write(const std::initializer_list<T> &list) const { write(std::vector<T>{list}); } //! //! \brief write data to disk //! //! Write data to disk however we can pass a custom memory type //! to this method. This is particularly useful in the case of //! string types where the HDF5 datatype cannot be determined //! uniquely from a C++ type. //! //! \code //! String fixed_type = String::fixed(20); //! Attribute a = dataset.attributes.create("note",fixed_type,Scalar()); //! //! //we have to pass the type here explicitely otherwise the library //! //would take std::string as a variable length string and HDF5 //! //considers variable and fixed length strings as incompatible. //! std::string data = "hello"; //! a.write(data,fixed_type); //! \endcode //! //! \throws std::runtime_error in case of an error //! \tparam T type of input data //! \param data refernce to input data //! \param mem_type HDF5 memory type of the input data //! template<typename T> void write(const T& data,const datatype::Datatype &mem_type) const; void write(const char *data,const datatype::Datatype &mem_type) const; template<typename T> void read(T &data) const; template<typename T> void read(T &data,const datatype::Datatype &mem_type) const; private: ObjectHandle handle_; node::Link parent_link_; template<typename T> void write_fixed_length_string(const T &data, const datatype::Datatype &mem_type) const { using Trait = FixedLengthStringTrait<T>; using SpaceTrait = hdf5::dataspace::TypeTrait<T>; auto buffer = Trait::to_buffer(data,mem_type,SpaceTrait::create(data)); if(H5Awrite(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to write data to attribute!"); } } template<typename T> void write_variable_length_string(const T &data, const datatype::Datatype &mem_type) const { using Trait = VarLengthStringTrait<T>; auto buffer = Trait::to_buffer(data); if(H5Awrite(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to write data to attribute!"); } } template<typename T> void write_contiguous_data(const T &data, const datatype::Datatype &mem_type) const { const void *ptr = dataspace::cptr(data); if(H5Awrite(static_cast<hid_t>(handle_),static_cast<hid_t>(mem_type),ptr)<0) { error::Singleton::instance().throw_with_stack("Failure to write data to attribute!"); } } template<typename T> void read_fixed_length_string(T &data, const datatype::Datatype &mem_type) const { using Trait = FixedLengthStringTrait<T>; using SpaceTrait = hdf5::dataspace::TypeTrait<T>; auto buffer = Trait::BufferType::create(mem_type,SpaceTrait::create(data)); if(H5Aread(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to read data from attribute!"); } data = Trait::from_buffer(buffer,mem_type,SpaceTrait::create(data)); } template<typename T> void read_variable_length_string(T &data, const datatype::Datatype &mem_type) const { using Trait = VarLengthStringTrait<T>; typename Trait::BufferType buffer(dataspace().size()); if(H5Aread(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to read data from attribute!"); } Trait::from_buffer(buffer,data); if(H5Dvlen_reclaim(static_cast<hid_t>(mem_type), static_cast<hid_t>(dataspace()), static_cast<hid_t>(property::DatasetTransferList()), buffer.data())<0) { std::stringstream ss; ss<<"Failure to reclaim buffer for variable length string" <<" string read on attribute!"; error::Singleton::instance().throw_with_stack(ss.str()); } } template<typename T> void read_contiguous_data(T &data, const datatype::Datatype &mem_type) const { void *ptr = dataspace::ptr(data); if(H5Aread(static_cast<hid_t>(handle_),static_cast<hid_t>(mem_type),ptr)<0) { error::Singleton::instance().throw_with_stack("Failure to read data from attribute!"); } } void check_size(const dataspace::Dataspace &mem_space, const dataspace::Dataspace &file_space, const std::string &operation) const; }; template<typename T> void Attribute::write(const T &data,const datatype::Datatype &mem_type) const { datatype::Datatype file_type = datatype(); check_size(dataspace::create(data),dataspace(),"write"); if(file_type.get_class()==datatype::Class::STRING) { datatype::String string_type(file_type); if(string_type.is_variable_length()) { write_variable_length_string(data,mem_type); } else { write_fixed_length_string(data,mem_type); } } else { write_contiguous_data(data,mem_type); } } template<typename T> void Attribute::write(const T &data) const { auto mem_type = datatype::create<T>(data); write(data,mem_type); } template<typename T> void Attribute::read(T &data) const { // auto mem_type = datatype(); auto mem_type = datatype::create<T>(data); read(data,mem_type); } template<typename T> void Attribute::read(T &data,const datatype::Datatype &mem_type) const { datatype::Datatype file_type = datatype(); check_size(dataspace::create(data),dataspace(),"read"); if(file_type.get_class()==datatype::Class::STRING) { datatype::String string_type(file_type); if(string_type.is_variable_length()) { read_variable_length_string(data,mem_type); } else { read_fixed_length_string(data,mem_type); } } else { read_contiguous_data(data,mem_type); } } } // namespace attribute } // namespace hdf5 <commit_msg>add fix<commit_after>// // (c) Copyright 2017 DESY,ESS // // This file is part of h5cpp. // // 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 ofMERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor // Boston, MA 02110-1301 USA // =========================================================================== // // Authors: // Eugen Wintersberger <eugen.wintersberger@desy.de> // Jan Kotanski <jan.kotanski@desy.de> // Created on: Sep 14, 2017 // #pragma once #include <h5cpp/datatype/datatype.hpp> #include <h5cpp/dataspace/dataspace.hpp> #include <h5cpp/datatype/factory.hpp> #include <h5cpp/dataspace/type_trait.hpp> #include <h5cpp/property/dataset_transfer.hpp> #include <h5cpp/core/object_handle.hpp> #include <h5cpp/core/windows.hpp> #include <h5cpp/core/types.hpp> #include <h5cpp/node/link.hpp> #include <h5cpp/error/error.hpp> #include <initializer_list> namespace hdf5 { namespace attribute { class DLL_EXPORT Attribute { public: //! //! \brief constructor //! //! \param handle rvalue reference to the attributes handle //! Attribute(ObjectHandle &&handle,const node::Link &parent_link); //! //! \brief default constructor //! //! Uses default compiler implementation. //! Attribute() = default; //! //! \brief copy assignment operator //! //! Uses default compiler implementation. //! Attribute(const Attribute &) = default; //! //! \brief return the data type of the attribute //! //! Returns a copy of the datatype used to create the attribute. //! datatype::Datatype datatype() const; //! //! \brief return the dataspace of the attribute //! //! Returns the dataspace used to create the attribute. //! dataspace::Dataspace dataspace() const; //! //! \brief return the name of the attribute //! std::string name() const; //! //! \brief check if object is valid //! bool is_valid() const; //! //! @brief close the attribute //! //! This method will close the attribute and leave it in an invalid state. //! A subsequent call to is_valid should return false. The parent //! link remains valid though. //! void close(); //! //! @brief conversion operator to hid_t //! operator hid_t() const { return static_cast<hid_t>(handle_); } //! //! @brief get the parent ndoe //! //! Return a reference to the node to which the attribute is attached. //! const node::Link &parent_link() const noexcept; //! //! \brief write data to attribute //! //! Write data to disk. This is the simplest form of writting //! datat to disk. Its only argument is a reference to the object //! holding the data which should be written. //! //! \throws std::runtime_error in case of a failure //! //! \tparam T data type to write to disk //! \param data reference to the datas instance //! template<typename T> void write(const T& data) const; //! //! \brief write string literal to disk //! //! This is used whenever a string literal must be //! written to disk. //! //! \code //! attribute::Attribute a = dataset.attributes.create<std::string>("note"); //! a.write("a short text"); //! \endcode //! //! You should be aware that this currently only works if the //! string type used for the attribute is a variable length string. //! //! \throws std::runtime_error in case of a failure //! void write(const char *data) const; //! //! \brief write from initializer list //! //! This method is used if the data to write is provided via //! an initializer list. //! //! \code //! Attribute a = dataset.attributes.create<int>("index_list",{4}); //! a.write({56,23,4,12}); //! \endcode //! //! Internaly this method stores the content of the list to an instance //! of std::vector<T> which is then written to the attribute. //! //! \tparam T type of the list elements //! \param list reference to the initializer list //! template<typename T> void write(const std::initializer_list<T> &list) const { write(std::vector<T>{list}); } //! //! \brief write data to disk //! //! Write data to disk however we can pass a custom memory type //! to this method. This is particularly useful in the case of //! string types where the HDF5 datatype cannot be determined //! uniquely from a C++ type. //! //! \code //! String fixed_type = String::fixed(20); //! Attribute a = dataset.attributes.create("note",fixed_type,Scalar()); //! //! //we have to pass the type here explicitely otherwise the library //! //would take std::string as a variable length string and HDF5 //! //considers variable and fixed length strings as incompatible. //! std::string data = "hello"; //! a.write(data,fixed_type); //! \endcode //! //! \throws std::runtime_error in case of an error //! \tparam T type of input data //! \param data refernce to input data //! \param mem_type HDF5 memory type of the input data //! template<typename T> void write(const T& data,const datatype::Datatype &mem_type) const; void write(const char *data,const datatype::Datatype &mem_type) const; template<typename T> void read(T &data) const; template<typename T> void read(T &data,const datatype::Datatype &mem_type) const; private: ObjectHandle handle_; node::Link parent_link_; template<typename T> void write_fixed_length_string(const T &data, const datatype::Datatype &mem_type) const { using Trait = FixedLengthStringTrait<T>; using SpaceTrait = hdf5::dataspace::TypeTrait<T>; auto buffer = Trait::to_buffer(data,mem_type,SpaceTrait::create(data)); if(H5Awrite(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to write data to attribute!"); } } template<typename T> void write_variable_length_string(const T &data, const datatype::Datatype &mem_type) const { using Trait = VarLengthStringTrait<T>; auto buffer = Trait::to_buffer(data); if(H5Awrite(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to write data to attribute!"); } } template<typename T> void write_contiguous_data(const T &data, const datatype::Datatype &mem_type) const { const void *ptr = dataspace::cptr(data); if(H5Awrite(static_cast<hid_t>(handle_),static_cast<hid_t>(mem_type),ptr)<0) { error::Singleton::instance().throw_with_stack("Failure to write data to attribute!"); } } template<typename T> void read_fixed_length_string(T &data, const datatype::Datatype &mem_type) const { using Trait = FixedLengthStringTrait<T>; using SpaceTrait = hdf5::dataspace::TypeTrait<T>; auto buffer = Trait::BufferType::create(mem_type,SpaceTrait::create(data)); if(H5Aread(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to read data from attribute!"); } data = Trait::from_buffer(buffer,mem_type,SpaceTrait::create(data)); } template<typename T> void read_variable_length_string(T &data, const datatype::Datatype &mem_type) const { using Trait = VarLengthStringTrait<T>; typename Trait::BufferType buffer(dataspace().size()); if(H5Aread(static_cast<hid_t>(handle_), static_cast<hid_t>(mem_type), buffer.data())<0) { error::Singleton::instance().throw_with_stack("Failure to read data from attribute!"); } Trait::from_buffer(buffer,data); if(H5Dvlen_reclaim(static_cast<hid_t>(mem_type), static_cast<hid_t>(dataspace()), static_cast<hid_t>(property::DatasetTransferList()), buffer.data())<0) { std::stringstream ss; ss<<"Failure to reclaim buffer for variable length string" <<" string read on attribute!"; error::Singleton::instance().throw_with_stack(ss.str()); } } template<typename T> void read_contiguous_data(T &data, const datatype::Datatype &mem_type) const { void *ptr = dataspace::ptr(data); if(H5Aread(static_cast<hid_t>(handle_),static_cast<hid_t>(mem_type),ptr)<0) { error::Singleton::instance().throw_with_stack("Failure to read data from attribute!"); } } void check_size(const dataspace::Dataspace &mem_space, const dataspace::Dataspace &file_space, const std::string &operation) const; }; template<typename T> void Attribute::write(const T &data,const datatype::Datatype &mem_type) const { datatype::Datatype file_type = datatype(); check_size(dataspace::create(data),dataspace(),"write"); if(file_type.get_class()==datatype::Class::STRING) { datatype::String string_type(file_type); if(string_type.is_variable_length()) { write_variable_length_string(data,mem_type); } else { write_fixed_length_string(data,mem_type); } } else { write_contiguous_data(data,mem_type); } } template<typename T> void Attribute::write(const T &data) const { auto mem_type = datatype::create<T>(data); write(data,mem_type); } template<typename T> void Attribute::read(T &data) const { auto mem_type = datatype(); read(data,mem_type); } template<typename T> void Attribute::read(T &data,const datatype::Datatype &mem_type) const { datatype::Datatype file_type = datatype(); check_size(dataspace::create(data),dataspace(),"read"); if(file_type.get_class()==datatype::Class::STRING) { datatype::String string_type(file_type); if(string_type.is_variable_length()) { read_variable_length_string(data,mem_type); } else { read_fixed_length_string(data,mem_type); } } else { read_contiguous_data(data,mem_type); } } } // namespace attribute } // namespace hdf5 <|endoftext|>
<commit_before>/** ****************************************************************************** * @file main.c * @author Ac6 * @version V1.0 * @date 01-December-2013 * @brief Default main function. ****************************************************************************** */ #include "stm32f4xx_hal.h" #include "stm32f4xx_nucleo.h" #include "MPU6050.h" #include "LEDs.h" #include "Timer.h" using namespace flyhero; extern "C" void initialise_monitor_handles(void); MPU6050 *mpu = MPU6050::Instance(); extern "C" { void DMA1_Stream5_IRQHandler(void) { HAL_DMA_IRQHandler(mpu->Get_DMA_Rx_Handle()); } void EXTI1_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_1); } void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(mpu->Get_I2C_Handle()); } void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) { mpu->Data_Read_Callback(); } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { mpu->Data_Ready_Callback(); } void TIM5_IRQHandler(void) { TIM_HandleTypeDef *htim5 = Timer::Get_Handle(); // Channel 2 for HAL 1 ms tick if (__HAL_TIM_GET_ITSTATUS(htim5, TIM_IT_CC2) == SET) { __HAL_TIM_CLEAR_IT(htim5, TIM_IT_CC2); uint32_t val = __HAL_TIM_GetCounter(htim5); //if ((val - prev) >= 1000) { HAL_IncTick(); // Prepare next interrupt __HAL_TIM_SetCompare(htim5, TIM_CHANNEL_2, val + 1000); //prev = val; //} //else { // printf("should not happen\n"); //} } //HAL_TIM_IRQHandler(Timer::Get_Handle()); } } int main(void) { HAL_Init(); initialise_monitor_handles(); LEDs::Init(); HAL_Delay(1000); if (mpu->Init() || mpu->Calibrate()) { while (true) { LEDs::Toggle(LEDs::Green); HAL_Delay(500); } } printf("init complete\n"); MPU6050::Raw_Data gyro, accel; uint32_t ppos = 0; double p[100][6]; mpu->ready = true; uint32_t ticks = Timer::Get_Tick_Count(); float roll, pitch, yaw; while (true) { if (mpu->Data_Ready() && Timer::Get_Tick_Count() - ticks >= 1000000) { if (mpu->Start_Read_Raw() != HAL_OK) { printf("a"); } ticks = Timer::Get_Tick_Count(); } if (mpu->Data_Read()) { //mpu->Complete_Read_Raw(&gyro, &accel); //printf("%d %d %d %d %d %d\n", accel.x, accel.y, accel.z, gyro.x, gyro.y, gyro.z); mpu->Get_Euler(&roll, &pitch, &yaw); printf("%f %f %f\n", roll, pitch, yaw); } } } <commit_msg>Import logger files into the IMU project<commit_after>/** ****************************************************************************** * @file main.c * @author Ac6 * @version V1.0 * @date 01-December-2013 * @brief Default main function. ****************************************************************************** */ #include "stm32f4xx_hal.h" #include "stm32f4xx_nucleo.h" #include "MPU6050.h" #include "LEDs.h" #include "Timer.h" #include "Logger.h" using namespace flyhero; extern "C" void initialise_monitor_handles(void); MPU6050 *mpu = MPU6050::Instance(); Logger *logger = Logger::Instance(); extern "C" { void DMA1_Stream5_IRQHandler(void) { HAL_DMA_IRQHandler(mpu->Get_DMA_Rx_Handle()); } void EXTI1_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_1); } void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(mpu->Get_I2C_Handle()); } void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) { mpu->Data_Read_Callback(); } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { mpu->Data_Ready_Callback(); } void TIM5_IRQHandler(void) { TIM_HandleTypeDef *htim5 = Timer::Get_Handle(); // Channel 2 for HAL 1 ms tick if (__HAL_TIM_GET_ITSTATUS(htim5, TIM_IT_CC2) == SET) { __HAL_TIM_CLEAR_IT(htim5, TIM_IT_CC2); uint32_t val = __HAL_TIM_GetCounter(htim5); //if ((val - prev) >= 1000) { HAL_IncTick(); // Prepare next interrupt __HAL_TIM_SetCompare(htim5, TIM_CHANNEL_2, val + 1000); //prev = val; //} //else { // printf("should not happen\n"); //} } //HAL_TIM_IRQHandler(Timer::Get_Handle()); } extern "C" void DMA1_Stream7_IRQHandler(void) { HAL_DMA_IRQHandler(&logger->hdma_uart5_tx); } extern "C" void UART5_IRQHandler(void) { HAL_UART_IRQHandler(&logger->huart); } } int main(void) { HAL_Init(); initialise_monitor_handles(); LEDs::Init(); logger->Init(); HAL_Delay(1000); if (mpu->Init() || mpu->Calibrate()) { while (true) { LEDs::Toggle(LEDs::Green); HAL_Delay(500); } } printf("init complete\n"); MPU6050::Raw_Data gyro, accel; uint32_t ppos = 0; double p[100][6]; mpu->ready = true; uint32_t ticks = Timer::Get_Tick_Count(); float roll, pitch, yaw; while (true) { if (mpu->Data_Ready() && Timer::Get_Tick_Count() - ticks >= 1000000) { if (mpu->Start_Read_Raw() != HAL_OK) { printf("a"); } ticks = Timer::Get_Tick_Count(); } if (mpu->Data_Read()) { mpu->Complete_Read_Raw(&gyro, &accel); uint8_t tmp[15]; tmp[0] = accel.x & 0xFF; tmp[1] = accel.x >> 8; tmp[2] = accel.y & 0xFF; tmp[3] = accel.y >> 8; tmp[4] = accel.z & 0xFF; tmp[5] = accel.z >> 8; tmp[6] = gyro.x & 0xFF; tmp[7] = gyro.x >> 8; tmp[8] = gyro.y & 0xFF; tmp[9] = gyro.y >> 8; tmp[10] = gyro.z & 0xFF; tmp[11] = gyro.z >> 8; tmp[12] = 0; tmp[13] = 0; tmp[14] = 0; for (uint8_t i = 0; i <= 13; i++) tmp[14] ^= tmp[i]; logger->Print(tmp, 15); //printf("%d %d %d %d %d %d\n", accel.x, accel.y, accel.z, gyro.x, gyro.y, gyro.z); //mpu->Get_Euler(&roll, &pitch, &yaw); //printf("%f %f %f\n", roll, pitch, yaw); } } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletview.h" #include "addressbookpage.h" #include "askpassphrasedialog.h" #include "bitcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "overviewpage.h" #include "receivecoinsdialog.h" #include "sendcoinsdialog.h" #include "sendmpdialog.h" #include "lookupspdialog.h" #include "metadexdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "balancesview.h" #include "walletmodel.h" #include "orderhistorydialog.h" #include "ui_interface.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> #include <QDebug> #include <QTableView> #include <QDialog> #include <QHeaderView> WalletView::WalletView(QWidget *parent): QStackedWidget(parent), clientModel(0), walletModel(0) { // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); balancesPage = new QWidget(this); // balances page QVBoxLayout *bvbox = new QVBoxLayout(); QHBoxLayout *bhbox_buttons = new QHBoxLayout(); balancesView = new BalancesView(this); bvbox->addWidget(balancesView); QPushButton *bexportButton = new QPushButton(tr("&Export"), this); bexportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac bexportButton->setIcon(QIcon(":/icons/export")); #endif bhbox_buttons->addStretch(); bhbox_buttons->addWidget(bexportButton); bvbox->addLayout(bhbox_buttons); balancesPage->setLayout(bvbox); // transactions page // bitcoin transactions in second tab, MP transactions in first //masterprotocol mpTXTab = new QWidget(); //bitcoin bitcoinTXTab = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac exportButton->setIcon(QIcon(":/icons/export")); #endif hbox_buttons->addStretch(); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); bitcoinTXTab->setLayout(vbox); transactionsPage = new QWidget(this); QVBoxLayout *txvbox = new QVBoxLayout(); QTabWidget *txTabHolder = new QTabWidget(); txTabHolder->addTab(mpTXTab,tr("Master Protocol")); txTabHolder->addTab(bitcoinTXTab,tr("Bitcoin")); txvbox->addWidget(txTabHolder); transactionsPage->setLayout(txvbox); // receive page receiveCoinsPage = new ReceiveCoinsDialog(); // sending page sendCoinsPage = new QWidget(this); QVBoxLayout *svbox = new QVBoxLayout(); sendCoinsTab = new SendCoinsDialog(); sendMPTab = new SendMPDialog(); QTabWidget *tabHolder = new QTabWidget(); tabHolder->addTab(sendMPTab,tr("Master Protocol")); tabHolder->addTab(sendCoinsTab,tr("Bitcoin")); svbox->addWidget(tabHolder); sendCoinsPage->setLayout(svbox); // exchange page exchangePage = new QWidget(this); QVBoxLayout *exvbox = new QVBoxLayout(); metaDExTab = new MetaDExDialog(); QTabWidget *exTabHolder = new QTabWidget(); orderHistoryTab = new OrderHistoryDialog; exTabHolder->addTab(new QWidget(),tr("Trade Bitcoin/Mastercoin")); exTabHolder->addTab(metaDExTab,tr("Trade Mastercoin/Smart Properties")); exTabHolder->addTab(orderHistoryTab,tr("Open Orders")); exvbox->addWidget(exTabHolder); exchangePage->setLayout(exvbox); // smart property page smartPropertyPage = new QWidget(this); QVBoxLayout *spvbox = new QVBoxLayout(); spLookupTab = new LookupSPDialog(); QTabWidget *spTabHolder = new QTabWidget(); spTabHolder->addTab(spLookupTab,tr("Lookup Property")); spTabHolder->addTab(new QWidget(),tr("Crowdsale Participation")); // spTabHolder->addTab(new QWidget(),tr("Property Issuance")); // spTabHolder->addTab(new QWidget(),tr("Revoke or Grant Tokens")); spvbox->addWidget(spTabHolder); smartPropertyPage->setLayout(spvbox); // toolbox page toolboxPage = new QWidget(this); // add pages addWidget(overviewPage); addWidget(balancesPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); addWidget(exchangePage); addWidget(smartPropertyPage); addWidget(toolboxPage); // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); } WalletView::~WalletView() { } void WalletView::setBitcoinGUI(BitcoinGUI *gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,qint64,QString,QString)), gui, SLOT(incomingTransaction(QString,int,qint64,QString,QString))); } } void WalletView::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); } void WalletView::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); receiveCoinsPage->setModel(walletModel); sendCoinsTab->setModel(walletModel); sendMPTab->setModel(walletModel); balancesView->setModel(walletModel); metaDExTab->setModel(walletModel); if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(processNewTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString(); emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); } void WalletView::gotoBalancesPage() { setCurrentWidget(balancesPage); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoExchangePage() { setCurrentWidget(exchangePage); } void WalletView::gotoToolboxPage() { setCurrentWidget(toolboxPage); } void WalletView::gotoSmartPropertyPage() { setCurrentWidget(smartPropertyPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsTab->setAddress(addr); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsTab->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { emit encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; if (!walletModel->backupWallet(filename)) { emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void WalletView::unlockWallet() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::usedSendingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::usedReceivingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } <commit_msg>Correct tabs<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletview.h" #include "addressbookpage.h" #include "askpassphrasedialog.h" #include "bitcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "overviewpage.h" #include "receivecoinsdialog.h" #include "sendcoinsdialog.h" #include "sendmpdialog.h" #include "lookupspdialog.h" #include "metadexdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "balancesview.h" #include "walletmodel.h" #include "orderhistorydialog.h" #include "ui_interface.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> #include <QDebug> #include <QTableView> #include <QDialog> #include <QHeaderView> WalletView::WalletView(QWidget *parent): QStackedWidget(parent), clientModel(0), walletModel(0) { // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); balancesPage = new QWidget(this); // balances page QVBoxLayout *bvbox = new QVBoxLayout(); QHBoxLayout *bhbox_buttons = new QHBoxLayout(); balancesView = new BalancesView(this); bvbox->addWidget(balancesView); QPushButton *bexportButton = new QPushButton(tr("&Export"), this); bexportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac bexportButton->setIcon(QIcon(":/icons/export")); #endif bhbox_buttons->addStretch(); bhbox_buttons->addWidget(bexportButton); bvbox->addLayout(bhbox_buttons); balancesPage->setLayout(bvbox); // transactions page // bitcoin transactions in second tab, MP transactions in first //masterprotocol mpTXTab = new QWidget(); //bitcoin bitcoinTXTab = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac exportButton->setIcon(QIcon(":/icons/export")); #endif hbox_buttons->addStretch(); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); bitcoinTXTab->setLayout(vbox); transactionsPage = new QWidget(this); QVBoxLayout *txvbox = new QVBoxLayout(); QTabWidget *txTabHolder = new QTabWidget(); txTabHolder->addTab(mpTXTab,tr("Master Protocol")); txTabHolder->addTab(bitcoinTXTab,tr("Bitcoin")); txvbox->addWidget(txTabHolder); transactionsPage->setLayout(txvbox); // receive page receiveCoinsPage = new ReceiveCoinsDialog(); // sending page sendCoinsPage = new QWidget(this); QVBoxLayout *svbox = new QVBoxLayout(); sendCoinsTab = new SendCoinsDialog(); sendMPTab = new SendMPDialog(); QTabWidget *tabHolder = new QTabWidget(); tabHolder->addTab(sendMPTab,tr("Master Protocol")); tabHolder->addTab(sendCoinsTab,tr("Bitcoin")); svbox->addWidget(tabHolder); sendCoinsPage->setLayout(svbox); // exchange page exchangePage = new QWidget(this); QVBoxLayout *exvbox = new QVBoxLayout(); metaDExTab = new MetaDExDialog(); QTabWidget *exTabHolder = new QTabWidget(); orderHistoryTab = new OrderHistoryDialog; //exTabHolder->addTab(new QWidget(),tr("Trade Bitcoin/Mastercoin")); not yet implemented exTabHolder->addTab(metaDExTab,tr("Trade Mastercoin/Smart Properties")); exTabHolder->addTab(orderHistoryTab,tr("Order History")); exvbox->addWidget(exTabHolder); exchangePage->setLayout(exvbox); // smart property page smartPropertyPage = new QWidget(this); QVBoxLayout *spvbox = new QVBoxLayout(); spLookupTab = new LookupSPDialog(); QTabWidget *spTabHolder = new QTabWidget(); spTabHolder->addTab(spLookupTab,tr("Lookup Property")); spTabHolder->addTab(new QWidget(),tr("Crowdsale Participation")); // spTabHolder->addTab(new QWidget(),tr("Property Issuance")); // spTabHolder->addTab(new QWidget(),tr("Revoke or Grant Tokens")); spvbox->addWidget(spTabHolder); smartPropertyPage->setLayout(spvbox); // toolbox page toolboxPage = new QWidget(this); // add pages addWidget(overviewPage); addWidget(balancesPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); addWidget(exchangePage); addWidget(smartPropertyPage); addWidget(toolboxPage); // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); } WalletView::~WalletView() { } void WalletView::setBitcoinGUI(BitcoinGUI *gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,qint64,QString,QString)), gui, SLOT(incomingTransaction(QString,int,qint64,QString,QString))); } } void WalletView::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); } void WalletView::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); receiveCoinsPage->setModel(walletModel); sendCoinsTab->setModel(walletModel); sendMPTab->setModel(walletModel); balancesView->setModel(walletModel); metaDExTab->setModel(walletModel); if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(processNewTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString(); emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); } void WalletView::gotoBalancesPage() { setCurrentWidget(balancesPage); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoExchangePage() { setCurrentWidget(exchangePage); } void WalletView::gotoToolboxPage() { setCurrentWidget(toolboxPage); } void WalletView::gotoSmartPropertyPage() { setCurrentWidget(smartPropertyPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsTab->setAddress(addr); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsTab->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { emit encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; if (!walletModel->backupWallet(filename)) { emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void WalletView::unlockWallet() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::usedSendingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::usedReceivingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletview.h" #include "addressbookpage.h" #include "askpassphrasedialog.h" #include "bitcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "throneconfig.h" #include "optionsmodel.h" #include "overviewpage.h" #include "receivecoinsdialog.h" #include "sendcoinsdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "walletmodel.h" #include "ui_interface.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QLabel> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> WalletView::WalletView(QWidget *parent): QStackedWidget(parent), clientModel(0), walletModel(0) { // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac exportButton->setIcon(QIcon(":/icons/export")); #endif hbox_buttons->addStretch(); // Sum of selected transactions QLabel *transactionSumLabel = new QLabel(); // Label transactionSumLabel->setObjectName("transactionSumLabel"); // Label ID as CSS-reference transactionSumLabel->setText(tr("Selected amount:")); hbox_buttons->addWidget(transactionSumLabel); transactionSum = new QLabel(); // Amount transactionSum->setObjectName("transactionSum"); // Label ID as CSS-reference transactionSum->setMinimumSize(200, 8); transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse); hbox_buttons->addWidget(transactionSum); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); transactionsPage->setLayout(vbox); receiveCoinsPage = new ReceiveCoinsDialog(); sendCoinsPage = new SendCoinsDialog(); if (throneConfig.getCount() >= 0) { throneListPage = new ThroneList(); } addWidget(overviewPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); if (throneConfig.getCount() >= 0) { addWidget(throneListPage); } // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Update wallet with sum of selected transactions connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString))); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); } WalletView::~WalletView() { } void WalletView::setBitcoinGUI(BitcoinGUI *gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString))); } } void WalletView::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); sendCoinsPage->setClientModel(clientModel); if (throneConfig.getCount() >= 0) { throneListPage->setClientModel(clientModel); } } void WalletView::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); receiveCoinsPage->setModel(walletModel); sendCoinsPage->setModel(walletModel); if (throneConfig.getCount() >= 0) { throneListPage->setWalletModel(walletModel); } if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(processNewTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); if (!ttm || ttm->processingQueuedTransactions()) return; QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString(); emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsPage->setAddress(addr); } void WalletView::gotoThronePage() { if (throneConfig.getCount() >= 0) { setCurrentWidget(throneListPage); } } void BitcoinGUI::gotoMultisigTab() { // calls show() in showTab_SM() MultisigDialog *multisigDialog = new MultisigDialog(this); multisigDialog->setAttribute(Qt::WA_DeleteOnClose); multisigDialog->setModel(walletModel); multisigDialog->showTab(true); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsPage->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { emit encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; if (!walletModel->backupWallet(filename)) { emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void WalletView::unlockWallet() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) { AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::lockWallet() { if(!walletModel) return; walletModel->setWalletLocked(true); } void WalletView::usedSendingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::usedReceivingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } /** Update wallet with the sum of the selected transactions */ void WalletView::trxAmount(QString amount) { transactionSum->setText(amount); } <commit_msg>fix last commit<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletview.h" #include "addressbookpage.h" #include "askpassphrasedialog.h" #include "bitcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "throneconfig.h" #include "optionsmodel.h" #include "overviewpage.h" #include "receivecoinsdialog.h" #include "sendcoinsdialog.h" #include "signverifymessagedialog.h" #include "transactiontablemodel.h" #include "transactionview.h" #include "walletmodel.h" #include "ui_interface.h" #include <QAction> #include <QActionGroup> #include <QFileDialog> #include <QHBoxLayout> #include <QLabel> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> WalletView::WalletView(QWidget *parent): QStackedWidget(parent), clientModel(0), walletModel(0) { // Create tabs overviewPage = new OverviewPage(); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(this); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); #ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac exportButton->setIcon(QIcon(":/icons/export")); #endif hbox_buttons->addStretch(); // Sum of selected transactions QLabel *transactionSumLabel = new QLabel(); // Label transactionSumLabel->setObjectName("transactionSumLabel"); // Label ID as CSS-reference transactionSumLabel->setText(tr("Selected amount:")); hbox_buttons->addWidget(transactionSumLabel); transactionSum = new QLabel(); // Amount transactionSum->setObjectName("transactionSum"); // Label ID as CSS-reference transactionSum->setMinimumSize(200, 8); transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse); hbox_buttons->addWidget(transactionSum); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); transactionsPage->setLayout(vbox); receiveCoinsPage = new ReceiveCoinsDialog(); sendCoinsPage = new SendCoinsDialog(); if (throneConfig.getCount() >= 0) { throneListPage = new ThroneList(); } addWidget(overviewPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); if (throneConfig.getCount() >= 0) { addWidget(throneListPage); } // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); // Update wallet with sum of selected transactions connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString))); // Clicking on "Export" allows to export the transaction list connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked())); // Pass through messages from sendCoinsPage connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Pass through messages from transactionView connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); } WalletView::~WalletView() { } void WalletView::setBitcoinGUI(BitcoinGUI *gui) { if (gui) { // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage())); // Receive and report messages connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int))); // Pass through encryption status changed signals connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int))); // Pass through transaction notifications connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString))); } } void WalletView::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; overviewPage->setClientModel(clientModel); sendCoinsPage->setClientModel(clientModel); if (throneConfig.getCount() >= 0) { throneListPage->setClientModel(clientModel); } } void WalletView::setWalletModel(WalletModel *walletModel) { this->walletModel = walletModel; // Put transaction list in tabs transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); receiveCoinsPage->setModel(walletModel); sendCoinsPage->setModel(walletModel); if (throneConfig.getCount() >= 0) { throneListPage->setWalletModel(walletModel); } if (walletModel) { // Receive and pass through messages from wallet model connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int))); // Handle changes in encryption status connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int))); updateEncryptionStatus(); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(processNewTransaction(QModelIndex,int,int))); // Ask for passphrase if needed connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet())); // Show progress dialog connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); } } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!walletModel || !clientModel || clientModel->inInitialBlockDownload()) return; TransactionTableModel *ttm = walletModel->getTransactionTableModel(); if (!ttm || ttm->processingQueuedTransactions()) return; QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString(); emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsPage->setAddress(addr); } void WalletView::gotoThronePage() { if (throneConfig.getCount() >= 0) { setCurrentWidget(throneListPage); } } void WalletView::gotoMultisigTab() { // calls show() in showTab_SM() MultisigDialog *multisigDialog = new MultisigDialog(this); multisigDialog->setAttribute(Qt::WA_DeleteOnClose); multisigDialog->setModel(walletModel); multisigDialog->showTab(true); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsPage->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::updateEncryptionStatus() { emit encryptionStatusChanged(walletModel->getEncryptionStatus()); } void WalletView::encryptWallet(bool status) { if(!walletModel) return; AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this); dlg.setModel(walletModel); dlg.exec(); updateEncryptionStatus(); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), tr("Wallet Data (*.dat)"), NULL); if (filename.isEmpty()) return; if (!walletModel->backupWallet(filename)) { emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this); dlg.setModel(walletModel); dlg.exec(); } void WalletView::unlockWallet() { if(!walletModel) return; // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked || walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) { AskPassphraseDialog dlg(AskPassphraseDialog::UnlockAnonymize, this); dlg.setModel(walletModel); dlg.exec(); } } void WalletView::lockWallet() { if(!walletModel) return; walletModel->setWalletLocked(true); } void WalletView::usedSendingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::usedReceivingAddresses() { if(!walletModel) return; AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setModel(walletModel->getAddressTableModel()); dlg->show(); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } /** Update wallet with the sum of the selected transactions */ void WalletView::trxAmount(QString amount) { transactionSum->setText(amount); } <|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; MTL M; // 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(); */ // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str()); Secret=read_Secretfile(F.Secretfile,F); F.Ngal= Secret.size(); std::vector<int> count; count=count_galaxies(Secret); 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]);} //read the three input files MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); assign_priority_class(Targ); //establish priority classes std::vector <int> count_class(Targ.priority_list.size(),0); printf("Number in each priority class. The last two are SF and SS.\n"); for(int i;i<Targ.size();++i){ count_class[Targ[i].priority_class]+=1; } for(int i;i<Targ.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } 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 OP = read_plate_centers(F); Plates P; printf(" future plates %d\n",P.size()); F.ONplate=OP.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.ONplate).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 collect_galaxies_for_all(M,T,OP,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,OP,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.ONplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,OP,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list for (int j=0;j<F.ONplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ P.push_back(OP[j]); A.suborder.push_back(j); not_done=false; } } } F.Nplate=P.size(); printf(" Plates after screening %d \n",F.Nplate); //if(F.diagnose)diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // 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++) { improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.Nplate;++j){ int js=A.suborder[j]; A.next_plate=js; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(js,M,P,pp,F,A); } init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size()&&F.pass_intervals[i]<F.Nplate;++i){ printf(" before pass = %d at %d tiles\n",i,F.pass_intervals[i]); //display_results("doc/figs/",G,P,pp,F,A,true); //execute this phase (i) of survey //A.next_plate=F.pass_intervals[i]; for (int jj=F.pass_intervals[i]; jj<F.Nplate; jj++) { int j = A.suborder[A.next_plate]; printf(" next plate is %d \n",j); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF assign_unused(j,M,P,pp,F,A); //A.next_plate++; } //update target information for this interval //A.next_plate=F.pass_intervals[i]; for (int jj=F.pass_intervals[i]; jj<F.pass_intervals[i+1]&&jj<F.Nplate; jj++) { //int j = A.suborder[A.next_plate]; int js=A.suborder[jj]; // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=js-F.Analysis) update_plan_from_one_obs(Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n"); //A.next_plate++; } /* if(A.next_plate<F.Nplate){ 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); } */ if(F.diagnose)diagnostic(M,Secret,F,A); } // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.Nplate; j++){ write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.Nplate; j++){ fa_write(j,F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,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>new diagnostic<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; MTL M; // 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(); */ // Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF Gals Secret; printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str()); Secret=read_Secretfile(F.Secretfile,F); F.Ngal= Secret.size(); std::vector<int> count; count=count_galaxies(Secret); 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]);} //read the three input files MTL Targ=read_MTLfile(F.Targfile,F,0,0); MTL SStars=read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1); //combine the three input files M=Targ; printf(" M size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" M size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" M size %d \n",M.size()); assign_priority_class(Targ); //establish priority classes std::vector <int> count_class(Targ.priority_list.size(),0); printf("Number in each priority class. The last two are SF and SS.\n"); for(int i;i<Targ.size();++i){ count_class[Targ[i].priority_class]+=1; } for(int i;i<Targ.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } 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 OP = read_plate_centers(F); Plates P; printf(" future plates %d\n",P.size()); F.ONplate=OP.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.ONplate).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 collect_galaxies_for_all(M,T,OP,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,OP,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.ONplate, F.Ngal, F.Nfiber); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs simple_assign(M,OP,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list for (int j=0;j<F.ONplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ P.push_back(OP[j]); A.suborder.push_back(j); not_done=false; } } } F.Nplate=P.size(); printf(" Plates after screening %d \n",F.Nplate); //if(F.diagnose)diagnostic(M,G,F,A); //diagnostic for (int j=0;j<F.Nplate;++j){ for (int k=0;k<F.Nfiber;++k){ if(k%500==0){ int g=A.TF[A.suborder[j]][k]; if(g!=-1){ dpair test_projection=projection(g,j,M,P); if (test_projection.f>500. || test_projection.s>500.){ printf(" g %d j %d test_projection.f %f test_projection.s %f\n",g,j,test_projection.f,test_projection.s); } } } } } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // 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++) { improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); //try assigning SF and SS before real time assignment for (int j=0;j<F.Nplate;++j){ int js=A.suborder[j]; A.next_plate=js; assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(js,M,P,pp,F,A); } init_time_at(time,"# Begin real time assignment",t); //Execute plan, updating targets at intervals for(int i=0;i<F.pass_intervals.size()&&F.pass_intervals[i]<F.Nplate;++i){ printf(" before pass = %d at %d tiles\n",i,F.pass_intervals[i]); //display_results("doc/figs/",G,P,pp,F,A,true); //execute this phase (i) of survey //A.next_plate=F.pass_intervals[i]; for (int jj=F.pass_intervals[i]; jj<F.Nplate; jj++) { int j = A.suborder[A.next_plate]; printf(" next plate is %d \n",j); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF assign_unused(j,M,P,pp,F,A); //A.next_plate++; } //update target information for this interval //A.next_plate=F.pass_intervals[i]; for (int jj=F.pass_intervals[i]; jj<F.pass_intervals[i+1]&&jj<F.Nplate; jj++) { //int j = A.suborder[A.next_plate]; int js=A.suborder[jj]; // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=js-F.Analysis) update_plan_from_one_obs(Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n"); //A.next_plate++; } /* if(A.next_plate<F.Nplate){ 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); } */ if(F.diagnose)diagnostic(M,Secret,F,A); } // Results ------------------------------------------------------- if (F.PrintAscii) for (int j=0; j<F.Nplate; j++){ write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); } if (F.PrintFits) for (int j=0; j<F.Nplate; j++){ fa_write(j,F.outDir,M,P,pp,F,A); // Write output } display_results("doc/figs/",Secret,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) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Dacrs developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/foreach.hpp> #include <algorithm> #include <cassert> #include <stdexcept> #include <string> #include <vector> #include "chainparams.h" #include "core.h" #include "init.h" #include "main.h" #include "miner.h" //#include "net.h" #include "rpcprotocol.h" #include "rpcserver.h" #include "serialize.h" #include "sync.h" #include "txmempool.h" #include "uint256.h" #include "util.h" #include "version.h" #include "../wallet/wallet.h" #include <stdint.h> #include "json/json_spirit_utils.h" #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; // Key used by getwork miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining //static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: // pMiningKey = new CReserveKey(pwalletMain); //assert(0); LogPrint("TODO","InitRPCMining"); } void ShutdownRPCMining() { // if (!pMiningKey) // return; // // delete pMiningKey; pMiningKey = NULL; } // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = chainActive.Tip(); if (height >= 0 && height < chainActive.Height()) pb = chainActive[height]; if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64_t minTime = pb0->GetBlockTime(); int64_t maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64_t time = pb0->GetBlockTime(); minTime = min(time, minTime); maxTime = max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64_t timeDiff = maxTime - minTime; return (int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps ( blocks height )\n" "\nReturns the estimated network hashes per second based on the last n blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found.\n" "\nArguments:\n" "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n" "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n" "\nResult:\n" "x (numeric) Hashes per second estimated\n" "\nExamples:\n" + HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", "") ); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } static bool IsMining = false; void SetMinerStatus(bool bstatue ) { IsMining =bstatue; } static bool getMiningInfo() { return IsMining; } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || (params.size() != 1 && params.size() != 2)) throw runtime_error( "setgenerate generate ( genproclimit )\n" "\nSet 'generate' true or false to turn generation on or off.\n" "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n" "See the getgenerate call for the current setting.\n" "\nArguments:\n" "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n" "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n" " Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n" "\nExamples:\n" "\nSet the generation on with a limit of one processor\n" + HelpExampleCli("setgenerate", "true 1") + "\nTurn off generation\n" + HelpExampleCli("setgenerate", "false") + "\nUsing json rpc\n" + HelpExampleRpc("setgenerate", "true, 1") ); static bool fGenerate = false; set<CKeyID>dmuy; if(!pwalletMain->GetKeyIds(dmuy,true)) throw JSONRPCError(RPC_INVALID_PARAMS, "no key for mining"); if (params.size() > 0) fGenerate = params[0].get_bool(); int nGenProcLimit = 1; if (params.size() == 2) { nGenProcLimit = params[1].get_int(); } // -regtest mode: don't return until nGenProcLimit blocks are generated if (SysCfg().NetworkID() != CBaseParams::MAIN) { if(fGenerate == false){ GenerateDacrsBlock(false, pwalletMain, 1); return Value::null; } //һһ int nHeightEnd = 0; auto getcurhigh = [&]() { LOCK(cs_main); return chainActive.Height(); }; int curhigh = getcurhigh(); nHeightEnd = curhigh + nGenProcLimit; int high = -1; while (getcurhigh() < nHeightEnd) { if (getcurhigh() != high) { high = getcurhigh(); // cout<< "curhight: " << high <<endl; GenerateDacrsBlock(true, pwalletMain, 1); } MilliSleep(1000); if (fGenerate == false || ShutdownRequested()) { GenerateDacrsBlock(false, pwalletMain, 1); return Value::null; } } } else // Not -regtest: start generate thread, return immediately { SysCfg().SoftSetArgCover("-gen", fGenerate ?"1" : "0"); GenerateDacrsBlock(fGenerate, pwalletMain, nGenProcLimit); } return Value::null; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "\nReturns a json object containing mining-related information." "\nResult:\n" "{\n" " \"blocks\": nnn, (numeric) The current block\n" " \"currentblocksize\": nnn, (numeric) The last block size\n" " \"currentblocktx\": nnn, (numeric) The last block transaction\n" " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n" " \"errors\": \"...\" (string) Current errors\n" " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n" " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n" " \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n" " \"pooledtx\": n (numeric) The size of the mem pool\n" " \"testnet\": true|false (boolean) If using testnet or not\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", "") ); Object obj; obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("genproclimit", 1)); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); static const string name[] = {"MAIN", "TESTNET", "REGTEST"}; obj.push_back(Pair("nettype", name[SysCfg().NetworkID()])); obj.push_back(Pair("posmaxnonce", SysCfg().GetBlockMaxNonce())); obj.push_back(Pair("generate", getMiningInfo())); return obj; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n" "\nAttempts to submit new block to network.\n" "The 'jsonparametersobject' parameter is currently ignored.\n" "See https://en.Dacrs.it/wiki/BIP_0022 for full specification.\n" "\nArguments\n" "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n" "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n" " {\n" " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n" " }\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\"") ); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); Object obj; if (!fAccepted) { obj.push_back(Pair("status", "rejected")); obj.push_back(Pair("reject code", state.GetRejectCode())); obj.push_back(Pair("info", state.GetRejectReason())); } else { obj.push_back(Pair("status", "OK")); obj.push_back(Pair("hash", pblock.GetHash().ToString())); } return obj; } <commit_msg>fix a mining stop bug Signed-off-by: frank <2942612645@qq.com><commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Dacrs developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/foreach.hpp> #include <algorithm> #include <cassert> #include <stdexcept> #include <string> #include <vector> #include "chainparams.h" #include "core.h" #include "init.h" #include "main.h" #include "miner.h" //#include "net.h" #include "rpcprotocol.h" #include "rpcserver.h" #include "serialize.h" #include "sync.h" #include "txmempool.h" #include "uint256.h" #include "util.h" #include "version.h" #include "../wallet/wallet.h" #include <stdint.h> #include "json/json_spirit_utils.h" #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; // Key used by getwork miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining //static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: // pMiningKey = new CReserveKey(pwalletMain); //assert(0); LogPrint("TODO","InitRPCMining"); } void ShutdownRPCMining() { // if (!pMiningKey) // return; // // delete pMiningKey; pMiningKey = NULL; } // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = chainActive.Tip(); if (height >= 0 && height < chainActive.Height()) pb = chainActive[height]; if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64_t minTime = pb0->GetBlockTime(); int64_t maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64_t time = pb0->GetBlockTime(); minTime = min(time, minTime); maxTime = max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64_t timeDiff = maxTime - minTime; return (int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps ( blocks height )\n" "\nReturns the estimated network hashes per second based on the last n blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found.\n" "\nArguments:\n" "1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n" "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n" "\nResult:\n" "x (numeric) Hashes per second estimated\n" "\nExamples:\n" + HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", "") ); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } static bool IsMining = false; void SetMinerStatus(bool bstatue ) { IsMining =bstatue; } static bool getMiningInfo() { return IsMining; } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || (params.size() != 1 && params.size() != 2)) throw runtime_error( "setgenerate generate ( genproclimit )\n" "\nSet 'generate' true or false to turn generation on or off.\n" "Generation is limited to 'genproclimit' processors, -1 is unlimited.\n" "See the getgenerate call for the current setting.\n" "\nArguments:\n" "1. generate (boolean, required) Set to true to turn on generation, off to turn off.\n" "2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n" " Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n" "\nExamples:\n" "\nSet the generation on with a limit of one processor\n" + HelpExampleCli("setgenerate", "true 1") + "\nTurn off generation\n" + HelpExampleCli("setgenerate", "false") + "\nUsing json rpc\n" + HelpExampleRpc("setgenerate", "true, 1") ); static bool fGenerate = false; set<CKeyID>dmuy; if(!pwalletMain->GetKeyIds(dmuy,true)) throw JSONRPCError(RPC_INVALID_PARAMS, "no key for mining"); if (params.size() > 0) fGenerate = params[0].get_bool(); int nGenProcLimit = 1; if (params.size() == 2) { nGenProcLimit = params[1].get_int(); } // -regtest mode: don't return until nGenProcLimit blocks are generated if (SysCfg().NetworkID() != CBaseParams::MAIN) { if(fGenerate == false){ GenerateDacrsBlock(false, pwalletMain, 1); return Value::null; } //һһ int nHeightEnd = 0; auto getcurhigh = [&]() { LOCK(cs_main); return chainActive.Height(); }; int curhigh = getcurhigh(); nHeightEnd = curhigh + nGenProcLimit; int high = -1; while (getcurhigh() < nHeightEnd) { if (getcurhigh() != high || !getMiningInfo()) { high = getcurhigh(); // cout<< "curhight: " << high <<endl; GenerateDacrsBlock(true, pwalletMain, 1); } MilliSleep(1000); if (fGenerate == false || ShutdownRequested()) { GenerateDacrsBlock(false, pwalletMain, 1); return Value::null; } } GenerateDacrsBlock(false, pwalletMain, 1);//֮Ҫ˳ } else // Not -regtest: start generate thread, return immediately { SysCfg().SoftSetArgCover("-gen", fGenerate ?"1" : "0"); GenerateDacrsBlock(fGenerate, pwalletMain, nGenProcLimit); } return Value::null; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "\nReturns a json object containing mining-related information." "\nResult:\n" "{\n" " \"blocks\": nnn, (numeric) The current block\n" " \"currentblocksize\": nnn, (numeric) The last block size\n" " \"currentblocktx\": nnn, (numeric) The last block transaction\n" " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n" " \"errors\": \"...\" (string) Current errors\n" " \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n" " \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n" " \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n" " \"pooledtx\": n (numeric) The size of the mem pool\n" " \"testnet\": true|false (boolean) If using testnet or not\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", "") ); Object obj; obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("genproclimit", 1)); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); static const string name[] = {"MAIN", "TESTNET", "REGTEST"}; obj.push_back(Pair("nettype", name[SysCfg().NetworkID()])); obj.push_back(Pair("posmaxnonce", SysCfg().GetBlockMaxNonce())); obj.push_back(Pair("generate", getMiningInfo())); return obj; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n" "\nAttempts to submit new block to network.\n" "The 'jsonparametersobject' parameter is currently ignored.\n" "See https://en.Dacrs.it/wiki/BIP_0022 for full specification.\n" "\nArguments\n" "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n" "2. \"jsonparametersobject\" (string, optional) object of optional parameters\n" " {\n" " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n" " }\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\"") ); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); Object obj; if (!fAccepted) { obj.push_back(Pair("status", "rejected")); obj.push_back(Pair("reject code", state.GetRejectCode())); obj.push_back(Pair("info", state.GetRejectReason())); } else { obj.push_back(Pair("status", "OK")); obj.push_back(Pair("hash", pblock.GetHash().ToString())); } return obj; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin, Novacoin, and FlutterCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS(const CBlockIndex* blockindex) { int nPoWInterval = 72; int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS(const CBlockIndex* blockindex) { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; const CBlockIndex* pindex = pindexBest; const CBlockIndex* pindexPrevStake = NULL; if (blockindex != NULL) pindex = blockindex; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } return dStakeKernelsTriedAvg / nStakesTime; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); if (!blockindex->IsProofOfStake() && block.vtx[0].vout.size() > 1) result.push_back(Pair("extraflags", "proof-of-transaction")); else result.push_back(Pair("extraflags", "none")); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); if ( block.IsProofOfStake() || (!fTestNet && block.GetBlockTime() < ENTROPY_SWITCH_TIME) ) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // fluttercoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::ADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::PERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; } <commit_msg>update proof of transaction tracking<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin, Novacoin, and FlutterCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS(const CBlockIndex* blockindex) { int nPoWInterval = 72; int64 nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64 nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS(const CBlockIndex* blockindex) { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; const CBlockIndex* pindex = pindexBest; const CBlockIndex* pindexPrevStake = NULL; if (blockindex != NULL) pindex = blockindex; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } return dStakeKernelsTriedAvg / nStakesTime; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); if (!blockindex->IsProofOfStake() && block.vtx[0].vout.size() > 1) result.push_back(Pair("extraflags", "proof-of-transaction")); else if (blockindex->IsProofOfStake() && block.vtx[1].vout.size() == 4) //split stake with ProofOfTx result.push_back(Pair("extraflags", "proof-of-transaction")); else if (blockindex->IsProofOfStake() && block.vtx[1].vout.size() == 3 && block.vtx[1].vout[1].nValue / 2 > block.vtx[1].vout[2].nValue) //single stake with ProofOfTx result.push_back(Pair("extraflags", "proof-of-transaction")); else result.push_back(Pair("extraflags", "none")); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); if ( block.IsProofOfStake() || (!fTestNet && block.GetBlockTime() < ENTROPY_SWITCH_TIME) ) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // fluttercoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::ADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::PERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; } <|endoftext|>
<commit_before>#include "rprop.weights.h" #include <cmath> #include <cstdlib> #define DELTA0 0.1 #define ETAPLUS 1.2 #define ETAMINUS 0.5 Weights::Weights(const int& _height, const int& _width) { height = _height; width = _width; if(height) { float** weights = new float*[height]; for(int i = 0; i < height; ++i) { weights[i] = new float[width]; } } } Weights::~Weights(void) { if(height) { for(int i = 0; i < height; ++i) { delete[] weights[i]; } delete[] weights; } } int Weights::getWidth(void) const { return width; } int Weights::getHeight(void) const { return height; } float Weights::getWeight(const int& i, const int& j) const { return weights[i][j]; } inline float randomFloatAroundZero(void) { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX / 2.0) - 1.0; } void Weights::initializeForTraining(void) { derivative = new float*[height]; delta = new float*[height]; deltaW = new float*[height]; lastDerivative = new float*[height]; lastDelta = new float*[height]; lastDeltaW = new float*[height]; for(int i = 0; i < height; ++i) { derivative[i] = new float[width]; delta[i] = new float[width]; deltaW[i] = new float[width]; lastDerivative[i] = new float[width]; lastDelta[i] = new float[width]; lastDeltaW[i] = new float[width]; for(int j = 0; j < width; ++j) { weights[i][j] = randomFloatAroundZero(); derivative[i][j] = 1.0; delta[i][j] = DELTA0; deltaW[i][j] = DELTA0; } } } void Weights::cleanUpAfterTraining(void) { for(int i = 0; i < height; ++i) { delete[] derivative[i]; delete[] delta[i]; delete[] deltaW[i]; delete[] lastDerivative[i]; delete[] lastDelta[i]; delete[] lastDeltaW[i]; } delete[] derivative; delete[] delta; delete[] deltaW; delete[] lastDerivative; delete[] lastDelta; delete[] lastDeltaW; } inline float sign(const float& x) { if(x == 0.0) { return 0.0; } else if(x > 0.0) { return 1.0; } else { return -1.0; } } float Weights::updateElement(RProp& model, const int& i, const int& j) { float d = derivative[i][j] * lastDerivative[i][j]; if(d > 0.0) { delta[i][j] = fmin(ETAPLUS * lastDelta[i][j], deltaMax); deltaW[i][j] = -sign(derivative[i][j]) * delta[i][j]; return weights[i][j] + deltaW[i][j]; } else if(d < 0.0) { delta[i][j] = fmax(ETAMINUS * lastDelta[i][j], deltaMin); derivative[i][j] = 0.0; return weights[i][j] - lastDeltaW[i][j]; } else { delta[i][j] = lastDelta[i][j]; deltaW[i][j] = -sign(derivative[i][j]) * delta[i][j]; return weights[i][j] + deltaW[i][j]; } } inline void swapPointers(float**& x, float**& y) { float** t = y; y = x; x = t; } void Weights::update(RProp& model, float* features, const bool& alive) { swapPointers(derivative, lastDerivative); swapPointers(delta, lastDelta); swapPointers(deltaW, lastDeltaW); calculateDerivatives(model, features, alive); for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { weights[i][j] = updateElement(model, i, j); } } deltaMin = deltaMax = delta[0][0]; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { if(delta[i][j] < deltaMin) { deltaMin = delta[i][j]; } else if(delta[i][j] > deltaMax) { deltaMax = delta[i][j]; } } } } bool Weights::writeToFile(FILE* file) const { if(fwrite(&height, sizeof(int), 1, file) != 1 || fwrite(&width, sizeof(int), 1, file) != 1) { return false; } for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { if(fwrite(&weights[i][j], sizeof(float), 1, file) != 1) { return false; } } } return false; } bool Weights::readFromFile(FILE* file) { if(fread(&height, sizeof(int), 1, file) != 1 || fread(&width, sizeof(int), 1, file) != 1) { return false; } for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { if(fread(&weights[i][j], sizeof(float), 1, file) != 1) { return false; } } } return false; } <commit_msg>Fix allocation bug<commit_after>#include "rprop.weights.h" #include <cmath> #include <cstdlib> #define DELTA0 0.1 #define ETAPLUS 1.2 #define ETAMINUS 0.5 Weights::Weights(const int& _height, const int& _width) { height = _height; width = _width; if(height) { weights = new float*[height]; for(int i = 0; i < height; ++i) { weights[i] = new float[width]; } } } Weights::~Weights(void) { if(height) { for(int i = 0; i < height; ++i) { delete[] weights[i]; } delete[] weights; } } int Weights::getWidth(void) const { return width; } int Weights::getHeight(void) const { return height; } float Weights::getWeight(const int& i, const int& j) const { return weights[i][j]; } inline float randomFloatAroundZero(void) { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX / 2.0) - 1.0; } void Weights::initializeForTraining(void) { derivative = new float*[height]; delta = new float*[height]; deltaW = new float*[height]; lastDerivative = new float*[height]; lastDelta = new float*[height]; lastDeltaW = new float*[height]; for(int i = 0; i < height; ++i) { derivative[i] = new float[width]; delta[i] = new float[width]; deltaW[i] = new float[width]; lastDerivative[i] = new float[width]; lastDelta[i] = new float[width]; lastDeltaW[i] = new float[width]; for(int j = 0; j < width; ++j) { weights[i][j] = randomFloatAroundZero(); derivative[i][j] = 1.0; delta[i][j] = DELTA0; deltaW[i][j] = DELTA0; } } } void Weights::cleanUpAfterTraining(void) { for(int i = 0; i < height; ++i) { delete[] derivative[i]; delete[] delta[i]; delete[] deltaW[i]; delete[] lastDerivative[i]; delete[] lastDelta[i]; delete[] lastDeltaW[i]; } delete[] derivative; delete[] delta; delete[] deltaW; delete[] lastDerivative; delete[] lastDelta; delete[] lastDeltaW; } inline float sign(const float& x) { if(x == 0.0) { return 0.0; } else if(x > 0.0) { return 1.0; } else { return -1.0; } } float Weights::updateElement(RProp& model, const int& i, const int& j) { float d = derivative[i][j] * lastDerivative[i][j]; if(d > 0.0) { delta[i][j] = fmin(ETAPLUS * lastDelta[i][j], deltaMax); deltaW[i][j] = -sign(derivative[i][j]) * delta[i][j]; return weights[i][j] + deltaW[i][j]; } else if(d < 0.0) { delta[i][j] = fmax(ETAMINUS * lastDelta[i][j], deltaMin); derivative[i][j] = 0.0; return weights[i][j] - lastDeltaW[i][j]; } else { delta[i][j] = lastDelta[i][j]; deltaW[i][j] = -sign(derivative[i][j]) * delta[i][j]; return weights[i][j] + deltaW[i][j]; } } inline void swapPointers(float**& x, float**& y) { float** t = y; y = x; x = t; } void Weights::update(RProp& model, float* features, const bool& alive) { swapPointers(derivative, lastDerivative); swapPointers(delta, lastDelta); swapPointers(deltaW, lastDeltaW); calculateDerivatives(model, features, alive); for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { weights[i][j] = updateElement(model, i, j); } } deltaMin = deltaMax = delta[0][0]; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { if(delta[i][j] < deltaMin) { deltaMin = delta[i][j]; } else if(delta[i][j] > deltaMax) { deltaMax = delta[i][j]; } } } } bool Weights::writeToFile(FILE* file) const { if(fwrite(&height, sizeof(int), 1, file) != 1 || fwrite(&width, sizeof(int), 1, file) != 1) { return false; } for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { if(fwrite(&weights[i][j], sizeof(float), 1, file) != 1) { return false; } } } return false; } bool Weights::readFromFile(FILE* file) { if(fread(&height, sizeof(int), 1, file) != 1 || fread(&width, sizeof(int), 1, file) != 1) { return false; } for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { if(fread(&weights[i][j], sizeof(float), 1, file) != 1) { return false; } } } return false; } <|endoftext|>
<commit_before>#include <libbruce/bruce.h> #include <awsbruce/awsbruce.h> #include <boost/iostreams/stream.hpp> #include <aws/core/utils/logging/AWSLogging.h> #include <aws/core/utils/logging/DefaultLogSystem.h> #include <aws/core/utils/logging/LogLevel.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/http/HttpClientFactory.h> using namespace libbruce; using namespace awsbruce; using namespace Aws::Auth; using namespace Aws::Http; using namespace Aws::Client; using namespace Aws::S3; using namespace Aws::Utils; namespace io = boost::iostreams; const int MB = 1024 * 1024; #define S3_BUCKET "huijbers-test" #define S3_PREFIX "bruce/" void noop(void *p) { } struct Params { bool ok; maybe_nodeid root; bool hasKey = false; std::string key; bool hasValue = false; std::string value; std::map<std::string, std::string> otherKVs; }; Params parseParams(int argc, char* argv[]) { Params ret; if (argc == 1) { std::cout << "Usage:" << std::endl; std::cout << " s3kv '' KEY VALUE" << std::endl; std::cout << " s3kv ID" << std::endl; std::cout << " s3kv ID KEY" << std::endl; std::cout << " s3kv ID KEY VALUE [KEY VALUE [...]]" << std::endl; ret.ok = false; return ret; } ret.ok = true; // Parse params if (strlen(argv[1])) ret.root = boost::lexical_cast<nodeid_t>(argv[1]); if (argc >= 3) { ret.hasKey = true; ret.key = std::string(argv[2]); } if (argc >= 4) { ret.hasValue = true; ret.value = std::string(argv[3]); } for (int i = 4; i + 1 < argc; i += 2) { ret.otherKVs[std::string(argv[i])] = std::string(argv[i + 1]); } return ret; } int putKeyValue(bruce &b, const Params &params) { auto edit = params.root ? b.edit<std::string, std::string>(*params.root) : b.create<std::string, std::string>(); edit->insert(params.key, params.value); for (std::map<std::string, std::string>::const_iterator it = params.otherKVs.begin(); it != params.otherKVs.end(); ++it) edit->insert(it->first, it->second); mutation mut = edit->flush(); b.finish(mut, true); if (!mut.success()) { fprintf(stderr, "Error!\n"); return 1; } std::cout << *mut.newRootID() << std::endl; return 0; } int queryKey(bruce &b, const Params &params) { if (!params.root) { fprintf(stderr, "Can't query without a root\n"); return 1; } auto query = b.query<std::string, std::string>(*params.root); query_tree<std::string, std::string>::iterator it = query->find(params.key); while (it && it.key() == params.key) { std::cout << it.key() << " -> " << it.value() << std::endl; ++it; } return 0; } int fullScan(bruce &b, const Params &params) { auto query = b.query<std::string, std::string>(*params.root); query_tree<std::string, std::string>::iterator it = query->begin(); while (it) { std::cout << it.key() << " -> " << it.value() << std::endl; ++it; } return 0; } int main(int argc, char* argv[]) { // Params Params params = parseParams(argc, argv); if (!params.ok) return 1; std::shared_ptr<Aws::OStream> output(&std::cerr, noop); auto logger = std::make_shared<Aws::Utils::Logging::DefaultLogSystem>(Aws::Utils::Logging::LogLevel::Warn, output); Aws::Utils::Logging::InitializeAWSLogging(logger); // Create a client ClientConfiguration config; config.region = Aws::Region::EU_WEST_1; config.scheme = Scheme::HTTPS; config.connectTimeoutMs = 30000; config.requestTimeoutMs = 30000; auto clientFactory = Aws::MakeShared<HttpClientFactory>(NULL); auto s3 = Aws::MakeShared<S3Client>(NULL, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(NULL), config, clientFactory); s3be be(s3, S3_BUCKET, S3_PREFIX, 1 * MB, 100 * MB); bruce b(be); int exit; if (params.hasKey && params.hasValue) exit = putKeyValue(b, params); else if (params.hasKey) exit = queryKey(b, params); else exit = fullScan(b, params); Aws::Utils::Logging::ShutdownAWSLogging(); return exit; } <commit_msg>Add timing to s3kv<commit_after>#include <libbruce/bruce.h> #include <awsbruce/awsbruce.h> #include <boost/iostreams/stream.hpp> #include <aws/core/utils/logging/AWSLogging.h> #include <aws/core/utils/logging/DefaultLogSystem.h> #include <aws/core/utils/logging/LogLevel.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/http/HttpClientFactory.h> #include <sys/time.h> #include <fstream> using namespace libbruce; using namespace awsbruce; using namespace Aws::Auth; using namespace Aws::Http; using namespace Aws::Client; using namespace Aws::S3; using namespace Aws::Utils; namespace io = boost::iostreams; typedef bruce<std::string, std::string> stringbruce; const int MB = 1024 * 1024; #define S3_BUCKET "huijbers-test" #define S3_PREFIX "bruce/" struct Timer { Timer() { timeval now; gettimeofday(&now, NULL); m_start = now.tv_sec + (now.tv_usec / 1e6); } /** * Return elapsed time in ms */ size_t elapsed() { timeval now; gettimeofday(&now, NULL); double t = now.tv_sec + (now.tv_usec / 1e6); return (t - m_start) * 1000; } private: double m_start; }; void noop(void *p) { } struct Params { maybe_nodeid root; bool hasKey = false; std::string key; bool hasValue = false; std::string value; std::map<std::string, std::string> otherKVs; std::fstream metrics; }; bool parseParams(int argc, char* argv[], Params &ret) { if (argc == 1) { std::cout << "Usage:" << std::endl; std::cout << " s3kv '' KEY VALUE" << std::endl; std::cout << " s3kv ID" << std::endl; std::cout << " s3kv ID KEY" << std::endl; std::cout << " s3kv ID KEY VALUE [KEY VALUE [...]]" << std::endl; return false; } ret.metrics.open("metrics.csv", std::fstream::out | std::fstream::app); // Parse params if (strlen(argv[1])) ret.root = boost::lexical_cast<nodeid_t>(argv[1]); if (argc >= 3) { ret.hasKey = true; ret.key = std::string(argv[2]); } if (argc >= 4) { ret.hasValue = true; ret.value = std::string(argv[3]); } for (int i = 4; i + 1 < argc; i += 2) { ret.otherKVs[std::string(argv[i])] = std::string(argv[i + 1]); } return true; } int putKeyValue(stringbruce &b, Params &params) { Timer t; auto edit = params.root ? b.edit(*params.root) : b.create(); edit->insert(params.key, params.value); for (std::map<std::string, std::string>::const_iterator it = params.otherKVs.begin(); it != params.otherKVs.end(); ++it) edit->insert(it->first, it->second); mutation mut = edit->flush(); /* b.finish(mut, true); if (!mut.success()) { fprintf(stderr, "Error!\n"); return 1; } */ params.metrics << "put," << 1 + params.otherKVs.size() << "," << t.elapsed() << std::endl; std::cout << *mut.newRootID() << std::endl; return 0; } int queryKey(stringbruce &b, Params &params) { if (!params.root) { fprintf(stderr, "Can't query without a root\n"); return 1; } auto query = b.query(*params.root); stringbruce::iterator it = query->find(params.key); while (it && it.key() == params.key) { std::cout << it.key() << " -> " << it.value() << std::endl; ++it; } return 0; } int fullScan(stringbruce &b, Params &params) { auto query = b.query(*params.root); stringbruce::iterator it = query->begin(); while (it) { std::cout << it.key() << " -> " << it.value() << std::endl; ++it; } return 0; } int main(int argc, char* argv[]) { // Params Params params; if (!parseParams(argc, argv, params)) return 1; std::shared_ptr<Aws::OStream> output(&std::cerr, noop); auto logger = std::make_shared<Aws::Utils::Logging::DefaultLogSystem>(Aws::Utils::Logging::LogLevel::Warn, output); Aws::Utils::Logging::InitializeAWSLogging(logger); // Create a client ClientConfiguration config; config.region = Aws::Region::EU_WEST_1; config.scheme = Scheme::HTTPS; config.connectTimeoutMs = 30000; config.requestTimeoutMs = 30000; auto clientFactory = Aws::MakeShared<HttpClientFactory>(NULL); auto s3 = Aws::MakeShared<S3Client>(NULL, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(NULL), config, clientFactory); //s3be be(s3, S3_BUCKET, S3_PREFIX, 1 * MB, 100 * MB); be::disk be("temp/", 1 * MB); stringbruce b(be); int exit; if (params.hasKey && params.hasValue) exit = putKeyValue(b, params); else if (params.hasKey) exit = queryKey(b, params); else exit = fullScan(b, params); Aws::Utils::Logging::ShutdownAWSLogging(); return exit; } <|endoftext|>
<commit_before>/* Class that auto configures link-local xmpp account Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "salut-enabler.h" #include <TelepathyQt/ConnectionManager> #include <TelepathyQt/ProfileManager> #include <TelepathyQt/AccountManager> #include <TelepathyQt/PendingOperation> #include <TelepathyQt/PendingReady> #include <TelepathyQt/PendingAccount> #include <KDebug> #include <KUser> #include <KLocalizedString> #include <QtGui/QFrame> #include "salut-details-dialog.h" #include "salut-message-widget.h" #define TP_PROP_ACCOUNT_ENABLED (QLatin1String("org.freedesktop.Telepathy.Account.Enabled")) #define TP_PROP_ACCOUNT_SERVICE (QLatin1String("org.freedesktop.Telepathy.Account.Service")) const QLatin1String salutConnManager("salut"); const QLatin1String localXmppProtocol("local-xmpp"); const QLatin1String firstNamePar("first-name"); const QLatin1String lastNamePar("last-name"); const QLatin1String nickNamePar("nickname"); class SalutEnabler::Private { public: Private(SalutEnabler* parent) : q(parent), detailsDialog(0), messageWidget(0) { } SalutEnabler *q; Tp::ConnectionManagerPtr connectionManager; Tp::ProfileManagerPtr profileManager; Tp::AccountManagerPtr accountManager; Tp::ProfilePtr profile; QVariantMap values; SalutDetailsDialog *detailsDialog; SalutMessageWidget *messageWidget; QWeakPointer<QFrame> salutMessageFrame; }; SalutEnabler::SalutEnabler(const Tp::AccountManagerPtr accountManager, QObject *parent) : QObject(parent), d(new Private(this)) { d->accountManager = accountManager; d->connectionManager = Tp::ConnectionManager::create(salutConnManager); connect(d->connectionManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionManagerReady(Tp::PendingOperation*))); } SalutEnabler::~SalutEnabler() { delete d; } void SalutEnabler::onConnectionManagerReady(Tp::PendingOperation* op) { if (op->isError()) { kWarning() << "Creating ConnectionManager failed:" << op->errorName() << op->errorMessage(); } if (!d->connectionManager->isValid()) { kWarning() << "Invalid ConnectionManager"; } d->profileManager = Tp::ProfileManager::create(QDBusConnection::sessionBus()); // FIXME: Until all distros ship correct profile files, we should fake them connect(d->profileManager->becomeReady(Tp::Features() << Tp::ProfileManager::FeatureFakeProfiles), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onProfileManagerReady(Tp::PendingOperation*))); } void SalutEnabler::onProfileManagerReady(Tp::PendingOperation* op) { if (op->isError()) { kWarning() << "Creating ProfileManager failed:" << op->errorName() << op->errorMessage(); } // Get the protocol's parameters and values. Tp::ProtocolInfo protocolInfo = d->connectionManager->protocol(localXmppProtocol); Tp::ProtocolParameterList parameters = protocolInfo.parameters(); d->profile = d->profileManager->profilesForCM(salutConnManager).first(); Q_ASSERT(!d->profile.isNull()); Q_ASSERT(d->profile->isValid()); Q_ASSERT(d->profile->protocolName() == localXmppProtocol); if (d->profile.isNull() || !d->profile->isValid() || d->profile->protocolName() != localXmppProtocol) { kWarning() << "Something went wrong with telepathy salut"; } KUser user = KUser(); QString name = user.property(KUser::FullName).toString(); QString nick = user.loginName(); int lastSpacePosition = name.lastIndexOf(QLatin1Char(' ')); QString lastname = name.mid(lastSpacePosition + 1); QString firstName = name.left(lastSpacePosition); d->values.insert(firstNamePar, firstName); d->values.insert(lastNamePar, lastname); d->values.insert(nickNamePar, nick); Q_EMIT userInfoReady(); } QFrame* SalutEnabler::frameWidget(QWidget* parent) { if (d->salutMessageFrame.isNull()) { d->salutMessageFrame = new QFrame(parent); } d->salutMessageFrame.data()->setMinimumWidth(parent->width()); d->salutMessageFrame.data()->setFrameShape(QFrame::StyledPanel); d->messageWidget = new SalutMessageWidget(d->salutMessageFrame.data()); d->messageWidget->setParams(d->values[firstNamePar].toString(), d->values[lastNamePar].toString(), d->values[nickNamePar].toString()); d->messageWidget->hide(); QPropertyAnimation *animation = new QPropertyAnimation(d->salutMessageFrame.data(), "minimumHeight", d->messageWidget); animation->setDuration(150); animation->setStartValue(0); animation->setEndValue(d->messageWidget->sizeHint().height()); animation->start(); connect(animation, SIGNAL(finished()), d->messageWidget, SLOT(animatedShow())); connect(d->messageWidget, SIGNAL(timeout()), this, SLOT(onUserAccepted())); connect(d->messageWidget, SIGNAL(configPressed()), this, SLOT(onUserWantingChanges())); connect(d->messageWidget, SIGNAL(cancelPressed()), this, SLOT(onUserCancelled())); return d->salutMessageFrame.data(); } void SalutEnabler::onUserAccepted() { // FIXME: In some next version of tp-qt4 there should be a convenience class for this // https://bugs.freedesktop.org/show_bug.cgi?id=33153 QVariantMap properties; if (d->accountManager->supportedAccountProperties().contains(TP_PROP_ACCOUNT_SERVICE)) { properties.insert(TP_PROP_ACCOUNT_SERVICE, d->profile->serviceName()); } if (d->accountManager->supportedAccountProperties().contains(TP_PROP_ACCOUNT_ENABLED)) { properties.insert(TP_PROP_ACCOUNT_ENABLED, true); } // FIXME: Ask the user to submit a Display Name QString displayName; QString lastname = d->values[lastNamePar].toString(); QString firstname = d->values[firstNamePar].toString(); QString nick = d->values[nickNamePar].toString(); //either one of the names is filled and nick is filled if (((lastname.isEmpty() && !firstname.isEmpty()) || (!lastname.isEmpty() && firstname.isEmpty())) && !nick.isEmpty()) { displayName = QString::fromLatin1("%1 (%2)").arg(d->values[firstNamePar].toString().isEmpty() ? d->values[lastNamePar].toString() : d->values[firstNamePar].toString(), d->values[nickNamePar].toString()); //either one of the names is filled and nick is empty } else if (((lastname.isEmpty() && !firstname.isEmpty()) || (!lastname.isEmpty() && firstname.isEmpty())) && nick.isEmpty()) { displayName = d->values[firstNamePar].toString().isEmpty() ? d->values[lastNamePar].toString() : d->values[firstNamePar].toString(); //both first & last names are empty but nick is not } else if (lastname.isEmpty() && firstname.isEmpty() && !nick.isEmpty()) { displayName = d->values[nickNamePar].toString(); } else if (lastname.isEmpty() && firstname.isEmpty() && nick.isEmpty()) { //FIXME: let the user know that he reached a very strange situation } else { displayName = QString::fromLatin1("%1 %2 (%3)").arg(d->values[firstNamePar].toString(), d->values[lastNamePar].toString(), d->values[nickNamePar].toString()); } Tp::PendingAccount *pa = d->accountManager->createAccount(d->profile->cmName(), d->profile->protocolName(), displayName, d->values, properties); connect(pa, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountCreated(Tp::PendingOperation*))); } void SalutEnabler::onAccountCreated(Tp::PendingOperation* op) { kDebug() << "Account created"; if (op->isError()) { kWarning() << "Creating Account failed:" << op->errorName() << op->errorMessage(); } if (op->isError()) { Q_EMIT feedbackMessage(i18n("Failed to create account"), i18n("Possibly not all required fields are valid"), KMessageWidget::Error); kWarning() << "Adding Account failed:" << op->errorName() << op->errorMessage(); return; } // Get the PendingAccount. Tp::PendingAccount *pendingAccount = qobject_cast<Tp::PendingAccount*>(op); if (!pendingAccount) { Q_EMIT feedbackMessage(i18n("Something went wrong with Telepathy"), QString(), KMessageWidget::Error); kWarning() << "Method called with wrong type."; return; } pendingAccount->account()->setRequestedPresence(Tp::Presence::available()); pendingAccount->account()->setServiceName(d->profile->serviceName()); d->salutMessageFrame.data()->deleteLater();; Q_EMIT done(); } void SalutEnabler::onUserWantingChanges() { d->detailsDialog = new SalutDetailsDialog(d->profileManager, d->connectionManager, 0); connect(d->detailsDialog, SIGNAL(dialogAccepted(QVariantMap)), this, SLOT(onDialogAccepted(QVariantMap))); connect(d->detailsDialog, SIGNAL(rejected()), this, SLOT(onUserCancelled())); connect(d->detailsDialog, SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType)), this, SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType))); d->detailsDialog->exec(); } void SalutEnabler::onDialogAccepted(const QVariantMap &values) { kDebug() << values; d->values.insert(firstNamePar, values[firstNamePar].toString()); d->values.insert(lastNamePar, values[lastNamePar].toString()); d->values.insert(nickNamePar, values[nickNamePar].toString()); onUserAccepted(); } void SalutEnabler::onUserCancelled() { d->messageWidget->animatedHide(); QPropertyAnimation *animation = new QPropertyAnimation(d->salutMessageFrame.data(), "maximumHeight", d->messageWidget); animation->setDuration(150); animation->setStartValue(d->messageWidget->sizeHint().height()); animation->setEndValue(0); QTimer::singleShot(300, animation, SLOT(start())); connect(animation, SIGNAL(finished()), d->salutMessageFrame.data(), SLOT(deleteLater())); connect(animation, SIGNAL(finished()), this, SIGNAL(cancelled())); } <commit_msg>Simplify and fix displayName creation in SalutEnabler<commit_after>/* Class that auto configures link-local xmpp account Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com> Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "salut-enabler.h" #include <TelepathyQt/ConnectionManager> #include <TelepathyQt/ProfileManager> #include <TelepathyQt/AccountManager> #include <TelepathyQt/PendingOperation> #include <TelepathyQt/PendingReady> #include <TelepathyQt/PendingAccount> #include <KDebug> #include <KUser> #include <KLocalizedString> #include <QtGui/QFrame> #include "salut-details-dialog.h" #include "salut-message-widget.h" #define TP_PROP_ACCOUNT_ENABLED (QLatin1String("org.freedesktop.Telepathy.Account.Enabled")) #define TP_PROP_ACCOUNT_SERVICE (QLatin1String("org.freedesktop.Telepathy.Account.Service")) const QLatin1String salutConnManager("salut"); const QLatin1String localXmppProtocol("local-xmpp"); const QLatin1String firstNamePar("first-name"); const QLatin1String lastNamePar("last-name"); const QLatin1String nickNamePar("nickname"); class SalutEnabler::Private { public: Private(SalutEnabler* parent) : q(parent), detailsDialog(0), messageWidget(0) { } SalutEnabler *q; Tp::ConnectionManagerPtr connectionManager; Tp::ProfileManagerPtr profileManager; Tp::AccountManagerPtr accountManager; Tp::ProfilePtr profile; QVariantMap values; SalutDetailsDialog *detailsDialog; SalutMessageWidget *messageWidget; QWeakPointer<QFrame> salutMessageFrame; }; SalutEnabler::SalutEnabler(const Tp::AccountManagerPtr accountManager, QObject *parent) : QObject(parent), d(new Private(this)) { d->accountManager = accountManager; d->connectionManager = Tp::ConnectionManager::create(salutConnManager); connect(d->connectionManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionManagerReady(Tp::PendingOperation*))); } SalutEnabler::~SalutEnabler() { delete d; } void SalutEnabler::onConnectionManagerReady(Tp::PendingOperation* op) { if (op->isError()) { kWarning() << "Creating ConnectionManager failed:" << op->errorName() << op->errorMessage(); } if (!d->connectionManager->isValid()) { kWarning() << "Invalid ConnectionManager"; } d->profileManager = Tp::ProfileManager::create(QDBusConnection::sessionBus()); // FIXME: Until all distros ship correct profile files, we should fake them connect(d->profileManager->becomeReady(Tp::Features() << Tp::ProfileManager::FeatureFakeProfiles), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onProfileManagerReady(Tp::PendingOperation*))); } void SalutEnabler::onProfileManagerReady(Tp::PendingOperation* op) { if (op->isError()) { kWarning() << "Creating ProfileManager failed:" << op->errorName() << op->errorMessage(); } // Get the protocol's parameters and values. Tp::ProtocolInfo protocolInfo = d->connectionManager->protocol(localXmppProtocol); Tp::ProtocolParameterList parameters = protocolInfo.parameters(); d->profile = d->profileManager->profilesForCM(salutConnManager).first(); Q_ASSERT(!d->profile.isNull()); Q_ASSERT(d->profile->isValid()); Q_ASSERT(d->profile->protocolName() == localXmppProtocol); if (d->profile.isNull() || !d->profile->isValid() || d->profile->protocolName() != localXmppProtocol) { kWarning() << "Something went wrong with telepathy salut"; } KUser user = KUser(); QString name = user.property(KUser::FullName).toString(); QString nick = user.loginName(); int lastSpacePosition = name.lastIndexOf(QLatin1Char(' ')); QString lastname = name.mid(lastSpacePosition + 1); QString firstName = name.left(lastSpacePosition); d->values.insert(firstNamePar, firstName); d->values.insert(lastNamePar, lastname); d->values.insert(nickNamePar, nick); Q_EMIT userInfoReady(); } QFrame* SalutEnabler::frameWidget(QWidget* parent) { if (d->salutMessageFrame.isNull()) { d->salutMessageFrame = new QFrame(parent); } d->salutMessageFrame.data()->setMinimumWidth(parent->width()); d->salutMessageFrame.data()->setFrameShape(QFrame::StyledPanel); d->messageWidget = new SalutMessageWidget(d->salutMessageFrame.data()); d->messageWidget->setParams(d->values[firstNamePar].toString(), d->values[lastNamePar].toString(), d->values[nickNamePar].toString()); d->messageWidget->hide(); QPropertyAnimation *animation = new QPropertyAnimation(d->salutMessageFrame.data(), "minimumHeight", d->messageWidget); animation->setDuration(150); animation->setStartValue(0); animation->setEndValue(d->messageWidget->sizeHint().height()); animation->start(); connect(animation, SIGNAL(finished()), d->messageWidget, SLOT(animatedShow())); connect(d->messageWidget, SIGNAL(timeout()), this, SLOT(onUserAccepted())); connect(d->messageWidget, SIGNAL(configPressed()), this, SLOT(onUserWantingChanges())); connect(d->messageWidget, SIGNAL(cancelPressed()), this, SLOT(onUserCancelled())); return d->salutMessageFrame.data(); } void SalutEnabler::onUserAccepted() { // FIXME: In some next version of tp-qt4 there should be a convenience class for this // https://bugs.freedesktop.org/show_bug.cgi?id=33153 QVariantMap properties; if (d->accountManager->supportedAccountProperties().contains(TP_PROP_ACCOUNT_SERVICE)) { properties.insert(TP_PROP_ACCOUNT_SERVICE, d->profile->serviceName()); } if (d->accountManager->supportedAccountProperties().contains(TP_PROP_ACCOUNT_ENABLED)) { properties.insert(TP_PROP_ACCOUNT_ENABLED, true); } // FIXME: Ask the user to submit a Display Name QString displayName; QString lastname = d->values[lastNamePar].toString(); QString firstname = d->values[firstNamePar].toString(); QString nickname = d->values[nickNamePar].toString(); if (!firstname.isEmpty()) { displayName = firstname; } if (!lastname.isEmpty()) { if (!displayName.isEmpty()) { displayName.append(QString::fromLatin1(" %1").arg(lastname)); } else { displayName = lastname; } } if (!nickname.isEmpty()) { if (!displayName.isEmpty()) { displayName.append(QString::fromLatin1(" (%1)").arg(nickname)); } else { displayName = nickname; } } if (displayName.isEmpty()) { //FIXME: let the user know that he reached a very strange situation kWarning() << "All fields are empty"; } Tp::PendingAccount *pa = d->accountManager->createAccount(d->profile->cmName(), d->profile->protocolName(), displayName, d->values, properties); connect(pa, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountCreated(Tp::PendingOperation*))); } void SalutEnabler::onAccountCreated(Tp::PendingOperation* op) { kDebug() << "Account created"; if (op->isError()) { kWarning() << "Creating Account failed:" << op->errorName() << op->errorMessage(); } if (op->isError()) { Q_EMIT feedbackMessage(i18n("Failed to create account"), i18n("Possibly not all required fields are valid"), KMessageWidget::Error); kWarning() << "Adding Account failed:" << op->errorName() << op->errorMessage(); return; } // Get the PendingAccount. Tp::PendingAccount *pendingAccount = qobject_cast<Tp::PendingAccount*>(op); if (!pendingAccount) { Q_EMIT feedbackMessage(i18n("Something went wrong with Telepathy"), QString(), KMessageWidget::Error); kWarning() << "Method called with wrong type."; return; } pendingAccount->account()->setRequestedPresence(Tp::Presence::available()); pendingAccount->account()->setServiceName(d->profile->serviceName()); d->salutMessageFrame.data()->deleteLater();; Q_EMIT done(); } void SalutEnabler::onUserWantingChanges() { d->detailsDialog = new SalutDetailsDialog(d->profileManager, d->connectionManager, 0); connect(d->detailsDialog, SIGNAL(dialogAccepted(QVariantMap)), this, SLOT(onDialogAccepted(QVariantMap))); connect(d->detailsDialog, SIGNAL(rejected()), this, SLOT(onUserCancelled())); connect(d->detailsDialog, SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType)), this, SIGNAL(feedbackMessage(QString,QString,KMessageWidget::MessageType))); d->detailsDialog->exec(); } void SalutEnabler::onDialogAccepted(const QVariantMap &values) { kDebug() << values; d->values.insert(firstNamePar, values[firstNamePar].toString()); d->values.insert(lastNamePar, values[lastNamePar].toString()); d->values.insert(nickNamePar, values[nickNamePar].toString()); onUserAccepted(); } void SalutEnabler::onUserCancelled() { d->messageWidget->animatedHide(); QPropertyAnimation *animation = new QPropertyAnimation(d->salutMessageFrame.data(), "maximumHeight", d->messageWidget); animation->setDuration(150); animation->setStartValue(d->messageWidget->sizeHint().height()); animation->setEndValue(0); QTimer::singleShot(300, animation, SLOT(start())); connect(animation, SIGNAL(finished()), d->salutMessageFrame.data(), SLOT(deleteLater())); connect(animation, SIGNAL(finished()), this, SIGNAL(cancelled())); } <|endoftext|>
<commit_before>// Copyright 2014 eric schkufza // // 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 "src/sandbox/cpu_io.h" using namespace std; using namespace x64asm; namespace stoke { Function CpuIo::write(CpuState& cs, const RegSet& mask) { Assembler assm; Function fxn; assm.start(fxn); // Backup rax if it won't ultimately be overwritten if (!mask.contains(rax)) { assm.push(rax); } // Write sse registers for (const auto& s : xmms) { if (mask.contains(s)) { assm.mov((R64)rax, Imm64 {cs.sse[s].data()}); assm.vmovdqu(ymms[s], M256 {rax}); } } // Write gp registers for (const auto& r : r64s) { if (mask.contains(r)) { assm.mov(r, Imm64 {cs.gp[r].data()}); assm.mov(r, M64 {r}); } } // Write rflags // @todo Need to check whether any rflags appear in the mask before we do this assm.mov((R64)rax, Imm64(cs.rf.data())); assm.mov(rax, M64(rax)); assm.push(rax); assm.popfq(); // Restore rax if it wasn't written over if (!mask.contains(rax)) { assm.pop(rax); } assm.ret(); assm.finish(); return fxn; } Function CpuIo::read(CpuState& cs, const RegSet& mask, const map<R64, uint64_t*>& alts) { Assembler assm; Function fxn; assm.start(fxn); // Backup scratch registers no matter what assm.push(rax); assm.push(rbx); // Read gp registers, for (const auto& r : r64s) { if (mask.contains(r)) { const auto itr = alts.find(r); if (itr != alts.end()) { assm.mov(rax, Moffs64 {itr->second}); } else { assm.mov(rax, r); } assm.mov(Moffs64 {cs.gp[r].data()}, rax); } } // Read sse registers for (const auto& s : xmms) { if (mask.contains(s)) { assm.mov((R64)rax, Imm64 {cs.sse[s].data()}); assm.vmovdqu(M256 {rax}, ymms[s]); } } // Read rflags // @todo Need to check whether any rflags appear in the mask before we do this assm.pushfq(); assm.mov((R64)rax, Imm64(cs.rf.data())); assm.mov((R64)rbx, M64(rsp)); assm.mov(M64(rax), rbx); assm.popfq(); // Restore scratch regs assm.pop(rbx); assm.pop(rax); assm.ret(); assm.finish(); return fxn; } } // namespace stoke <commit_msg>Sandbox isn't clobbering rax on write to cpu now.<commit_after>// Copyright 2014 eric schkufza // // 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 "src/sandbox/cpu_io.h" using namespace std; using namespace x64asm; namespace stoke { Function CpuIo::write(CpuState& cs, const RegSet& mask) { Assembler assm; Function fxn; assm.start(fxn); // Backup rax if it won't ultimately be overwritten if (!mask.contains(rax)) { assm.push(rax); } // Write rflags (this has to happen before writing gp) // @todo Need to check whether any rflags appear in the mask before we do this assm.mov((R64)rax, Imm64(cs.rf.data())); assm.mov(rax, M64(rax)); assm.push(rax); assm.popfq(); // Write sse registers (this has to happen before writing gp) for (const auto& s : xmms) { if (mask.contains(s)) { assm.mov((R64)rax, Imm64 {cs.sse[s].data()}); assm.vmovdqu(ymms[s], M256 {rax}); } } // Write gp registers for (const auto& r : r64s) { if (mask.contains(r)) { assm.mov(r, Imm64 {cs.gp[r].data()}); assm.mov(r, M64 {r}); } } // Restore rax if it wasn't written over if (!mask.contains(rax)) { assm.pop(rax); } assm.ret(); assm.finish(); return fxn; } Function CpuIo::read(CpuState& cs, const RegSet& mask, const map<R64, uint64_t*>& alts) { Assembler assm; Function fxn; assm.start(fxn); // Backup scratch registers no matter what assm.push(rax); assm.push(rbx); // Read gp registers, for (const auto& r : r64s) { if (mask.contains(r)) { const auto itr = alts.find(r); if (itr != alts.end()) { assm.mov(rax, Moffs64 {itr->second}); } else { assm.mov(rax, r); } assm.mov(Moffs64 {cs.gp[r].data()}, rax); } } // Read sse registers for (const auto& s : xmms) { if (mask.contains(s)) { assm.mov((R64)rax, Imm64 {cs.sse[s].data()}); assm.vmovdqu(M256 {rax}, ymms[s]); } } // Read rflags // @todo Need to check whether any rflags appear in the mask before we do this assm.pushfq(); assm.mov((R64)rax, Imm64(cs.rf.data())); assm.mov((R64)rbx, M64(rsp)); assm.mov(M64(rax), rbx); assm.popfq(); // Restore scratch regs assm.pop(rbx); assm.pop(rax); assm.ret(); assm.finish(); return fxn; } } // namespace stoke <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/ismine.h> #include <key.h> #include <keystore.h> #include <script/script.h> #include <script/sign.h> typedef std::vector<unsigned char> valtype; static bool HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore) { for (const valtype& pubkey : pubkeys) { CKeyID keyID = CPubKey(pubkey).GetID(); if (!keystore.HaveKey(keyID)) return false; } return true; } static isminetype IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid, SigVersion sigversion) { isInvalid = false; std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) { if (keystore.HaveWatchOnly(scriptPubKey)) return ISMINE_WATCH_UNSOLVABLE; return ISMINE_NO; } CKeyID keyID; switch (whichType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_WITNESS_UNKNOWN: break; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); if (sigversion != SigVersion::BASE && vSolutions[0].size() != 33) { isInvalid = true; return ISMINE_NO; } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_WITNESS_V0_KEYHASH: { if (!keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { // We do not support bare witness outputs unless the P2SH version of it would be // acceptable as well. This protects against matching before segwit activates. // This also applies to the P2WSH case. break; } isminetype ret = IsMineInner(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), isInvalid, SigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; break; } case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (sigversion != SigVersion::BASE) { CPubKey pubkey; if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) { isInvalid = true; return ISMINE_NO; } } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_SCRIPTHASH: { CScriptID scriptID = CScriptID(uint160(vSolutions[0])); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, SigVersion::BASE); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_WITNESS_V0_SCRIPTHASH: { if (!keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { break; } uint160 hash; CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(hash.begin()); CScriptID scriptID = CScriptID(hash); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, SigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_MULTISIG: { // Only consider transactions "mine" if we own ALL the // keys involved. Multi-signature transactions that are // partially owned (somebody else has a key that can spend // them) enable spend-out-from-under-you attacks, especially // in shared-wallet situations. std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1); if (sigversion != SigVersion::BASE) { for (size_t i = 0; i < keys.size(); i++) { if (keys[i].size() != 33) { isInvalid = true; return ISMINE_NO; } } } if (HaveKeys(keys, keystore)) return ISMINE_SPENDABLE; break; } } if (keystore.HaveWatchOnly(scriptPubKey)) { // TODO: This could be optimized some by doing some work after the above solver SignatureData sigs; return ProduceSignature(keystore, DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigs) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE; } return ISMINE_NO; } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid) { return IsMineInner(keystore, scriptPubKey, isInvalid, SigVersion::BASE); } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) { bool isInvalid = false; return IsMine(keystore, scriptPubKey, isInvalid); } isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest) { CScript script = GetScriptForDestination(dest); return IsMine(keystore, script); } <commit_msg>Switch to a private version of SigVersion inside IsMine<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/ismine.h> #include <key.h> #include <keystore.h> #include <script/script.h> #include <script/sign.h> typedef std::vector<unsigned char> valtype; enum class IsMineSigVersion { BASE = 0, WITNESS_V0 = 1 }; static bool HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore) { for (const valtype& pubkey : pubkeys) { CKeyID keyID = CPubKey(pubkey).GetID(); if (!keystore.HaveKey(keyID)) return false; } return true; } static isminetype IsMineInner(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid, IsMineSigVersion sigversion) { isInvalid = false; std::vector<valtype> vSolutions; txnouttype whichType; if (!Solver(scriptPubKey, whichType, vSolutions)) { if (keystore.HaveWatchOnly(scriptPubKey)) return ISMINE_WATCH_UNSOLVABLE; return ISMINE_NO; } CKeyID keyID; switch (whichType) { case TX_NONSTANDARD: case TX_NULL_DATA: case TX_WITNESS_UNKNOWN: break; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); if (sigversion != IsMineSigVersion::BASE && vSolutions[0].size() != 33) { isInvalid = true; return ISMINE_NO; } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_WITNESS_V0_KEYHASH: { if (!keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { // We do not support bare witness outputs unless the P2SH version of it would be // acceptable as well. This protects against matching before segwit activates. // This also applies to the P2WSH case. break; } isminetype ret = IsMineInner(keystore, GetScriptForDestination(CKeyID(uint160(vSolutions[0]))), isInvalid, IsMineSigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; break; } case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (sigversion != IsMineSigVersion::BASE) { CPubKey pubkey; if (keystore.GetPubKey(keyID, pubkey) && !pubkey.IsCompressed()) { isInvalid = true; return ISMINE_NO; } } if (keystore.HaveKey(keyID)) return ISMINE_SPENDABLE; break; case TX_SCRIPTHASH: { CScriptID scriptID = CScriptID(uint160(vSolutions[0])); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, IsMineSigVersion::BASE); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_WITNESS_V0_SCRIPTHASH: { if (!keystore.HaveCScript(CScriptID(CScript() << OP_0 << vSolutions[0]))) { break; } uint160 hash; CRIPEMD160().Write(&vSolutions[0][0], vSolutions[0].size()).Finalize(hash.begin()); CScriptID scriptID = CScriptID(hash); CScript subscript; if (keystore.GetCScript(scriptID, subscript)) { isminetype ret = IsMineInner(keystore, subscript, isInvalid, IsMineSigVersion::WITNESS_V0); if (ret == ISMINE_SPENDABLE || ret == ISMINE_WATCH_SOLVABLE || (ret == ISMINE_NO && isInvalid)) return ret; } break; } case TX_MULTISIG: { // Only consider transactions "mine" if we own ALL the // keys involved. Multi-signature transactions that are // partially owned (somebody else has a key that can spend // them) enable spend-out-from-under-you attacks, especially // in shared-wallet situations. std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1); if (sigversion != IsMineSigVersion::BASE) { for (size_t i = 0; i < keys.size(); i++) { if (keys[i].size() != 33) { isInvalid = true; return ISMINE_NO; } } } if (HaveKeys(keys, keystore)) return ISMINE_SPENDABLE; break; } } if (keystore.HaveWatchOnly(scriptPubKey)) { // TODO: This could be optimized some by doing some work after the above solver SignatureData sigs; return ProduceSignature(keystore, DUMMY_SIGNATURE_CREATOR, scriptPubKey, sigs) ? ISMINE_WATCH_SOLVABLE : ISMINE_WATCH_UNSOLVABLE; } return ISMINE_NO; } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey, bool& isInvalid) { return IsMineInner(keystore, scriptPubKey, isInvalid, IsMineSigVersion::BASE); } isminetype IsMine(const CKeyStore& keystore, const CScript& scriptPubKey) { bool isInvalid = false; return IsMine(keystore, scriptPubKey, isInvalid); } isminetype IsMine(const CKeyStore& keystore, const CTxDestination& dest) { CScript script = GetScriptForDestination(dest); return IsMine(keystore, script); } <|endoftext|>
<commit_before>#include "io_manager.h" IO_Manager::IO_Manager() { } ssize_t IO_Manager::process_read_stripe (uint32_t file_id, char *pathname, uint32_t stripe_id, uint32_t stripe_size, uint32_t chunk_size, const void *buf, int offset, size_t count) { uint32_t chunk_id, bytes_read = 0, read_size = 0; int chunk_offset, chunk_result, node_id; assert ((count - offset) <= stripe_size); printf ("\n(BARISTA) Process Read Stripe\n"); get_first_chunk (&chunk_id, chunk_size, &chunk_offset, offset); while (bytes_read < count) { struct file_chunk cur_chunk = {file_id, stripe_id, chunk_id}; struct ip_address cur_node; if (!chunk_exists (cur_chunk)) { // Current chunk does not exist. Report and error and stop the read. fprintf (stderr, "Could only read %d bytes (out of %d requested.\n", (int)bytes_read, (int)count); break; } // The chunk exists, so set the node_id node_id = chunk_to_node[cur_chunk]; cur_node = get_node_ip (node_id); // If the node isn't up, switch to the replica if (!is_node_up ((char *)cur_node.addr)) { assert (chunk_replica_exists (cur_chunk)); node_id = chunk_to_replica_node[cur_chunk]; cur_node = get_node_ip (node_id); } // Determine how much data to read from the current chunk if (count - bytes_read > chunk_size - chunk_offset) { read_size = chunk_size - chunk_offset; } else { read_size = count - bytes_read; } printf ("\tprocessing chunk %d (sending to node %d)\n", chunk_id, node_id); printf ("\t\toffset: %d, size: %d\n", chunk_offset, read_size); // Send the read to the node // ADD FD HERE chunk_result = process_read_chunk (0, file_id, node_id, stripe_id, chunk_id, chunk_offset, read_size); printf ("\t\treceived %d from network call.\n", chunk_result); // If the node cannot be read from // TODO: uncomment when network layer reports failures /*if (chunk_result < 0) { // Mark the node as "down" set_node_down (cur_node.addr); } // The read suceeded, so move on else { // update counters chunk_offset = 0; bytes_read += read_size; chunk_id++; }*/ // update counters chunk_offset = 0; bytes_read += read_size; chunk_id++; } return bytes_read; } ssize_t IO_Manager::process_write_stripe (uint32_t file_id, char *pathname, uint32_t stripe_id, uint32_t stripe_size, uint32_t chunk_size, const void *buf, int offset, size_t count) { uint32_t chunk_id, bytes_written = 0, write_size = 0; int chunk_offset, node_id, replica_node_id, write_result; assert ((count - offset) <= stripe_size); printf ("\n(BARISTA) Process Write Stripe\n"); get_first_chunk (&chunk_id, chunk_size, &chunk_offset, offset); while (bytes_written < count) { struct file_chunk cur_chunk = {file_id, stripe_id, chunk_id}; struct ip_address cur_node, cur_replica_node; // If the chunk does not exists, create it if (!chunk_exists (cur_chunk)) { node_id = put_chunk (file_id, pathname, stripe_id, chunk_id); printf ("\tchunk doesn't exist. Setting it's id to %d\n", node_id); chunk_to_node[cur_chunk] = node_id; } // If the replica does not exist, create it if (!chunk_replica_exists (cur_chunk)) { replica_node_id = put_replica (file_id, pathname, stripe_id, chunk_id); printf ("\tchunk replica doesn't exist. Setting it's id to %d\n", replica_node_id); chunk_to_replica_node[cur_chunk] = replica_node_id; } // Ensure that we have the proper node and replica id's to send data to node_id = chunk_to_node[cur_chunk]; cur_node = get_node_ip (node_id); replica_node_id = chunk_to_replica_node[cur_chunk]; cur_replica_node = get_node_ip (replica_node_id); // Determine the size of the write if (count - bytes_written > chunk_size - chunk_offset) { write_size = chunk_size - chunk_offset; } else { write_size = count - bytes_written; } // Send the write to the node // ADD FD HERE printf ("\tprocessing chunk %d (sending to node %d)\n", chunk_id, node_id); write_result = process_write_chunk (0, file_id, node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); printf ("\t\treceived %d from network call.\n", write_result); // If the write failed // TODO: uncomment when network layer reports errors /*if (write_result < 0) { // Set the node to "down" and try again set_node_down (cur_node.addr); } else { // Send the write to the replica node // ADD FD HERE printf ("\tprocessing chunk replica %d (sending to node %d)\n", chunk_id, replica_node_id); write_result = process_write_chunk (0, file_id, replica_node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); // if the replica write failed if (write_result < 0) { // Set the node to "down" set_node_down (cur_replica_node.addr); // Choose a different replica replica_node_id = put_replica (file_id, pathname, stripe_id, chunk_id); // Re-write the data process_write_chunk (0, file_id, replica_node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); } // update counters chunk_offset = 0; bytes_written += write_size; chunk_id++; }*/ printf ("\tprocessing chunk replica %d (sending to node %d)\n", chunk_id, replica_node_id); write_result = process_write_chunk (0, file_id, replica_node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); // update counters chunk_offset = 0; bytes_written += write_size; chunk_id++; } return bytes_written; } void IO_Manager::process_delete_file (uint32_t file_id) { std::vector<struct file_chunk> chunks = get_all_chunks (file_id); for (std::vector<struct file_chunk>::iterator it = chunks.begin(); it != chunks.end(); it++) { if (chunk_exists (*it)) { int chunk_node = get_node_id (file_id, (*it).stripe_id, (*it).chunk_num); process_delete_chunk (file_id, chunk_node, (*it).stripe_id, (*it).chunk_num); chunk_to_node.erase (*it); } if (chunk_replica_exists (*it)) { int chunk_node = get_replica_node_id (file_id, (*it).stripe_id, (*it).chunk_num); process_delete_chunk (file_id, chunk_node, (*it).stripe_id, (*it).chunk_num); chunk_to_replica_node.erase (*it); } } } int IO_Manager::set_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t node_id) { if (node_exists (node_id)) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; chunk_to_node[chunk] = node_id; return node_id; } return NODE_NOT_FOUND; } int IO_Manager::get_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; if (chunk_exists (chunk)) { return chunk_to_node[chunk]; } return CHUNK_NOT_FOUND; } int IO_Manager::set_replica_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t node_id) { if (node_exists (node_id)) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; chunk_to_replica_node[chunk] = node_id; return node_id; } return REPLICA_NODE_NOT_FOUND; } int IO_Manager::get_replica_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; if (chunk_replica_exists (chunk)) { return chunk_to_replica_node[chunk]; } return REPLICA_CHUNK_NOT_FOUND; } // These 4 functions should be moved up to Barista Core // this layer is stripe level not file level int IO_Manager::stat_file_name (char *pathname, struct decafs_file_stat *buf) { return 0; } int IO_Manager::stat_file_id (uint32_t file_id, struct decafs_file_stat *buf) { return 0; } int IO_Manager::stat_replica_name (char *pathname, struct decafs_file_stat *buf) { return 0; } int IO_Manager::stat_replica_id (uint32_t file_id, struct decafs_file_stat *buf) { return 0; } void IO_Manager::sync () { // Intentionally left blank, in this implementation, all file data is written // to disk when "write" completes. } bool IO_Manager::chunk_exists (struct file_chunk chunk) { return (chunk_to_node.find (chunk) != chunk_to_node.end()); } bool IO_Manager::chunk_replica_exists (struct file_chunk chunk) { return (chunk_to_replica_node.find (chunk) != chunk_to_replica_node.end()); } std::vector<struct file_chunk> IO_Manager::get_all_chunks (uint32_t file_id) { std::vector <struct file_chunk> chunks; for (std::map<struct file_chunk, int>::iterator it = chunk_to_node.begin(); it != chunk_to_node.end(); it++) { struct file_chunk cur = it->first; if (cur.file_id == file_id) { chunks.push_back (cur); } } return chunks; } void IO_Manager::get_first_chunk (uint32_t *id, uint32_t chunk_size, int *chunk_offset, int offset) { *id = CHUNK_ID_INIT; while (offset > (int)chunk_size) { (*id)++; offset -= chunk_size; } *chunk_offset = offset; } <commit_msg>Added buf back for buffer layer.<commit_after>#include "io_manager.h" IO_Manager::IO_Manager() { } ssize_t IO_Manager::process_read_stripe (uint32_t file_id, char *pathname, uint32_t stripe_id, uint32_t stripe_size, uint32_t chunk_size, const void *buf, int offset, size_t count) { uint32_t chunk_id, bytes_read = 0, read_size = 0; int chunk_offset, chunk_result, node_id; assert ((count - offset) <= stripe_size); printf ("\n(BARISTA) Process Read Stripe\n"); get_first_chunk (&chunk_id, chunk_size, &chunk_offset, offset); while (bytes_read < count) { struct file_chunk cur_chunk = {file_id, stripe_id, chunk_id}; struct ip_address cur_node; if (!chunk_exists (cur_chunk)) { // Current chunk does not exist. Report and error and stop the read. fprintf (stderr, "Could only read %d bytes (out of %d requested.\n", (int)bytes_read, (int)count); break; } // The chunk exists, so set the node_id node_id = chunk_to_node[cur_chunk]; cur_node = get_node_ip (node_id); // If the node isn't up, switch to the replica if (!is_node_up ((char *)cur_node.addr)) { assert (chunk_replica_exists (cur_chunk)); node_id = chunk_to_replica_node[cur_chunk]; cur_node = get_node_ip (node_id); } // Determine how much data to read from the current chunk if (count - bytes_read > chunk_size - chunk_offset) { read_size = chunk_size - chunk_offset; } else { read_size = count - bytes_read; } printf ("\tprocessing chunk %d (sending to node %d)\n", chunk_id, node_id); printf ("\t\toffset: %d, size: %d\n", chunk_offset, read_size); // Send the read to the node // ADD FD HERE chunk_result = process_read_chunk (0, file_id, node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_read, read_size); printf ("\t\treceived %d from network call.\n", chunk_result); // If the node cannot be read from // TODO: uncomment when network layer reports failures /*if (chunk_result < 0) { // Mark the node as "down" set_node_down (cur_node.addr); } // The read suceeded, so move on else { // update counters chunk_offset = 0; bytes_read += read_size; chunk_id++; }*/ // update counters chunk_offset = 0; bytes_read += read_size; chunk_id++; } return bytes_read; } ssize_t IO_Manager::process_write_stripe (uint32_t file_id, char *pathname, uint32_t stripe_id, uint32_t stripe_size, uint32_t chunk_size, const void *buf, int offset, size_t count) { uint32_t chunk_id, bytes_written = 0, write_size = 0; int chunk_offset, node_id, replica_node_id, write_result; assert ((count - offset) <= stripe_size); printf ("\n(BARISTA) Process Write Stripe\n"); get_first_chunk (&chunk_id, chunk_size, &chunk_offset, offset); while (bytes_written < count) { struct file_chunk cur_chunk = {file_id, stripe_id, chunk_id}; struct ip_address cur_node, cur_replica_node; // If the chunk does not exists, create it if (!chunk_exists (cur_chunk)) { node_id = put_chunk (file_id, pathname, stripe_id, chunk_id); printf ("\tchunk doesn't exist. Setting it's id to %d\n", node_id); chunk_to_node[cur_chunk] = node_id; } // If the replica does not exist, create it if (!chunk_replica_exists (cur_chunk)) { replica_node_id = put_replica (file_id, pathname, stripe_id, chunk_id); printf ("\tchunk replica doesn't exist. Setting it's id to %d\n", replica_node_id); chunk_to_replica_node[cur_chunk] = replica_node_id; } // Ensure that we have the proper node and replica id's to send data to node_id = chunk_to_node[cur_chunk]; cur_node = get_node_ip (node_id); replica_node_id = chunk_to_replica_node[cur_chunk]; cur_replica_node = get_node_ip (replica_node_id); // Determine the size of the write if (count - bytes_written > chunk_size - chunk_offset) { write_size = chunk_size - chunk_offset; } else { write_size = count - bytes_written; } // Send the write to the node // ADD FD HERE printf ("\tprocessing chunk %d (sending to node %d)\n", chunk_id, node_id); write_result = process_write_chunk (0, file_id, node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); printf ("\t\treceived %d from network call.\n", write_result); // If the write failed // TODO: uncomment when network layer reports errors /*if (write_result < 0) { // Set the node to "down" and try again set_node_down (cur_node.addr); } else { // Send the write to the replica node // ADD FD HERE printf ("\tprocessing chunk replica %d (sending to node %d)\n", chunk_id, replica_node_id); write_result = process_write_chunk (0, file_id, replica_node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); // if the replica write failed if (write_result < 0) { // Set the node to "down" set_node_down (cur_replica_node.addr); // Choose a different replica replica_node_id = put_replica (file_id, pathname, stripe_id, chunk_id); // Re-write the data process_write_chunk (0, file_id, replica_node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); } // update counters chunk_offset = 0; bytes_written += write_size; chunk_id++; }*/ printf ("\tprocessing chunk replica %d (sending to node %d)\n", chunk_id, replica_node_id); write_result = process_write_chunk (0, file_id, replica_node_id, stripe_id, chunk_id, chunk_offset, (uint8_t *)buf + bytes_written, write_size); // update counters chunk_offset = 0; bytes_written += write_size; chunk_id++; } return bytes_written; } void IO_Manager::process_delete_file (uint32_t file_id) { std::vector<struct file_chunk> chunks = get_all_chunks (file_id); for (std::vector<struct file_chunk>::iterator it = chunks.begin(); it != chunks.end(); it++) { if (chunk_exists (*it)) { int chunk_node = get_node_id (file_id, (*it).stripe_id, (*it).chunk_num); process_delete_chunk (file_id, chunk_node, (*it).stripe_id, (*it).chunk_num); chunk_to_node.erase (*it); } if (chunk_replica_exists (*it)) { int chunk_node = get_replica_node_id (file_id, (*it).stripe_id, (*it).chunk_num); process_delete_chunk (file_id, chunk_node, (*it).stripe_id, (*it).chunk_num); chunk_to_replica_node.erase (*it); } } } int IO_Manager::set_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t node_id) { if (node_exists (node_id)) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; chunk_to_node[chunk] = node_id; return node_id; } return NODE_NOT_FOUND; } int IO_Manager::get_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; if (chunk_exists (chunk)) { return chunk_to_node[chunk]; } return CHUNK_NOT_FOUND; } int IO_Manager::set_replica_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t node_id) { if (node_exists (node_id)) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; chunk_to_replica_node[chunk] = node_id; return node_id; } return REPLICA_NODE_NOT_FOUND; } int IO_Manager::get_replica_node_id (uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) { struct file_chunk chunk = {file_id, stripe_id, chunk_num}; if (chunk_replica_exists (chunk)) { return chunk_to_replica_node[chunk]; } return REPLICA_CHUNK_NOT_FOUND; } // These 4 functions should be moved up to Barista Core // this layer is stripe level not file level int IO_Manager::stat_file_name (char *pathname, struct decafs_file_stat *buf) { return 0; } int IO_Manager::stat_file_id (uint32_t file_id, struct decafs_file_stat *buf) { return 0; } int IO_Manager::stat_replica_name (char *pathname, struct decafs_file_stat *buf) { return 0; } int IO_Manager::stat_replica_id (uint32_t file_id, struct decafs_file_stat *buf) { return 0; } void IO_Manager::sync () { // Intentionally left blank, in this implementation, all file data is written // to disk when "write" completes. } bool IO_Manager::chunk_exists (struct file_chunk chunk) { return (chunk_to_node.find (chunk) != chunk_to_node.end()); } bool IO_Manager::chunk_replica_exists (struct file_chunk chunk) { return (chunk_to_replica_node.find (chunk) != chunk_to_replica_node.end()); } std::vector<struct file_chunk> IO_Manager::get_all_chunks (uint32_t file_id) { std::vector <struct file_chunk> chunks; for (std::map<struct file_chunk, int>::iterator it = chunk_to_node.begin(); it != chunk_to_node.end(); it++) { struct file_chunk cur = it->first; if (cur.file_id == file_id) { chunks.push_back (cur); } } return chunks; } void IO_Manager::get_first_chunk (uint32_t *id, uint32_t chunk_size, int *chunk_offset, int offset) { *id = CHUNK_ID_INIT; while (offset > (int)chunk_size) { (*id)++; offset -= chunk_size; } *chunk_offset = offset; } <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Siddharth Srivastava <akssps011@gmail.com> // Copyright 2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de> // #include "AutoNavigation.h" #include "GeoDataCoordinates.h" #include "PositionTracking.h" #include "MarbleDebug.h" #include "MarbleModel.h" #include "MarbleMath.h" #include "ViewportParams.h" #include "MarbleGlobal.h" #include <QPixmap> #include <QWidget> #include <QRect> #include <QPointF> #include <QTimer> #include <math.h> namespace Marble { class AutoNavigation::Private { public: AutoNavigation *const m_parent; const MarbleModel *const m_model; const ViewportParams *const m_viewport; const PositionTracking *const m_tracking; AutoNavigation::CenterMode m_recenterMode; bool m_adjustZoom; QTimer m_lastWidgetInteraction; bool m_selfInteraction; /** Constructor */ Private( MarbleModel *model, const ViewportParams *viewport, AutoNavigation *parent ); /** * @brief To center on when reaching custom defined border * @param position current gps location * @param speed optional speed argument */ void moveOnBorderToCenter( const GeoDataCoordinates &position, qreal speed ); /** * For calculating intersection point of projected LineString from * current gps location with the map border * @param position current gps location */ GeoDataCoordinates findIntersection( qreal currentX, qreal currentY ) const; /** * @brief Adjust the zoom value of the map * @param currentPosition current location of the gps device */ void adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed ); /** * Center the widget on the given position unless recentering is currently inhibited */ void centerOn( const GeoDataCoordinates &position ); }; AutoNavigation::Private::Private( MarbleModel *model, const ViewportParams *viewport, AutoNavigation *parent ) : m_parent( parent ), m_model( model ), m_viewport( viewport ), m_tracking( model->positionTracking() ), m_recenterMode( AutoNavigation::DontRecenter ), m_adjustZoom( 0 ), m_selfInteraction( false ) { m_lastWidgetInteraction.setInterval( 10 * 1000 ); m_lastWidgetInteraction.setSingleShot( true ); } void AutoNavigation::Private::moveOnBorderToCenter( const GeoDataCoordinates &position, qreal ) { qreal lon = 0.0; qreal lat = 0.0; position.geoCoordinates( lon, lat, GeoDataCoordinates::Degree ); qreal x = 0.0; qreal y = 0.0; //recenter if initially the gps location is not visible on the screen if(!( m_viewport->screenCoordinates( lon, lat, x, y ) ) ) { centerOn( position ); } qreal centerLon = m_viewport->centerLongitude(); qreal centerLat = m_viewport->centerLatitude(); qreal centerX = 0.0; qreal centerY = 0.0; m_viewport->screenCoordinates( centerLon, centerLat, centerX, centerY ); const qreal borderRatio = 0.25; //defining the default border distance from map center int shiftX = qRound( centerX * borderRatio ); int shiftY = qRound( centerY * borderRatio ); QRect recenterBorderBound; recenterBorderBound.setCoords( centerX-shiftX, centerY-shiftY, centerX+shiftX, centerY+shiftY ); if( !recenterBorderBound.contains( x,y ) ) { centerOn( position ); } } GeoDataCoordinates AutoNavigation::Private::findIntersection( qreal currentX, qreal currentY ) const { qreal direction = m_tracking->direction(); if ( direction >= 360 ) { direction = fmod( direction,360.0 ); } const qreal width = m_viewport->width(); const qreal height = m_viewport->height(); QPointF intercept; QPointF destinationHorizontal; QPointF destinationVertical; QPointF destination; bool crossHorizontal = false; bool crossVertical = false; //calculation of intersection point if( 0 < direction && direction < 90 ) { const qreal angle = direction; //Intersection with line x = width intercept.setX( width - currentX ); intercept.setY( intercept.x() / tan( angle ) ); destinationVertical.setX( width ); destinationVertical.setY( currentY-intercept.y() ); //Intersection with line y = 0 intercept.setY( currentY ); intercept.setX( intercept.y() * tan( angle ) ); destinationHorizontal.setX( currentX + intercept.x() ); destinationHorizontal.setY( 0 ); if ( destinationVertical.y() < 0 ) { crossHorizontal = true; } else if( destinationHorizontal.x() > width ) { crossVertical = true; } } else if( 270 < direction && direction < 360 ) { const qreal angle = direction - 270; //Intersection with line y = 0 intercept.setY( currentY ); intercept.setX( intercept.y() / tan( angle ) ); destinationHorizontal.setX( currentX - intercept.x() ); destinationHorizontal.setY( 0 ); //Intersection with line x = 0 intercept.setX( currentX ); intercept.setY( intercept.x() * tan( angle ) ); destinationVertical.setY( currentY - intercept.y() ); destinationVertical.setX( 0 ); if( destinationHorizontal.x() > width ) { crossVertical = true; } else if( destinationVertical.y() < 0 ) { crossHorizontal = true; } } else if( 180 < direction && direction < 270 ) { const qreal angle = direction - 180; //Intersection with line x = 0 intercept.setX( currentX ); intercept.setY( intercept.x() / tan( angle ) ); destinationVertical.setY( currentY + intercept.y() ); destinationVertical.setX( 0 ); //Intersection with line y = height intercept.setY( currentY ); intercept.setX( intercept.y() * tan( angle ) ); destinationHorizontal.setX( currentX - intercept.x() ); destinationHorizontal.setY( height ); if ( destinationVertical.y() > height ) { crossHorizontal = true; } else if ( destinationHorizontal.x() < 0 ) { crossVertical = true; } } else if( 90 < direction && direction < 180 ) { const qreal angle = direction - 90; //Intersection with line y = height intercept.setY( height - currentY ); intercept.setX( intercept.y() / tan( angle ) ); destinationHorizontal.setX( currentX + intercept.x() ); destinationHorizontal.setY( height ); //Intersection with line x = width intercept.setX( width - currentX ); intercept.setY( intercept.x() * tan( angle ) ); destinationVertical.setX( width ); destinationVertical.setY( currentY + intercept.y() ); if ( destinationHorizontal.x() > width ) { crossVertical = true; } else if( destinationVertical.y() > height ) { crossHorizontal = true; } } else if( direction == 0 ) { destinationHorizontal.setX( currentX ); destinationHorizontal.setY( 0 ); crossHorizontal = true; } else if( direction == 90 ) { destinationVertical.setX( width ); destinationVertical.setY( currentY ); crossVertical = true; } else if( direction == 190 ) { destinationHorizontal.setX( currentX ); destinationHorizontal.setY( height ); crossHorizontal = true; } else if( direction == 270 ) { destinationVertical.setX( 0 ); destinationVertical.setY( currentY ); crossVertical = true; } if ( crossHorizontal == true && crossVertical == false ) { destination.setX( destinationHorizontal.x() ); destination.setY( destinationHorizontal.y() ); } else if ( crossVertical == true && crossHorizontal == false ) { destination.setX( destinationVertical.x() ); destination.setY( destinationVertical.y() ); } qreal destinationLon = 0.0; qreal destinationLat = 0.0; m_viewport->geoCoordinates( destination.x(), destination.y(), destinationLon, destinationLat, GeoDataCoordinates::Radian ); GeoDataCoordinates destinationCoord( destinationLon, destinationLat, GeoDataCoordinates::Radian ); return destinationCoord; } void AutoNavigation::Private::adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed ) { const qreal lon = currentPosition.longitude( GeoDataCoordinates::Degree ); const qreal lat = currentPosition.latitude( GeoDataCoordinates::Degree ); qreal currentX = 0; qreal currentY = 0; if( !m_viewport->screenCoordinates( lon, lat, currentX, currentY ) ) { return; } const GeoDataCoordinates destination = findIntersection( currentX, currentY ); qreal greatCircleDistance = distanceSphere( currentPosition, destination ); qreal radius = m_model->planetRadius(); qreal distance = greatCircleDistance * radius; if( speed != 0 ) { //time(in minutes) remaining to reach the border of the map qreal remainingTime = ( distance / speed ) * SEC2MIN; //tolerance time limits( in minutes ) before auto zooming qreal thresholdLow = 1.0; qreal thresholdHigh = 12.0 * thresholdLow; m_selfInteraction = true; if ( remainingTime < thresholdLow ) { emit m_parent->zoomOut( Instant ); } else if ( remainingTime < thresholdHigh ) { /* zoom level optimal, nothing to do */ } else { emit m_parent->zoomIn( Instant ); } m_selfInteraction = false; } } void AutoNavigation::Private::centerOn( const GeoDataCoordinates &position ) { m_selfInteraction = true; emit m_parent->centerOn( position, false ); m_selfInteraction = false; } AutoNavigation::AutoNavigation( MarbleModel *model, const ViewportParams *viewport, QObject *parent ) : QObject( parent ), d( new AutoNavigation::Private( model, viewport, this ) ) { connect( d->m_tracking, SIGNAL(gpsLocation(GeoDataCoordinates,qreal)), this, SLOT(adjust(GeoDataCoordinates,qreal)) ); } AutoNavigation::~AutoNavigation() { delete d; } void AutoNavigation::adjust( const GeoDataCoordinates &position, qreal speed ) { if ( d->m_lastWidgetInteraction.isActive() ) { return; } switch( d->m_recenterMode ) { case DontRecenter: /* nothing to do */ break; case AlwaysRecenter: d->centerOn( position ); break; case RecenterOnBorder: d->moveOnBorderToCenter( position, speed ); break; } if ( d->m_adjustZoom ) { switch( d->m_recenterMode ) { case DontRecenter: /* nothing to do */ break; case AlwaysRecenter: case RecenterOnBorder: // fallthrough d->adjustZoom( position, speed ); break; } } } void AutoNavigation::setAutoZoom( bool autoZoom ) { d->m_adjustZoom = autoZoom; emit autoZoomToggled( autoZoom ); } void AutoNavigation::setRecenter( CenterMode recenterMode ) { d->m_recenterMode = recenterMode; emit recenterModeChanged( recenterMode ); } void AutoNavigation::inhibitAutoAdjustments() { if ( !d->m_selfInteraction ) { d->m_lastWidgetInteraction.start(); } } AutoNavigation::CenterMode AutoNavigation::recenterMode() const { return d->m_recenterMode; } bool AutoNavigation::autoZoom() const { return d->m_adjustZoom; } } // namespace Marble #include "AutoNavigation.moc" <commit_msg>fix AutoNavigation::RecenterOnBorder mode<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Siddharth Srivastava <akssps011@gmail.com> // Copyright 2011 Bernhard Beschow <bbeschow@cs.tu-berlin.de> // #include "AutoNavigation.h" #include "GeoDataCoordinates.h" #include "PositionTracking.h" #include "MarbleDebug.h" #include "MarbleModel.h" #include "MarbleMath.h" #include "ViewportParams.h" #include "MarbleGlobal.h" #include <QPixmap> #include <QWidget> #include <QRect> #include <QPointF> #include <QTimer> #include <math.h> namespace Marble { class AutoNavigation::Private { public: AutoNavigation *const m_parent; const MarbleModel *const m_model; const ViewportParams *const m_viewport; const PositionTracking *const m_tracking; AutoNavigation::CenterMode m_recenterMode; bool m_adjustZoom; QTimer m_lastWidgetInteraction; bool m_selfInteraction; /** Constructor */ Private( MarbleModel *model, const ViewportParams *viewport, AutoNavigation *parent ); /** * @brief To center on when reaching custom defined border * @param position current gps location * @param speed optional speed argument */ void moveOnBorderToCenter( const GeoDataCoordinates &position, qreal speed ); /** * For calculating intersection point of projected LineString from * current gps location with the map border * @param position current gps location */ GeoDataCoordinates findIntersection( qreal currentX, qreal currentY ) const; /** * @brief Adjust the zoom value of the map * @param currentPosition current location of the gps device */ void adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed ); /** * Center the widget on the given position unless recentering is currently inhibited */ void centerOn( const GeoDataCoordinates &position ); }; AutoNavigation::Private::Private( MarbleModel *model, const ViewportParams *viewport, AutoNavigation *parent ) : m_parent( parent ), m_model( model ), m_viewport( viewport ), m_tracking( model->positionTracking() ), m_recenterMode( AutoNavigation::DontRecenter ), m_adjustZoom( 0 ), m_selfInteraction( false ) { m_lastWidgetInteraction.setInterval( 10 * 1000 ); m_lastWidgetInteraction.setSingleShot( true ); } void AutoNavigation::Private::moveOnBorderToCenter( const GeoDataCoordinates &position, qreal ) { qreal x = 0.0; qreal y = 0.0; //recenter if initially the gps location is not visible on the screen if(!( m_viewport->screenCoordinates( position, x, y ) ) ) { centerOn( position ); } qreal centerLon = m_viewport->centerLongitude(); qreal centerLat = m_viewport->centerLatitude(); qreal centerX = 0.0; qreal centerY = 0.0; m_viewport->screenCoordinates( centerLon, centerLat, centerX, centerY ); const qreal borderRatio = 0.25; //defining the default border distance from map center int shiftX = qRound( centerX * borderRatio ); int shiftY = qRound( centerY * borderRatio ); QRect recenterBorderBound; recenterBorderBound.setCoords( centerX-shiftX, centerY-shiftY, centerX+shiftX, centerY+shiftY ); if( !recenterBorderBound.contains( x,y ) ) { centerOn( position ); } } GeoDataCoordinates AutoNavigation::Private::findIntersection( qreal currentX, qreal currentY ) const { qreal direction = m_tracking->direction(); if ( direction >= 360 ) { direction = fmod( direction,360.0 ); } const qreal width = m_viewport->width(); const qreal height = m_viewport->height(); QPointF intercept; QPointF destinationHorizontal; QPointF destinationVertical; QPointF destination; bool crossHorizontal = false; bool crossVertical = false; //calculation of intersection point if( 0 < direction && direction < 90 ) { const qreal angle = direction; //Intersection with line x = width intercept.setX( width - currentX ); intercept.setY( intercept.x() / tan( angle ) ); destinationVertical.setX( width ); destinationVertical.setY( currentY-intercept.y() ); //Intersection with line y = 0 intercept.setY( currentY ); intercept.setX( intercept.y() * tan( angle ) ); destinationHorizontal.setX( currentX + intercept.x() ); destinationHorizontal.setY( 0 ); if ( destinationVertical.y() < 0 ) { crossHorizontal = true; } else if( destinationHorizontal.x() > width ) { crossVertical = true; } } else if( 270 < direction && direction < 360 ) { const qreal angle = direction - 270; //Intersection with line y = 0 intercept.setY( currentY ); intercept.setX( intercept.y() / tan( angle ) ); destinationHorizontal.setX( currentX - intercept.x() ); destinationHorizontal.setY( 0 ); //Intersection with line x = 0 intercept.setX( currentX ); intercept.setY( intercept.x() * tan( angle ) ); destinationVertical.setY( currentY - intercept.y() ); destinationVertical.setX( 0 ); if( destinationHorizontal.x() > width ) { crossVertical = true; } else if( destinationVertical.y() < 0 ) { crossHorizontal = true; } } else if( 180 < direction && direction < 270 ) { const qreal angle = direction - 180; //Intersection with line x = 0 intercept.setX( currentX ); intercept.setY( intercept.x() / tan( angle ) ); destinationVertical.setY( currentY + intercept.y() ); destinationVertical.setX( 0 ); //Intersection with line y = height intercept.setY( currentY ); intercept.setX( intercept.y() * tan( angle ) ); destinationHorizontal.setX( currentX - intercept.x() ); destinationHorizontal.setY( height ); if ( destinationVertical.y() > height ) { crossHorizontal = true; } else if ( destinationHorizontal.x() < 0 ) { crossVertical = true; } } else if( 90 < direction && direction < 180 ) { const qreal angle = direction - 90; //Intersection with line y = height intercept.setY( height - currentY ); intercept.setX( intercept.y() / tan( angle ) ); destinationHorizontal.setX( currentX + intercept.x() ); destinationHorizontal.setY( height ); //Intersection with line x = width intercept.setX( width - currentX ); intercept.setY( intercept.x() * tan( angle ) ); destinationVertical.setX( width ); destinationVertical.setY( currentY + intercept.y() ); if ( destinationHorizontal.x() > width ) { crossVertical = true; } else if( destinationVertical.y() > height ) { crossHorizontal = true; } } else if( direction == 0 ) { destinationHorizontal.setX( currentX ); destinationHorizontal.setY( 0 ); crossHorizontal = true; } else if( direction == 90 ) { destinationVertical.setX( width ); destinationVertical.setY( currentY ); crossVertical = true; } else if( direction == 190 ) { destinationHorizontal.setX( currentX ); destinationHorizontal.setY( height ); crossHorizontal = true; } else if( direction == 270 ) { destinationVertical.setX( 0 ); destinationVertical.setY( currentY ); crossVertical = true; } if ( crossHorizontal == true && crossVertical == false ) { destination.setX( destinationHorizontal.x() ); destination.setY( destinationHorizontal.y() ); } else if ( crossVertical == true && crossHorizontal == false ) { destination.setX( destinationVertical.x() ); destination.setY( destinationVertical.y() ); } qreal destinationLon = 0.0; qreal destinationLat = 0.0; m_viewport->geoCoordinates( destination.x(), destination.y(), destinationLon, destinationLat, GeoDataCoordinates::Radian ); GeoDataCoordinates destinationCoord( destinationLon, destinationLat, GeoDataCoordinates::Radian ); return destinationCoord; } void AutoNavigation::Private::adjustZoom( const GeoDataCoordinates &currentPosition, qreal speed ) { const qreal lon = currentPosition.longitude( GeoDataCoordinates::Degree ); const qreal lat = currentPosition.latitude( GeoDataCoordinates::Degree ); qreal currentX = 0; qreal currentY = 0; if( !m_viewport->screenCoordinates( lon, lat, currentX, currentY ) ) { return; } const GeoDataCoordinates destination = findIntersection( currentX, currentY ); qreal greatCircleDistance = distanceSphere( currentPosition, destination ); qreal radius = m_model->planetRadius(); qreal distance = greatCircleDistance * radius; if( speed != 0 ) { //time(in minutes) remaining to reach the border of the map qreal remainingTime = ( distance / speed ) * SEC2MIN; //tolerance time limits( in minutes ) before auto zooming qreal thresholdLow = 1.0; qreal thresholdHigh = 12.0 * thresholdLow; m_selfInteraction = true; if ( remainingTime < thresholdLow ) { emit m_parent->zoomOut( Instant ); } else if ( remainingTime < thresholdHigh ) { /* zoom level optimal, nothing to do */ } else { emit m_parent->zoomIn( Instant ); } m_selfInteraction = false; } } void AutoNavigation::Private::centerOn( const GeoDataCoordinates &position ) { m_selfInteraction = true; emit m_parent->centerOn( position, false ); m_selfInteraction = false; } AutoNavigation::AutoNavigation( MarbleModel *model, const ViewportParams *viewport, QObject *parent ) : QObject( parent ), d( new AutoNavigation::Private( model, viewport, this ) ) { connect( d->m_tracking, SIGNAL(gpsLocation(GeoDataCoordinates,qreal)), this, SLOT(adjust(GeoDataCoordinates,qreal)) ); } AutoNavigation::~AutoNavigation() { delete d; } void AutoNavigation::adjust( const GeoDataCoordinates &position, qreal speed ) { if ( d->m_lastWidgetInteraction.isActive() ) { return; } switch( d->m_recenterMode ) { case DontRecenter: /* nothing to do */ break; case AlwaysRecenter: d->centerOn( position ); break; case RecenterOnBorder: d->moveOnBorderToCenter( position, speed ); break; } if ( d->m_adjustZoom ) { switch( d->m_recenterMode ) { case DontRecenter: /* nothing to do */ break; case AlwaysRecenter: case RecenterOnBorder: // fallthrough d->adjustZoom( position, speed ); break; } } } void AutoNavigation::setAutoZoom( bool autoZoom ) { d->m_adjustZoom = autoZoom; emit autoZoomToggled( autoZoom ); } void AutoNavigation::setRecenter( CenterMode recenterMode ) { d->m_recenterMode = recenterMode; emit recenterModeChanged( recenterMode ); } void AutoNavigation::inhibitAutoAdjustments() { if ( !d->m_selfInteraction ) { d->m_lastWidgetInteraction.start(); } } AutoNavigation::CenterMode AutoNavigation::recenterMode() const { return d->m_recenterMode; } bool AutoNavigation::autoZoom() const { return d->m_adjustZoom; } } // namespace Marble #include "AutoNavigation.moc" <|endoftext|>
<commit_before>#include <algorithm> #include "levenshtein.h" uint32_t levenshteinCore(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, std::vector<uint32_t> &current, std::vector<uint32_t> &last) { const size_t n(s.size()), m(t.size()); // Initialise with unmatched characters in t for (size_t j = 0; j <= m; ++j) last[j] = j; for (size_t i = 0; i < n; ++i) { current[0] = i+1; // = last[0]+1, corresponds to unmatched character in s for (size_t j = 1; j <= m; ++j) { current[j] = std::min(last[j] + 1, current[j-1] + 1); // insertion / deletion current[j] = std::min(current[j], last[j-1] + (int)(s[i] != t[j-1])); // modification } current.swap(last); } return last.back(); } /** * Levenshtein distance for UTF-32 "strings". */ uint32_t levenshtein(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t) { const size_t n(s.size()), m(t.size()); std::vector<uint32_t> current(m + 1), last(m + 1); return levenshteinCore(s, t, current, last); } uint32_t levenshteinStatic(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t) { const size_t m(t.size()); static std::vector<uint32_t> current; static std::vector<uint32_t> last; if (current.size() < m + 1) { // Also: g_last.size < m + 1 current.resize(m + 1); last.resize(m + 1); } return levenshteinCore(s, t, current, last); } uint32_t levenshteinLimitCore(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, std::vector<uint32_t> &current, std::vector<uint32_t> &last, const uint32_t threshold) { const size_t n(s.size()), m(t.size()); // Initialise with unmatched characters in t for (size_t j = 0; j <= m; ++j) last[j] = j; for (size_t i = 0; i < n; ++i) { current[0] = i+1; // min(start) = 1 as position 0 is handled above const uint32_t start(std::max(1, (int)i - (int)threshold)), stop(std::min(m, i + threshold)); for (size_t j = start; j <= stop; ++j) { current[j] = std::min(last[j] + 1, current[j-1] + 1); // insertion / deletion current[j] = std::min(current[j], last[j-1] + (int)(s[i] != t[j-1])); // modification } // start needs to include position 0 and current[stop] const auto it_start(current.cbegin() + std::max(0, (int)i - (int)threshold)), it_stop(current.cbegin() + stop + 1); if (*std::min_element(it_start, it_stop) > threshold) { return -1; } current.swap(last); } return last.back(); } /** * Levenshtein distance for UTF-32 "strings". */ uint32_t levenshteinLimit(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, const uint32_t threshold) { const size_t n(s.size()), m(t.size()); std::vector<uint32_t> current(m + 1), last(m + 1); return levenshteinLimitCore(s, t, current, last, threshold); } uint32_t levenshteinLimitStatic(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, const uint32_t threshold) { const size_t m(t.size()); static std::vector<uint32_t> current; static std::vector<uint32_t> last; if (current.size() < m + 1) { // Also: last.size < m + 1 current.resize(m + 1); last.resize(m + 1); } return levenshteinLimitCore(s, t, current, last, threshold); } <commit_msg>Don't compare strings if the difference in length exceeds threshold<commit_after>#include <algorithm> #include "levenshtein.h" uint32_t levenshteinCore(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, std::vector<uint32_t> &current, std::vector<uint32_t> &last) { const size_t n(s.size()), m(t.size()); // Initialise with unmatched characters in t for (size_t j = 0; j <= m; ++j) last[j] = j; for (size_t i = 0; i < n; ++i) { current[0] = i+1; // = last[0]+1, corresponds to unmatched character in s for (size_t j = 1; j <= m; ++j) { current[j] = std::min(last[j] + 1, current[j-1] + 1); // insertion / deletion current[j] = std::min(current[j], last[j-1] + (int)(s[i] != t[j-1])); // modification } current.swap(last); } return last.back(); } /** * Levenshtein distance for UTF-32 "strings". */ uint32_t levenshtein(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t) { const size_t n(s.size()), m(t.size()); std::vector<uint32_t> current(m + 1), last(m + 1); return levenshteinCore(s, t, current, last); } uint32_t levenshteinStatic(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t) { const size_t m(t.size()); static std::vector<uint32_t> current; static std::vector<uint32_t> last; if (current.size() < m + 1) { // Also: g_last.size < m + 1 current.resize(m + 1); last.resize(m + 1); } return levenshteinCore(s, t, current, last); } uint32_t levenshteinLimitCore(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, std::vector<uint32_t> &current, std::vector<uint32_t> &last, const uint32_t threshold) { const size_t n(s.size()), m(t.size()); // Initialise with unmatched characters in t for (size_t j = 0; j <= m; ++j) last[j] = j; for (size_t i = 0; i < n; ++i) { current[0] = i+1; // min(start) = 1 as position 0 is handled above const uint32_t start(std::max(1, (int)i - (int)threshold)), stop(std::min(m, i + threshold)); for (size_t j = start; j <= stop; ++j) { current[j] = std::min(last[j] + 1, current[j-1] + 1); // insertion / deletion current[j] = std::min(current[j], last[j-1] + (int)(s[i] != t[j-1])); // modification } // start needs to include position 0 and current[stop] const auto it_start(current.cbegin() + std::max(0, (int)i - (int)threshold)), it_stop(current.cbegin() + stop + 1); if (*std::min_element(it_start, it_stop) > threshold) { return -1; } current.swap(last); } return last.back(); } /** * Levenshtein distance for UTF-32 "strings". */ uint32_t levenshteinLimit(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, const uint32_t threshold) { const size_t n(s.size()), m(t.size()); // If the difference in word length exceeds the threshold, don't even bother if ((m < n && n-m > threshold) || (m > n && m-n > threshold)) { return -1; } std::vector<uint32_t> current(m + 1), last(m + 1); return levenshteinLimitCore(s, t, current, last, threshold); } uint32_t levenshteinLimitStatic(const std::vector<uint32_t> &s, const std::vector<uint32_t> &t, const uint32_t threshold) { const size_t n(s.size()), m(t.size()); static std::vector<uint32_t> current; static std::vector<uint32_t> last; // If the difference in word length exceeds the threshold, don't even bother if ((m < n && n-m > threshold) || (m > n && m-n > threshold)) { return -1; } if (current.size() < m + 1) { // Also: last.size < m + 1 current.resize(m + 1); last.resize(m + 1); } return levenshteinLimitCore(s, t, current, last, threshold); } <|endoftext|>
<commit_before>#include "sleekwindowclass.h" #include "sleekwindow.h" #include "windowsx.h" #include <QPushButton> #include <QSettings> #include <QCoreApplication> #include <QFileInfo> #include <QDebug> SleekWindowClass::SleekWindowClass() : _ivoryBrush(CreateSolidBrush(RGB(226,226,226))), _graphiteBrush(CreateSolidBrush(RGB(51,51,51))), _hInstance( GetModuleHandle( NULL ) ) { QSettings settings(QApplication::applicationDirPath() + "/settings.ini", QSettings::IniFormat); QString theme = settings.value("theme").toString(); WNDCLASSEX wcx = { 0 }; wcx.cbSize = sizeof( WNDCLASSEX ); wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.hInstance = _hInstance; wcx.lpfnWndProc = WndProc; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.lpszClassName = L"SleekWindowClass"; if (theme == "graphite") wcx.hbrBackground = _graphiteBrush; else if (theme == "ivory") wcx.hbrBackground = _ivoryBrush; else wcx.hbrBackground = _graphiteBrush; wcx.hCursor = LoadCursor( _hInstance, IDC_ARROW ); wcx.hIconSm = NULL; wcx.hIcon = LoadIcon(_hInstance, L"IDI_ICON1"); RegisterClassEx( &wcx ); if ( FAILED( RegisterClassEx( &wcx ) ) ) throw std::runtime_error( "Couldn't register window class" ); } SleekWindowClass::~SleekWindowClass() { DeleteObject(_graphiteBrush); DeleteObject(_ivoryBrush); UnregisterClass(L"SleekWindowClass", _hInstance); } void SleekWindowClass::setBackgroundBrush(HWND hWnd, QString theme) { if (theme == "graphite") SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND , (LONG)_graphiteBrush); else if (theme == "ivory") SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND , (LONG)_ivoryBrush); } HINSTANCE SleekWindowClass::getHInstance() { return _hInstance; } HDC hdc; PAINTSTRUCT ps; LRESULT CALLBACK SleekWindowClass::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { SleekWindow *win = reinterpret_cast<SleekWindow*>( GetWindowLongPtr( hWnd, GWLP_USERDATA ) ); if ( !win ) return DefWindowProc( hWnd, message, wParam, lParam ); QWidget *window = win->getMainPanel(); switch ( message ) { case WM_DESTROY: { qDebug() << "SleekWindowClass: WM_DESTROY RECEIVED!"; //PostQuitMessage(0); break; } case WM_CLOSE: { qDebug() << "SleekWindowClass: WM_CLOSE RECEIVED!"; DestroyWindow(win->getHandle()); break; } case WM_KEYDOWN: { switch ( wParam ) { case VK_F5: { qDebug() << window->childAt(window->mapFromGlobal(QCursor::pos())); break; } case VK_F6: { win->toggleShadow(); win->toggleBorderless(); SetFocus( (HWND)window->winId() ); break; } case VK_F7: { win->toggleShadow(); break; } } if ( wParam != VK_TAB ) return DefWindowProc( hWnd, message, wParam, lParam ); SetFocus( (HWND)window->winId() ); break; } // ALT + SPACE or F10 system menu case WM_SYSCOMMAND: { if ( wParam == SC_KEYMENU ) { RECT winrect; GetWindowRect( hWnd, &winrect ); TrackPopupMenu( GetSystemMenu( hWnd, false ), TPM_TOPALIGN | TPM_LEFTALIGN, winrect.left + 5, winrect.top + 5, 0, hWnd, NULL); break; } else { return DefWindowProc( hWnd, message, wParam, lParam ); } } case WM_SETFOCUS: { QString str( "Got focus" ); QWidget *widget = QWidget::find( ( WId )HWND( wParam ) ); if ( widget ) str += QString( " from %1 (%2)" ).arg( widget->objectName() ).arg(widget->metaObject()->className() ); str += "\n"; OutputDebugStringA( str.toLocal8Bit().data() ); break; } case WM_NCCALCSIZE: { //this kills the window frame and title bar we added with //WS_THICKFRAME and WS_CAPTION if (win->getBorderless()) { return 0; } break; } case WM_KILLFOCUS: { QString str( "Lost focus" ); QWidget *widget = QWidget::find( (WId)HWND( wParam ) ); if ( widget ) str += QString( " to %1 (%2)" ).arg( widget->objectName() ).arg(widget->metaObject()->className() ); str += "\n"; OutputDebugStringA( str.toLocal8Bit().data() ); break; } case WM_NCHITTEST: { if ( win->getBorderless() ) { if ( win->getBorderlessResizable() ) { const LONG borderWidth = 5; //in pixels RECT winrect; GetWindowRect(hWnd, &winrect); long x = GET_X_LPARAM( lParam ); long y = GET_Y_LPARAM( lParam ); //bottom left corner if ( x >= winrect.left && x < winrect.left + borderWidth + 6 && y < winrect.bottom && y >= winrect.bottom - borderWidth - 6 ) { return HTBOTTOMLEFT; } //bottom right corner if ( x < winrect.right && x >= winrect.right - borderWidth - 6 && y < winrect.bottom && y >= winrect.bottom - borderWidth - 6 ) { return HTBOTTOMRIGHT; } //top left corner if ( x >= winrect.left && x < winrect.left + borderWidth + 6 && y >= winrect.top && y < winrect.top + borderWidth + 6 ) { return HTTOPLEFT; } //top right corner if ( x < winrect.right && x >= winrect.right - borderWidth - 6 && y >= winrect.top && y < winrect.top + borderWidth + 6 ) { return HTTOPRIGHT; } //left border if ( x >= winrect.left && x < winrect.left + borderWidth ) { return HTLEFT; } //right border if ( x < winrect.right && x >= winrect.right - borderWidth ) { return HTRIGHT; } //bottom border if ( y < winrect.bottom && y >= winrect.bottom - borderWidth ) { return HTBOTTOM; } //top border if ( y >= winrect.top && y < winrect.top + borderWidth ) { return HTTOP; } } } } case WM_SIZE: { RECT winrect; GetClientRect( hWnd, &winrect ); WINDOWPLACEMENT wp; wp.length = sizeof( WINDOWPLACEMENT ); GetWindowPlacement( hWnd, &wp ); if ( wp.showCmd == SW_MAXIMIZE ) { QPushButton* pushButtonMaximize = win->getSleekBorderless()->findChild<QPushButton*>( "pushButtonMaximize" ); pushButtonMaximize->setStyleSheet( "#pushButtonMaximize {image: url(:/icons/header/Restore.png);} #pushButtonMaximize:hover { image: url(:/icons/header/RestoreHover.png); }" ); win->getSleekBorderless()->setGeometry( 8, 8, winrect.right - 16, winrect.bottom - 16); } else { QPushButton* pushButtonMaximize = win->getSleekBorderless()->findChild<QPushButton*>( "pushButtonMaximize" ); pushButtonMaximize->setStyleSheet( "#pushButtonMaximize {image: url(:/icons/header/Maximize.png);} #pushButtonMaximize:hover { image: url(:/icons/header/MaximizeHover.png); }" ); win->getSleekBorderless()->setGeometry( 0, 0, winrect.right, winrect.bottom); } break; } case WM_GETMINMAXINFO: { MINMAXINFO* minMaxInfo = ( MINMAXINFO* )lParam; if ( win->isSetMinimumSize() ) { minMaxInfo->ptMinTrackSize.x = win->getMinimumWidth(); minMaxInfo->ptMinTrackSize.y = win->getMinimumHeight(); } if ( win->isSetMaximumSize() ) { minMaxInfo->ptMaxTrackSize.x = win->getMaximumWidth(); minMaxInfo->ptMaxTrackSize.y = win->getMaximumHeight(); minMaxInfo->ptMaxSize.x = win->getMaximumWidth(); minMaxInfo->ptMaxSize.y = win->getMaximumHeight(); } break; } } return DefWindowProc(hWnd, message, wParam, lParam); } <commit_msg>Close using taskbar context menu.<commit_after>#include "sleekwindowclass.h" #include "sleekwindow.h" #include "windowsx.h" #include <QPushButton> #include <QSettings> #include <QCoreApplication> #include <QFileInfo> #include <QDebug> SleekWindowClass::SleekWindowClass() : _ivoryBrush(CreateSolidBrush(RGB(226,226,226))), _graphiteBrush(CreateSolidBrush(RGB(51,51,51))), _hInstance( GetModuleHandle( NULL ) ) { QSettings settings(QApplication::applicationDirPath() + "/settings.ini", QSettings::IniFormat); QString theme = settings.value("theme").toString(); WNDCLASSEX wcx = { 0 }; wcx.cbSize = sizeof( WNDCLASSEX ); wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.hInstance = _hInstance; wcx.lpfnWndProc = WndProc; wcx.cbClsExtra = 0; wcx.cbWndExtra = 0; wcx.lpszClassName = L"SleekWindowClass"; if (theme == "graphite") wcx.hbrBackground = _graphiteBrush; else if (theme == "ivory") wcx.hbrBackground = _ivoryBrush; else wcx.hbrBackground = _graphiteBrush; wcx.hCursor = LoadCursor( _hInstance, IDC_ARROW ); wcx.hIconSm = NULL; wcx.hIcon = LoadIcon(_hInstance, L"IDI_ICON1"); RegisterClassEx( &wcx ); if ( FAILED( RegisterClassEx( &wcx ) ) ) throw std::runtime_error( "Couldn't register window class" ); } SleekWindowClass::~SleekWindowClass() { DeleteObject(_graphiteBrush); DeleteObject(_ivoryBrush); UnregisterClass(L"SleekWindowClass", _hInstance); } void SleekWindowClass::setBackgroundBrush(HWND hWnd, QString theme) { if (theme == "graphite") SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND , (LONG)_graphiteBrush); else if (theme == "ivory") SetClassLongPtr(hWnd, GCLP_HBRBACKGROUND , (LONG)_ivoryBrush); } HINSTANCE SleekWindowClass::getHInstance() { return _hInstance; } HDC hdc; PAINTSTRUCT ps; LRESULT CALLBACK SleekWindowClass::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { SleekWindow *win = reinterpret_cast<SleekWindow*>( GetWindowLongPtr( hWnd, GWLP_USERDATA ) ); if ( !win ) return DefWindowProc( hWnd, message, wParam, lParam ); QWidget *window = win->getMainPanel(); switch ( message ) { case WM_DESTROY: { qDebug() << "SleekWindowClass: WM_DESTROY RECEIVED!"; //PostQuitMessage(0); break; } case WM_CLOSE: { qDebug() << "SleekWindowClass: WM_CLOSE RECEIVED!"; //DestroyWindow(win->getHandle()); win->close(); break; } case WM_KEYDOWN: { switch ( wParam ) { case VK_F5: { qDebug() << window->childAt(window->mapFromGlobal(QCursor::pos())); break; } case VK_F6: { win->toggleShadow(); win->toggleBorderless(); SetFocus( (HWND)window->winId() ); break; } case VK_F7: { win->toggleShadow(); break; } } if ( wParam != VK_TAB ) return DefWindowProc( hWnd, message, wParam, lParam ); SetFocus( (HWND)window->winId() ); break; } // ALT + SPACE or F10 system menu case WM_SYSCOMMAND: { if ( wParam == SC_KEYMENU ) { RECT winrect; GetWindowRect( hWnd, &winrect ); TrackPopupMenu( GetSystemMenu( hWnd, false ), TPM_TOPALIGN | TPM_LEFTALIGN, winrect.left + 5, winrect.top + 5, 0, hWnd, NULL); break; } else { return DefWindowProc( hWnd, message, wParam, lParam ); } } case WM_SETFOCUS: { QString str( "Got focus" ); QWidget *widget = QWidget::find( ( WId )HWND( wParam ) ); if ( widget ) str += QString( " from %1 (%2)" ).arg( widget->objectName() ).arg(widget->metaObject()->className() ); str += "\n"; OutputDebugStringA( str.toLocal8Bit().data() ); break; } case WM_NCCALCSIZE: { //this kills the window frame and title bar we added with //WS_THICKFRAME and WS_CAPTION if (win->getBorderless()) { return 0; } break; } case WM_KILLFOCUS: { QString str( "Lost focus" ); QWidget *widget = QWidget::find( (WId)HWND( wParam ) ); if ( widget ) str += QString( " to %1 (%2)" ).arg( widget->objectName() ).arg(widget->metaObject()->className() ); str += "\n"; OutputDebugStringA( str.toLocal8Bit().data() ); break; } case WM_NCHITTEST: { if ( win->getBorderless() ) { if ( win->getBorderlessResizable() ) { const LONG borderWidth = 5; //in pixels RECT winrect; GetWindowRect(hWnd, &winrect); long x = GET_X_LPARAM( lParam ); long y = GET_Y_LPARAM( lParam ); //bottom left corner if ( x >= winrect.left && x < winrect.left + borderWidth + 6 && y < winrect.bottom && y >= winrect.bottom - borderWidth - 6 ) { return HTBOTTOMLEFT; } //bottom right corner if ( x < winrect.right && x >= winrect.right - borderWidth - 6 && y < winrect.bottom && y >= winrect.bottom - borderWidth - 6 ) { return HTBOTTOMRIGHT; } //top left corner if ( x >= winrect.left && x < winrect.left + borderWidth + 6 && y >= winrect.top && y < winrect.top + borderWidth + 6 ) { return HTTOPLEFT; } //top right corner if ( x < winrect.right && x >= winrect.right - borderWidth - 6 && y >= winrect.top && y < winrect.top + borderWidth + 6 ) { return HTTOPRIGHT; } //left border if ( x >= winrect.left && x < winrect.left + borderWidth ) { return HTLEFT; } //right border if ( x < winrect.right && x >= winrect.right - borderWidth ) { return HTRIGHT; } //bottom border if ( y < winrect.bottom && y >= winrect.bottom - borderWidth ) { return HTBOTTOM; } //top border if ( y >= winrect.top && y < winrect.top + borderWidth ) { return HTTOP; } } } } case WM_SIZE: { RECT winrect; GetClientRect( hWnd, &winrect ); WINDOWPLACEMENT wp; wp.length = sizeof( WINDOWPLACEMENT ); GetWindowPlacement( hWnd, &wp ); if ( wp.showCmd == SW_MAXIMIZE ) { QPushButton* pushButtonMaximize = win->getSleekBorderless()->findChild<QPushButton*>( "pushButtonMaximize" ); pushButtonMaximize->setStyleSheet( "#pushButtonMaximize {image: url(:/icons/header/Restore.png);} #pushButtonMaximize:hover { image: url(:/icons/header/RestoreHover.png); }" ); win->getSleekBorderless()->setGeometry( 8, 8, winrect.right - 16, winrect.bottom - 16); } else { QPushButton* pushButtonMaximize = win->getSleekBorderless()->findChild<QPushButton*>( "pushButtonMaximize" ); pushButtonMaximize->setStyleSheet( "#pushButtonMaximize {image: url(:/icons/header/Maximize.png);} #pushButtonMaximize:hover { image: url(:/icons/header/MaximizeHover.png); }" ); win->getSleekBorderless()->setGeometry( 0, 0, winrect.right, winrect.bottom); } break; } case WM_GETMINMAXINFO: { MINMAXINFO* minMaxInfo = ( MINMAXINFO* )lParam; if ( win->isSetMinimumSize() ) { minMaxInfo->ptMinTrackSize.x = win->getMinimumWidth(); minMaxInfo->ptMinTrackSize.y = win->getMinimumHeight(); } if ( win->isSetMaximumSize() ) { minMaxInfo->ptMaxTrackSize.x = win->getMaximumWidth(); minMaxInfo->ptMaxTrackSize.y = win->getMaximumHeight(); minMaxInfo->ptMaxSize.x = win->getMaximumWidth(); minMaxInfo->ptMaxSize.y = win->getMaximumHeight(); } break; } } return DefWindowProc(hWnd, message, wParam, lParam); } <|endoftext|>
<commit_before>/* Copyright 2016 Streampunk Media Ltd 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. */ /* -LICENSE-START- ** Copyright (c) 2015 Blackmagic Design ** ** Permission is hereby granted, free of charge, to any person or organization ** obtaining a copy of the software and accompanying documentation covered by ** this license (the "Software") to use, reproduce, display, distribute, ** execute, and transmit the Software, and to prepare derivative works of the ** Software, and to permit third-parties to whom the Software is furnished to ** do so, all subject to the following: ** ** The copyright notices in the Software and this entire statement, including ** the above license grant, this restriction and the following disclaimer, ** must be included in all copies of the Software, in whole or in part, and ** all derivative works of the Software, unless such copies or derivative ** works are solely in the form of machine-executable object code generated by ** a source language processor. ** ** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** -LICENSE-END- */ #include <node.h> #include "node_buffer.h" #include "DeckLinkAPI.h" #include <stdio.h> #include "Capture.h" #include "Playback.h" using namespace v8; void DeckLinkVersion(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); IDeckLinkIterator* deckLinkIterator; HRESULT result; IDeckLinkAPIInformation* deckLinkAPIInformation; deckLinkIterator = CreateDeckLinkIteratorInstance(); result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void**)&deckLinkAPIInformation); if (result != S_OK) { isolate->ThrowException(Exception::Error( String::NewFromUtf8(isolate, "Error connecting to DeckLinkAPI."))); } char deckVer [80]; int64_t deckLinkVersion; int dlVerMajor, dlVerMinor, dlVerPoint; // We can also use the BMDDeckLinkAPIVersion flag with GetString deckLinkAPIInformation->GetInt(BMDDeckLinkAPIVersion, &deckLinkVersion); dlVerMajor = (deckLinkVersion & 0xFF000000) >> 24; dlVerMinor = (deckLinkVersion & 0x00FF0000) >> 16; dlVerPoint = (deckLinkVersion & 0x0000FF00) >> 8; sprintf(deckVer, "DeckLinkAPI version: %d.%d.%d", dlVerMajor, dlVerMinor, dlVerPoint); deckLinkAPIInformation->Release(); Local<String> deckVerString = String::NewFromUtf8(isolate, deckVer); args.GetReturnValue().Set(deckVerString); } void GetFirstDevice(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); IDeckLinkIterator* deckLinkIterator; HRESULT result; IDeckLinkAPIInformation *deckLinkAPIInformation; IDeckLink* deckLink; deckLinkIterator = CreateDeckLinkIteratorInstance(); result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void**)&deckLinkAPIInformation); if (result != S_OK) { isolate->ThrowException(Exception::Error( String::NewFromUtf8(isolate, "Error connecting to DeckLinkAPI."))); } if (deckLinkIterator->Next(&deckLink) != S_OK) { args.GetReturnValue().Set(Undefined(isolate)); return; } CFStringRef deviceNameCFString = NULL; result = deckLink->GetModelName(&deviceNameCFString); if (result == S_OK) { char deviceName [64]; CFStringGetCString(deviceNameCFString, deviceName, sizeof(deviceName), kCFStringEncodingMacRoman); args.GetReturnValue().Set(String::NewFromUtf8(isolate, deviceName)); return; } args.GetReturnValue().Set(Undefined(isolate)); node::Buffer::New(isolate, 42); } /* static Local<Object> makeBuffer(char* data, size_t size) { HandleScope scope; // It ends up being kind of a pain to convert a slow buffer into a fast // one since the fast part is implemented in JavaScript. Local<Buffer> slowBuffer = Buffer::New(data, size); // First get the Buffer from global scope... Local<Object> global = Context::GetCurrent()->Global(); Local<Value> bv = global->Get(String::NewSymbol("Buffer")); assert(bv->IsFunction()); Local<Function> b = Local<Function>::Cast(bv); // ...call Buffer() with the slow buffer and get a fast buffer back... Handle<Value> argv[3] = { slowBuffer->handle_, Integer::New(size), Integer::New(0) }; Local<Object> fastBuffer = b->NewInstance(3, argv); return scope.Close(fastBuffer); } */ void init(Local<Object> exports) { NODE_SET_METHOD(exports, "deckLinkVersion", DeckLinkVersion); NODE_SET_METHOD(exports, "getFirstDevice", GetFirstDevice); streampunk::Capture::Init(exports); streampunk::Playback::Init(exports); } NODE_MODULE(macadam, init); <commit_msg>Added define to stop re-definition of winsock stuff.<commit_after>/* Copyright 2016 Streampunk Media Ltd 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. */ /* -LICENSE-START- ** Copyright (c) 2015 Blackmagic Design ** ** Permission is hereby granted, free of charge, to any person or organization ** obtaining a copy of the software and accompanying documentation covered by ** this license (the "Software") to use, reproduce, display, distribute, ** execute, and transmit the Software, and to prepare derivative works of the ** Software, and to permit third-parties to whom the Software is furnished to ** do so, all subject to the following: ** ** The copyright notices in the Software and this entire statement, including ** the above license grant, this restriction and the following disclaimer, ** must be included in all copies of the Software, in whole or in part, and ** all derivative works of the Software, unless such copies or derivative ** works are solely in the form of machine-executable object code generated by ** a source language processor. ** ** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** -LICENSE-END- */ #define _WINSOCKAPI_:wq #include <node.h> #include "node_buffer.h" #include "DeckLinkAPI.h" #include <stdio.h> #include "Capture.h" #include "Playback.h" using namespace v8; void DeckLinkVersion(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); IDeckLinkIterator* deckLinkIterator; HRESULT result; IDeckLinkAPIInformation* deckLinkAPIInformation; deckLinkIterator = CreateDeckLinkIteratorInstance(); result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void**)&deckLinkAPIInformation); if (result != S_OK) { isolate->ThrowException(Exception::Error( String::NewFromUtf8(isolate, "Error connecting to DeckLinkAPI."))); } char deckVer [80]; int64_t deckLinkVersion; int dlVerMajor, dlVerMinor, dlVerPoint; // We can also use the BMDDeckLinkAPIVersion flag with GetString deckLinkAPIInformation->GetInt(BMDDeckLinkAPIVersion, &deckLinkVersion); dlVerMajor = (deckLinkVersion & 0xFF000000) >> 24; dlVerMinor = (deckLinkVersion & 0x00FF0000) >> 16; dlVerPoint = (deckLinkVersion & 0x0000FF00) >> 8; sprintf(deckVer, "DeckLinkAPI version: %d.%d.%d", dlVerMajor, dlVerMinor, dlVerPoint); deckLinkAPIInformation->Release(); Local<String> deckVerString = String::NewFromUtf8(isolate, deckVer); args.GetReturnValue().Set(deckVerString); } void GetFirstDevice(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); IDeckLinkIterator* deckLinkIterator; HRESULT result; IDeckLinkAPIInformation *deckLinkAPIInformation; IDeckLink* deckLink; deckLinkIterator = CreateDeckLinkIteratorInstance(); result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void**)&deckLinkAPIInformation); if (result != S_OK) { isolate->ThrowException(Exception::Error( String::NewFromUtf8(isolate, "Error connecting to DeckLinkAPI."))); } if (deckLinkIterator->Next(&deckLink) != S_OK) { args.GetReturnValue().Set(Undefined(isolate)); return; } CFStringRef deviceNameCFString = NULL; result = deckLink->GetModelName(&deviceNameCFString); if (result == S_OK) { char deviceName [64]; CFStringGetCString(deviceNameCFString, deviceName, sizeof(deviceName), kCFStringEncodingMacRoman); args.GetReturnValue().Set(String::NewFromUtf8(isolate, deviceName)); return; } args.GetReturnValue().Set(Undefined(isolate)); node::Buffer::New(isolate, 42); } /* static Local<Object> makeBuffer(char* data, size_t size) { HandleScope scope; // It ends up being kind of a pain to convert a slow buffer into a fast // one since the fast part is implemented in JavaScript. Local<Buffer> slowBuffer = Buffer::New(data, size); // First get the Buffer from global scope... Local<Object> global = Context::GetCurrent()->Global(); Local<Value> bv = global->Get(String::NewSymbol("Buffer")); assert(bv->IsFunction()); Local<Function> b = Local<Function>::Cast(bv); // ...call Buffer() with the slow buffer and get a fast buffer back... Handle<Value> argv[3] = { slowBuffer->handle_, Integer::New(size), Integer::New(0) }; Local<Object> fastBuffer = b->NewInstance(3, argv); return scope.Close(fastBuffer); } */ void init(Local<Object> exports) { NODE_SET_METHOD(exports, "deckLinkVersion", DeckLinkVersion); NODE_SET_METHOD(exports, "getFirstDevice", GetFirstDevice); streampunk::Capture::Init(exports); streampunk::Playback::Init(exports); } NODE_MODULE(macadam, init); <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkVTKRenderView.h" #include "ctkVTKRenderView_p.h" // VTK includes #include <vtkRendererCollection.h> #include <vtkRenderWindowInteractor.h> #include <vtkTextProperty.h> // -------------------------------------------------------------------------- // ctkVTKRenderViewPrivate methods // -------------------------------------------------------------------------- ctkVTKRenderViewPrivate::ctkVTKRenderViewPrivate() { this->Renderer = vtkSmartPointer<vtkRenderer>::New(); this->RenderWindow = vtkSmartPointer<vtkRenderWindow>::New(); this->Axes = vtkSmartPointer<vtkAxesActor>::New(); this->Orientation = vtkSmartPointer<vtkOrientationMarkerWidget>::New(); this->CornerAnnotation = vtkSmartPointer<vtkCornerAnnotation>::New(); this->RenderPending = false; this->RenderEnabled = false; } // -------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupCornerAnnotation() { if (!this->Renderer->HasViewProp(this->CornerAnnotation)) { this->Renderer->AddViewProp(this->CornerAnnotation); this->CornerAnnotation->SetMaximumLineHeight(0.07); vtkTextProperty *tprop = this->CornerAnnotation->GetTextProperty(); tprop->ShadowOn(); } this->CornerAnnotation->ClearAllTexts(); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupRendering() { Q_ASSERT(this->RenderWindow); this->RenderWindow->SetAlphaBitPlanes(1); this->RenderWindow->SetMultiSamples(0); this->RenderWindow->StereoCapableWindowOn(); this->RenderWindow->GetRenderers()->RemoveAllItems(); // Add renderer this->RenderWindow->AddRenderer(this->Renderer); // Setup the corner annotation this->setupCornerAnnotation(); this->VTKWidget->SetRenderWindow(this->RenderWindow); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupDefaultInteractor() { CTK_P(ctkVTKRenderView); p->setInteractor(this->RenderWindow->GetInteractor()); } //--------------------------------------------------------------------------- // ctkVTKRenderView methods // -------------------------------------------------------------------------- ctkVTKRenderView::ctkVTKRenderView(QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkVTKRenderView); CTK_D(ctkVTKRenderView); d->VTKWidget = new QVTKWidget(this); this->setLayout(new QVBoxLayout); this->layout()->setMargin(0); this->layout()->setSpacing(0); this->layout()->addWidget(d->VTKWidget); d->setupRendering(); d->setupDefaultInteractor(); } // -------------------------------------------------------------------------- ctkVTKRenderView::~ctkVTKRenderView() { } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderWindowInteractor*, interactor, CurrentInteractor); //---------------------------------------------------------------------------- void ctkVTKRenderView::scheduleRender() { CTK_D(ctkVTKRenderView); if (!d->RenderEnabled) { return; } if (!d->RenderPending) { d->RenderPending = true; QTimer::singleShot(0, this, SLOT(forceRender())); } } //---------------------------------------------------------------------------- void ctkVTKRenderView::forceRender() { CTK_D(ctkVTKRenderView); if (!d->RenderEnabled) { return; } d->RenderWindow->Render(); d->RenderPending = false; } //---------------------------------------------------------------------------- void ctkVTKRenderView::setInteractor(vtkRenderWindowInteractor* newInteractor) { Q_ASSERT(newInteractor); CTK_D(ctkVTKRenderView); d->RenderWindow->SetInteractor(newInteractor); d->Orientation->SetOrientationMarker(d->Axes); d->Orientation->SetInteractor(newInteractor); d->Orientation->SetEnabled(1); d->Orientation->InteractiveOff(); d->CurrentInteractor = newInteractor; } //---------------------------------------------------------------------------- void ctkVTKRenderView::setCornerAnnotationText(const QString& text) { CTK_D(ctkVTKRenderView); d->CornerAnnotation->ClearAllTexts(); d->CornerAnnotation->SetText(2, text.toLatin1()); } // -------------------------------------------------------------------------- void ctkVTKRenderView::setBackgroundColor(double r, double g, double b) { CTK_D(ctkVTKRenderView); double background_color[3] = {r, g, b}; d->Renderer->SetBackground(background_color); } //---------------------------------------------------------------------------- vtkCamera* ctkVTKRenderView::activeCamera() { CTK_D(ctkVTKRenderView); if (d->Renderer->IsActiveCameraCreated()) { return 0; } else { return d->Renderer->GetActiveCamera(); } } //---------------------------------------------------------------------------- void ctkVTKRenderView::resetCamera() { CTK_D(ctkVTKRenderView); d->Renderer->ResetCamera(); } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderer*, renderer, Renderer); //---------------------------------------------------------------------------- CTK_SET_CXX(ctkVTKRenderView, bool, setRenderEnabled, RenderEnabled); <commit_msg>BUG: In ctkVTKRenderView, fix function activeCamera()<commit_after>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.commontk.org/LICENSE 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. =========================================================================*/ // Qt includes #include <QTimer> #include <QVBoxLayout> // CTK includes #include "ctkVTKRenderView.h" #include "ctkVTKRenderView_p.h" // VTK includes #include <vtkRendererCollection.h> #include <vtkRenderWindowInteractor.h> #include <vtkTextProperty.h> // -------------------------------------------------------------------------- // ctkVTKRenderViewPrivate methods // -------------------------------------------------------------------------- ctkVTKRenderViewPrivate::ctkVTKRenderViewPrivate() { this->Renderer = vtkSmartPointer<vtkRenderer>::New(); this->RenderWindow = vtkSmartPointer<vtkRenderWindow>::New(); this->Axes = vtkSmartPointer<vtkAxesActor>::New(); this->Orientation = vtkSmartPointer<vtkOrientationMarkerWidget>::New(); this->CornerAnnotation = vtkSmartPointer<vtkCornerAnnotation>::New(); this->RenderPending = false; this->RenderEnabled = false; } // -------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupCornerAnnotation() { if (!this->Renderer->HasViewProp(this->CornerAnnotation)) { this->Renderer->AddViewProp(this->CornerAnnotation); this->CornerAnnotation->SetMaximumLineHeight(0.07); vtkTextProperty *tprop = this->CornerAnnotation->GetTextProperty(); tprop->ShadowOn(); } this->CornerAnnotation->ClearAllTexts(); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupRendering() { Q_ASSERT(this->RenderWindow); this->RenderWindow->SetAlphaBitPlanes(1); this->RenderWindow->SetMultiSamples(0); this->RenderWindow->StereoCapableWindowOn(); this->RenderWindow->GetRenderers()->RemoveAllItems(); // Add renderer this->RenderWindow->AddRenderer(this->Renderer); // Setup the corner annotation this->setupCornerAnnotation(); this->VTKWidget->SetRenderWindow(this->RenderWindow); } //--------------------------------------------------------------------------- void ctkVTKRenderViewPrivate::setupDefaultInteractor() { CTK_P(ctkVTKRenderView); p->setInteractor(this->RenderWindow->GetInteractor()); } //--------------------------------------------------------------------------- // ctkVTKRenderView methods // -------------------------------------------------------------------------- ctkVTKRenderView::ctkVTKRenderView(QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkVTKRenderView); CTK_D(ctkVTKRenderView); d->VTKWidget = new QVTKWidget(this); this->setLayout(new QVBoxLayout); this->layout()->setMargin(0); this->layout()->setSpacing(0); this->layout()->addWidget(d->VTKWidget); d->setupRendering(); d->setupDefaultInteractor(); } // -------------------------------------------------------------------------- ctkVTKRenderView::~ctkVTKRenderView() { } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderWindowInteractor*, interactor, CurrentInteractor); //---------------------------------------------------------------------------- void ctkVTKRenderView::scheduleRender() { CTK_D(ctkVTKRenderView); if (!d->RenderEnabled) { return; } if (!d->RenderPending) { d->RenderPending = true; QTimer::singleShot(0, this, SLOT(forceRender())); } } //---------------------------------------------------------------------------- void ctkVTKRenderView::forceRender() { CTK_D(ctkVTKRenderView); if (!d->RenderEnabled) { return; } d->RenderWindow->Render(); d->RenderPending = false; } //---------------------------------------------------------------------------- void ctkVTKRenderView::setInteractor(vtkRenderWindowInteractor* newInteractor) { Q_ASSERT(newInteractor); CTK_D(ctkVTKRenderView); d->RenderWindow->SetInteractor(newInteractor); d->Orientation->SetOrientationMarker(d->Axes); d->Orientation->SetInteractor(newInteractor); d->Orientation->SetEnabled(1); d->Orientation->InteractiveOff(); d->CurrentInteractor = newInteractor; } //---------------------------------------------------------------------------- void ctkVTKRenderView::setCornerAnnotationText(const QString& text) { CTK_D(ctkVTKRenderView); d->CornerAnnotation->ClearAllTexts(); d->CornerAnnotation->SetText(2, text.toLatin1()); } // -------------------------------------------------------------------------- void ctkVTKRenderView::setBackgroundColor(double r, double g, double b) { CTK_D(ctkVTKRenderView); double background_color[3] = {r, g, b}; d->Renderer->SetBackground(background_color); } //---------------------------------------------------------------------------- vtkCamera* ctkVTKRenderView::activeCamera() { CTK_D(ctkVTKRenderView); if (d->Renderer->IsActiveCameraCreated()) { return d->Renderer->GetActiveCamera(); } else { return 0; } } //---------------------------------------------------------------------------- void ctkVTKRenderView::resetCamera() { CTK_D(ctkVTKRenderView); d->Renderer->ResetCamera(); } //---------------------------------------------------------------------------- CTK_GET_CXX(ctkVTKRenderView, vtkRenderer*, renderer, Renderer); //---------------------------------------------------------------------------- CTK_SET_CXX(ctkVTKRenderView, bool, setRenderEnabled, RenderEnabled); <|endoftext|>
<commit_before>/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/operator.h" namespace paddle { namespace operators { class TruncOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { OP_INOUT_CHECK(ctx->HasInput("X"), "Input", "X", "trunc"); OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "trunc"); auto input_dims = ctx->GetInputDim("X"); ctx->SetOutputDim("Out", input_dims); ctx->ShareLoD("X", /*->*/ "Out"); } }; class TruncOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor), The input tensor of trunc op."); AddOutput("Out", "(Tensor), The output tensor of trunc op."); AddComment(R"DOC( Trunc Operator. Returns a new tensor with the truncated integer values of input. $$out = trunc(x)$$ )DOC"); } }; class TruncGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input", framework::GradVarName("Out"), "TruncGrad"); OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", framework::GradVarName("X"), "TruncGrad"); auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out")); ctx->SetOutputDim(framework::GradVarName("X"), dout_dims); } }; template <typename T> class TruncGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; void Apply(GradOpPtr<T> retv) const override { retv->SetType("trunc_grad"); retv->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); retv->SetAttrMap(this->Attrs()); retv->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(trunc, ops::TruncOp, ops::TruncOpMaker, ops::TruncGradOpMaker<paddle::framework::OpDesc>, ops::TruncGradOpMaker<paddle::imperative::OpBase>); REGISTER_OPERATOR(trunc_grad, ops::TruncGradOp); <commit_msg>move trunc_op's infere shape to phi (#39772)<commit_after>/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/infershape_utils.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/phi/core/infermeta_utils.h" #include "paddle/phi/infermeta/unary.h" namespace paddle { namespace operators { class TruncOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; }; class TruncOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(Tensor), The input tensor of trunc op."); AddOutput("Out", "(Tensor), The output tensor of trunc op."); AddComment(R"DOC( Trunc Operator. Returns a new tensor with the truncated integer values of input. $$out = trunc(x)$$ )DOC"); } }; class TruncGradOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")), "Input", framework::GradVarName("Out"), "TruncGrad"); OP_INOUT_CHECK(ctx->HasOutput(framework::GradVarName("X")), "Output", framework::GradVarName("X"), "TruncGrad"); auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out")); ctx->SetOutputDim(framework::GradVarName("X"), dout_dims); } }; template <typename T> class TruncGradOpMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; void Apply(GradOpPtr<T> retv) const override { retv->SetType("trunc_grad"); retv->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out")); retv->SetAttrMap(this->Attrs()); retv->SetOutput(framework::GradVarName("X"), this->InputGrad("X")); } }; } // namespace operators } // namespace paddle DELCARE_INFER_SHAPE_FUNCTOR(trunc, TruncInferShapeFunctor, PT_INFER_META(phi::UnchangedInferMeta)); namespace ops = paddle::operators; REGISTER_OPERATOR(trunc, ops::TruncOp, ops::TruncOpMaker, ops::TruncGradOpMaker<paddle::framework::OpDesc>, ops::TruncGradOpMaker<paddle::imperative::OpBase>, TruncInferShapeFunctor); REGISTER_OPERATOR(trunc_grad, ops::TruncGradOp); <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "iree/compiler/Dialect/Flow/Utils/DispatchUtils.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "llvm/ADT/SetVector.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { bool isOpOfKnownDialect(Operation *op) { if (!op->getDialect()) return false; // TODO(benvanik): replace with op dispatchability interface to allow dialects // to opt into dispatch. auto dialectNamespace = op->getDialect()->getNamespace(); return dialectNamespace == xla_hlo::XlaHloDialect::getDialectNamespace() || dialectNamespace == mlir::StandardOpsDialect::getDialectNamespace() || dialectNamespace == FlowDialect::getDialectNamespace(); } namespace { // Returns the set of values that must be captured for use by |ops| and the // set of values defined by |ops| that are used outside of the set. LogicalResult analyzeOpRangeValues( const llvm::SmallDenseSet<Operation *> &opSet, llvm::SetVector<Value> *capturedValues, llvm::SetVector<Value> *escapingValues) { for (auto *op : opSet) { for (auto value : op->getOperands()) { if (!llvm::is_contained(opSet, value.getDefiningOp())) { // Op is using a value not in the ops set, ensure we capture it. capturedValues->insert(value); } } for (auto value : op->getResults()) { for (auto &use : value.getUses()) { if (!llvm::is_contained(opSet, use.getOwner())) { // An op outside of the ops set is using the value, needs to escape. escapingValues->insert(value); } } } } return success(); } } // namespace LogicalResult buildDispatchRegion(Block *parentBlock, Value workload, ArrayRef<Operation *> ops) { // Fused location with all ops. SmallVector<Location, 16> opLocs; for (auto *op : ops) { opLocs.push_back(op->getLoc()); } auto regionLoc = FusedLoc::get(opLocs, workload.getContext()); // Get a list of values that we need to capture and values that escape the // region and need to be returned. llvm::SmallDenseSet<Operation *> opSet; opSet.reserve(ops.size()); opSet.insert(ops.begin(), ops.end()); llvm::SetVector<Value> capturedValues; llvm::SetVector<Value> escapingValues; if (failed(analyzeOpRangeValues(opSet, &capturedValues, &escapingValues))) { return failure(); } SmallVector<Type, 8> escapingTypes; for (auto value : escapingValues) escapingTypes.push_back(value.getType()); // Build the region op and add it to the parent block. OpBuilder parentBuilder(parentBlock); parentBuilder.setInsertionPoint(ops.back()); auto dispatchRegionOp = parentBuilder.create<IREE::Flow::DispatchRegionOp>( regionLoc, escapingTypes, workload, capturedValues.getArrayRef()); // Create the block and setup the arg mapping for captured values. auto *regionBlock = new Block(); dispatchRegionOp.body().push_back(regionBlock); OpBuilder regionBuilder(regionBlock); BlockAndValueMapping mapping; for (auto capturedValue : capturedValues) { auto blockArg = regionBlock->addArgument(capturedValue.getType()); mapping.map(capturedValue, blockArg); } // Clone ops into the new region block. for (auto *op : ops) { // Note that this updates the mapping with the new values (so at the end // we have those new values). regionBuilder.clone(*op, mapping); } // Return results (as we need a terminator in our block). // These are all of the values that escape our region. SmallVector<Value, 8> resultValues; for (auto oldValue : escapingValues) { resultValues.push_back(mapping.lookupOrDefault(oldValue)); } regionBuilder.create<IREE::Flow::ReturnOp>(opLocs.back(), resultValues); // Replace usage of values with the results of the region. for (int i = 0; i < escapingValues.size(); ++i) { escapingValues[i].replaceAllUsesWith(dispatchRegionOp.getResult(i)); } // Remove original ops from the parent region. for (auto it = ops.rbegin(); it != ops.rend(); ++it) { (*it)->erase(); } return success(); } namespace { // Recursively finds all reachable functions from the given |rootFunc| and adds // them to the |reachableFuncs| set. // // Note that indirect calls are not supported, however we don't allow those in // dispatch regions anyway so they should not be present here. LogicalResult findReachableFunctions( FuncOp rootFuncOp, llvm::SetVector<FuncOp> &reachableFuncs, llvm::StringMap<FuncOp> &dispatchableFuncOps) { llvm::SetVector<FuncOp> worklist; worklist.insert(rootFuncOp); while (!worklist.empty()) { auto funcOp = worklist.pop_back_val(); funcOp.walk([&](CallOp callOp) { auto calleeOp = dispatchableFuncOps.find(callOp.callee())->second; if (reachableFuncs.insert(calleeOp)) { worklist.insert(calleeOp); } }); } return success(); } } // namespace std::pair<IREE::Flow::ExecutableOp, FuncOp> createRegionExecutable( Operation *op, FunctionType functionType, StringRef symbolSuffix, llvm::StringMap<FuncOp> &dispatchableFuncOps) { // Create the function and take the region body directly. // NOTE: this will get uniquified if we have multiple in the same block. auto parentFunc = op->getParentOfType<FuncOp>(); std::string functionName = (parentFunc.getName().str() + "_rgn" + symbolSuffix).str(); auto outlinedFunc = FuncOp::create(op->getLoc(), functionName, functionType); BlockAndValueMapping mapping; op->getRegion(0).cloneInto(&outlinedFunc.getBody(), mapping); // Replace flow.return with std.return. for (auto &block : outlinedFunc.getBlocks()) { if (auto returnOp = dyn_cast<IREE::Flow::ReturnOp>(block.back())) { OpBuilder builder(returnOp); builder.create<mlir::ReturnOp>( returnOp.getLoc(), llvm::to_vector<4>(returnOp.getOperands())); returnOp.erase(); } } // Gather all reachable functions. llvm::SetVector<FuncOp> reachableFuncs; findReachableFunctions(outlinedFunc, reachableFuncs, dispatchableFuncOps); // Create the executable that will contain the outlined region. // NOTE: this will get uniquified if we have multiple in the same block. auto parentModule = parentFunc.getParentOfType<ModuleOp>(); OpBuilder parentModuleBuilder(parentModule); parentModuleBuilder.setInsertionPoint(parentFunc); std::string executableName = (parentFunc.getName().str() + "_ex" + symbolSuffix).str(); auto executableOp = parentModuleBuilder.create<IREE::Flow::ExecutableOp>( outlinedFunc.getLoc(), executableName); // Create the inner ModuleOp that contains the original functions. We need // to provide this shim as some ops (like std.call) look for the // containing module to provide symbol resolution. OpBuilder executableBuilder(executableOp); executableBuilder.setInsertionPointToStart(&executableOp.getBlock()); auto innerModule = executableBuilder.create<ModuleOp>(outlinedFunc.getLoc()); innerModule.push_back(outlinedFunc); // Copy all reachable functions into the executable. // Linker passes may dedupe these later on. OpBuilder innerModuleBuilder(innerModule.getBody()); innerModuleBuilder.setInsertionPoint(innerModule.getBody(), ++innerModule.getBody()->begin()); for (auto reachableFunc : reachableFuncs) { innerModuleBuilder.clone(*reachableFunc); } return std::make_pair(executableOp, outlinedFunc); } } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>Skip checking all remaining users if the value already escaped<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "iree/compiler/Dialect/Flow/Utils/DispatchUtils.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "llvm/ADT/SetVector.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { bool isOpOfKnownDialect(Operation *op) { if (!op->getDialect()) return false; // TODO(benvanik): replace with op dispatchability interface to allow dialects // to opt into dispatch. auto dialectNamespace = op->getDialect()->getNamespace(); return dialectNamespace == xla_hlo::XlaHloDialect::getDialectNamespace() || dialectNamespace == mlir::StandardOpsDialect::getDialectNamespace() || dialectNamespace == FlowDialect::getDialectNamespace(); } namespace { // Returns the set of values that must be captured for use by |ops| and the // set of values defined by |ops| that are used outside of the set. LogicalResult analyzeOpRangeValues( const llvm::SmallDenseSet<Operation *> &opSet, llvm::SetVector<Value> *capturedValues, llvm::SetVector<Value> *escapingValues) { for (auto *op : opSet) { for (auto value : op->getOperands()) { if (!llvm::is_contained(opSet, value.getDefiningOp())) { // Op is using a value not in the ops set, ensure we capture it. capturedValues->insert(value); } } for (auto value : op->getResults()) { for (auto &use : value.getUses()) { if (!llvm::is_contained(opSet, use.getOwner())) { // An op outside of the ops set is using the value, needs to escape. escapingValues->insert(value); continue; } } } } return success(); } } // namespace LogicalResult buildDispatchRegion(Block *parentBlock, Value workload, ArrayRef<Operation *> ops) { // Fused location with all ops. SmallVector<Location, 16> opLocs; for (auto *op : ops) { opLocs.push_back(op->getLoc()); } auto regionLoc = FusedLoc::get(opLocs, workload.getContext()); // Get a list of values that we need to capture and values that escape the // region and need to be returned. llvm::SmallDenseSet<Operation *> opSet; opSet.reserve(ops.size()); opSet.insert(ops.begin(), ops.end()); llvm::SetVector<Value> capturedValues; llvm::SetVector<Value> escapingValues; if (failed(analyzeOpRangeValues(opSet, &capturedValues, &escapingValues))) { return failure(); } SmallVector<Type, 8> escapingTypes; for (auto value : escapingValues) escapingTypes.push_back(value.getType()); // Build the region op and add it to the parent block. OpBuilder parentBuilder(parentBlock); parentBuilder.setInsertionPoint(ops.back()); auto dispatchRegionOp = parentBuilder.create<IREE::Flow::DispatchRegionOp>( regionLoc, escapingTypes, workload, capturedValues.getArrayRef()); // Create the block and setup the arg mapping for captured values. auto *regionBlock = new Block(); dispatchRegionOp.body().push_back(regionBlock); OpBuilder regionBuilder(regionBlock); BlockAndValueMapping mapping; for (auto capturedValue : capturedValues) { auto blockArg = regionBlock->addArgument(capturedValue.getType()); mapping.map(capturedValue, blockArg); } // Clone ops into the new region block. for (auto *op : ops) { // Note that this updates the mapping with the new values (so at the end // we have those new values). regionBuilder.clone(*op, mapping); } // Return results (as we need a terminator in our block). // These are all of the values that escape our region. SmallVector<Value, 8> resultValues; for (auto oldValue : escapingValues) { resultValues.push_back(mapping.lookupOrDefault(oldValue)); } regionBuilder.create<IREE::Flow::ReturnOp>(opLocs.back(), resultValues); // Replace usage of values with the results of the region. for (int i = 0; i < escapingValues.size(); ++i) { escapingValues[i].replaceAllUsesWith(dispatchRegionOp.getResult(i)); } // Remove original ops from the parent region. for (auto it = ops.rbegin(); it != ops.rend(); ++it) { (*it)->erase(); } return success(); } namespace { // Recursively finds all reachable functions from the given |rootFunc| and adds // them to the |reachableFuncs| set. // // Note that indirect calls are not supported, however we don't allow those in // dispatch regions anyway so they should not be present here. LogicalResult findReachableFunctions( FuncOp rootFuncOp, llvm::SetVector<FuncOp> &reachableFuncs, llvm::StringMap<FuncOp> &dispatchableFuncOps) { llvm::SetVector<FuncOp> worklist; worklist.insert(rootFuncOp); while (!worklist.empty()) { auto funcOp = worklist.pop_back_val(); funcOp.walk([&](CallOp callOp) { auto calleeOp = dispatchableFuncOps.find(callOp.callee())->second; if (reachableFuncs.insert(calleeOp)) { worklist.insert(calleeOp); } }); } return success(); } } // namespace std::pair<IREE::Flow::ExecutableOp, FuncOp> createRegionExecutable( Operation *op, FunctionType functionType, StringRef symbolSuffix, llvm::StringMap<FuncOp> &dispatchableFuncOps) { // Create the function and take the region body directly. // NOTE: this will get uniquified if we have multiple in the same block. auto parentFunc = op->getParentOfType<FuncOp>(); std::string functionName = (parentFunc.getName().str() + "_rgn" + symbolSuffix).str(); auto outlinedFunc = FuncOp::create(op->getLoc(), functionName, functionType); BlockAndValueMapping mapping; op->getRegion(0).cloneInto(&outlinedFunc.getBody(), mapping); // Replace flow.return with std.return. for (auto &block : outlinedFunc.getBlocks()) { if (auto returnOp = dyn_cast<IREE::Flow::ReturnOp>(block.back())) { OpBuilder builder(returnOp); builder.create<mlir::ReturnOp>( returnOp.getLoc(), llvm::to_vector<4>(returnOp.getOperands())); returnOp.erase(); } } // Gather all reachable functions. llvm::SetVector<FuncOp> reachableFuncs; findReachableFunctions(outlinedFunc, reachableFuncs, dispatchableFuncOps); // Create the executable that will contain the outlined region. // NOTE: this will get uniquified if we have multiple in the same block. auto parentModule = parentFunc.getParentOfType<ModuleOp>(); OpBuilder parentModuleBuilder(parentModule); parentModuleBuilder.setInsertionPoint(parentFunc); std::string executableName = (parentFunc.getName().str() + "_ex" + symbolSuffix).str(); auto executableOp = parentModuleBuilder.create<IREE::Flow::ExecutableOp>( outlinedFunc.getLoc(), executableName); // Create the inner ModuleOp that contains the original functions. We need // to provide this shim as some ops (like std.call) look for the // containing module to provide symbol resolution. OpBuilder executableBuilder(executableOp); executableBuilder.setInsertionPointToStart(&executableOp.getBlock()); auto innerModule = executableBuilder.create<ModuleOp>(outlinedFunc.getLoc()); innerModule.push_back(outlinedFunc); // Copy all reachable functions into the executable. // Linker passes may dedupe these later on. OpBuilder innerModuleBuilder(innerModule.getBody()); innerModuleBuilder.setInsertionPoint(innerModule.getBody(), ++innerModule.getBody()->begin()); for (auto reachableFunc : reachableFuncs) { innerModuleBuilder.clone(*reachableFunc); } return std::make_pair(executableOp, outlinedFunc); } } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>/*! * \file painter_attribute_data.hpp * \brief file painter_attribute_data.hpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <fastuidraw/util/util.hpp> #include <fastuidraw/stroked_path.hpp> #include <fastuidraw/filled_path.hpp> #include <fastuidraw/painter/painter_attribute.hpp> #include <fastuidraw/painter/painter_enums.hpp> #include <fastuidraw/text/glyph.hpp> namespace fastuidraw { /*!\addtogroup Painter @{ */ /*! PainterAttributeData represents the attribute and index data ready to be consumed by a Painter. Data is organized into individual chuncks that can be drawn seperately. */ class PainterAttributeData:noncopyable { public: /*! Enumation values are indexes into attribute_data_chunks() and index_data_chunks() for different portions of data needed for stroking a path when the data of this PainterAttributeData has been set with set_data(const reference_counted_ptr<const StrokedPath> &). */ enum stroking_data_t { rounded_joins_closing_edge, /*!< index for rounded join data with closing edge */ bevel_joins_closing_edge, /*!< index for bevel join data with closing edge */ miter_joins_closing_edge, /*!< index for miter join data with closing edge */ edge_closing_edge, /*!< index for edge data including closing edge */ number_with_closing_edge, /*!< number of types with closing edge */ rounded_joins_no_closing_edge = number_with_closing_edge, /*!< index for rounded join data without closing edge */ bevel_joins_no_closing_edge, /*!< index for bevel join data without closing edge */ miter_joins_no_closing_edge, /*!< index for miter join data without closing edge */ edge_no_closing_edge, /*!< index for edge data not including closing edge */ rounded_cap, /*!< index for rounded cap data */ square_cap, /*!< index for square cap data */ stroking_data_count /*!< count of enums */ }; /*! Given an enumeration of stroking_data_t, returns the matching enumeration for drawing without the closing edge. */ static enum stroking_data_t without_closing_edge(enum stroking_data_t v) { return (v < number_with_closing_edge) ? static_cast<enum stroking_data_t>(v + number_with_closing_edge) : v; } /*! Ctor. */ PainterAttributeData(void); ~PainterAttributeData(); /*! Set the attribute and index data for stroking a path. The enumerations of \ref stroking_data_t provide the indices into attribute_data_chunks() and index_data_chunks() for the data to draw the path stroked. The indices into attribute_data_chunks(V) for a join style V match the indices for the join style coming from the generating StrokedPath. Data for stroking is packed as follows: - PainterAttribute::m_attrib0 .xy -> StrokedPath::point::m_position - PainterAttribute::m_attrib0 .zw -> StrokedPath::point::m_pre_offset - PainterAttribute::m_attrib1 .x -> StrokedPath::point::m_distance_from_edge_start - PainterAttribute::m_attrib1 .y -> StrokedPath::point::m_distance_from_contour_start - PainterAttribute::m_attrib1 .zw -> StrokedPath::point::m_auxilary_offset - PainterAttribute::m_attrib2 .x -> StrokedPath::point::m_depth - PainterAttribute::m_attrib2 .y -> StrokedPath::point::m_tag - PainterAttribute::m_attrib2 .z -> StrokedPath::point::m_on_boundary - PainterAttribute::m_attrib2 .w -> 0 (free) */ void set_data(const reference_counted_ptr<const StrokedPath> &path); /*! Set the attribute and index data for filling a path. The enumeration values of PainterEnums::fill_rule_t provide the indices into attribute_data_chunks() for the fill rules. To get the index data for the component of a filled path with a given winding number, use the function index_chunk_from_winding_number(int). The attribute data, regardless of winding number or fill rule is the same value, the 0'th chunk. Data for filling is packed as follows: - PainterAttribute::m_attrib0 .xy -> coordinate of point. - PainterAttribute::m_attrib0 .zw -> 0.0 (free) - PainterAttribute::m_attrib1 .xyz -> 0.0 (free) - PainterAttribute::m_attrib1 .w -> 0.0 (free) - PainterAttribute::m_attrib2 .x -> 0 (free) - PainterAttribute::m_attrib2 .y -> 0 (free) - PainterAttribute::m_attrib2 .z -> 0 (free) - PainterAttribute::m_attrib2 .w -> 0 (free) */ void set_data(const reference_counted_ptr<const FilledPath> &path); /*! Set the data for drawing glyphs. The enumeration glyph_type provide the indices into attribute_data_chunks() and index_data_chunks() for the different glyph types. If a glyph is not uploaded to the GlyphCache and failed to be uploaded to its GlyphCache, then set_data() will create index and attribute data up to that glyph and returns the index into glyphs of the glyph that failed to be uploaded. If all glyphs can be in the cache, then returns the size of the array. Data for glyphs is packed as follows: - PainterAttribute::m_attrib0 .xy -> xy-texel location in primary atlas - PainterAttribute::m_attrib0 .zw -> xy-texel location in secondary atlas - PainterAttribute::m_attrib1 .xy -> position in item coordinates - PainterAttribute::m_attrib1 .z -> 0.0 (free) - PainterAttribute::m_attrib1 .w -> 0.0 (free) - PainterAttribute::m_attrib2 .x -> 0 - PainterAttribute::m_attrib2 .y -> glyph offset - PainterAttribute::m_attrib2 .z -> layer in primary atlas - PainterAttribute::m_attrib2 .w -> layer in secondary atlas \param glyph_positions position of the bottom left corner of each glyph \param glyphs glyphs to draw, array must be same size as glyph_positions \param scale_factors scale factors to apply to each glyph, must be either empty (indicating no scaling factors) or the exact same length as glyph_positions \param orientation orientation of drawing */ unsigned int set_data(const_c_array<vec2> glyph_positions, const_c_array<Glyph> glyphs, const_c_array<float> scale_factors, enum PainterEnums::glyph_orientation orientation = PainterEnums::y_increases_downwards); /*! Set the data for drawing glyphs. The enumeration glyph_type provide the indices into attribute_data_chunks() and index_data_chunks() for the different glyph types. If a glyph is not uploaded to the GlyphCache and failed to be uploaded to its GlyphCache, then set_data() will create index and attribute data up to that glyph and returns the index into glyphs of the glyph that failed to be uploaded. If all glyphs can be in the cache, then returns the size of the array. Data for glyphs is packed as follows: - PainterAttribute::m_attrib0 .xy -> xy-texel location in primary atlas - PainterAttribute::m_attrib0 .zw -> xy-texel location in secondary atlas - PainterAttribute::m_attrib1 .xy -> position in item coordinates - PainterAttribute::m_attrib1 .z -> 0.0 (free) - PainterAttribute::m_attrib1 .w -> 0.0 (free) - PainterAttribute::m_attrib2 .x -> 0 - PainterAttribute::m_attrib2 .y -> glyph offset - PainterAttribute::m_attrib2 .z -> layer in primary atlas - PainterAttribute::m_attrib2 .w -> layer in secondary atlas \param glyph_positions position of the bottom left corner of each glyph \param glyphs glyphs to draw, array must be same size as glyph_positions \param render_pixel_size pixel size to which to scale the glyphs \param orientation orientation of drawing */ unsigned int set_data(const_c_array<vec2> glyph_positions, const_c_array<Glyph> glyphs, float render_pixel_size, enum PainterEnums::glyph_orientation orientation = PainterEnums::y_increases_downwards); /*! Set the data for drawing glyphs. The enumeration glyph_type provide the indices into attribute_data_chunks() and index_data_chunks() for the different glyph types. If a glyph is not uploaded to the GlyphCache and failed to be uploaded to its GlyphCache, then set_data() will create index and attribute data up to that glyph and returns the index into glyphs of the glyph that failed to be uploaded. If all glyphs can be in the cache, then returns the size of the array. Data for glyphs is packed as follows: - PainterAttribute::m_attrib0 .xy -> xy-texel location in primary atlas - PainterAttribute::m_attrib0 .zw -> xy-texel location in secondary atlas - PainterAttribute::m_attrib1 .xy -> position in item coordinates - PainterAttribute::m_attrib1 .z -> 0.0 (free) - PainterAttribute::m_attrib1 .w -> 0.0 (free) - PainterAttribute::m_attrib2 .x -> 0 - PainterAttribute::m_attrib2 .y -> glyph offset - PainterAttribute::m_attrib2 .z -> layer in primary atlas - PainterAttribute::m_attrib2 .w -> layer in secondary atlas \param glyph_positions position of the bottom left corner of each glyph \param glyphs glyphs to draw, array must be same size as glyph_positions \param orientation orientation of drawing */ unsigned int set_data(const_c_array<vec2> glyph_positions, const_c_array<Glyph> glyphs, enum PainterEnums::glyph_orientation orientation = PainterEnums::y_increases_downwards) { c_array<float> empty; return set_data(glyph_positions, glyphs, empty, orientation); } /*! Returns the attribute data chunks. For all but those objects set by set_data(const reference_counted_ptr<const FilledPath> &), for each attribute data chunk, there is a matching index data chunk. A chunk is an attribute and index data chunk pair. Specifically one uses index_data_chunks()[i] to draw the contents of attribute_data_chunks()[i]. */ const_c_array<const_c_array<PainterAttribute> > attribute_data_chunks(void) const; /*! Provided as an API conveniance to fetch the named chunk of attribute_data_chunks() or an empty chunk if the index is larger then attribute_data_chunks().size(). \param i index of attribute_data_chunks() to fetch */ const_c_array<PainterAttribute> attribute_data_chunk(unsigned int i) const; /*! Returns the index data chunks. For all but those objects set by set_data(const reference_counted_ptr<const FilledPath> &), for each attribute data chunk, there is a matching index data chunk. A chunk is an attribute and index data chunk pair. Specifically one uses index_data_chunks()[i] to draw the contents of attribute_data_chunks()[i]. */ const_c_array<const_c_array<PainterIndex> > index_data_chunks(void) const; /*! Provided as an API conveniance to fetch the named chunk of index_data_chunks() or an empty chunk if the index is larger then index_data_chunks().size(). \param i index of index_data_chunks() to fetch */ const_c_array<PainterIndex> index_data_chunk(unsigned int i) const; /*! Returns an array that holds those value i for which index_data_chunk(i) is non-empty. */ const_c_array<unsigned int> non_empty_index_data_chunks(void) const; /*! Returns by how much to increment a z-value (see Painter::increment_z()) when using an attribute/index pair. */ const_c_array<unsigned int> increment_z_values(void) const; /*! Provided as an API conveniance to fetch the named increment-z value of increment_z_values() or 0 if the index is larger then increment_z_values().size(). \param i index of increment_z_values() to fetch */ unsigned int increment_z_value(unsigned int i) const; /*! Returns the value to feed to index_data_chunk() to get the index data for the fill of a path (see set_data(const reference_counted_ptr<const FilledPath>&)) with a specified winding number. \param winding_number winding number of fill data to fetch */ static unsigned int index_chunk_from_winding_number(int winding_number); /*! Is the inverse of index_chunk_from_winding_number(), i.e. returns the winding number that lives on a given index chunk. It is required that the index fed is not one of PainterEnums::odd_even_fill_rule, PainterEnums::nonzero_fill_rule and PainterEnums::complement_odd_even_fill_rule. \param idx index into index_data_chunk() */ static int winding_number_from_index_chunk(unsigned int idx); private: void *m_d; }; /*! @} */ } <commit_msg>fastuidraw/painter: note type packed for PainterAttributeData<commit_after>/*! * \file painter_attribute_data.hpp * \brief file painter_attribute_data.hpp * * Copyright 2016 by Intel. * * Contact: kevin.rogovin@intel.com * * This Source Code Form is subject to the * terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with * this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * \author Kevin Rogovin <kevin.rogovin@intel.com> * */ #pragma once #include <fastuidraw/util/util.hpp> #include <fastuidraw/stroked_path.hpp> #include <fastuidraw/filled_path.hpp> #include <fastuidraw/painter/painter_attribute.hpp> #include <fastuidraw/painter/painter_enums.hpp> #include <fastuidraw/text/glyph.hpp> namespace fastuidraw { /*!\addtogroup Painter @{ */ /*! PainterAttributeData represents the attribute and index data ready to be consumed by a Painter. Data is organized into individual chuncks that can be drawn seperately. */ class PainterAttributeData:noncopyable { public: /*! Enumation values are indexes into attribute_data_chunks() and index_data_chunks() for different portions of data needed for stroking a path when the data of this PainterAttributeData has been set with set_data(const reference_counted_ptr<const StrokedPath> &). */ enum stroking_data_t { rounded_joins_closing_edge, /*!< index for rounded join data with closing edge */ bevel_joins_closing_edge, /*!< index for bevel join data with closing edge */ miter_joins_closing_edge, /*!< index for miter join data with closing edge */ edge_closing_edge, /*!< index for edge data including closing edge */ number_with_closing_edge, /*!< number of types with closing edge */ rounded_joins_no_closing_edge = number_with_closing_edge, /*!< index for rounded join data without closing edge */ bevel_joins_no_closing_edge, /*!< index for bevel join data without closing edge */ miter_joins_no_closing_edge, /*!< index for miter join data without closing edge */ edge_no_closing_edge, /*!< index for edge data not including closing edge */ rounded_cap, /*!< index for rounded cap data */ square_cap, /*!< index for square cap data */ stroking_data_count /*!< count of enums */ }; /*! Given an enumeration of stroking_data_t, returns the matching enumeration for drawing without the closing edge. */ static enum stroking_data_t without_closing_edge(enum stroking_data_t v) { return (v < number_with_closing_edge) ? static_cast<enum stroking_data_t>(v + number_with_closing_edge) : v; } /*! Ctor. */ PainterAttributeData(void); ~PainterAttributeData(); /*! Set the attribute and index data for stroking a path. The enumerations of \ref stroking_data_t provide the indices into attribute_data_chunks() and index_data_chunks() for the data to draw the path stroked. The indices into attribute_data_chunks(V) for a join style V match the indices for the join style coming from the generating StrokedPath. Data for stroking is packed as follows: - PainterAttribute::m_attrib0 .xy -> StrokedPath::point::m_position (float) - PainterAttribute::m_attrib0 .zw -> StrokedPath::point::m_pre_offset (float) - PainterAttribute::m_attrib1 .x -> StrokedPath::point::m_distance_from_edge_start (float) - PainterAttribute::m_attrib1 .y -> StrokedPath::point::m_distance_from_contour_start (float) - PainterAttribute::m_attrib1 .zw -> StrokedPath::point::m_auxilary_offset (float) - PainterAttribute::m_attrib2 .x -> StrokedPath::point::m_depth (uint) - PainterAttribute::m_attrib2 .y -> StrokedPath::point::m_tag (uint) - PainterAttribute::m_attrib2 .z -> StrokedPath::point::m_on_boundary (uint) - PainterAttribute::m_attrib2 .w -> 0 (free) */ void set_data(const reference_counted_ptr<const StrokedPath> &path); /*! Set the attribute and index data for filling a path. The enumeration values of PainterEnums::fill_rule_t provide the indices into attribute_data_chunks() for the fill rules. To get the index data for the component of a filled path with a given winding number, use the function index_chunk_from_winding_number(int). The attribute data, regardless of winding number or fill rule is the same value, the 0'th chunk. Data for filling is packed as follows: - PainterAttribute::m_attrib0 .xy -> coordinate of point (float) - PainterAttribute::m_attrib0 .zw -> 0 (free) - PainterAttribute::m_attrib1 .xyz -> 0 (free) - PainterAttribute::m_attrib1 .w -> 0 (free) - PainterAttribute::m_attrib2 .x -> 0 (free) - PainterAttribute::m_attrib2 .y -> 0 (free) - PainterAttribute::m_attrib2 .z -> 0 (free) - PainterAttribute::m_attrib2 .w -> 0 (free) */ void set_data(const reference_counted_ptr<const FilledPath> &path); /*! Set the data for drawing glyphs. The enumeration glyph_type provide the indices into attribute_data_chunks() and index_data_chunks() for the different glyph types. If a glyph is not uploaded to the GlyphCache and failed to be uploaded to its GlyphCache, then set_data() will create index and attribute data up to that glyph and returns the index into glyphs of the glyph that failed to be uploaded. If all glyphs can be in the cache, then returns the size of the array. Data for glyphs is packed as follows: - PainterAttribute::m_attrib0 .xy -> xy-texel location in primary atlas (float) - PainterAttribute::m_attrib0 .zw -> xy-texel location in secondary atlas (float) - PainterAttribute::m_attrib1 .xy -> position in item coordinates (float) - PainterAttribute::m_attrib1 .z -> 0 (free) - PainterAttribute::m_attrib1 .w -> 0 (free) - PainterAttribute::m_attrib2 .x -> 0 (free) - PainterAttribute::m_attrib2 .y -> glyph offset (uint) - PainterAttribute::m_attrib2 .z -> layer in primary atlas (uint) - PainterAttribute::m_attrib2 .w -> layer in secondary atlas (uint) \param glyph_positions position of the bottom left corner of each glyph \param glyphs glyphs to draw, array must be same size as glyph_positions \param scale_factors scale factors to apply to each glyph, must be either empty (indicating no scaling factors) or the exact same length as glyph_positions \param orientation orientation of drawing */ unsigned int set_data(const_c_array<vec2> glyph_positions, const_c_array<Glyph> glyphs, const_c_array<float> scale_factors, enum PainterEnums::glyph_orientation orientation = PainterEnums::y_increases_downwards); /*! Set the data for drawing glyphs. The enumeration glyph_type provide the indices into attribute_data_chunks() and index_data_chunks() for the different glyph types. If a glyph is not uploaded to the GlyphCache and failed to be uploaded to its GlyphCache, then set_data() will create index and attribute data up to that glyph and returns the index into glyphs of the glyph that failed to be uploaded. If all glyphs can be in the cache, then returns the size of the array. Data for glyphs is packed as follows: - PainterAttribute::m_attrib0 .xy -> xy-texel location in primary atlas (float) - PainterAttribute::m_attrib0 .zw -> xy-texel location in secondary atlas (float) - PainterAttribute::m_attrib1 .xy -> position in item coordinates (float) - PainterAttribute::m_attrib1 .z -> 0 (free) - PainterAttribute::m_attrib1 .w -> 0 (free) - PainterAttribute::m_attrib2 .x -> 0 (free) - PainterAttribute::m_attrib2 .y -> glyph offset (uint) - PainterAttribute::m_attrib2 .z -> layer in primary atlas (uint) - PainterAttribute::m_attrib2 .w -> layer in secondary atlas (uint) \param glyph_positions position of the bottom left corner of each glyph \param glyphs glyphs to draw, array must be same size as glyph_positions \param render_pixel_size pixel size to which to scale the glyphs \param orientation orientation of drawing */ unsigned int set_data(const_c_array<vec2> glyph_positions, const_c_array<Glyph> glyphs, float render_pixel_size, enum PainterEnums::glyph_orientation orientation = PainterEnums::y_increases_downwards); /*! Set the data for drawing glyphs. The enumeration glyph_type provide the indices into attribute_data_chunks() and index_data_chunks() for the different glyph types. If a glyph is not uploaded to the GlyphCache and failed to be uploaded to its GlyphCache, then set_data() will create index and attribute data up to that glyph and returns the index into glyphs of the glyph that failed to be uploaded. If all glyphs can be in the cache, then returns the size of the array. Data for glyphs is packed as follows: - PainterAttribute::m_attrib0 .xy -> xy-texel location in primary atlas (float) - PainterAttribute::m_attrib0 .zw -> xy-texel location in secondary atlas (float) - PainterAttribute::m_attrib1 .xy -> position in item coordinates (float) - PainterAttribute::m_attrib1 .z -> 0 (free) - PainterAttribute::m_attrib1 .w -> 0 (free) - PainterAttribute::m_attrib2 .x -> 0 (free) - PainterAttribute::m_attrib2 .y -> glyph offset (uint) - PainterAttribute::m_attrib2 .z -> layer in primary atlas (uint) - PainterAttribute::m_attrib2 .w -> layer in secondary atlas (uint) \param glyph_positions position of the bottom left corner of each glyph \param glyphs glyphs to draw, array must be same size as glyph_positions \param orientation orientation of drawing */ unsigned int set_data(const_c_array<vec2> glyph_positions, const_c_array<Glyph> glyphs, enum PainterEnums::glyph_orientation orientation = PainterEnums::y_increases_downwards) { c_array<float> empty; return set_data(glyph_positions, glyphs, empty, orientation); } /*! Returns the attribute data chunks. For all but those objects set by set_data(const reference_counted_ptr<const FilledPath> &), for each attribute data chunk, there is a matching index data chunk. A chunk is an attribute and index data chunk pair. Specifically one uses index_data_chunks()[i] to draw the contents of attribute_data_chunks()[i]. */ const_c_array<const_c_array<PainterAttribute> > attribute_data_chunks(void) const; /*! Provided as an API conveniance to fetch the named chunk of attribute_data_chunks() or an empty chunk if the index is larger then attribute_data_chunks().size(). \param i index of attribute_data_chunks() to fetch */ const_c_array<PainterAttribute> attribute_data_chunk(unsigned int i) const; /*! Returns the index data chunks. For all but those objects set by set_data(const reference_counted_ptr<const FilledPath> &), for each attribute data chunk, there is a matching index data chunk. A chunk is an attribute and index data chunk pair. Specifically one uses index_data_chunks()[i] to draw the contents of attribute_data_chunks()[i]. */ const_c_array<const_c_array<PainterIndex> > index_data_chunks(void) const; /*! Provided as an API conveniance to fetch the named chunk of index_data_chunks() or an empty chunk if the index is larger then index_data_chunks().size(). \param i index of index_data_chunks() to fetch */ const_c_array<PainterIndex> index_data_chunk(unsigned int i) const; /*! Returns an array that holds those value i for which index_data_chunk(i) is non-empty. */ const_c_array<unsigned int> non_empty_index_data_chunks(void) const; /*! Returns by how much to increment a z-value (see Painter::increment_z()) when using an attribute/index pair. */ const_c_array<unsigned int> increment_z_values(void) const; /*! Provided as an API conveniance to fetch the named increment-z value of increment_z_values() or 0 if the index is larger then increment_z_values().size(). \param i index of increment_z_values() to fetch */ unsigned int increment_z_value(unsigned int i) const; /*! Returns the value to feed to index_data_chunk() to get the index data for the fill of a path (see set_data(const reference_counted_ptr<const FilledPath>&)) with a specified winding number. \param winding_number winding number of fill data to fetch */ static unsigned int index_chunk_from_winding_number(int winding_number); /*! Is the inverse of index_chunk_from_winding_number(), i.e. returns the winding number that lives on a given index chunk. It is required that the index fed is not one of PainterEnums::odd_even_fill_rule, PainterEnums::nonzero_fill_rule and PainterEnums::complement_odd_even_fill_rule. \param idx index into index_data_chunk() */ static int winding_number_from_index_chunk(unsigned int idx); private: void *m_d; }; /*! @} */ } <|endoftext|>
<commit_before>/** */ template < typename T, std::size_t number_of_dimensions> struct optimisation_algorithm_state { std::vector<std::array<T, number_of_dimensions>> parameters; std::vector<T> objective_values; std::array<T, number_of_dimensions> best_found_parameter; T best_found_objective_value; std::size_t used_number_of_iterations; std::size_t stagnating_number_of_iterations; constexpr optimisation_algorithm_state() noexcept; }; template < typename T1, std::size_t number_of_dimensions, template <class, std::size_t> class T2 = optimisation_algorithm_state> struct optimisation_algorithm { typedef T1 value_type; typedef T2<T1, number_of_dimensions> state_type; typedef std::function<void( state_type& state)> initialising_function_type; typedef std::function<void( state_type& state)> boundary_handling_function_type; typedef std::function<bool( const state_type& state)> is_stagnating_function_type; typedef std::function<void( state_type& state)> next_parameters_function_type; typedef std::function<void( state_type& state)> restarting_function_type; std::vector<std::pair<initialising_function_type, std::string>> initialising_functions; std::vector<std::pair<boundary_handling_function_type, std::string>> boundary_handling_functions; std::vector<std::pair<is_stagnating_function_type, std::string>> is_stagnating_functions; std::vector<std::pair<next_parameters_function_type, std::string>> next_parameters_functions; std::vector<std::pair<restarting_function_type, std::string>> restarting_functions; T1 acceptable_objective_value; std::size_t maximal_number_of_iterations; std::size_t maximal_stagnating_number_of_iterations; std::vector<std::size_t> active_dimensions; constexpr optimisation_algorithm() noexcept; }; // // Implementation // template < typename T, std::size_t number_of_dimensions> constexpr optimisation_algorithm_state<T, number_of_dimensions>::optimisation_algorithm_state() noexcept { static_assert(std::is_floating_point<T>::value, ""); static_assert(number_of_dimensions > 0, ""); parameters.resize(1); for (auto& parameter : this->parameters) { std::generate( parameter.begin(), parameter.end(), std::bind( std::uniform_real_distribution<T>(0.0, 1.0), std::ref(random_number_generator()))); } best_found_objective_value = std::numeric_limits<T>::infinity(); used_number_of_iterations = 0; stagnating_number_of_iterations = 0; } template < typename T1, std::size_t number_of_dimensions, template <class, std::size_t> class T2> constexpr optimisation_algorithm<T1, number_of_dimensions, T2>::optimisation_algorithm() noexcept { static_assert(std::is_floating_point<T1>::value, ""); static_assert(number_of_dimensions > 0, ""); static_assert(std::is_base_of<state_type, T2<T1, number_of_dimensions>>::value, ""); boundary_handling_functions = {{ [this]( auto& state) { for (auto& parameter : state.parameters) { std::transform( parameter.cbegin(), std::next(parameter.cbegin(), active_dimensions.size()), parameter.begin(), [] (const auto& element) { if (element < T1(0.0)) { return T1(0.0); } else if(element > T1(1.0)) { return T1(1.0); } return element; }); } }, "Default boundary handling" }}; is_stagnating_functions = {{ [this]( const auto& state) { return state.stagnating_number_of_iterations > maximal_stagnating_number_of_iterations; }, "Default is-stagnating" }}; restarting_functions = {{ [this]( auto& state) { for (auto& parameter : state.parameters) { std::generate( parameter.begin(), std::next(parameter.begin(), active_dimensions.size()), std::bind( std::uniform_real_distribution<T1>(0.0, 1.0), std::ref(random_number_generator()))); } }, "Default restarting" }}; acceptable_objective_value = -std::numeric_limits<T1>::infinity(); maximal_number_of_iterations = 10000; maximal_stagnating_number_of_iterations = 100; active_dimensions.resize(number_of_dimensions); std::iota(active_dimensions.begin(), active_dimensions.end(), 0); } // // Unit tests // #if defined(MANTELLA_BUILD_TESTS) TEST_CASE("optimisation_algorithm_state", "[optimisation_algorithm][optimisation_algorithm_state]") { typedef double value_type; constexpr std::size_t number_of_dimensions = 3; const mant::optimisation_algorithm_state<value_type, number_of_dimensions> optimisation_algorithm_state; CHECK(optimisation_algorithm_state.parameters.size() == 1); CHECK(optimisation_algorithm_state.objective_values.empty() == true); // Checks that all elements are within [0, 1]. for (const auto& parameter : optimisation_algorithm_state.parameters) { CHECK(std::all_of( parameter.cbegin(), parameter.end(), [](const auto element) { return (0.0 <= element && element <= 1.0); }) == true); } CHECK(optimisation_algorithm_state.best_found_objective_value == std::numeric_limits<value_type>::infinity()); CHECK(optimisation_algorithm_state.used_number_of_iterations == 0); CHECK(optimisation_algorithm_state.stagnating_number_of_iterations == 0); } TEST_CASE("optimisation_algorithm", "[optimisation_algorithm]") { typedef double value_type; constexpr std::size_t number_of_dimensions = 3; mant::optimisation_algorithm<value_type, number_of_dimensions> optimisation_algorithm; mant::optimisation_algorithm_state<value_type, number_of_dimensions> optimisation_algorithm_state; SECTION("Default values") { CHECK(optimisation_algorithm.acceptable_objective_value == -::std::numeric_limits<double>::infinity()); CHECK(optimisation_algorithm.maximal_number_of_iterations == 10000); CHECK(optimisation_algorithm.maximal_stagnating_number_of_iterations == 100); CHECK(optimisation_algorithm.active_dimensions == std::vector<::std::size_t>({0, 1, 2})); } SECTION("Initialising functions") { CHECK(optimisation_algorithm.initialising_functions.size() == 0); } SECTION("Boundary handling functions") { CHECK(optimisation_algorithm.boundary_handling_functions.size() == 1); CHECK(std::get<1>(optimisation_algorithm.boundary_handling_functions.at(0)) == "Default boundary handling"); optimisation_algorithm.active_dimensions = {0, 2}; optimisation_algorithm_state.parameters = {{-0.1, 0.2, 3.2}, {0.8, 1.2, -2.4}}; std::get<0>(optimisation_algorithm.boundary_handling_functions.at(0))(optimisation_algorithm_state); CHECK((optimisation_algorithm_state.parameters == std::vector<std::array<value_type, number_of_dimensions>>({{0.0, 0.2, 3.2}, {0.8, 1.0, -2.4}}))); } SECTION("Is-stagnating functions") { optimisation_algorithm.active_dimensions = {0, 2}; CHECK(optimisation_algorithm.is_stagnating_functions.size() == 1); CHECK(std::get<1>(optimisation_algorithm.is_stagnating_functions.at(0)) == "Default is-stagnating"); optimisation_algorithm_state.stagnating_number_of_iterations = 0; CHECK(std::get<0>(optimisation_algorithm.is_stagnating_functions.at(0))(optimisation_algorithm_state) == false); optimisation_algorithm_state.stagnating_number_of_iterations = 101; CHECK(std::get<0>(optimisation_algorithm.is_stagnating_functions.at(0))(optimisation_algorithm_state) == true); } SECTION("Next parameters functions") { CHECK(optimisation_algorithm.next_parameters_functions.size() == 0); } SECTION("Restarting functions") { CHECK(optimisation_algorithm.restarting_functions.size() == 1); CHECK(std::get<1>(optimisation_algorithm.restarting_functions.at(0)) == "Default restarting"); optimisation_algorithm.active_dimensions = {0, 2}; optimisation_algorithm_state.parameters.resize(2); std::get<0>(optimisation_algorithm.restarting_functions.at(0))(optimisation_algorithm_state); CHECK(optimisation_algorithm_state.parameters.size() == 2); // Checks that all elements are within [0, 1]. for (const auto& parameter : optimisation_algorithm_state.parameters) { CHECK(std::all_of( parameter.cbegin(), std::next(parameter.cbegin(), optimisation_algorithm.active_dimensions.size()), [](const auto element) { return (0.0 <= element && element <= 1.0); }) == true); } } } #endif <commit_msg>develop: Removed unnecessary this (#256)<commit_after>/** */ template < typename T, std::size_t number_of_dimensions> struct optimisation_algorithm_state { std::vector<std::array<T, number_of_dimensions>> parameters; std::vector<T> objective_values; std::array<T, number_of_dimensions> best_found_parameter; T best_found_objective_value; std::size_t used_number_of_iterations; std::size_t stagnating_number_of_iterations; constexpr optimisation_algorithm_state() noexcept; }; template < typename T1, std::size_t number_of_dimensions, template <class, std::size_t> class T2 = optimisation_algorithm_state> struct optimisation_algorithm { typedef T1 value_type; typedef T2<T1, number_of_dimensions> state_type; typedef std::function<void( state_type& state)> initialising_function_type; typedef std::function<void( state_type& state)> boundary_handling_function_type; typedef std::function<bool( const state_type& state)> is_stagnating_function_type; typedef std::function<void( state_type& state)> next_parameters_function_type; typedef std::function<void( state_type& state)> restarting_function_type; std::vector<std::pair<initialising_function_type, std::string>> initialising_functions; std::vector<std::pair<boundary_handling_function_type, std::string>> boundary_handling_functions; std::vector<std::pair<is_stagnating_function_type, std::string>> is_stagnating_functions; std::vector<std::pair<next_parameters_function_type, std::string>> next_parameters_functions; std::vector<std::pair<restarting_function_type, std::string>> restarting_functions; T1 acceptable_objective_value; std::size_t maximal_number_of_iterations; std::size_t maximal_stagnating_number_of_iterations; std::vector<std::size_t> active_dimensions; constexpr optimisation_algorithm() noexcept; }; // // Implementation // template < typename T, std::size_t number_of_dimensions> constexpr optimisation_algorithm_state<T, number_of_dimensions>::optimisation_algorithm_state() noexcept { static_assert(std::is_floating_point<T>::value, ""); static_assert(number_of_dimensions > 0, ""); parameters.resize(1); for (auto& parameter : parameters) { std::generate( parameter.begin(), parameter.end(), std::bind( std::uniform_real_distribution<T>(0.0, 1.0), std::ref(random_number_generator()))); } best_found_objective_value = std::numeric_limits<T>::infinity(); used_number_of_iterations = 0; stagnating_number_of_iterations = 0; } template < typename T1, std::size_t number_of_dimensions, template <class, std::size_t> class T2> constexpr optimisation_algorithm<T1, number_of_dimensions, T2>::optimisation_algorithm() noexcept { static_assert(std::is_floating_point<T1>::value, ""); static_assert(number_of_dimensions > 0, ""); static_assert(std::is_base_of<state_type, T2<T1, number_of_dimensions>>::value, ""); boundary_handling_functions = {{ [this]( auto& state) { for (auto& parameter : state.parameters) { std::transform( parameter.cbegin(), std::next(parameter.cbegin(), active_dimensions.size()), parameter.begin(), [] (const auto& element) { if (element < T1(0.0)) { return T1(0.0); } else if(element > T1(1.0)) { return T1(1.0); } return element; }); } }, "Default boundary handling" }}; is_stagnating_functions = {{ [this]( const auto& state) { return state.stagnating_number_of_iterations > maximal_stagnating_number_of_iterations; }, "Default is-stagnating" }}; restarting_functions = {{ [this]( auto& state) { for (auto& parameter : state.parameters) { std::generate( parameter.begin(), std::next(parameter.begin(), active_dimensions.size()), std::bind( std::uniform_real_distribution<T1>(0.0, 1.0), std::ref(random_number_generator()))); } }, "Default restarting" }}; acceptable_objective_value = -std::numeric_limits<T1>::infinity(); maximal_number_of_iterations = 10000; maximal_stagnating_number_of_iterations = 100; active_dimensions.resize(number_of_dimensions); std::iota(active_dimensions.begin(), active_dimensions.end(), 0); } // // Unit tests // #if defined(MANTELLA_BUILD_TESTS) TEST_CASE("optimisation_algorithm_state", "[optimisation_algorithm][optimisation_algorithm_state]") { typedef double value_type; constexpr std::size_t number_of_dimensions = 3; const mant::optimisation_algorithm_state<value_type, number_of_dimensions> optimisation_algorithm_state; CHECK(optimisation_algorithm_state.parameters.size() == 1); CHECK(optimisation_algorithm_state.objective_values.empty() == true); // Checks that all elements are within [0, 1]. for (const auto& parameter : optimisation_algorithm_state.parameters) { CHECK(std::all_of( parameter.cbegin(), parameter.end(), [](const auto element) { return (0.0 <= element && element <= 1.0); }) == true); } CHECK(optimisation_algorithm_state.best_found_objective_value == std::numeric_limits<value_type>::infinity()); CHECK(optimisation_algorithm_state.used_number_of_iterations == 0); CHECK(optimisation_algorithm_state.stagnating_number_of_iterations == 0); } TEST_CASE("optimisation_algorithm", "[optimisation_algorithm]") { typedef double value_type; constexpr std::size_t number_of_dimensions = 3; mant::optimisation_algorithm<value_type, number_of_dimensions> optimisation_algorithm; mant::optimisation_algorithm_state<value_type, number_of_dimensions> optimisation_algorithm_state; SECTION("Default values") { CHECK(optimisation_algorithm.acceptable_objective_value == -::std::numeric_limits<double>::infinity()); CHECK(optimisation_algorithm.maximal_number_of_iterations == 10000); CHECK(optimisation_algorithm.maximal_stagnating_number_of_iterations == 100); CHECK(optimisation_algorithm.active_dimensions == std::vector<::std::size_t>({0, 1, 2})); } SECTION("Initialising functions") { CHECK(optimisation_algorithm.initialising_functions.size() == 0); } SECTION("Boundary handling functions") { CHECK(optimisation_algorithm.boundary_handling_functions.size() == 1); CHECK(std::get<1>(optimisation_algorithm.boundary_handling_functions.at(0)) == "Default boundary handling"); optimisation_algorithm.active_dimensions = {0, 2}; optimisation_algorithm_state.parameters = {{-0.1, 0.2, 3.2}, {0.8, 1.2, -2.4}}; std::get<0>(optimisation_algorithm.boundary_handling_functions.at(0))(optimisation_algorithm_state); CHECK((optimisation_algorithm_state.parameters == std::vector<std::array<value_type, number_of_dimensions>>({{0.0, 0.2, 3.2}, {0.8, 1.0, -2.4}}))); } SECTION("Is-stagnating functions") { optimisation_algorithm.active_dimensions = {0, 2}; CHECK(optimisation_algorithm.is_stagnating_functions.size() == 1); CHECK(std::get<1>(optimisation_algorithm.is_stagnating_functions.at(0)) == "Default is-stagnating"); optimisation_algorithm_state.stagnating_number_of_iterations = 0; CHECK(std::get<0>(optimisation_algorithm.is_stagnating_functions.at(0))(optimisation_algorithm_state) == false); optimisation_algorithm_state.stagnating_number_of_iterations = 101; CHECK(std::get<0>(optimisation_algorithm.is_stagnating_functions.at(0))(optimisation_algorithm_state) == true); } SECTION("Next parameters functions") { CHECK(optimisation_algorithm.next_parameters_functions.size() == 0); } SECTION("Restarting functions") { CHECK(optimisation_algorithm.restarting_functions.size() == 1); CHECK(std::get<1>(optimisation_algorithm.restarting_functions.at(0)) == "Default restarting"); optimisation_algorithm.active_dimensions = {0, 2}; optimisation_algorithm_state.parameters.resize(2); std::get<0>(optimisation_algorithm.restarting_functions.at(0))(optimisation_algorithm_state); CHECK(optimisation_algorithm_state.parameters.size() == 2); // Checks that all elements are within [0, 1]. for (const auto& parameter : optimisation_algorithm_state.parameters) { CHECK(std::all_of( parameter.cbegin(), std::next(parameter.cbegin(), optimisation_algorithm.active_dimensions.size()), [](const auto element) { return (0.0 <= element && element <= 1.0); }) == true); } } } #endif <|endoftext|>
<commit_before>/** * @file llcapabilitylistener_test.cpp * @author Nat Goodspeed * @date 2008-12-31 * @brief Test for llcapabilitylistener.cpp. * * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ // Precompiled header #include "../llviewerprecompiledheaders.h" // Own header #include "../llcapabilitylistener.h" // STL headers #include <stdexcept> #include <map> #include <vector> // std headers // external library headers #include "boost/bind.hpp" // other Linden headers #include "../test/lltut.h" #include "../llcapabilityprovider.h" #include "lluuid.h" #include "tests/networkio.h" #include "tests/commtest.h" #include "tests/wrapllerrs.h" #include "message.h" #include "stringize.h" #if defined(LL_WINDOWS) #pragma warning(disable: 4355) // using 'this' in base-class ctor initializer expr #endif /***************************************************************************** * TestCapabilityProvider *****************************************************************************/ struct TestCapabilityProvider: public LLCapabilityProvider { TestCapabilityProvider(const LLHost& host): mHost(host) {} std::string getCapability(const std::string& cap) const { CapMap::const_iterator found = mCaps.find(cap); if (found != mCaps.end()) return found->second; // normal LLViewerRegion lookup failure mode return ""; } void setCapability(const std::string& cap, const std::string& url) { mCaps[cap] = url; } LLHost getHost() const { return mHost; } std::string getDescription() const { return "TestCapabilityProvider"; } LLHost mHost; typedef std::map<std::string, std::string> CapMap; CapMap mCaps; }; /***************************************************************************** * Dummy LLMessageSystem methods *****************************************************************************/ /*==========================================================================*| // This doesn't work because we're already linking in llmessage.a, and we get // duplicate-symbol errors from the linker. Perhaps if I wanted to go through // the exercise of providing dummy versions of every single symbol defined in // message.o -- maybe some day. typedef std::vector< std::pair<std::string, std::string> > StringPairVector; StringPairVector call_history; S32 LLMessageSystem::sendReliable(const LLHost& host) { call_history.push_back(StringPairVector::value_type("sendReliable", stringize(host))); return 0; } |*==========================================================================*/ /***************************************************************************** * TUT *****************************************************************************/ namespace tut { struct llcapears_data: public commtest_data { TestCapabilityProvider provider; LLCapabilityListener regionListener; LLEventPump& regionPump; llcapears_data(): provider(host), regionListener("testCapabilityListener", NULL, provider, LLUUID(), LLUUID()), regionPump(regionListener.getCapAPI()) { provider.setCapability("good", server + "capability-test"); provider.setCapability("fail", server + "fail"); } }; typedef test_group<llcapears_data> llcapears_group; typedef llcapears_group::object llcapears_object; llcapears_group llsdmgr("llcapabilitylistener"); template<> template<> void llcapears_object::test<1>() { LLSD request, body; body["data"] = "yes"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); std::string threw; try { WrapLL_ERRS capture; regionPump.post(request); } catch (const WrapLL_ERRS::FatalException& e) { threw = e.what(); } ensure_contains("missing capability name", threw, "without 'message' key"); } template<> template<> void llcapears_object::test<2>() { LLSD request, body; body["data"] = "yes"; request["message"] = "good"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); regionPump.post(request); ensure("got response", netio.pump()); ensure("success response", success); ensure_equals(result.asString(), "success"); body["status"] = 499; body["reason"] = "custom error message"; request["message"] = "fail"; request["payload"] = body; regionPump.post(request); ensure("got response", netio.pump()); ensure("failure response", ! success); ensure_equals(result["status"].asInteger(), body["status"].asInteger()); ensure_equals(result["reason"].asString(), body["reason"].asString()); } template<> template<> void llcapears_object::test<3>() { LLSD request, body; body["data"] = "yes"; request["message"] = "unknown"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); std::string threw; try { WrapLL_ERRS capture; regionPump.post(request); } catch (const WrapLL_ERRS::FatalException& e) { threw = e.what(); } ensure_contains("bad capability name", threw, "unsupported capability"); } struct TestMapper: public LLCapabilityListener::CapabilityMapper { // Instantiator gets to specify whether mapper expects a reply. // I'd really like to be able to test CapabilityMapper::buildMessage() // functionality, too, but -- even though LLCapabilityListener accepts // the LLMessageSystem* that it passes to CapabilityMapper -- // LLMessageSystem::sendReliable(const LLHost&) isn't virtual, so it's // not helpful to pass a subclass instance. I suspect that making any // LLMessageSystem methods virtual would provoke howls of outrage, // given how heavily it's used. Nor can I just provide a local // definition of LLMessageSystem::sendReliable(const LLHost&) because // we're already linking in the rest of message.o via llmessage.a, and // that produces duplicate-symbol link errors. TestMapper(const std::string& replyMessage = std::string()): LLCapabilityListener::CapabilityMapper("test", replyMessage) {} virtual void buildMessage(LLMessageSystem* msg, const LLUUID& agentID, const LLUUID& sessionID, const std::string& capabilityName, const LLSD& payload) const { msg->newMessageFast(_PREHASH_SetStartLocationRequest); msg->nextBlockFast( _PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, agentID); msg->addUUIDFast(_PREHASH_SessionID, sessionID); msg->nextBlockFast( _PREHASH_StartLocationData); // corrected by sim msg->addStringFast(_PREHASH_SimName, ""); msg->addU32Fast(_PREHASH_LocationID, payload["HomeLocation"]["LocationId"].asInteger()); /*==========================================================================*| msg->addVector3Fast(_PREHASH_LocationPos, ll_vector3_from_sdmap(payload["HomeLocation"]["LocationPos"])); msg->addVector3Fast(_PREHASH_LocationLookAt, ll_vector3_from_sdmap(payload["HomeLocation"]["LocationLookAt"])); |*==========================================================================*/ } }; template<> template<> void llcapears_object::test<4>() { TestMapper testMapper("WantReply"); LLSD request, body; body["data"] = "yes"; request["message"] = "test"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); std::string threw; try { WrapLL_ERRS capture; regionPump.post(request); } catch (const WrapLL_ERRS::FatalException& e) { threw = e.what(); } ensure_contains("capability mapper wants reply", threw, "unimplemented support for reply message"); } template<> template<> void llcapears_object::test<5>() { TestMapper testMapper; std::string threw; try { TestMapper testMapper2; } catch (const std::runtime_error& e) { threw = e.what(); } ensure_contains("no dup cap mapper", threw, "DupCapMapper"); } } <commit_msg>Fixed TestCapabilityProvider build issue.<commit_after>/** * @file llcapabilitylistener_test.cpp * @author Nat Goodspeed * @date 2008-12-31 * @brief Test for llcapabilitylistener.cpp. * * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ // Precompiled header #include "../llviewerprecompiledheaders.h" // Own header #include "../llcapabilitylistener.h" // STL headers #include <stdexcept> #include <map> #include <vector> // std headers // external library headers #include "boost/bind.hpp" // other Linden headers #include "../test/lltut.h" #include "../llcapabilityprovider.h" #include "lluuid.h" #include "tests/networkio.h" #include "tests/commtest.h" #include "tests/wrapllerrs.h" #include "message.h" #include "stringize.h" #if defined(LL_WINDOWS) #pragma warning(disable: 4355) // using 'this' in base-class ctor initializer expr #endif /***************************************************************************** * TestCapabilityProvider *****************************************************************************/ struct TestCapabilityProvider: public LLCapabilityProvider { TestCapabilityProvider(const LLHost& host): mHost(host) {} std::string getCapability(const std::string& cap) const { CapMap::const_iterator found = mCaps.find(cap); if (found != mCaps.end()) return found->second; // normal LLViewerRegion lookup failure mode return ""; } void setCapability(const std::string& cap, const std::string& url) { mCaps[cap] = url; } const LLHost& getHost() const { return mHost; } std::string getDescription() const { return "TestCapabilityProvider"; } LLHost mHost; typedef std::map<std::string, std::string> CapMap; CapMap mCaps; }; /***************************************************************************** * Dummy LLMessageSystem methods *****************************************************************************/ /*==========================================================================*| // This doesn't work because we're already linking in llmessage.a, and we get // duplicate-symbol errors from the linker. Perhaps if I wanted to go through // the exercise of providing dummy versions of every single symbol defined in // message.o -- maybe some day. typedef std::vector< std::pair<std::string, std::string> > StringPairVector; StringPairVector call_history; S32 LLMessageSystem::sendReliable(const LLHost& host) { call_history.push_back(StringPairVector::value_type("sendReliable", stringize(host))); return 0; } |*==========================================================================*/ /***************************************************************************** * TUT *****************************************************************************/ namespace tut { struct llcapears_data: public commtest_data { TestCapabilityProvider provider; LLCapabilityListener regionListener; LLEventPump& regionPump; llcapears_data(): provider(host), regionListener("testCapabilityListener", NULL, provider, LLUUID(), LLUUID()), regionPump(regionListener.getCapAPI()) { provider.setCapability("good", server + "capability-test"); provider.setCapability("fail", server + "fail"); } }; typedef test_group<llcapears_data> llcapears_group; typedef llcapears_group::object llcapears_object; llcapears_group llsdmgr("llcapabilitylistener"); template<> template<> void llcapears_object::test<1>() { LLSD request, body; body["data"] = "yes"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); std::string threw; try { WrapLL_ERRS capture; regionPump.post(request); } catch (const WrapLL_ERRS::FatalException& e) { threw = e.what(); } ensure_contains("missing capability name", threw, "without 'message' key"); } template<> template<> void llcapears_object::test<2>() { LLSD request, body; body["data"] = "yes"; request["message"] = "good"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); regionPump.post(request); ensure("got response", netio.pump()); ensure("success response", success); ensure_equals(result.asString(), "success"); body["status"] = 499; body["reason"] = "custom error message"; request["message"] = "fail"; request["payload"] = body; regionPump.post(request); ensure("got response", netio.pump()); ensure("failure response", ! success); ensure_equals(result["status"].asInteger(), body["status"].asInteger()); ensure_equals(result["reason"].asString(), body["reason"].asString()); } template<> template<> void llcapears_object::test<3>() { LLSD request, body; body["data"] = "yes"; request["message"] = "unknown"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); std::string threw; try { WrapLL_ERRS capture; regionPump.post(request); } catch (const WrapLL_ERRS::FatalException& e) { threw = e.what(); } ensure_contains("bad capability name", threw, "unsupported capability"); } struct TestMapper: public LLCapabilityListener::CapabilityMapper { // Instantiator gets to specify whether mapper expects a reply. // I'd really like to be able to test CapabilityMapper::buildMessage() // functionality, too, but -- even though LLCapabilityListener accepts // the LLMessageSystem* that it passes to CapabilityMapper -- // LLMessageSystem::sendReliable(const LLHost&) isn't virtual, so it's // not helpful to pass a subclass instance. I suspect that making any // LLMessageSystem methods virtual would provoke howls of outrage, // given how heavily it's used. Nor can I just provide a local // definition of LLMessageSystem::sendReliable(const LLHost&) because // we're already linking in the rest of message.o via llmessage.a, and // that produces duplicate-symbol link errors. TestMapper(const std::string& replyMessage = std::string()): LLCapabilityListener::CapabilityMapper("test", replyMessage) {} virtual void buildMessage(LLMessageSystem* msg, const LLUUID& agentID, const LLUUID& sessionID, const std::string& capabilityName, const LLSD& payload) const { msg->newMessageFast(_PREHASH_SetStartLocationRequest); msg->nextBlockFast( _PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, agentID); msg->addUUIDFast(_PREHASH_SessionID, sessionID); msg->nextBlockFast( _PREHASH_StartLocationData); // corrected by sim msg->addStringFast(_PREHASH_SimName, ""); msg->addU32Fast(_PREHASH_LocationID, payload["HomeLocation"]["LocationId"].asInteger()); /*==========================================================================*| msg->addVector3Fast(_PREHASH_LocationPos, ll_vector3_from_sdmap(payload["HomeLocation"]["LocationPos"])); msg->addVector3Fast(_PREHASH_LocationLookAt, ll_vector3_from_sdmap(payload["HomeLocation"]["LocationLookAt"])); |*==========================================================================*/ } }; template<> template<> void llcapears_object::test<4>() { TestMapper testMapper("WantReply"); LLSD request, body; body["data"] = "yes"; request["message"] = "test"; request["payload"] = body; request["reply"] = replyPump.getName(); request["error"] = errorPump.getName(); std::string threw; try { WrapLL_ERRS capture; regionPump.post(request); } catch (const WrapLL_ERRS::FatalException& e) { threw = e.what(); } ensure_contains("capability mapper wants reply", threw, "unimplemented support for reply message"); } template<> template<> void llcapears_object::test<5>() { TestMapper testMapper; std::string threw; try { TestMapper testMapper2; } catch (const std::runtime_error& e) { threw = e.what(); } ensure_contains("no dup cap mapper", threw, "DupCapMapper"); } } <|endoftext|>
<commit_before>// Copyright (c) 2014 Horia Cretescu. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "integer.hpp" #include "bytestring.hpp" class List : public BencodeType { std::vector<BencodeType*> data; public: void push(BencodeType*); }; void List::push(BencodeType *value) { data.push_back(value); } <commit_msg>added functionality<commit_after>// Copyright (c) 2014 Horia Cretescu. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "integer.hpp" #include "bytestring.hpp" class List : public BencodeType { std::vector<BencodeType*> data; public: List(); ~List(); List(const List&); List& operator = (const List&); void push(BencodeType*); BencodeType *clone(); }; List::List() { } List::~List() { for (size_t i = 0; i < data.size(); i++) { delete data[i]; } data.clear(); } List::List(const List& other) { data.resize(other.data.size()); for (size_t i = 0; i < data.size(); i++) { data[i] = other.data[i]->clone(); } } List& List::operator = (const List& other) { if (&other == this) { return *this; } this->~List(); data.resize(other.data.size()); for (size_t i = 0; i < data.size(); i++) { data[i] = other.data[i]->clone(); } return *this; } void List::push(BencodeType *value) { data.push_back(value); } BencodeType* List::clone() { return new List(*this); } <|endoftext|>
<commit_before>// Lowest Common Ancestor <O(nlogn), O(logn)> int par[25][N], h[N]; // build (sparse table) par[0][1] = 1; for (int i = 0; (1<<i) < n; ++i) for (int j = 1; j <= n; ++j) par[i][j] = par[i-1][par[i-1][j]]; // query int lca(int u, int v) { if (h[u] < h[v]) swap(u, v); for (int i = 20; i >= 0; --i) if (h[v]+(1<<i) <= h[u]) u = par[u][i]; if (u == v) return u; for (int i = 20; i >= 0; --i) if (par[i][u] != par[i][u]) u = par[i][u], v = par[i][u]; return par[0][u]; } <commit_msg>Fixed bugs in LCA.<commit_after>// Lowest Common Ancestor <O(nlogn), O(logn)> int anc[25][N], h[N], rt; // build (sancse table) anc[0][rt] = rt; // set ancent of the root to itself for (int i = 0; (1<<i) < n; ++i) for (int j = 1; j <= n; ++j) anc[i][j] = anc[i-1][anc[i-1][j]]; // query int lca(int u, int v) { if (h[u] < h[v]) swap(u, v); for (int i = 20; i >= 0; --i) if (h[u]-(1<<i) <= h[v]) u = anc[i][u]; if (u == v) return u; for (int i = 20; i >= 0; --i) if (anc[i][u] != anc[i][v]) u = anc[i][u], v = anc[i][v]; return anc[0][u]; } <|endoftext|>
<commit_before>#include <assert.h> #include <PCU.h> #include <apf.h> #include <apfMesh.h> #include <apfNumbering.h> #include "parma_weights.h" #include "parma_sides.h" #include "parma_ghostOwner.h" namespace { apf::MeshEntity* getOtherVtx(apf::Mesh* m, apf::MeshEntity* edge, apf::MeshEntity* vtx) { apf::Downward dwnVtx; int nDwnVtx = m->getDownward(edge,getDimension(m,edge)-1,dwnVtx); assert(nDwnVtx==2); return (dwnVtx[0] != vtx) ? dwnVtx[0] : dwnVtx[1]; } bool isOwnedByPeer(apf::Mesh* m,apf::MeshEntity* v, int peer) { if( ! m->isShared(v) ) return false; return (parma::getOwner(m,v) == peer); } // vertex based BFS // return an array of vertex, edge and element weights // - no one needs faces... yet // the returned array needs to be deallocated double* runBFS(apf::Mesh* m, int layers, std::vector<apf::MeshEntity*> current, apf::MeshTag* visited, apf::MeshTag* wtag, int peer) { assert(layers>=0); const int elmDim = m->getDimension(); double* weight = new double[4]; for(unsigned int i=0; i<4; i++) weight[i] = 0; std::vector<apf::MeshEntity*> next; for (int i=1;i<=layers;i++) { // when i==1: current contains shared vertices // owned by the peer that are not ghosted for (unsigned int j=0;j<current.size();j++) { apf::MeshEntity* vertex = current[j]; apf::Up edges; m->getUp(vertex,edges); for (int k=0;k<edges.n;k++) { apf::MeshEntity* edge = edges.e[k]; apf::MeshEntity* v = getOtherVtx(m,edge,vertex); //ghost vertices if (parma::isOwned(m, v) && !m->hasTag(v,visited)) { next.push_back(v); m->setIntTag(v,visited,&i); weight[0] += parma::getEntWeight(m,v,wtag); } //ghost edges if (parma::isOwned(m, edge) && !m->hasTag(edge,visited)) { weight[1] += parma::getEntWeight(m,edge,wtag); m->setIntTag(edge,visited,&i); } } //ghost elements apf::Adjacent elms; m->getAdjacent(vertex, elmDim, elms); for(size_t k=0; k<elms.size(); k++) { if (!m->hasTag(elms[k],visited)) { m->setIntTag(elms[k],visited,&i); weight[elmDim] += parma::getEntWeight(m,elms[k],wtag); } } } current=next; next.clear(); } PCU_Debug_Print("ghostW peer %d vtx %f edge %f elm %f\n", peer, weight[0], weight[1], weight[elmDim]); return weight; } double ownedWeight(apf::Mesh* m, apf::MeshTag* w, int dim) { apf::MeshIterator* it = m->begin(dim); apf::MeshEntity* e; double entW = 0; double sum = 0; while ((e = m->iterate(it))) { assert(m->hasTag(e,w)); if (parma::isOwned(m,e)) { m->getDoubleTag(e,w,&entW); sum += entW; } } m->end(it); return sum; } } namespace parma { class GhostFinder { public: GhostFinder(apf::Mesh* m, apf::MeshTag* w, int l) : mesh(m), wtag(w), layers(l) { depth = NULL; } double* weight(int peer) { int lvl = 0; depth = mesh->createIntTag("parma_depths_ver",1); apf::MeshIterator* itr = mesh->begin(0); apf::MeshEntity* e; std::vector<apf::MeshEntity*> current; while( (e=mesh->iterate(itr)) ) if( isOwnedByPeer(mesh,e,peer) ) current.push_back(e); mesh->end(itr); //tag the un-owned boundary edges so their weights are not counted itr = mesh->begin(1); while( (e=mesh->iterate(itr)) ) if( isOwnedByPeer(mesh,e,peer) ) mesh->setIntTag(e,depth,&lvl); mesh->end(itr); // current: peer owned vtx double* weight = runBFS(mesh,layers,current,depth,wtag,peer); for (unsigned int i=0;i<4;i++) apf::removeTagFromDimension(mesh,depth,i); mesh->destroyTag(depth); return weight; } private: GhostFinder(); apf::Mesh* mesh; apf::MeshTag* wtag; int layers; apf::MeshTag* depth; }; class GhostWeights : public Associative<double*> { public: GhostWeights(apf::Mesh* m, apf::MeshTag* w, Sides* s, int layers) : weight(0) { const int dim = m->getDimension(); weight = new double[4]; for(int d=0; d<=dim; d++) weight[d] = ownedWeight(m,w,d); for(int d=dim+1; d<=4; d++) weight[d] = 0; GhostFinder finder(m, w, layers); findGhosts(&finder, s); exchangeGhostsFrom(); exchange(); PCU_Debug_Print("totW vtx %f edge %f elm %f\n", weight[0], weight[1], weight[dim]); } ~GhostWeights() { const GhostWeights::Item* w; begin(); while( (w = iterate()) ) delete [] w->second; end(); delete [] weight; } double self(int dim) { return weight[dim]; } private: GhostWeights(); double* weight; void findGhosts(GhostFinder* finder, Sides* sides) { const Sides::Item* side; sides->begin(); while( (side = sides->iterate()) ) set(side->first, finder->weight(side->first)); sides->end(); } void exchangeGhostsFrom() { PCU_Comm_Begin(); const GhostWeights::Item* ghost; begin(); while( (ghost = iterate()) ) PCU_Comm_Pack(ghost->first, ghost->second, 4*sizeof(double)); end(); PCU_Comm_Send(); while (PCU_Comm_Listen()) { double* ghostsFromPeer = new double[4]; PCU_Comm_Unpack(ghostsFromPeer, 4*sizeof(double)); for(int i=0; i<4; i++) weight[i] += ghostsFromPeer[i]; } } void exchange() { PCU_Comm_Begin(); const GhostWeights::Item* ghost; begin(); while( (ghost = iterate()) ) PCU_Comm_Pack(ghost->first, weight, 4*sizeof(double)); end(); PCU_Comm_Send(); while (PCU_Comm_Listen()) { double* peerWeight = new double[4]; PCU_Comm_Unpack(peerWeight, 4*sizeof(double)); int peer = PCU_Comm_Sender(); set(peer, peerWeight); } } }; class GhostToEntWeight : public Weights { public: GhostToEntWeight(GhostWeights* gw, int dim) : Weights(NULL,NULL,NULL) { const GhostWeights::Item* ghost; gw->begin(); while( (ghost = gw->iterate()) ) set(ghost->first, ghost->second[dim]); gw->end(); weight = gw->self(dim); } double self() { return weight; } private: GhostToEntWeight(); double weight; }; Weights* convertGhostToEntWeight(GhostWeights* gw, int dim) { return new GhostToEntWeight(gw,dim); } GhostWeights* makeGhostWeights(apf::Mesh* m, apf::MeshTag* w, Sides* s, int layers) { return new GhostWeights(m, w, s, layers); } void destroyGhostWeights(GhostWeights* gw) { delete gw; } } //end namespace <commit_msg>get all the ghosted ents<commit_after>#include <assert.h> #include <PCU.h> #include <apf.h> #include <apfMesh.h> #include <apfNumbering.h> #include "parma_weights.h" #include "parma_sides.h" #include "parma_ghostOwner.h" namespace { bool isOwnedByPeer(apf::Mesh* m,apf::MeshEntity* v, int peer) { if( ! m->isShared(v) ) return false; return (parma::getOwner(m,v) == peer); } // vertex based BFS // return an array of vertex, edge and element weights // - no one needs faces... yet // the returned array needs to be deallocated double* runBFS(apf::Mesh* m, int layers, std::vector<apf::MeshEntity*> current, apf::MeshTag* visited, apf::MeshTag* wtag, int peer) { assert(layers>=0); const int elmDim = m->getDimension(); double* weight = new double[4]; for(unsigned int i=0; i<4; i++) weight[i] = 0; std::vector<apf::MeshEntity*> next; for (int i=1;i<=layers;i++) { for (unsigned int j=0;j<current.size();j++) { apf::MeshEntity* vertex = current[j]; apf::Adjacent elms; apf::Downward verts; apf::Downward edges; m->getAdjacent(vertex, elmDim, elms); for(size_t k=0; k<elms.size(); k++) { if (!m->hasTag(elms[k],visited)) { //ghost elements m->setIntTag(elms[k],visited,&i); weight[elmDim] += parma::getEntWeight(m,elms[k],wtag); //ghost edges const int nedges = m->getDownward(elms[k],1,edges); for(int l=0; l < nedges; l++) if (!m->hasTag(edges[l],visited)) { m->setIntTag(edges[l],visited,&i); weight[1] += parma::getEntWeight(m,edges[l],wtag); } //ghost vertices const int nverts = m->getDownward(elms[k],0,verts); for(int l=0; l < nverts; l++) if (parma::isOwned(m, verts[l]) && !m->hasTag(verts[l],visited)) { next.push_back(verts[l]); m->setIntTag(verts[l],visited,&i); weight[0] += parma::getEntWeight(m,verts[l],wtag); } } } } current=next; next.clear(); } PCU_Debug_Print("ghostW peer %d vtx %f edge %f elm %f\n", peer, weight[0], weight[1], weight[elmDim]); return weight; } double ownedWeight(apf::Mesh* m, apf::MeshTag* w, int dim) { apf::MeshIterator* it = m->begin(dim); apf::MeshEntity* e; double entW = 0; double sum = 0; while ((e = m->iterate(it))) { assert(m->hasTag(e,w)); if (parma::isOwned(m,e)) { m->getDoubleTag(e,w,&entW); sum += entW; } } m->end(it); return sum; } } namespace parma { class GhostFinder { public: GhostFinder(apf::Mesh* m, apf::MeshTag* w, int l) : mesh(m), wtag(w), layers(l) { depth = NULL; } double* weight(int peer) { int lvl = 0; depth = mesh->createIntTag("parma_depths_ver",1); apf::MeshIterator* itr = mesh->begin(0); apf::MeshEntity* e; std::vector<apf::MeshEntity*> current; while( (e=mesh->iterate(itr)) ) if( isOwnedByPeer(mesh,e,peer) ) current.push_back(e); mesh->end(itr); //tag the un-owned boundary edges so their weights are not counted itr = mesh->begin(1); while( (e=mesh->iterate(itr)) ) if( isOwnedByPeer(mesh,e,peer) ) mesh->setIntTag(e,depth,&lvl); mesh->end(itr); // current: peer owned vtx double* weight = runBFS(mesh,layers,current,depth,wtag,peer); for (unsigned int i=0;i<4;i++) apf::removeTagFromDimension(mesh,depth,i); mesh->destroyTag(depth); return weight; } private: GhostFinder(); apf::Mesh* mesh; apf::MeshTag* wtag; int layers; apf::MeshTag* depth; }; class GhostWeights : public Associative<double*> { public: GhostWeights(apf::Mesh* m, apf::MeshTag* w, Sides* s, int layers) : weight(0) { const int dim = m->getDimension(); weight = new double[4]; for(int d=0; d<=dim; d++) weight[d] = ownedWeight(m,w,d); for(int d=dim+1; d<=4; d++) weight[d] = 0; GhostFinder finder(m, w, layers); findGhosts(&finder, s); exchangeGhostsFrom(); exchange(); PCU_Debug_Print("totW vtx %f edge %f elm %f\n", weight[0], weight[1], weight[dim]); } ~GhostWeights() { const GhostWeights::Item* w; begin(); while( (w = iterate()) ) delete [] w->second; end(); delete [] weight; } double self(int dim) { return weight[dim]; } private: GhostWeights(); double* weight; void findGhosts(GhostFinder* finder, Sides* sides) { const Sides::Item* side; sides->begin(); while( (side = sides->iterate()) ) set(side->first, finder->weight(side->first)); sides->end(); } void exchangeGhostsFrom() { PCU_Comm_Begin(); const GhostWeights::Item* ghost; begin(); while( (ghost = iterate()) ) PCU_Comm_Pack(ghost->first, ghost->second, 4*sizeof(double)); end(); PCU_Comm_Send(); while (PCU_Comm_Listen()) { double* ghostsFromPeer = new double[4]; PCU_Comm_Unpack(ghostsFromPeer, 4*sizeof(double)); for(int i=0; i<4; i++) weight[i] += ghostsFromPeer[i]; } } void exchange() { PCU_Comm_Begin(); const GhostWeights::Item* ghost; begin(); while( (ghost = iterate()) ) PCU_Comm_Pack(ghost->first, weight, 4*sizeof(double)); end(); PCU_Comm_Send(); while (PCU_Comm_Listen()) { double* peerWeight = new double[4]; PCU_Comm_Unpack(peerWeight, 4*sizeof(double)); int peer = PCU_Comm_Sender(); set(peer, peerWeight); } } }; class GhostToEntWeight : public Weights { public: GhostToEntWeight(GhostWeights* gw, int dim) : Weights(NULL,NULL,NULL) { const GhostWeights::Item* ghost; gw->begin(); while( (ghost = gw->iterate()) ) set(ghost->first, ghost->second[dim]); gw->end(); weight = gw->self(dim); } double self() { return weight; } private: GhostToEntWeight(); double weight; }; Weights* convertGhostToEntWeight(GhostWeights* gw, int dim) { return new GhostToEntWeight(gw,dim); } GhostWeights* makeGhostWeights(apf::Mesh* m, apf::MeshTag* w, Sides* s, int layers) { return new GhostWeights(m, w, s, layers); } void destroyGhostWeights(GhostWeights* gw) { delete gw; } } //end namespace <|endoftext|>
<commit_before>//===-- GenericSpecializer.cpp - Specialization of generic functions ------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Specialize calls to generic functions by substituting static type // information. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-generic-specialize" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILOptimizer/Utils/Generics.h" #include "swift/SILOptimizer/Utils/Local.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/ADT/SmallVector.h" using namespace swift; // STATISTIC(NumEscapingAllocas, "Number of aggregate allocas not chopped up " // "due to uses."); // STATISTIC(NumChoppedAllocas, "Number of chopped up aggregate allocas."); // STATISTIC(NumUnhandledAllocas, "Number of non struct, tuple allocas."); namespace {} // end anonymous namespace namespace { class GenericSpecializer : public SILFunctionTransform { bool specializeAppliesInFunction(SILFunction &F); /// The entry point to the transformation. void run() override { SILFunction &F = *getFunction(); DEBUG(llvm::dbgs() << "***** GenericSpecializer on function:" << F.getName() << " *****\n"); if (specializeAppliesInFunction(F)) invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody); } StringRef getName() override { return "Generic Specializer"; } }; } // end anonymous namespace bool GenericSpecializer::specializeAppliesInFunction(SILFunction &F) { bool Changed = false; llvm::SmallVector<SILInstruction *, 8> DeadApplies; for (auto &BB : F) { for (auto It = BB.begin(), End = BB.end(); It != End;) { auto &I = *It++; // Skip non-apply instructions, apply instructions with no // substitutions, apply instructions where we do not statically // know the called function, and apply instructions where we do // not have the body of the called function. ApplySite Apply = ApplySite::isa(&I); if (!Apply || !Apply.hasSubstitutions()) continue; auto *Callee = Apply.getCalleeFunction(); if (!Callee || !Callee->isDefinition()) continue; // We have a call that can potentially be specialized, so // attempt to do so. // The specializer helper function currently expects a collector // argument, but we aren't going to make use of the results so // we'll have our filter always return false; auto Filter = [](SILInstruction *I) -> bool { return false; }; CloneCollector Collector(Filter); SILFunction *SpecializedFunction; auto Specialized = trySpecializeApplyOfGeneric(Apply, SpecializedFunction, Collector); if (Specialized) { Changed = true; // If calling the specialization utility resulted in a new // function (as opposed to returning a previous // specialization), we need to notify the pass manager so that // the new function gets optimized. if (SpecializedFunction) notifyPassManagerOfFunction(SpecializedFunction); auto *AI = Apply.getInstruction(); if (!isa<TryApplyInst>(AI)) AI->replaceAllUsesWith(Specialized.getInstruction()); DeadApplies.push_back(AI); } } } // Remove all the now-dead applies. while (!DeadApplies.empty()) { auto *AI = DeadApplies.pop_back_val(); recursivelyDeleteTriviallyDeadInstructions(AI, true); } return Changed; } SILTransform *swift::createGenericSpecializer() { return new GenericSpecializer(); } <commit_msg>Remove some inadvertantly committed code.<commit_after>//===-- GenericSpecializer.cpp - Specialization of generic functions ------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Specialize calls to generic functions by substituting static type // information. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-generic-specializer" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILOptimizer/Utils/Generics.h" #include "swift/SILOptimizer/Utils/Local.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "llvm/ADT/SmallVector.h" using namespace swift; namespace { class GenericSpecializer : public SILFunctionTransform { bool specializeAppliesInFunction(SILFunction &F); /// The entry point to the transformation. void run() override { SILFunction &F = *getFunction(); DEBUG(llvm::dbgs() << "***** GenericSpecializer on function:" << F.getName() << " *****\n"); if (specializeAppliesInFunction(F)) invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody); } StringRef getName() override { return "Generic Specializer"; } }; } // end anonymous namespace bool GenericSpecializer::specializeAppliesInFunction(SILFunction &F) { bool Changed = false; llvm::SmallVector<SILInstruction *, 8> DeadApplies; for (auto &BB : F) { for (auto It = BB.begin(), End = BB.end(); It != End;) { auto &I = *It++; // Skip non-apply instructions, apply instructions with no // substitutions, apply instructions where we do not statically // know the called function, and apply instructions where we do // not have the body of the called function. ApplySite Apply = ApplySite::isa(&I); if (!Apply || !Apply.hasSubstitutions()) continue; auto *Callee = Apply.getCalleeFunction(); if (!Callee || !Callee->isDefinition()) continue; // We have a call that can potentially be specialized, so // attempt to do so. // The specializer helper function currently expects a collector // argument, but we aren't going to make use of the results so // we'll have our filter always return false; auto Filter = [](SILInstruction *I) -> bool { return false; }; CloneCollector Collector(Filter); SILFunction *SpecializedFunction; auto Specialized = trySpecializeApplyOfGeneric(Apply, SpecializedFunction, Collector); if (Specialized) { Changed = true; // If calling the specialization utility resulted in a new // function (as opposed to returning a previous // specialization), we need to notify the pass manager so that // the new function gets optimized. if (SpecializedFunction) notifyPassManagerOfFunction(SpecializedFunction); auto *AI = Apply.getInstruction(); if (!isa<TryApplyInst>(AI)) AI->replaceAllUsesWith(Specialized.getInstruction()); DeadApplies.push_back(AI); } } } // Remove all the now-dead applies. while (!DeadApplies.empty()) { auto *AI = DeadApplies.pop_back_val(); recursivelyDeleteTriviallyDeadInstructions(AI, true); } return Changed; } SILTransform *swift::createGenericSpecializer() { return new GenericSpecializer(); } <|endoftext|>
<commit_before>//===-- MSP430MCInstLower.cpp - Convert MSP430 MachineInstr to an MCInst---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains code to lower MSP430 MachineInstrs to their corresponding // MCInst records. // //===----------------------------------------------------------------------===// #include "MSP430MCInstLower.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Mangler.h" #include "llvm/ADT/SmallString.h" using namespace llvm; MCSymbol *MSP430MCInstLower:: GetGlobalAddressSymbol(const MachineOperand &MO) const { const GlobalValue *GV = MO.getGlobal(); SmallString<128> Name; Mang.getNameWithPrefix(Name, GV, false); switch (MO.getTargetFlags()) { default: llvm_unreachable(0 && "Unknown target flag on GV operand"); case 0: break; } return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *MSP430MCInstLower:: GetExternalSymbolSymbol(const MachineOperand &MO) const { SmallString<128> Name; Name += Printer.MAI->getGlobalPrefix(); Name += MO.getSymbolName(); switch (MO.getTargetFlags()) { default: assert(0 && "Unknown target flag on GV operand"); case 0: break; } return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *MSP430MCInstLower:: GetJumpTableSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "JTI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *MSP430MCInstLower:: GetConstantPoolIndexSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "CPI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCOperand MSP430MCInstLower:: LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const { // FIXME: We would like an efficient form for this, so we don't have to do a // lot of extra uniquing. const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } if (!MO.isJTI() && MO.getOffset()) Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx); return MCOperand::CreateExpr(Expr); } void MSP430MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const { OutMI.setOpcode(MI->getOpcode()); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); MCOperand MCOp; switch (MO.getType()) { default: MI->dump(); assert(0 && "unknown operand type"); case MachineOperand::MO_Register: // Ignore all implicit register operands. if (MO.isImplicit()) continue; MCOp = MCOperand::CreateReg(MO.getReg()); break; case MachineOperand::MO_Immediate: MCOp = MCOperand::CreateImm(MO.getImm()); break; case MachineOperand::MO_MachineBasicBlock: MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create( Printer.GetMBBSymbol(MO.getMBB()->getNumber()), Ctx)); break; case MachineOperand::MO_GlobalAddress: MCOp = LowerSymbolOperand(MO, GetGlobalAddressSymbol(MO)); break; case MachineOperand::MO_ExternalSymbol: MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO)); break; case MachineOperand::MO_JumpTableIndex: MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO)); break; case MachineOperand::MO_ConstantPoolIndex: MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO)); break; } OutMI.addOperand(MCOp); } } <commit_msg>Pass the error string directly to llvm_unreachable instead of the residual (0 && "error"). Rough consensus seems to be that g++ *should* be diagnosing this because the pointer makes it not an ICE in c++03. Everyone agrees that the current standard is silly and null-pointer-ness should not be based on ICE-ness. Excellent fight scene in Act II, denouement weak, two stars.<commit_after>//===-- MSP430MCInstLower.cpp - Convert MSP430 MachineInstr to an MCInst---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains code to lower MSP430 MachineInstrs to their corresponding // MCInst records. // //===----------------------------------------------------------------------===// #include "MSP430MCInstLower.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Mangler.h" #include "llvm/ADT/SmallString.h" using namespace llvm; MCSymbol *MSP430MCInstLower:: GetGlobalAddressSymbol(const MachineOperand &MO) const { const GlobalValue *GV = MO.getGlobal(); SmallString<128> Name; Mang.getNameWithPrefix(Name, GV, false); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *MSP430MCInstLower:: GetExternalSymbolSymbol(const MachineOperand &MO) const { SmallString<128> Name; Name += Printer.MAI->getGlobalPrefix(); Name += MO.getSymbolName(); switch (MO.getTargetFlags()) { default: assert(0 && "Unknown target flag on GV operand"); case 0: break; } return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *MSP430MCInstLower:: GetJumpTableSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "JTI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCSymbol *MSP430MCInstLower:: GetConstantPoolIndexSymbol(const MachineOperand &MO) const { SmallString<256> Name; raw_svector_ostream(Name) << Printer.MAI->getPrivateGlobalPrefix() << "CPI" << Printer.getFunctionNumber() << '_' << MO.getIndex(); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } // Create a symbol for the name. return Ctx.GetOrCreateSymbol(Name.str()); } MCOperand MSP430MCInstLower:: LowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym) const { // FIXME: We would like an efficient form for this, so we don't have to do a // lot of extra uniquing. const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, Ctx); switch (MO.getTargetFlags()) { default: llvm_unreachable("Unknown target flag on GV operand"); case 0: break; } if (!MO.isJTI() && MO.getOffset()) Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx); return MCOperand::CreateExpr(Expr); } void MSP430MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const { OutMI.setOpcode(MI->getOpcode()); for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { const MachineOperand &MO = MI->getOperand(i); MCOperand MCOp; switch (MO.getType()) { default: MI->dump(); assert(0 && "unknown operand type"); case MachineOperand::MO_Register: // Ignore all implicit register operands. if (MO.isImplicit()) continue; MCOp = MCOperand::CreateReg(MO.getReg()); break; case MachineOperand::MO_Immediate: MCOp = MCOperand::CreateImm(MO.getImm()); break; case MachineOperand::MO_MachineBasicBlock: MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create( Printer.GetMBBSymbol(MO.getMBB()->getNumber()), Ctx)); break; case MachineOperand::MO_GlobalAddress: MCOp = LowerSymbolOperand(MO, GetGlobalAddressSymbol(MO)); break; case MachineOperand::MO_ExternalSymbol: MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO)); break; case MachineOperand::MO_JumpTableIndex: MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO)); break; case MachineOperand::MO_ConstantPoolIndex: MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO)); break; } OutMI.addOperand(MCOp); } } <|endoftext|>
<commit_before>#include "power.hpp" #include <cmath> #include <cstdio> #include <fstream> #include <iostream> #include <cstddef> #include <limits> #include <cassert> //For the normalized power spectrum #include <gsl/gsl_integration.h> PowerSpec_Tabulated::PowerSpec_Tabulated(const std::string& FileWithTransfer, const std::string & FileWithInputSpectrum, double Omega, double OmegaLambda, double OmegaBaryon, double OmegaNu, double InputSpectrum_UnitLength_in_cm, double UnitLength_in_cm, bool no_gas, bool combined_neutrinos) { //Set up conversion factor between internal units and CAMB units scale = (InputSpectrum_UnitLength_in_cm / UnitLength_in_cm); std::vector<double> kmatter_vector; std::vector<double> pmatter_vector; std::fstream matpow; matpow.open(FileWithInputSpectrum, std::fstream::in); if ( ! matpow.is_open() ) { std::cerr<<"Can't open matter power spectrum in file: "<< FileWithInputSpectrum<<std::endl; exit(17); } /* define matter array */ while ( matpow.good() ) { double ktmp,ptmp; //Discard comments if (matpow.get() == '#') matpow.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); else matpow.unget(); matpow >> ktmp; matpow >> ptmp; if (!matpow.good() ) break; kmatter_vector.push_back(ktmp); pmatter_vector.push_back(ptmp); } std::cerr<<"Found "<<pmatter_vector.size()<<" rows in input spectrum table: "<<FileWithInputSpectrum<<std::endl; matpow.close(); //Allocate arrays for the gsl interpolation (which must be raw arrays, unfortunately) //Then allocate the interpolation objects kmatter_table = new double[kmatter_vector.size()]; pmatter_table = new double[pmatter_vector.size()]; assert(kmatter_vector.size() == pmatter_vector.size()); //Copy over the k values and convert Fourier convention for (size_t i=0; i<kmatter_vector.size(); i++) { kmatter_table[i] = log10(kmatter_vector[i]); pmatter_table[i] = log10(pmatter_vector[i]/pow(2*M_PI,3)); if(i >0 && kmatter_table[i] <= kmatter_table[i-1]) { std::cerr<<"Matter power table is not increasing in k: i = "<<i<<", k = "<<kmatter_table[i]<<" <= "<<kmatter_table[i-1]<<std::endl; exit(48); } } //Set up the interpolation structures for the matter power pmat_interp = gsl_interp_alloc(gsl_interp_cspline,kmatter_vector.size()); pmat_interp_accel = gsl_interp_accel_alloc(); //Initialise the interpolator; same k values for each one, different T values. gsl_interp_init(pmat_interp,kmatter_table, pmatter_table,pmatter_vector.size()); NPowerTable = pmatter_vector.size(); std::fstream transfer; transfer.open(FileWithTransfer, std::fstream::in); if ( ! transfer.is_open() ) { std::cerr<<"Can't open transfer function in file: "<< FileWithTransfer<<std::endl; exit(17); } //Temporary arrays which can be resized so we don't have to read the file twice std::vector<double> ktransfer_vector; std::vector<double> transfer_vector[N_TYPES_TAB]; while ( transfer.good() ) { double T_b, dummy, T_nu, T_nu2,T_tot, T_cdm; double k; //Discard comments if (transfer.get() == '#') transfer.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); else transfer.unget(); //Read the row. transfer >> k; transfer >> T_cdm; transfer >> T_b; //radiation transfer >> dummy; transfer >> T_nu2; transfer >> T_nu; transfer >> T_tot; //Ignore the rest of the line transfer.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if ( ! transfer.good() ) break; /* The dark matter may incorporate other particle types as well, eg, * fake neutrinos, or baryons. * NOTE that CAMB defines T_tot = (T_CDM M_CDM + T_b M_b +T_nu M_nu) / (M_CDM + M_b +M_nu) * HOWEVER, when relativistic (ie, in the early universe), neutrinos will redshift * like radiation. The CAMB transfer function takes this into account when calculating T_tot, * so instead of summing the transfer functions, use the total transfer function and * optionally subtract the baryons. * We want to incorporate neutrinos into the dark matter if we are changing the transfer function, * but not if we are using the full kspace method. */ if(combined_neutrinos){ T_cdm = T_tot; /*If we have separate gas particles, subtract * the baryon transfer function */ if(!no_gas){ T_cdm = (Omega*T_tot - T_b*OmegaBaryon)/(Omega-OmegaBaryon); } } /*Add baryons to the CDM if there are no gas particles*/ else if(no_gas){ // T_cdm = (Omega*T_tot - T_nu*OmegaDM_2ndSpecies)/(Omega-OmegaDM_2ndSpecies); T_cdm = (T_cdm*(Omega-OmegaNu - OmegaBaryon) + T_b*OmegaBaryon)/(Omega-OmegaNu); } /*This should be equivalent to the above in almost all cases, * but perhaps we want to see the effect of changing only the ICs in CAMB for the neutrinos.*/ if(no_gas && OmegaNu == 0){ T_cdm = T_tot; } //Assign transfer functions to structures as T_s/T_t^2 ktransfer_vector.push_back(k); transfer_vector[0].push_back(pow(T_b/T_tot,2)); transfer_vector[1].push_back(pow(T_cdm/T_tot,2)); transfer_vector[2].push_back(pow(T_nu/T_tot,2)); transfer_vector[3].push_back(pow(T_nu2/T_tot,2)); } transfer.close(); //Allocate arrays for the gsl interpolation (which must be raw arrays, unfortunately) //Then allocate the interpolation objects ktransfer_table = new double[ktransfer_vector.size()]; //Copy over the k values for (size_t i=0; i<ktransfer_vector.size(); i++) { ktransfer_table[i] = log10(ktransfer_vector[i]); if(i >0 && ktransfer_table[i] <= ktransfer_table[i-1]) { std::cerr<<"Transfer table is not increasing in k: i = "<<i<<", k = "<<ktransfer_table[i]<<" <= "<<ktransfer_table[i-1]<<std::endl; exit(48); } } for(int type=0; type < N_TYPES_TAB; type++){ //Check everything is the same size assert( ktransfer_vector.size() == transfer_vector[type].size() ); transfer_table[type] = new double[transfer_vector[type].size()]; //Copy data from the temporary vectors to the statically sized C-arrays for (size_t i=0; i<transfer_vector[type].size(); i++) { //Make sure we do not take log(0) transfer_table[type][i] = transfer_vector[type][i]; } //Set up the interpolation structures trans_interp[type] = gsl_interp_alloc(gsl_interp_cspline,transfer_vector[type].size()); trans_interp_accel[type] = gsl_interp_accel_alloc(); //Initialise the interpolator; same k values for each one, different T values. //Size asserted to be the same. gsl_interp_init(trans_interp[type],ktransfer_table, transfer_table[type],transfer_vector[type].size()); } //Store the size of the arrays NTransferTable = ktransfer_vector.size(); } PowerSpec_Tabulated::~PowerSpec_Tabulated() { //Free memory for power table delete[] kmatter_table; delete[] pmatter_table; gsl_interp_free(pmat_interp); gsl_interp_accel_free(pmat_interp_accel); //Free memory for transfer table delete[] ktransfer_table; for (int i=0; i<N_TYPES_TAB;i++) { delete[] transfer_table[i]; gsl_interp_free(trans_interp[i]); gsl_interp_accel_free(trans_interp_accel[i]); } } double PowerSpec_Tabulated::power(double k, int Type) { double logk = log10(k*scale); double transfer; if(logk < ktransfer_table[0] || logk > ktransfer_table[NTransferTable - 1]) return 0; if(logk < kmatter_table[0] || logk > kmatter_table[NPowerTable - 1]) return 0; //If a type is requested that isn't defined, assume we want the total matter power. if (Type > N_TYPES_TAB-1 || Type < 0) transfer = 1; else transfer = gsl_interp_eval(trans_interp[Type], ktransfer_table, transfer_table[Type], logk, trans_interp_accel[Type]); /* Sometimes, due to numerical roundoff in CAMB, the massive neutrino transfer function will become * slightly negative. Set it to close to zero in this case.*/ if(transfer < 0 && Type==2 && transfer > -1e-6){ transfer = 1e-14; } double logP = gsl_interp_eval(pmat_interp, kmatter_table, pmatter_table, logk, pmat_interp_accel); double P = pow(10.0, logP) * pow(scale, 3) * transfer; assert(P >= 0); return P; } //Definitions for the normalized power spectrum //These mostly compute sigma_8 via the GSL NormalizedPowerSpec::NormalizedPowerSpec(PowerSpec * PSpec, double Sigma8, double PrimordialIndex, double Dplus, double UnitLength_in_cm): PSpec(PSpec), PrimordialIndex(PrimordialIndex), Dplus(Dplus) { R8 = 8 * (3.085678e24 / UnitLength_in_cm); /* 8 Mpc/h */ //Uses R8 Norm = Sigma8 * Sigma8 / TopHatSigma2(); printf("Normalization adjusted to Sigma8=%g (Normfac=%g)\n\n", Sigma8, Norm); // Cosmology cosmo(HubbleParam, Omega, OmegaLambda, MNu, InvertedHierarchy); // Dplus = cosmo.GrowthFactor(InitTime, 1.0); printf("Dplus initial redshift =%g \n\n", Dplus); } double sigma2_int(double k, void * params) { NormalizedPowerSpec * PSpec = (NormalizedPowerSpec *) params; double r = PSpec->R8; double kr, kr2, w, x; kr = r * k; kr2 = kr * kr; /*Series expansion; actually good until kr~1*/ if(kr < 1e-2) w = 1./3. - kr2/30. +kr2*kr2/840.; else w = 3 * (sin(kr) / kr - cos(kr)) / kr2; x = 4 * M_PI * k * k * w * w * PSpec->power(k,100); return x; } double NormalizedPowerSpec::TopHatSigma2() { gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double result,abserr; gsl_function F; F.function = &sigma2_int; F.params = this; /* note: 500/R is here chosen as integration boundary (infinity) */ gsl_integration_qags (&F, 0, 500./this->R8, 0, 1e-4,1000,w,&result, &abserr); // printf("gsl_integration_qng in TopHatSigma2. Result %g, error: %g, intervals: %lu\n",result, abserr,w->size); gsl_integration_workspace_free (w); return result; } <commit_msg>Use camb's built-in DM + baryon field<commit_after>#include "power.hpp" #include <cmath> #include <cstdio> #include <fstream> #include <iostream> #include <cstddef> #include <limits> #include <cassert> //For the normalized power spectrum #include <gsl/gsl_integration.h> PowerSpec_Tabulated::PowerSpec_Tabulated(const std::string& FileWithTransfer, const std::string & FileWithInputSpectrum, double Omega, double OmegaLambda, double OmegaBaryon, double OmegaNu, double InputSpectrum_UnitLength_in_cm, double UnitLength_in_cm, bool no_gas, bool combined_neutrinos) { //Set up conversion factor between internal units and CAMB units scale = (InputSpectrum_UnitLength_in_cm / UnitLength_in_cm); std::vector<double> kmatter_vector; std::vector<double> pmatter_vector; std::fstream matpow; matpow.open(FileWithInputSpectrum, std::fstream::in); if ( ! matpow.is_open() ) { std::cerr<<"Can't open matter power spectrum in file: "<< FileWithInputSpectrum<<std::endl; exit(17); } /* define matter array */ while ( matpow.good() ) { double ktmp,ptmp; //Discard comments if (matpow.get() == '#') matpow.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); else matpow.unget(); matpow >> ktmp; matpow >> ptmp; if (!matpow.good() ) break; kmatter_vector.push_back(ktmp); pmatter_vector.push_back(ptmp); } std::cerr<<"Found "<<pmatter_vector.size()<<" rows in input spectrum table: "<<FileWithInputSpectrum<<std::endl; matpow.close(); //Allocate arrays for the gsl interpolation (which must be raw arrays, unfortunately) //Then allocate the interpolation objects kmatter_table = new double[kmatter_vector.size()]; pmatter_table = new double[pmatter_vector.size()]; assert(kmatter_vector.size() == pmatter_vector.size()); //Copy over the k values and convert Fourier convention for (size_t i=0; i<kmatter_vector.size(); i++) { kmatter_table[i] = log10(kmatter_vector[i]); pmatter_table[i] = log10(pmatter_vector[i]/pow(2*M_PI,3)); if(i >0 && kmatter_table[i] <= kmatter_table[i-1]) { std::cerr<<"Matter power table is not increasing in k: i = "<<i<<", k = "<<kmatter_table[i]<<" <= "<<kmatter_table[i-1]<<std::endl; exit(48); } } //Set up the interpolation structures for the matter power pmat_interp = gsl_interp_alloc(gsl_interp_cspline,kmatter_vector.size()); pmat_interp_accel = gsl_interp_accel_alloc(); //Initialise the interpolator; same k values for each one, different T values. gsl_interp_init(pmat_interp,kmatter_table, pmatter_table,pmatter_vector.size()); NPowerTable = pmatter_vector.size(); std::fstream transfer; transfer.open(FileWithTransfer, std::fstream::in); if ( ! transfer.is_open() ) { std::cerr<<"Can't open transfer function in file: "<< FileWithTransfer<<std::endl; exit(17); } //Temporary arrays which can be resized so we don't have to read the file twice std::vector<double> ktransfer_vector; std::vector<double> transfer_vector[N_TYPES_TAB]; while ( transfer.good() ) { double T_b, dummy, T_nu, T_nu2,T_tot, T_cdm, T_dmb; double k; //Discard comments if (transfer.get() == '#') transfer.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); else transfer.unget(); //Read the row. transfer >> k; transfer >> T_cdm; transfer >> T_b; //radiation transfer >> dummy; //massless neutrinos transfer >> T_nu2; //massive neutrinos transfer >> T_nu; transfer >> T_tot; //DM+baryons transfer >> T_dmb; //Ignore the rest of the line transfer.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if ( ! transfer.good() ) break; /* The dark matter may incorporate other particle types as well, eg, * fake neutrinos, or baryons. * NOTE that CAMB defines T_tot = (T_CDM M_CDM + T_b M_b +T_nu M_nu) / (M_CDM + M_b +M_nu) * HOWEVER, when relativistic (ie, in the early universe), neutrinos will redshift * like radiation. The CAMB transfer function takes this into account when calculating T_tot, * so instead of summing the transfer functions, use the total transfer function and * optionally subtract the baryons. * We want to incorporate neutrinos into the dark matter if we are changing the transfer function, * but not if we are using the full kspace method. */ if(combined_neutrinos){ T_cdm = T_tot; /*If we have separate gas particles, subtract * the baryon transfer function */ if(!no_gas){ T_cdm = (Omega*T_tot - T_b*OmegaBaryon)/(Omega-OmegaBaryon); } } /*Add baryons to the CDM if there are no gas particles*/ else if(no_gas){ T_cdm = T_dmb; } /*This should be equivalent to the above in almost all cases, * but perhaps we want to see the effect of changing only the ICs in CAMB for the neutrinos.*/ if(no_gas && OmegaNu == 0){ T_cdm = T_tot; } //Assign transfer functions to structures as T_s/T_t^2 ktransfer_vector.push_back(k); transfer_vector[0].push_back(pow(T_b/T_tot,2)); transfer_vector[1].push_back(pow(T_cdm/T_tot,2)); transfer_vector[2].push_back(pow(T_nu/T_tot,2)); transfer_vector[3].push_back(pow(T_nu2/T_tot,2)); } transfer.close(); //Allocate arrays for the gsl interpolation (which must be raw arrays, unfortunately) //Then allocate the interpolation objects ktransfer_table = new double[ktransfer_vector.size()]; //Copy over the k values for (size_t i=0; i<ktransfer_vector.size(); i++) { ktransfer_table[i] = log10(ktransfer_vector[i]); if(i >0 && ktransfer_table[i] <= ktransfer_table[i-1]) { std::cerr<<"Transfer table is not increasing in k: i = "<<i<<", k = "<<ktransfer_table[i]<<" <= "<<ktransfer_table[i-1]<<std::endl; exit(48); } } for(int type=0; type < N_TYPES_TAB; type++){ //Check everything is the same size assert( ktransfer_vector.size() == transfer_vector[type].size() ); transfer_table[type] = new double[transfer_vector[type].size()]; //Copy data from the temporary vectors to the statically sized C-arrays for (size_t i=0; i<transfer_vector[type].size(); i++) { //Make sure we do not take log(0) transfer_table[type][i] = transfer_vector[type][i]; } //Set up the interpolation structures trans_interp[type] = gsl_interp_alloc(gsl_interp_cspline,transfer_vector[type].size()); trans_interp_accel[type] = gsl_interp_accel_alloc(); //Initialise the interpolator; same k values for each one, different T values. //Size asserted to be the same. gsl_interp_init(trans_interp[type],ktransfer_table, transfer_table[type],transfer_vector[type].size()); } //Store the size of the arrays NTransferTable = ktransfer_vector.size(); } PowerSpec_Tabulated::~PowerSpec_Tabulated() { //Free memory for power table delete[] kmatter_table; delete[] pmatter_table; gsl_interp_free(pmat_interp); gsl_interp_accel_free(pmat_interp_accel); //Free memory for transfer table delete[] ktransfer_table; for (int i=0; i<N_TYPES_TAB;i++) { delete[] transfer_table[i]; gsl_interp_free(trans_interp[i]); gsl_interp_accel_free(trans_interp_accel[i]); } } double PowerSpec_Tabulated::power(double k, int Type) { double logk = log10(k*scale); double transfer; if(logk < ktransfer_table[0] || logk > ktransfer_table[NTransferTable - 1]) return 0; if(logk < kmatter_table[0] || logk > kmatter_table[NPowerTable - 1]) return 0; //If a type is requested that isn't defined, assume we want the total matter power. if (Type > N_TYPES_TAB-1 || Type < 0) transfer = 1; else transfer = gsl_interp_eval(trans_interp[Type], ktransfer_table, transfer_table[Type], logk, trans_interp_accel[Type]); /* Sometimes, due to numerical roundoff in CAMB, the massive neutrino transfer function will become * slightly negative. Set it to close to zero in this case.*/ if(transfer < 0 && Type==2 && transfer > -1e-6){ transfer = 1e-14; } double logP = gsl_interp_eval(pmat_interp, kmatter_table, pmatter_table, logk, pmat_interp_accel); double P = pow(10.0, logP) * pow(scale, 3) * transfer; assert(P >= 0); return P; } //Definitions for the normalized power spectrum //These mostly compute sigma_8 via the GSL NormalizedPowerSpec::NormalizedPowerSpec(PowerSpec * PSpec, double Sigma8, double PrimordialIndex, double Dplus, double UnitLength_in_cm): PSpec(PSpec), PrimordialIndex(PrimordialIndex), Dplus(Dplus) { R8 = 8 * (3.085678e24 / UnitLength_in_cm); /* 8 Mpc/h */ //Uses R8 Norm = Sigma8 * Sigma8 / TopHatSigma2(); printf("Normalization adjusted to Sigma8=%g (Normfac=%g)\n\n", Sigma8, Norm); // Cosmology cosmo(HubbleParam, Omega, OmegaLambda, MNu, InvertedHierarchy); // Dplus = cosmo.GrowthFactor(InitTime, 1.0); printf("Dplus initial redshift =%g \n\n", Dplus); } double sigma2_int(double k, void * params) { NormalizedPowerSpec * PSpec = (NormalizedPowerSpec *) params; double r = PSpec->R8; double kr, kr2, w, x; kr = r * k; kr2 = kr * kr; /*Series expansion; actually good until kr~1*/ if(kr < 1e-2) w = 1./3. - kr2/30. +kr2*kr2/840.; else w = 3 * (sin(kr) / kr - cos(kr)) / kr2; x = 4 * M_PI * k * k * w * w * PSpec->power(k,100); return x; } double NormalizedPowerSpec::TopHatSigma2() { gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double result,abserr; gsl_function F; F.function = &sigma2_int; F.params = this; /* note: 500/R is here chosen as integration boundary (infinity) */ gsl_integration_qags (&F, 0, 500./this->R8, 0, 1e-4,1000,w,&result, &abserr); // printf("gsl_integration_qng in TopHatSigma2. Result %g, error: %g, intervals: %lu\n",result, abserr,w->size); gsl_integration_workspace_free (w); return result; } <|endoftext|>
<commit_before>extern "C" { #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> /* Directive handlers */ static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic /* Directives */ static ngx_command_t ngx_http_lmdb_queue_commands[] = { { ngx_string("lmdb_queue"), NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2, ngx_http_lmdb_queue, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, { ngx_string("lmdb_queue_topic"), NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3, ngx_http_lmdb_queue_topic, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, { ngx_string("lmdb_queue_push"), NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1, ngx_http_lmdb_queue_push, NGX_HTTP_LOC_CONF_OFFSET, 0, NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_lmdb_queue_module = { NGX_MODULE_V1, &ngx_http_lmdb_queue_module_ctx, /* module context */ ngx_http_lmdb_queue_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { return NGX_CONF_OK; } static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { return NGX_CONF_OK; } static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { return NGX_CONF_OK; } }<commit_msg>lmdb_queue conf<commit_after>#include <string> #include <stdio.h> std::string queue_path; extern "C" { #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> /* Directive handlers */ static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic /* Directives */ static ngx_command_t ngx_http_lmdb_queue_commands[] = { { ngx_string("lmdb_queue"), NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1, ngx_http_lmdb_queue, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, { ngx_string("lmdb_queue_topic"), NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3, ngx_http_lmdb_queue_topic, NGX_HTTP_MAIN_CONF_OFFSET, 0, NULL }, { ngx_string("lmdb_queue_push"), NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1, ngx_http_lmdb_queue_push, NGX_HTTP_LOC_CONF_OFFSET, 0, NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_lmdb_queue_module = { NGX_MODULE_V1, &ngx_http_lmdb_queue_module_ctx, /* module context */ ngx_http_lmdb_queue_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_str_t *args = (ngx_str_t*)cf->args->elts; const char* path = (const char*)args[1].data; int res = mkdir(path, 0666); if (res == 0 || errno == EEXIST) { queue_path = path; return NGX_CONF_OK; } else { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, strerror(errno), args[1]); return (char*)NGX_CONF_ERROR; } } static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { return NGX_CONF_OK; } static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { return NGX_CONF_OK; } }<|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jefftk@google.com (Jeff Kaufman) #include "ngx_rewrite_driver_factory.h" #include <cstdio> #include "log_message_handler.h" #include "ngx_message_handler.h" #include "ngx_rewrite_options.h" #include "ngx_server_context.h" #include "ngx_thread_system.h" #include "ngx_url_async_fetcher.h" #include "pthread_shared_mem.h" #include "net/instaweb/apache/serf_url_async_fetcher.h" #include "net/instaweb/http/public/content_type.h" #include "net/instaweb/http/public/fake_url_async_fetcher.h" #include "net/instaweb/http/public/wget_url_fetcher.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_driver_factory.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/static_asset_manager.h" #include "net/instaweb/system/public/system_caches.h" #include "net/instaweb/util/public/google_message_handler.h" #include "net/instaweb/util/public/null_shared_mem.h" #include "net/instaweb/util/public/property_cache.h" #include "net/instaweb/util/public/scheduler_thread.h" #include "net/instaweb/util/public/posix_timer.h" #include "net/instaweb/util/public/shared_circular_buffer.h" #include "net/instaweb/util/public/shared_mem_statistics.h" #include "net/instaweb/util/public/slow_worker.h" #include "net/instaweb/util/public/stdio_file_system.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/thread_system.h" namespace net_instaweb { class FileSystem; class Hasher; class MessageHandler; class Statistics; class Timer; class UrlAsyncFetcher; class UrlFetcher; class Writer; const char NgxRewriteDriverFactory::kStaticAssetPrefix[] = "/ngx_pagespeed_static/"; namespace { const char kShutdownCount[] = "child_shutdown_count"; } // namespace NgxRewriteDriverFactory::NgxRewriteDriverFactory( NgxThreadSystem* ngx_thread_system) : SystemRewriteDriverFactory(ngx_thread_system), ngx_thread_system_(ngx_thread_system), // TODO(oschaaf): mod_pagespeed ifdefs this: shared_mem_runtime_(new ngx::PthreadSharedMem()), main_conf_(NULL), threads_started_(false), use_per_vhost_statistics_(false), is_root_process_(true), ngx_message_handler_(new NgxMessageHandler(thread_system()->NewMutex())), ngx_html_parse_message_handler_( new NgxMessageHandler(thread_system()->NewMutex())), install_crash_handler_(false), message_buffer_size_(0), shared_circular_buffer_(NULL), statistics_frozen_(false), ngx_url_async_fetcher_(NULL), log_(NULL), resolver_timeout_(NGX_CONF_UNSET_MSEC), use_native_fetcher_(false) { InitializeDefaultOptions(); default_options()->set_beacon_url("/ngx_pagespeed_beacon"); set_message_handler(ngx_message_handler_); set_html_parse_message_handler(ngx_html_parse_message_handler_); // see https://code.google.com/p/modpagespeed/issues/detail?id=672 int thread_limit = 1; caches_.reset( new SystemCaches(this, shared_mem_runtime_.get(), thread_limit)); } NgxRewriteDriverFactory::~NgxRewriteDriverFactory() { ShutDown(); CHECK(uninitialized_server_contexts_.empty() || is_root_process_); STLDeleteElements(&uninitialized_server_contexts_); shared_mem_statistics_.reset(NULL); } Hasher* NgxRewriteDriverFactory::NewHasher() { return new MD5Hasher; } UrlFetcher* NgxRewriteDriverFactory::DefaultUrlFetcher() { CHECK(false) << "Nothing should still be using DefaultUrlFetcher()"; return NULL; } UrlAsyncFetcher* NgxRewriteDriverFactory::DefaultAsyncUrlFetcher() { const char* fetcher_proxy = ""; if (main_conf_ != NULL) { fetcher_proxy = main_conf_->fetcher_proxy().c_str(); } if (use_native_fetcher_) { net_instaweb::NgxUrlAsyncFetcher* fetcher = new net_instaweb::NgxUrlAsyncFetcher( fetcher_proxy, log_, resolver_timeout_, 25000, resolver_, thread_system(), message_handler()); ngx_url_async_fetcher_ = fetcher; return fetcher; } else { net_instaweb::UrlAsyncFetcher* fetcher = new net_instaweb::SerfUrlAsyncFetcher( fetcher_proxy, NULL, thread_system(), statistics(), timer(), 2500, message_handler()); return fetcher; } } MessageHandler* NgxRewriteDriverFactory::DefaultHtmlParseMessageHandler() { return ngx_html_parse_message_handler_; } MessageHandler* NgxRewriteDriverFactory::DefaultMessageHandler() { return ngx_message_handler_; } FileSystem* NgxRewriteDriverFactory::DefaultFileSystem() { return new StdioFileSystem(); } Timer* NgxRewriteDriverFactory::DefaultTimer() { return new PosixTimer; } NamedLockManager* NgxRewriteDriverFactory::DefaultLockManager() { CHECK(false); return NULL; } void NgxRewriteDriverFactory::SetupCaches(ServerContext* server_context) { caches_->SetupCaches(server_context); server_context->set_enable_property_cache(true); PropertyCache* pcache = server_context->page_property_cache(); if (pcache->GetCohort(RewriteDriver::kBeaconCohort) == NULL) { pcache->AddCohort(RewriteDriver::kBeaconCohort); } if (pcache->GetCohort(RewriteDriver::kDomCohort) == NULL) { pcache->AddCohort(RewriteDriver::kDomCohort); } } RewriteOptions* NgxRewriteDriverFactory::NewRewriteOptions() { NgxRewriteOptions* options = new NgxRewriteOptions(); options->SetRewriteLevel(RewriteOptions::kCoreFilters); return options; } void NgxRewriteDriverFactory::InitStaticAssetManager( StaticAssetManager* static_asset_manager) { static_asset_manager->set_library_url_prefix(kStaticAssetPrefix); } void NgxRewriteDriverFactory::PrintMemCacheStats(GoogleString* out) { // TODO(morlovich): Port the client code to proper API, so it gets // shm stats, too. caches_->PrintCacheStats(SystemCaches::kIncludeMemcached, out); } bool NgxRewriteDriverFactory::InitNgxUrlAsyncFetcher() { if (ngx_url_async_fetcher_ == NULL) { return true; } log_ = ngx_cycle->log; return ngx_url_async_fetcher_->Init(); } bool NgxRewriteDriverFactory::CheckResolver() { if (use_native_fetcher_ && resolver_ == NULL) { return false; } return true; } void NgxRewriteDriverFactory::StopCacheActivity() { RewriteDriverFactory::StopCacheActivity(); caches_->StopCacheActivity(); } NgxServerContext* NgxRewriteDriverFactory::MakeNgxServerContext() { NgxServerContext* server_context = new NgxServerContext(this); uninitialized_server_contexts_.insert(server_context); return server_context; } ServerContext* NgxRewriteDriverFactory::NewServerContext() { LOG(DFATAL) << "MakeNgxServerContext should be used instead"; return NULL; } void NgxRewriteDriverFactory::ShutDown() { StopCacheActivity(); if (!is_root_process_) { Variable* child_shutdown_count = statistics()->GetVariable(kShutdownCount); child_shutdown_count->Add(1); } RewriteDriverFactory::ShutDown(); caches_->ShutDown(message_handler()); ngx_message_handler_->set_buffer(NULL); ngx_html_parse_message_handler_->set_buffer(NULL); if (is_root_process_) { // Cleanup statistics. // TODO(morlovich): This looks dangerous with async. if (shared_mem_statistics_.get() != NULL) { shared_mem_statistics_->GlobalCleanup(message_handler()); } if (shared_circular_buffer_ != NULL) { shared_circular_buffer_->GlobalCleanup(message_handler()); } } } void NgxRewriteDriverFactory::StartThreads() { if (threads_started_) { return; } ngx_thread_system_->PermitThreadStarting(); // TODO(jefftk): use a native nginx timer instead of running our own thread. // See issue #111. SchedulerThread* thread = new SchedulerThread(thread_system(), scheduler()); bool ok = thread->Start(); CHECK(ok) << "Unable to start scheduler thread"; defer_cleanup(thread->MakeDeleter()); threads_started_ = true; } void NgxRewriteDriverFactory::ParentOrChildInit(ngx_log_t* log) { if (install_crash_handler_) { NgxMessageHandler::InstallCrashHandler(log); } ngx_message_handler_->set_log(log); ngx_html_parse_message_handler_->set_log(log); SharedCircularBufferInit(is_root_process_); } // TODO(jmarantz): make this per-vhost. void NgxRewriteDriverFactory::SharedCircularBufferInit(bool is_root) { // Set buffer size to 0 means turning it off if (shared_mem_runtime() != NULL && (message_buffer_size_ != 0)) { // TODO(jmarantz): it appears that filename_prefix() is not actually // established at the time of this construction, calling into question // whether we are naming our shared-memory segments correctly. shared_circular_buffer_.reset(new SharedCircularBuffer( shared_mem_runtime(), message_buffer_size_, filename_prefix().as_string(), "foo.com" /*hostname_identifier()*/)); if (shared_circular_buffer_->InitSegment(is_root, message_handler())) { ngx_message_handler_->set_buffer(shared_circular_buffer_.get()); ngx_html_parse_message_handler_->set_buffer( shared_circular_buffer_.get()); } } } void NgxRewriteDriverFactory::RootInit(ngx_log_t* log) { net_instaweb::log_message_handler::Install(log); ParentOrChildInit(log); // Let SystemCaches know about the various paths we have in configuration // first, as well as the memcached instances. for (NgxServerContextSet::iterator p = uninitialized_server_contexts_.begin(), e = uninitialized_server_contexts_.end(); p != e; ++p) { NgxServerContext* server_context = *p; caches_->RegisterConfig(server_context->config()); } caches_->RootInit(); } void NgxRewriteDriverFactory::ChildInit(ngx_log_t* log) { is_root_process_ = false; ParentOrChildInit(log); if (shared_mem_statistics_.get() != NULL) { shared_mem_statistics_->Init(false, message_handler()); } caches_->ChildInit(); for (NgxServerContextSet::iterator p = uninitialized_server_contexts_.begin(), e = uninitialized_server_contexts_.end(); p != e; ++p) { NgxServerContext* server_context = *p; server_context->ChildInit(); } uninitialized_server_contexts_.clear(); } // Initializes global statistics object if needed, using factory to // help with the settings if needed. // Note: does not call set_statistics() on the factory. Statistics* NgxRewriteDriverFactory::MakeGlobalSharedMemStatistics( bool logging, int64 logging_interval_ms, const GoogleString& logging_file_base) { if (shared_mem_statistics_.get() == NULL) { shared_mem_statistics_.reset(AllocateAndInitSharedMemStatistics( "global", logging, logging_interval_ms, logging_file_base)); } DCHECK(!statistics_frozen_); statistics_frozen_ = true; SetStatistics(shared_mem_statistics_.get()); return shared_mem_statistics_.get(); } SharedMemStatistics* NgxRewriteDriverFactory:: AllocateAndInitSharedMemStatistics( const StringPiece& name, const bool logging, const int64 logging_interval_ms, const GoogleString& logging_file_base) { // Note that we create the statistics object in the parent process, and // it stays around in the kids but gets reinitialized for them // inside ChildInit(), called from pagespeed_child_init. SharedMemStatistics* stats = new SharedMemStatistics( logging_interval_ms, StrCat(logging_file_base, name), logging, StrCat(filename_prefix(), name), shared_mem_runtime(), message_handler(), file_system(), timer()); InitStats(stats); stats->Init(true, message_handler()); return stats; } void NgxRewriteDriverFactory::InitStats(Statistics* statistics) { // Init standard PSOL stats. RewriteDriverFactory::InitStats(statistics); // Init Ngx-specific stats. NgxServerContext::InitStats(statistics); SystemCaches::InitStats(statistics); SerfUrlAsyncFetcher::InitStats(statistics); PropertyCache::InitCohortStats(RewriteDriver::kBeaconCohort, statistics); PropertyCache::InitCohortStats(RewriteDriver::kDomCohort, statistics); statistics->AddVariable(kShutdownCount); } } // namespace net_instaweb <commit_msg>serf: force threaded fetches<commit_after>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jefftk@google.com (Jeff Kaufman) #include "ngx_rewrite_driver_factory.h" #include <cstdio> #include "log_message_handler.h" #include "ngx_message_handler.h" #include "ngx_rewrite_options.h" #include "ngx_server_context.h" #include "ngx_thread_system.h" #include "ngx_url_async_fetcher.h" #include "pthread_shared_mem.h" #include "net/instaweb/apache/serf_url_async_fetcher.h" #include "net/instaweb/http/public/content_type.h" #include "net/instaweb/http/public/fake_url_async_fetcher.h" #include "net/instaweb/http/public/wget_url_fetcher.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_driver_factory.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/static_asset_manager.h" #include "net/instaweb/system/public/system_caches.h" #include "net/instaweb/util/public/google_message_handler.h" #include "net/instaweb/util/public/null_shared_mem.h" #include "net/instaweb/util/public/property_cache.h" #include "net/instaweb/util/public/scheduler_thread.h" #include "net/instaweb/util/public/posix_timer.h" #include "net/instaweb/util/public/shared_circular_buffer.h" #include "net/instaweb/util/public/shared_mem_statistics.h" #include "net/instaweb/util/public/slow_worker.h" #include "net/instaweb/util/public/stdio_file_system.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" #include "net/instaweb/util/public/thread_system.h" namespace net_instaweb { class FileSystem; class Hasher; class MessageHandler; class Statistics; class Timer; class UrlAsyncFetcher; class UrlFetcher; class Writer; const char NgxRewriteDriverFactory::kStaticAssetPrefix[] = "/ngx_pagespeed_static/"; namespace { const char kShutdownCount[] = "child_shutdown_count"; } // namespace NgxRewriteDriverFactory::NgxRewriteDriverFactory( NgxThreadSystem* ngx_thread_system) : SystemRewriteDriverFactory(ngx_thread_system), ngx_thread_system_(ngx_thread_system), // TODO(oschaaf): mod_pagespeed ifdefs this: shared_mem_runtime_(new ngx::PthreadSharedMem()), main_conf_(NULL), threads_started_(false), use_per_vhost_statistics_(false), is_root_process_(true), ngx_message_handler_(new NgxMessageHandler(thread_system()->NewMutex())), ngx_html_parse_message_handler_( new NgxMessageHandler(thread_system()->NewMutex())), install_crash_handler_(false), message_buffer_size_(0), shared_circular_buffer_(NULL), statistics_frozen_(false), ngx_url_async_fetcher_(NULL), log_(NULL), resolver_timeout_(NGX_CONF_UNSET_MSEC), use_native_fetcher_(false) { InitializeDefaultOptions(); default_options()->set_beacon_url("/ngx_pagespeed_beacon"); set_message_handler(ngx_message_handler_); set_html_parse_message_handler(ngx_html_parse_message_handler_); // see https://code.google.com/p/modpagespeed/issues/detail?id=672 int thread_limit = 1; caches_.reset( new SystemCaches(this, shared_mem_runtime_.get(), thread_limit)); } NgxRewriteDriverFactory::~NgxRewriteDriverFactory() { ShutDown(); CHECK(uninitialized_server_contexts_.empty() || is_root_process_); STLDeleteElements(&uninitialized_server_contexts_); shared_mem_statistics_.reset(NULL); } Hasher* NgxRewriteDriverFactory::NewHasher() { return new MD5Hasher; } UrlFetcher* NgxRewriteDriverFactory::DefaultUrlFetcher() { CHECK(false) << "Nothing should still be using DefaultUrlFetcher()"; return NULL; } UrlAsyncFetcher* NgxRewriteDriverFactory::DefaultAsyncUrlFetcher() { const char* fetcher_proxy = ""; if (main_conf_ != NULL) { fetcher_proxy = main_conf_->fetcher_proxy().c_str(); } if (use_native_fetcher_) { net_instaweb::NgxUrlAsyncFetcher* fetcher = new net_instaweb::NgxUrlAsyncFetcher( fetcher_proxy, log_, resolver_timeout_, 25000, resolver_, thread_system(), message_handler()); ngx_url_async_fetcher_ = fetcher; return fetcher; } else { net_instaweb::SerfUrlAsyncFetcher* fetcher = new net_instaweb::SerfUrlAsyncFetcher( fetcher_proxy, NULL, thread_system(), statistics(), timer(), 2500, message_handler()); // Make sure we don't block the nginx event loop fetcher->set_force_threaded(true); return fetcher; } } MessageHandler* NgxRewriteDriverFactory::DefaultHtmlParseMessageHandler() { return ngx_html_parse_message_handler_; } MessageHandler* NgxRewriteDriverFactory::DefaultMessageHandler() { return ngx_message_handler_; } FileSystem* NgxRewriteDriverFactory::DefaultFileSystem() { return new StdioFileSystem(); } Timer* NgxRewriteDriverFactory::DefaultTimer() { return new PosixTimer; } NamedLockManager* NgxRewriteDriverFactory::DefaultLockManager() { CHECK(false); return NULL; } void NgxRewriteDriverFactory::SetupCaches(ServerContext* server_context) { caches_->SetupCaches(server_context); server_context->set_enable_property_cache(true); PropertyCache* pcache = server_context->page_property_cache(); if (pcache->GetCohort(RewriteDriver::kBeaconCohort) == NULL) { pcache->AddCohort(RewriteDriver::kBeaconCohort); } if (pcache->GetCohort(RewriteDriver::kDomCohort) == NULL) { pcache->AddCohort(RewriteDriver::kDomCohort); } } RewriteOptions* NgxRewriteDriverFactory::NewRewriteOptions() { NgxRewriteOptions* options = new NgxRewriteOptions(); options->SetRewriteLevel(RewriteOptions::kCoreFilters); return options; } void NgxRewriteDriverFactory::InitStaticAssetManager( StaticAssetManager* static_asset_manager) { static_asset_manager->set_library_url_prefix(kStaticAssetPrefix); } void NgxRewriteDriverFactory::PrintMemCacheStats(GoogleString* out) { // TODO(morlovich): Port the client code to proper API, so it gets // shm stats, too. caches_->PrintCacheStats(SystemCaches::kIncludeMemcached, out); } bool NgxRewriteDriverFactory::InitNgxUrlAsyncFetcher() { if (ngx_url_async_fetcher_ == NULL) { return true; } log_ = ngx_cycle->log; return ngx_url_async_fetcher_->Init(); } bool NgxRewriteDriverFactory::CheckResolver() { if (use_native_fetcher_ && resolver_ == NULL) { return false; } return true; } void NgxRewriteDriverFactory::StopCacheActivity() { RewriteDriverFactory::StopCacheActivity(); caches_->StopCacheActivity(); } NgxServerContext* NgxRewriteDriverFactory::MakeNgxServerContext() { NgxServerContext* server_context = new NgxServerContext(this); uninitialized_server_contexts_.insert(server_context); return server_context; } ServerContext* NgxRewriteDriverFactory::NewServerContext() { LOG(DFATAL) << "MakeNgxServerContext should be used instead"; return NULL; } void NgxRewriteDriverFactory::ShutDown() { StopCacheActivity(); if (!is_root_process_) { Variable* child_shutdown_count = statistics()->GetVariable(kShutdownCount); child_shutdown_count->Add(1); } RewriteDriverFactory::ShutDown(); caches_->ShutDown(message_handler()); ngx_message_handler_->set_buffer(NULL); ngx_html_parse_message_handler_->set_buffer(NULL); if (is_root_process_) { // Cleanup statistics. // TODO(morlovich): This looks dangerous with async. if (shared_mem_statistics_.get() != NULL) { shared_mem_statistics_->GlobalCleanup(message_handler()); } if (shared_circular_buffer_ != NULL) { shared_circular_buffer_->GlobalCleanup(message_handler()); } } } void NgxRewriteDriverFactory::StartThreads() { if (threads_started_) { return; } ngx_thread_system_->PermitThreadStarting(); // TODO(jefftk): use a native nginx timer instead of running our own thread. // See issue #111. SchedulerThread* thread = new SchedulerThread(thread_system(), scheduler()); bool ok = thread->Start(); CHECK(ok) << "Unable to start scheduler thread"; defer_cleanup(thread->MakeDeleter()); threads_started_ = true; } void NgxRewriteDriverFactory::ParentOrChildInit(ngx_log_t* log) { if (install_crash_handler_) { NgxMessageHandler::InstallCrashHandler(log); } ngx_message_handler_->set_log(log); ngx_html_parse_message_handler_->set_log(log); SharedCircularBufferInit(is_root_process_); } // TODO(jmarantz): make this per-vhost. void NgxRewriteDriverFactory::SharedCircularBufferInit(bool is_root) { // Set buffer size to 0 means turning it off if (shared_mem_runtime() != NULL && (message_buffer_size_ != 0)) { // TODO(jmarantz): it appears that filename_prefix() is not actually // established at the time of this construction, calling into question // whether we are naming our shared-memory segments correctly. shared_circular_buffer_.reset(new SharedCircularBuffer( shared_mem_runtime(), message_buffer_size_, filename_prefix().as_string(), "foo.com" /*hostname_identifier()*/)); if (shared_circular_buffer_->InitSegment(is_root, message_handler())) { ngx_message_handler_->set_buffer(shared_circular_buffer_.get()); ngx_html_parse_message_handler_->set_buffer( shared_circular_buffer_.get()); } } } void NgxRewriteDriverFactory::RootInit(ngx_log_t* log) { net_instaweb::log_message_handler::Install(log); ParentOrChildInit(log); // Let SystemCaches know about the various paths we have in configuration // first, as well as the memcached instances. for (NgxServerContextSet::iterator p = uninitialized_server_contexts_.begin(), e = uninitialized_server_contexts_.end(); p != e; ++p) { NgxServerContext* server_context = *p; caches_->RegisterConfig(server_context->config()); } caches_->RootInit(); } void NgxRewriteDriverFactory::ChildInit(ngx_log_t* log) { is_root_process_ = false; ParentOrChildInit(log); if (shared_mem_statistics_.get() != NULL) { shared_mem_statistics_->Init(false, message_handler()); } caches_->ChildInit(); for (NgxServerContextSet::iterator p = uninitialized_server_contexts_.begin(), e = uninitialized_server_contexts_.end(); p != e; ++p) { NgxServerContext* server_context = *p; server_context->ChildInit(); } uninitialized_server_contexts_.clear(); } // Initializes global statistics object if needed, using factory to // help with the settings if needed. // Note: does not call set_statistics() on the factory. Statistics* NgxRewriteDriverFactory::MakeGlobalSharedMemStatistics( bool logging, int64 logging_interval_ms, const GoogleString& logging_file_base) { if (shared_mem_statistics_.get() == NULL) { shared_mem_statistics_.reset(AllocateAndInitSharedMemStatistics( "global", logging, logging_interval_ms, logging_file_base)); } DCHECK(!statistics_frozen_); statistics_frozen_ = true; SetStatistics(shared_mem_statistics_.get()); return shared_mem_statistics_.get(); } SharedMemStatistics* NgxRewriteDriverFactory:: AllocateAndInitSharedMemStatistics( const StringPiece& name, const bool logging, const int64 logging_interval_ms, const GoogleString& logging_file_base) { // Note that we create the statistics object in the parent process, and // it stays around in the kids but gets reinitialized for them // inside ChildInit(), called from pagespeed_child_init. SharedMemStatistics* stats = new SharedMemStatistics( logging_interval_ms, StrCat(logging_file_base, name), logging, StrCat(filename_prefix(), name), shared_mem_runtime(), message_handler(), file_system(), timer()); InitStats(stats); stats->Init(true, message_handler()); return stats; } void NgxRewriteDriverFactory::InitStats(Statistics* statistics) { // Init standard PSOL stats. RewriteDriverFactory::InitStats(statistics); // Init Ngx-specific stats. NgxServerContext::InitStats(statistics); SystemCaches::InitStats(statistics); SerfUrlAsyncFetcher::InitStats(statistics); PropertyCache::InitCohortStats(RewriteDriver::kBeaconCohort, statistics); PropertyCache::InitCohortStats(RewriteDriver::kDomCohort, statistics); statistics->AddVariable(kShutdownCount); } } // namespace net_instaweb <|endoftext|>
<commit_before>#include "Runtime/Weapon/CFlameThrower.hpp" #include "Runtime/CSimplePool.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/GameGlobalObjects.hpp" #include "Runtime/Collision/CInternalRayCastStructure.hpp" #include "Runtime/Graphics/CBooRenderer.hpp" #include "Runtime/Particle/CElementGen.hpp" #include "Runtime/Weapon/CFlameInfo.hpp" #include "Runtime/Weapon/CFlameThrower.hpp" #include "Runtime/World/CGameLight.hpp" #include "Runtime/World/CPlayer.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { const zeus::CVector3f CFlameThrower::kLightOffset(0, 3.f, 2.f); CFlameThrower::CFlameThrower(const TToken<CWeaponDescription>& wDesc, std::string_view name, EWeaponType wType, const CFlameInfo& flameInfo, const zeus::CTransform& xf, EMaterialTypes matType, const CDamageInfo& dInfo, TUniqueId uid, TAreaId aId, TUniqueId owner, EProjectileAttrib attribs, CAssetId playerSteamTxtr, s16 playerHitSfx, CAssetId playerIceTxtr) : CGameProjectile(false, wDesc, name, wType, xf, matType, dInfo, uid, aId, owner, kInvalidUniqueId, attribs, false, zeus::CVector3f(1.f), {}, -1, false) , x2e8_flameXf(xf) , x338_(flameInfo.x10_) , x33c_flameDesc(g_SimplePool->GetObj({FOURCC('PART'), flameInfo.GetFlameFxId()})) , x348_flameGen(std::make_unique<CElementGen>(x33c_flameDesc)) , x34c_flameWarp(176.f - float(flameInfo.GetLength()), xf.origin, bool(flameInfo.GetAttributes() & 0x4)) , x3f4_playerSteamTxtr(playerSteamTxtr) , x3f8_playerHitSfx(playerHitSfx) , x3fc_playerIceTxtr(playerIceTxtr) , x400_26_((flameInfo.GetAttributes() & 1) == 0) , x400_27_coneCollision((flameInfo.GetAttributes() & 0x2) != 0) {} void CFlameThrower::Accept(IVisitor& visitor) { visitor.Visit(this); } void CFlameThrower::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { if (msg == EScriptObjectMessage::Registered) { xe6_27_thermalVisorFlags = 2; mgr.AddWeaponId(xec_ownerId, xf0_weaponType); } else if (msg == EScriptObjectMessage::Deleted) { mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType); DeleteProjectileLight(mgr); } CGameProjectile::AcceptScriptMsg(msg, uid, mgr); } void CFlameThrower::SetTransform(const zeus::CTransform& xf, float) { x2e8_flameXf = xf; } void CFlameThrower::Reset(CStateManager& mgr, bool resetWarp) { SetFlameLightActive(mgr, false); if (resetWarp) { SetActive(false); x400_25_particlesActive = false; x3f0_flameState = EFlameState::Default; x330_particleWaitDelayTimer = 0.f; x334_fireStopTimer = 0.f; x318_flameBounds = zeus::skNullBox; x348_flameGen->SetParticleEmission(false); x34c_flameWarp.ResetPosition(x2e8_flameXf.origin); } else { x348_flameGen->SetParticleEmission(false); x400_25_particlesActive = false; x3f0_flameState = EFlameState::FireStopTimer; } } void CFlameThrower::Fire(const zeus::CTransform&, CStateManager& mgr, bool) { SetActive(true); x400_25_particlesActive = true; x400_24_active = true; x3f0_flameState = EFlameState::FireStart; CreateFlameParticles(mgr); } void CFlameThrower::CreateFlameParticles(CStateManager& mgr) { DeleteProjectileLight(mgr); x348_flameGen = std::make_unique<CElementGen>(x33c_flameDesc); x348_flameGen->SetParticleEmission(true); x348_flameGen->SetZTest(x400_27_coneCollision); x348_flameGen->AddModifier(&x34c_flameWarp); if (x348_flameGen->SystemHasLight() && x2c8_projectileLight == kInvalidUniqueId) CreateProjectileLight("FlameThrower_Light"sv, x348_flameGen->GetLight(), mgr); } void CFlameThrower::AddToRenderer(const zeus::CFrustum&, CStateManager& mgr) { g_Renderer->AddParticleGen(*x348_flameGen); EnsureRendered(mgr, x2e8_flameXf.origin, GetRenderBounds()); } void CFlameThrower::Render(CStateManager&) {} std::optional<zeus::CAABox> CFlameThrower::GetTouchBounds() const { return std::nullopt; } void CFlameThrower::Touch(CActor&, CStateManager&) {} void CFlameThrower::SetFlameLightActive(CStateManager& mgr, bool active) { if (x2c8_projectileLight == kInvalidUniqueId) return; if (TCastToPtr<CGameLight> light = mgr.ObjectById(x2c8_projectileLight)) light->SetActive(active); } void CFlameThrower::UpdateFlameState(float dt, CStateManager& mgr) { switch(x3f0_flameState) { case EFlameState::FireStart: x3f0_flameState = EFlameState::FireActive; break; case EFlameState::FireStopTimer: x334_fireStopTimer += 4.f * dt; if (x334_fireStopTimer > 1.f) { x334_fireStopTimer = 1.f; x3f0_flameState = EFlameState::FireWaitForParticlesDone; x400_24_active = false; } break; case EFlameState::FireWaitForParticlesDone: x330_particleWaitDelayTimer += dt; if (x330_particleWaitDelayTimer > 0.1f && x348_flameGen && x348_flameGen->GetParticleCountAll() == 0) { x3f0_flameState = EFlameState::Default; Reset(mgr, true); } break; default: break; } } CRayCastResult CFlameThrower::DoCollisionCheck(TUniqueId& idOut, const zeus::CAABox& aabb, CStateManager& mgr) { CRayCastResult ret; rstl::reserved_vector<TUniqueId, 1024> nearList; mgr.BuildNearList(nearList, aabb, CMaterialFilter::skPassEverything, this); const auto& colPoints = x34c_flameWarp.GetCollisionPoints(); if (x400_27_coneCollision && !colPoints.empty()) { const float radiusPitch = (x34c_flameWarp.GetMaxSize() - x34c_flameWarp.GetMinSize()) / float(colPoints.size()) * 0.5f; float curRadius = radiusPitch; for (size_t i = 1; i < colPoints.size(); ++i) { const zeus::CVector3f delta = colPoints[i] - colPoints[i - 1]; zeus::CTransform lookXf = zeus::lookAt(colPoints[i - 1], colPoints[i]); lookXf.origin = delta * 0.5f + colPoints[i - 1]; const zeus::COBBox obb(lookXf, {curRadius, delta.magnitude() * 0.5f, curRadius}); for (const TUniqueId id : nearList) { if (auto* act = static_cast<CActor*>(mgr.ObjectById(id))) { const CProjectileTouchResult tres = CanCollideWith(*act, mgr); if (tres.GetActorId() == kInvalidUniqueId) { continue; } const auto tb = act->GetTouchBounds(); if (!tb) { continue; } if (obb.AABoxIntersectsBox(*tb)) { const CCollidableAABox caabb(*tb, act->GetMaterialList()); const zeus::CVector3f flameToAct = act->GetAimPosition(mgr, 0.f) - x2e8_flameXf.origin; const float flameToActDist = flameToAct.magnitude(); const CInternalRayCastStructure rc(x2e8_flameXf.origin, flameToAct.normalized(), flameToActDist, {}, CMaterialFilter::skPassEverything); const CRayCastResult cres = caabb.CastRayInternal(rc); if (cres.IsInvalid()) { continue; } return cres; } } } curRadius += radiusPitch; } } else { for (size_t i = 0; i < colPoints.size() - 1; ++i) { const zeus::CVector3f delta = colPoints[i + 1] - colPoints[i]; const float deltaMag = delta.magnitude(); if (deltaMag <= 0.f) { break; } const CRayCastResult cres = RayCollisionCheckWithWorld(idOut, colPoints[i], colPoints[i + 1], deltaMag, nearList, mgr); if (cres.IsValid()) { return cres; } } } return ret; } void CFlameThrower::ApplyDamageToActor(CStateManager& mgr, TUniqueId id, float dt) { if (mgr.GetPlayer().GetUniqueId() == id && x3f4_playerSteamTxtr.IsValid() && x3fc_playerIceTxtr.IsValid()) mgr.GetPlayer().Freeze(mgr, x3f4_playerSteamTxtr, x3f8_playerHitSfx, x3fc_playerIceTxtr); CDamageInfo useDInfo = CDamageInfo(x12c_curDamageInfo, dt); ApplyDamageToActors(mgr, useDInfo); } void CFlameThrower::Think(float dt, CStateManager& mgr) { CWeapon::Think(dt, mgr); if (!GetActive()) return; UpdateFlameState(dt, mgr); zeus::CVector3f flamePoint = x2e8_flameXf.origin; bool r28 = x3f0_flameState == EFlameState::FireActive || x3f0_flameState == EFlameState::FireStopTimer; if (r28) { x34c_flameWarp.Activate(true); x34c_flameWarp.SetWarpPoint(flamePoint); x34c_flameWarp.SetStateManager(mgr); x348_flameGen->SetTranslation(flamePoint); x348_flameGen->SetOrientation(x2e8_flameXf.getRotation()); } else { x34c_flameWarp.Activate(false); } x348_flameGen->Update(dt); x34c_flameWarp.SetMaxDistSq(0.f); x34c_flameWarp.SetFloatingPoint(flamePoint); if (r28 && x34c_flameWarp.IsProcessed()) { x318_flameBounds = x34c_flameWarp.CalculateBounds(); TUniqueId id = kInvalidUniqueId; CRayCastResult res = DoCollisionCheck(id, x318_flameBounds, mgr); if (TCastToPtr<CActor> act = mgr.ObjectById(id)) { ApplyDamageToActor(mgr, id, dt); } else if (res.IsValid()) { CMaterialFilter useFilter = xf8_filter; CDamageInfo useDInfo = CDamageInfo(x12c_curDamageInfo, dt); mgr.ApplyDamageToWorld(xec_ownerId, *this, res.GetPoint(), useDInfo, useFilter); } } CActor::SetTransform(x2e8_flameXf.getRotation()); CActor::SetTranslation(x2e8_flameXf.origin); if (x2c8_projectileLight != kInvalidUniqueId) { if (TCastToPtr<CGameLight> light = mgr.ObjectById(x2c8_projectileLight)) { light->SetTransform(GetTransform()); light->SetTranslation(x34c_flameWarp.GetFloatingPoint()); if (x348_flameGen && x348_flameGen->SystemHasLight()) light->SetLight(x348_flameGen->GetLight()); } } } } // namespace urde <commit_msg>CFlameThrower: Silence unused variable warning<commit_after>#include "Runtime/Weapon/CFlameThrower.hpp" #include "Runtime/CSimplePool.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/GameGlobalObjects.hpp" #include "Runtime/Collision/CInternalRayCastStructure.hpp" #include "Runtime/Graphics/CBooRenderer.hpp" #include "Runtime/Particle/CElementGen.hpp" #include "Runtime/Weapon/CFlameInfo.hpp" #include "Runtime/Weapon/CFlameThrower.hpp" #include "Runtime/World/CGameLight.hpp" #include "Runtime/World/CPlayer.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace urde { const zeus::CVector3f CFlameThrower::kLightOffset(0, 3.f, 2.f); CFlameThrower::CFlameThrower(const TToken<CWeaponDescription>& wDesc, std::string_view name, EWeaponType wType, const CFlameInfo& flameInfo, const zeus::CTransform& xf, EMaterialTypes matType, const CDamageInfo& dInfo, TUniqueId uid, TAreaId aId, TUniqueId owner, EProjectileAttrib attribs, CAssetId playerSteamTxtr, s16 playerHitSfx, CAssetId playerIceTxtr) : CGameProjectile(false, wDesc, name, wType, xf, matType, dInfo, uid, aId, owner, kInvalidUniqueId, attribs, false, zeus::CVector3f(1.f), {}, -1, false) , x2e8_flameXf(xf) , x338_(flameInfo.x10_) , x33c_flameDesc(g_SimplePool->GetObj({FOURCC('PART'), flameInfo.GetFlameFxId()})) , x348_flameGen(std::make_unique<CElementGen>(x33c_flameDesc)) , x34c_flameWarp(176.f - float(flameInfo.GetLength()), xf.origin, bool(flameInfo.GetAttributes() & 0x4)) , x3f4_playerSteamTxtr(playerSteamTxtr) , x3f8_playerHitSfx(playerHitSfx) , x3fc_playerIceTxtr(playerIceTxtr) , x400_26_((flameInfo.GetAttributes() & 1) == 0) , x400_27_coneCollision((flameInfo.GetAttributes() & 0x2) != 0) {} void CFlameThrower::Accept(IVisitor& visitor) { visitor.Visit(this); } void CFlameThrower::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { if (msg == EScriptObjectMessage::Registered) { xe6_27_thermalVisorFlags = 2; mgr.AddWeaponId(xec_ownerId, xf0_weaponType); } else if (msg == EScriptObjectMessage::Deleted) { mgr.RemoveWeaponId(xec_ownerId, xf0_weaponType); DeleteProjectileLight(mgr); } CGameProjectile::AcceptScriptMsg(msg, uid, mgr); } void CFlameThrower::SetTransform(const zeus::CTransform& xf, float) { x2e8_flameXf = xf; } void CFlameThrower::Reset(CStateManager& mgr, bool resetWarp) { SetFlameLightActive(mgr, false); if (resetWarp) { SetActive(false); x400_25_particlesActive = false; x3f0_flameState = EFlameState::Default; x330_particleWaitDelayTimer = 0.f; x334_fireStopTimer = 0.f; x318_flameBounds = zeus::skNullBox; x348_flameGen->SetParticleEmission(false); x34c_flameWarp.ResetPosition(x2e8_flameXf.origin); } else { x348_flameGen->SetParticleEmission(false); x400_25_particlesActive = false; x3f0_flameState = EFlameState::FireStopTimer; } } void CFlameThrower::Fire(const zeus::CTransform&, CStateManager& mgr, bool) { SetActive(true); x400_25_particlesActive = true; x400_24_active = true; x3f0_flameState = EFlameState::FireStart; CreateFlameParticles(mgr); } void CFlameThrower::CreateFlameParticles(CStateManager& mgr) { DeleteProjectileLight(mgr); x348_flameGen = std::make_unique<CElementGen>(x33c_flameDesc); x348_flameGen->SetParticleEmission(true); x348_flameGen->SetZTest(x400_27_coneCollision); x348_flameGen->AddModifier(&x34c_flameWarp); if (x348_flameGen->SystemHasLight() && x2c8_projectileLight == kInvalidUniqueId) CreateProjectileLight("FlameThrower_Light"sv, x348_flameGen->GetLight(), mgr); } void CFlameThrower::AddToRenderer(const zeus::CFrustum&, CStateManager& mgr) { g_Renderer->AddParticleGen(*x348_flameGen); EnsureRendered(mgr, x2e8_flameXf.origin, GetRenderBounds()); } void CFlameThrower::Render(CStateManager&) {} std::optional<zeus::CAABox> CFlameThrower::GetTouchBounds() const { return std::nullopt; } void CFlameThrower::Touch(CActor&, CStateManager&) {} void CFlameThrower::SetFlameLightActive(CStateManager& mgr, bool active) { if (x2c8_projectileLight == kInvalidUniqueId) return; if (TCastToPtr<CGameLight> light = mgr.ObjectById(x2c8_projectileLight)) light->SetActive(active); } void CFlameThrower::UpdateFlameState(float dt, CStateManager& mgr) { switch(x3f0_flameState) { case EFlameState::FireStart: x3f0_flameState = EFlameState::FireActive; break; case EFlameState::FireStopTimer: x334_fireStopTimer += 4.f * dt; if (x334_fireStopTimer > 1.f) { x334_fireStopTimer = 1.f; x3f0_flameState = EFlameState::FireWaitForParticlesDone; x400_24_active = false; } break; case EFlameState::FireWaitForParticlesDone: x330_particleWaitDelayTimer += dt; if (x330_particleWaitDelayTimer > 0.1f && x348_flameGen && x348_flameGen->GetParticleCountAll() == 0) { x3f0_flameState = EFlameState::Default; Reset(mgr, true); } break; default: break; } } CRayCastResult CFlameThrower::DoCollisionCheck(TUniqueId& idOut, const zeus::CAABox& aabb, CStateManager& mgr) { CRayCastResult ret; rstl::reserved_vector<TUniqueId, 1024> nearList; mgr.BuildNearList(nearList, aabb, CMaterialFilter::skPassEverything, this); const auto& colPoints = x34c_flameWarp.GetCollisionPoints(); if (x400_27_coneCollision && !colPoints.empty()) { const float radiusPitch = (x34c_flameWarp.GetMaxSize() - x34c_flameWarp.GetMinSize()) / float(colPoints.size()) * 0.5f; float curRadius = radiusPitch; for (size_t i = 1; i < colPoints.size(); ++i) { const zeus::CVector3f delta = colPoints[i] - colPoints[i - 1]; zeus::CTransform lookXf = zeus::lookAt(colPoints[i - 1], colPoints[i]); lookXf.origin = delta * 0.5f + colPoints[i - 1]; const zeus::COBBox obb(lookXf, {curRadius, delta.magnitude() * 0.5f, curRadius}); for (const TUniqueId id : nearList) { if (auto* act = static_cast<CActor*>(mgr.ObjectById(id))) { const CProjectileTouchResult tres = CanCollideWith(*act, mgr); if (tres.GetActorId() == kInvalidUniqueId) { continue; } const auto tb = act->GetTouchBounds(); if (!tb) { continue; } if (obb.AABoxIntersectsBox(*tb)) { const CCollidableAABox caabb(*tb, act->GetMaterialList()); const zeus::CVector3f flameToAct = act->GetAimPosition(mgr, 0.f) - x2e8_flameXf.origin; const float flameToActDist = flameToAct.magnitude(); const CInternalRayCastStructure rc(x2e8_flameXf.origin, flameToAct.normalized(), flameToActDist, {}, CMaterialFilter::skPassEverything); const CRayCastResult cres = caabb.CastRayInternal(rc); if (cres.IsInvalid()) { continue; } return cres; } } } curRadius += radiusPitch; } } else { for (size_t i = 0; i < colPoints.size() - 1; ++i) { const zeus::CVector3f delta = colPoints[i + 1] - colPoints[i]; const float deltaMag = delta.magnitude(); if (deltaMag <= 0.f) { break; } const CRayCastResult cres = RayCollisionCheckWithWorld(idOut, colPoints[i], colPoints[i + 1], deltaMag, nearList, mgr); if (cres.IsValid()) { return cres; } } } return ret; } void CFlameThrower::ApplyDamageToActor(CStateManager& mgr, TUniqueId id, float dt) { if (mgr.GetPlayer().GetUniqueId() == id && x3f4_playerSteamTxtr.IsValid() && x3fc_playerIceTxtr.IsValid()) mgr.GetPlayer().Freeze(mgr, x3f4_playerSteamTxtr, x3f8_playerHitSfx, x3fc_playerIceTxtr); CDamageInfo useDInfo = CDamageInfo(x12c_curDamageInfo, dt); ApplyDamageToActors(mgr, useDInfo); } void CFlameThrower::Think(float dt, CStateManager& mgr) { CWeapon::Think(dt, mgr); if (!GetActive()) return; UpdateFlameState(dt, mgr); zeus::CVector3f flamePoint = x2e8_flameXf.origin; bool r28 = x3f0_flameState == EFlameState::FireActive || x3f0_flameState == EFlameState::FireStopTimer; if (r28) { x34c_flameWarp.Activate(true); x34c_flameWarp.SetWarpPoint(flamePoint); x34c_flameWarp.SetStateManager(mgr); x348_flameGen->SetTranslation(flamePoint); x348_flameGen->SetOrientation(x2e8_flameXf.getRotation()); } else { x34c_flameWarp.Activate(false); } x348_flameGen->Update(dt); x34c_flameWarp.SetMaxDistSq(0.f); x34c_flameWarp.SetFloatingPoint(flamePoint); if (r28 && x34c_flameWarp.IsProcessed()) { x318_flameBounds = x34c_flameWarp.CalculateBounds(); TUniqueId id = kInvalidUniqueId; const CRayCastResult res = DoCollisionCheck(id, x318_flameBounds, mgr); if (TCastToConstPtr<CActor>(mgr.ObjectById(id))) { ApplyDamageToActor(mgr, id, dt); } else if (res.IsValid()) { const CMaterialFilter useFilter = xf8_filter; const CDamageInfo useDInfo = CDamageInfo(x12c_curDamageInfo, dt); mgr.ApplyDamageToWorld(xec_ownerId, *this, res.GetPoint(), useDInfo, useFilter); } } CActor::SetTransform(x2e8_flameXf.getRotation()); CActor::SetTranslation(x2e8_flameXf.origin); if (x2c8_projectileLight != kInvalidUniqueId) { if (TCastToPtr<CGameLight> light = mgr.ObjectById(x2c8_projectileLight)) { light->SetTransform(GetTransform()); light->SetTranslation(x34c_flameWarp.GetFloatingPoint()); if (x348_flameGen && x348_flameGen->SystemHasLight()) light->SetLight(x348_flameGen->GetLight()); } } } } // namespace urde <|endoftext|>
<commit_before>#include "oddlib/compressiontype3ae.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <vector> #include <cassert> void commonLogic1(int& control_byte_sub6, unsigned int& srcByte, unsigned short int*& srcPtr) { if (control_byte_sub6) { if (control_byte_sub6 == 0xE) { control_byte_sub6 = 0x1Eu; srcByte |= *srcPtr << 14; ++srcPtr; } } else { srcByte = *(unsigned int *)srcPtr; control_byte_sub6 = 0x20u; srcPtr += 2; } control_byte_sub6 -= 6; } namespace Oddlib { std::vector<Uint8> CompressionType3Ae::Decompress(IStream& stream, Uint32 size, Uint32 w, Uint32 h) { std::vector<Uint8> ret; LOG_INFO("Data size is " << size); //Uint32 unknown = 0; //stream.ReadUInt32(unknown); //assert(unknown == size); std::vector<Uint8> tmp(size); stream.ReadBytes(tmp.data(), tmp.size()); tmp.resize(tmp.size()); // QByteArray d = aFrame.iFrameData.mid(4); unsigned char* aAnimDataPtr = (unsigned char*)tmp.data(); // (unsigned char*)d.data(); unsigned short int *aFramePtr = (unsigned short int *)aAnimDataPtr; std::vector< unsigned char > buffer; buffer.resize(w*h*4); // Ensure big enough via a guess! unsigned char *aDbufPtr = &buffer[0]; int height_copy; // eax@1 unsigned short int *srcPtr; // ebp@1 int control_byte; // esi@1 int dstIndex; // edx@2 unsigned char *dstPtr; // edi@2 int count; // ebx@3 unsigned char blackBytes; // al@8 unsigned int srcByte; // edx@8 int bytesToWrite; // ebx@8 int control_byte_sub6; // esi@8 int i; // ecx@9 unsigned char *dstBlackBytesPtr; // edi@9 unsigned int doubleBBytes; // ecx@9 int byteCount; // ecx@18 char dstByte; // al@23 int v18; // [sp+8h] [bp-14h]@1 int v19; // [sp+8h] [bp-14h]@8 int width; // [sp+10h] [bp-Ch]@1 int height; // [sp+14h] [bp-8h]@2 unsigned char bytes; // [sp+20h] [bp+4h]@17 control_byte = 0; width = *aFramePtr; // Byte 0 is W v18 = 0; height_copy = aFramePtr[1]; // Byte 1 is H srcPtr = aFramePtr + 2; // Data after W/H if (height_copy > 0) { dstIndex = (int)aDbufPtr; dstPtr = aDbufPtr; height = aFramePtr[1]; do { count = 0; while (count < width) { if (control_byte) { if (control_byte == 0xE) { control_byte = 0x1Eu; dstIndex |= *srcPtr << 14; ++srcPtr; } } else { dstIndex = *(unsigned int *)srcPtr; control_byte = 0x20u; srcPtr += 2; } blackBytes = dstIndex & 0x3F; control_byte_sub6 = control_byte - 6; srcByte = (unsigned int)dstIndex >> 6; v19 = v18 - 1; bytesToWrite = blackBytes + count; if ((signed int)blackBytes > 0) { doubleBBytes = (unsigned int)blackBytes >> 2; memset(dstPtr, 0, 4 * doubleBBytes); dstBlackBytesPtr = &dstPtr[4 * doubleBBytes]; for (i = blackBytes & 3; i; --i) *dstBlackBytesPtr++ = 0; dstPtr = &aDbufPtr[blackBytes]; aDbufPtr += blackBytes; } if (control_byte_sub6) { if (control_byte_sub6 == 0xE) { control_byte_sub6 = 0x1Eu; srcByte |= *srcPtr << 14; ++srcPtr; } } else { srcByte = *(unsigned int *)srcPtr; control_byte_sub6 = 0x20u; srcPtr += 2; } control_byte = control_byte_sub6 - 6; bytes = srcByte & 0x3F; dstIndex = srcByte >> 6; v18 = v19 - 1; count = bytes + bytesToWrite; if ((signed int)bytes > 0) { byteCount = bytes; v18 -= bytes; do { if (control_byte) { if (control_byte == 0xE) { control_byte = 0x1Eu; dstIndex |= *srcPtr << 14; ++srcPtr; } } else { dstIndex = *(unsigned int *)srcPtr; control_byte = 0x20u; srcPtr += 2; } control_byte -= 6; dstByte = dstIndex & 0x3F; dstIndex = (unsigned int)dstIndex >> 6; *dstPtr++ = dstByte; --byteCount; } while (byteCount); aDbufPtr = dstPtr; } } if (count & 3) { do { ++dstPtr; ++count; } while (count & 3); aDbufPtr = dstPtr; } height_copy = height - 1; } while (height-- != 1); } return buffer; } } <commit_msg>clean up and fixes last row of pixels corrupted issue<commit_after>#include "oddlib/compressiontype3ae.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <vector> #include <cassert> static Uint16 ReadUint16(Oddlib::IStream& stream) { Uint16 ret = 0; stream.ReadUInt16(ret); return ret; } static Uint32 ReadUint32(Oddlib::IStream& stream) { Uint32 ret = 0; stream.ReadUInt32(ret); return ret; } namespace Oddlib { std::vector<Uint8> CompressionType3Ae::Decompress(IStream& stream, Uint32 size, Uint32 w, Uint32 h) { std::vector<Uint8> ret; LOG_INFO("Data size is " << size); //Uint32 unknown = 0; //stream.ReadUInt32(unknown); //assert(unknown == size); /* std::vector<Uint8> tmp(size); stream.ReadBytes(tmp.data(), tmp.size()); tmp.resize(tmp.size()); // QByteArray d = aFrame.iFrameData.mid(4); unsigned char* aAnimDataPtr = (unsigned char*)tmp.data(); // (unsigned char*)d.data(); unsigned short int *aFramePtr = (unsigned short int *)aAnimDataPtr; */ std::vector< unsigned char > buffer; buffer.resize(w*h*4); // Ensure big enough via a guess! unsigned char *aDbufPtr = &buffer[0]; int height_copy; // eax@1 // unsigned short int *srcPtr; // ebp@1 int control_byte; // esi@1 int dstIndex; // edx@2 unsigned char *dstPtr; // edi@2 int count; // ebx@3 unsigned char blackBytes; // al@8 unsigned int srcByte; // edx@8 int bytesToWrite; // ebx@8 int control_byte_sub6; // esi@8 int i; // ecx@9 unsigned char *dstBlackBytesPtr; // edi@9 unsigned int doubleBBytes; // ecx@9 int byteCount; // ecx@18 char dstByte; // al@23 int v18; // [sp+8h] [bp-14h]@1 int v19; // [sp+8h] [bp-14h]@8 int width; // [sp+10h] [bp-Ch]@1 int height; // [sp+14h] [bp-8h]@2 unsigned char bytes; // [sp+20h] [bp+4h]@17 control_byte = 0; width = ReadUint16(stream); v18 = 0; height_copy = ReadUint16(stream); if (height_copy > 0) { dstIndex = (int)aDbufPtr; dstPtr = aDbufPtr; height = height_copy; do { count = 0; while (count < width) { if (control_byte) { if (control_byte == 0xE) { control_byte = 0x1Eu; dstIndex |= ReadUint16(stream) << 14; } } else { dstIndex = ReadUint32(stream); control_byte = 0x20u; } blackBytes = dstIndex & 0x3F; control_byte_sub6 = control_byte - 6; srcByte = (unsigned int)dstIndex >> 6; v19 = v18 - 1; bytesToWrite = blackBytes + count; if ((signed int)blackBytes > 0) { doubleBBytes = (unsigned int)blackBytes >> 2; memset(dstPtr, 0, 4 * doubleBBytes); dstBlackBytesPtr = &dstPtr[4 * doubleBBytes]; for (i = blackBytes & 3; i; --i) *dstBlackBytesPtr++ = 0; dstPtr = &aDbufPtr[blackBytes]; aDbufPtr += blackBytes; } if (control_byte_sub6) { if (control_byte_sub6 == 0xE) { control_byte_sub6 = 0x1Eu; srcByte |= ReadUint16(stream) << 14; } } else { srcByte = ReadUint32(stream); control_byte_sub6 = 0x20u; } control_byte = control_byte_sub6 - 6; bytes = srcByte & 0x3F; dstIndex = srcByte >> 6; v18 = v19 - 1; count = bytes + bytesToWrite; if ((signed int)bytes > 0) { byteCount = bytes; v18 -= bytes; do { if (control_byte) { if (control_byte == 0xE) { control_byte = 0x1Eu; dstIndex |= ReadUint16(stream) << 14; } } else { dstIndex = ReadUint32(stream); control_byte = 0x20u; } control_byte -= 6; dstByte = dstIndex & 0x3F; dstIndex = (unsigned int)dstIndex >> 6; *dstPtr++ = dstByte; --byteCount; } while (byteCount); aDbufPtr = dstPtr; } } if (count & 3) { do { ++dstPtr; ++count; } while (count & 3); aDbufPtr = dstPtr; } height_copy = height - 1; } while (height-- != 1); } return buffer; } } <|endoftext|>
<commit_before>/* Copyright (c) 2015, Project OSRM contributors 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. */ #ifndef TRIP_FARTHEST_INSERTION_HPP #define TRIP_FARTHEST_INSERTION_HPP #include "../data_structures/search_engine.hpp" #include "../util/dist_table_wrapper.hpp" #include <osrm/json_container.hpp> #include <boost/assert.hpp> #include <cstdlib> #include <algorithm> #include <string> #include <vector> #include <limits> namespace osrm { namespace trip { // given a route and a new location, find the best place of insertion and // check the distance of roundtrip when the new location is additionally visited using NodeIDIter = std::vector<NodeID>::iterator; std::pair<EdgeWeight, NodeIDIter> GetShortestRoundTrip(const NodeID new_loc, const DistTableWrapper<EdgeWeight> &dist_table, const std::size_t number_of_locations, std::vector<NodeID> &route) { (void)number_of_locations; // unused auto min_trip_distance = INVALID_EDGE_WEIGHT; NodeIDIter next_insert_point_candidate; // for all nodes in the current trip find the best insertion resulting in the shortest path // assert min 2 nodes in route const auto start = std::begin(route); const auto end = std::end(route); for (auto from_node = start; from_node != end; ++from_node) { auto to_node = std::next(from_node); if (to_node == end) { to_node = start; } const auto dist_from = dist_table(*from_node, new_loc); const auto dist_to = dist_table(new_loc, *to_node); const auto trip_dist = dist_from + dist_to - dist_table(*from_node, *to_node); BOOST_ASSERT_MSG(dist_from != INVALID_EDGE_WEIGHT, "distance has invalid edge weight"); BOOST_ASSERT_MSG(dist_to != INVALID_EDGE_WEIGHT, "distance has invalid edge weight"); // This is not neccessarily true: // Lets say you have an edge (u, v) with duration 100. If you place a coordinate exactly in // the middle of the segment yielding (u, v'), the adjusted duration will be 100 * 0.5 = 50. // Now imagine two coordinates. One placed at 0.99 and one at 0.999. This means (u, v') now // has a duration of 100 * 0.99 = 99, but (u, v'') also has a duration of 100 * 0.995 = 99. // In which case (v', v'') has a duration of 0. // BOOST_ASSERT_MSG(trip_dist >= 0, "previous trip was not minimal. something's wrong"); // from all possible insertions to the current trip, choose the shortest of all insertions if (trip_dist < min_trip_distance) { min_trip_distance = trip_dist; next_insert_point_candidate = to_node; } } BOOST_ASSERT_MSG(min_trip_distance != INVALID_EDGE_WEIGHT, "trip has invalid edge weight"); return std::make_pair(min_trip_distance, next_insert_point_candidate); } template <typename NodeIDIterator> // given two initial start nodes, find a roundtrip route using the farthest insertion algorithm std::vector<NodeID> FindRoute(const std::size_t &number_of_locations, const std::size_t &component_size, const NodeIDIterator &start, const NodeIDIterator &end, const DistTableWrapper<EdgeWeight> &dist_table, const NodeID &start1, const NodeID &start2) { BOOST_ASSERT_MSG(number_of_locations >= component_size, "component size bigger than total number of locations"); std::vector<NodeID> route; route.reserve(number_of_locations); // tracks which nodes have been already visited std::vector<bool> visited(number_of_locations, false); visited[start1] = true; visited[start2] = true; route.push_back(start1); route.push_back(start2); // add all other nodes missing (two nodes are already in the initial start trip) for (std::size_t j = 2; j < component_size; ++j) { auto farthest_distance = 0; auto next_node = -1; NodeIDIter next_insert_point; // find unvisited loc i that is the farthest away from all other visited locs for (auto i = start; i != end; ++i) { // find the shortest distance from i to all visited nodes if (!visited[*i]) { const auto insert_candidate = GetShortestRoundTrip(*i, dist_table, number_of_locations, route); BOOST_ASSERT_MSG(insert_candidate.first != INVALID_EDGE_WEIGHT, "shortest round trip is invalid"); // add the location to the current trip such that it results in the shortest total // tour if (insert_candidate.first >= farthest_distance) { farthest_distance = insert_candidate.first; next_node = *i; next_insert_point = insert_candidate.second; } } } BOOST_ASSERT_MSG(next_node >= 0, "next node to visit is invalid"); // mark as visited and insert node visited[next_node] = true; route.insert(next_insert_point, next_node); } return route; } template <typename NodeIDIterator> std::vector<NodeID> FarthestInsertionTrip(const NodeIDIterator &start, const NodeIDIterator &end, const std::size_t number_of_locations, const DistTableWrapper<EdgeWeight> &dist_table) { ////////////////////////////////////////////////////////////////////////////////////////////////// // START FARTHEST INSERTION HERE // 1. start at a random round trip of 2 locations // 2. find the location that is the farthest away from the visited locations and whose insertion // will make the round trip the longest // 3. add the found location to the current round trip such that round trip is the shortest // 4. repeat 2-3 until all locations are visited // 5. DONE! ////////////////////////////////////////////////////////////////////////////////////////////////// const auto component_size = std::distance(start, end); BOOST_ASSERT(component_size >= 0); auto max_from = -1; auto max_to = -1; if (static_cast<std::size_t>(component_size) == number_of_locations) { // find the pair of location with the biggest distance and make the pair the initial start // trip const auto index = std::distance( std::begin(dist_table), std::max_element(std::begin(dist_table), std::end(dist_table))); max_from = index / number_of_locations; max_to = index % number_of_locations; } else { auto max_dist = 0; for (auto x = start; x != end; ++x) { for (auto y = start; y != end; ++y) { const auto xy_dist = dist_table(*x, *y); if (xy_dist > max_dist) { max_dist = xy_dist; max_from = *x; max_to = *y; } } } } BOOST_ASSERT(max_from >= 0); BOOST_ASSERT(max_to >= 0); BOOST_ASSERT_MSG(static_cast<std::size_t>(max_from) < number_of_locations, "start node"); BOOST_ASSERT_MSG(static_cast<std::size_t>(max_to) < number_of_locations, "start node"); return FindRoute(number_of_locations, component_size, start, end, dist_table, max_from, max_to); } } // end namespace trip } // end namespace osrm #endif // TRIP_FARTHEST_INSERTION_HPP <commit_msg>Correctly initialize the min value<commit_after>/* Copyright (c) 2015, Project OSRM contributors 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. */ #ifndef TRIP_FARTHEST_INSERTION_HPP #define TRIP_FARTHEST_INSERTION_HPP #include "../data_structures/search_engine.hpp" #include "../util/dist_table_wrapper.hpp" #include <osrm/json_container.hpp> #include <boost/assert.hpp> #include <cstdlib> #include <algorithm> #include <string> #include <vector> #include <limits> namespace osrm { namespace trip { // given a route and a new location, find the best place of insertion and // check the distance of roundtrip when the new location is additionally visited using NodeIDIter = std::vector<NodeID>::iterator; std::pair<EdgeWeight, NodeIDIter> GetShortestRoundTrip(const NodeID new_loc, const DistTableWrapper<EdgeWeight> &dist_table, const std::size_t number_of_locations, std::vector<NodeID> &route) { (void)number_of_locations; // unused auto min_trip_distance = INVALID_EDGE_WEIGHT; NodeIDIter next_insert_point_candidate; // for all nodes in the current trip find the best insertion resulting in the shortest path // assert min 2 nodes in route const auto start = std::begin(route); const auto end = std::end(route); for (auto from_node = start; from_node != end; ++from_node) { auto to_node = std::next(from_node); if (to_node == end) { to_node = start; } const auto dist_from = dist_table(*from_node, new_loc); const auto dist_to = dist_table(new_loc, *to_node); const auto trip_dist = dist_from + dist_to - dist_table(*from_node, *to_node); BOOST_ASSERT_MSG(dist_from != INVALID_EDGE_WEIGHT, "distance has invalid edge weight"); BOOST_ASSERT_MSG(dist_to != INVALID_EDGE_WEIGHT, "distance has invalid edge weight"); // This is not neccessarily true: // Lets say you have an edge (u, v) with duration 100. If you place a coordinate exactly in // the middle of the segment yielding (u, v'), the adjusted duration will be 100 * 0.5 = 50. // Now imagine two coordinates. One placed at 0.99 and one at 0.999. This means (u, v') now // has a duration of 100 * 0.99 = 99, but (u, v'') also has a duration of 100 * 0.995 = 99. // In which case (v', v'') has a duration of 0. // BOOST_ASSERT_MSG(trip_dist >= 0, "previous trip was not minimal. something's wrong"); // from all possible insertions to the current trip, choose the shortest of all insertions if (trip_dist < min_trip_distance) { min_trip_distance = trip_dist; next_insert_point_candidate = to_node; } } BOOST_ASSERT_MSG(min_trip_distance != INVALID_EDGE_WEIGHT, "trip has invalid edge weight"); return std::make_pair(min_trip_distance, next_insert_point_candidate); } template <typename NodeIDIterator> // given two initial start nodes, find a roundtrip route using the farthest insertion algorithm std::vector<NodeID> FindRoute(const std::size_t &number_of_locations, const std::size_t &component_size, const NodeIDIterator &start, const NodeIDIterator &end, const DistTableWrapper<EdgeWeight> &dist_table, const NodeID &start1, const NodeID &start2) { BOOST_ASSERT_MSG(number_of_locations >= component_size, "component size bigger than total number of locations"); std::vector<NodeID> route; route.reserve(number_of_locations); // tracks which nodes have been already visited std::vector<bool> visited(number_of_locations, false); visited[start1] = true; visited[start2] = true; route.push_back(start1); route.push_back(start2); // add all other nodes missing (two nodes are already in the initial start trip) for (std::size_t j = 2; j < component_size; ++j) { auto farthest_distance = -std::numeric_limits<int>::max(); auto next_node = -1; NodeIDIter next_insert_point; // find unvisited loc i that is the farthest away from all other visited locs for (auto i = start; i != end; ++i) { // find the shortest distance from i to all visited nodes if (!visited[*i]) { const auto insert_candidate = GetShortestRoundTrip(*i, dist_table, number_of_locations, route); BOOST_ASSERT_MSG(insert_candidate.first != INVALID_EDGE_WEIGHT, "shortest round trip is invalid"); // add the location to the current trip such that it results in the shortest total // tour if (insert_candidate.first >= farthest_distance) { farthest_distance = insert_candidate.first; next_node = *i; next_insert_point = insert_candidate.second; } } } BOOST_ASSERT_MSG(next_node >= 0, "next node to visit is invalid"); // mark as visited and insert node visited[next_node] = true; route.insert(next_insert_point, next_node); } return route; } template <typename NodeIDIterator> std::vector<NodeID> FarthestInsertionTrip(const NodeIDIterator &start, const NodeIDIterator &end, const std::size_t number_of_locations, const DistTableWrapper<EdgeWeight> &dist_table) { ////////////////////////////////////////////////////////////////////////////////////////////////// // START FARTHEST INSERTION HERE // 1. start at a random round trip of 2 locations // 2. find the location that is the farthest away from the visited locations and whose insertion // will make the round trip the longest // 3. add the found location to the current round trip such that round trip is the shortest // 4. repeat 2-3 until all locations are visited // 5. DONE! ////////////////////////////////////////////////////////////////////////////////////////////////// const auto component_size = std::distance(start, end); BOOST_ASSERT(component_size >= 0); auto max_from = -1; auto max_to = -1; if (static_cast<std::size_t>(component_size) == number_of_locations) { // find the pair of location with the biggest distance and make the pair the initial start // trip const auto index = std::distance( std::begin(dist_table), std::max_element(std::begin(dist_table), std::end(dist_table))); max_from = index / number_of_locations; max_to = index % number_of_locations; } else { auto max_dist = 0; for (auto x = start; x != end; ++x) { for (auto y = start; y != end; ++y) { const auto xy_dist = dist_table(*x, *y); if (xy_dist > max_dist) { max_dist = xy_dist; max_from = *x; max_to = *y; } } } } BOOST_ASSERT(max_from >= 0); BOOST_ASSERT(max_to >= 0); BOOST_ASSERT_MSG(static_cast<std::size_t>(max_from) < number_of_locations, "start node"); BOOST_ASSERT_MSG(static_cast<std::size_t>(max_to) < number_of_locations, "start node"); return FindRoute(number_of_locations, component_size, start, end, dist_table, max_from, max_to); } } // end namespace trip } // end namespace osrm #endif // TRIP_FARTHEST_INSERTION_HPP <|endoftext|>
<commit_before>#include "ofApp.h" void ofApp::setup(){ ofSetVerticalSync(false); ofSetFrameRate(60); // Create 3 particle emitters emitters = {ParticleEmitter(), ParticleEmitter(), ParticleEmitter()}; // Setup the particle emitters for(auto& e : emitters){ e.setup(); } // Setup the curl noise, pass the emitter and // the number of particles we want curlNoise.setup(emitters, 1024*256); curlNoise.setTurbulence(0.3); renderShader.load("shaders/render_vert.glsl", "shaders/render_frag.glsl"); // Add 'lifespan' and 'emitterId' attributes to the particle vbo // (see the shaders for how to use these) curlNoise.setAttributes(renderShader); // Setup GUI parameters.add(curlNoise.parameters); for(auto& e : emitters){ parameters.add(e.parameters); } gui.setup(parameters); gui.add(fps.setup("Fps:", "")); gui.minimizeAll(); } void ofApp::update(){ fps = ofToString(ofGetFrameRate()); // Update emitters' positions for(uint i = 0; i < emitters.size(); ++i){ updateEmitter(i); } // Update curl noise curlNoise.update(); } void ofApp::updateEmitter(int i){ float t = ofGetElapsedTimef(); float r = 150.0; float theta = t + 4*M_PI*i/float(emitters.size()); float x = r*cos(theta) + r/2.0*cos(2*M_PI*i/float(emitters.size())); float y = r*sin(theta) + r/2.0*sin(2*M_PI*i/float(emitters.size())); emitters[i].update(x, y, z); } void ofApp::draw(){ ofBackground(ofColor::lightGrey); ofEnableAlphaBlending(); cam.begin(); // Draw particles renderShader.begin(); curlNoise.draw(); renderShader.end(); cam.end(); // Draw GUI gui.draw(); } <commit_msg>Fix bug<commit_after>#include "ofApp.h" void ofApp::setup(){ ofSetVerticalSync(false); ofSetFrameRate(60); // Create 3 particle emitters emitters = {ParticleEmitter(), ParticleEmitter(), ParticleEmitter()}; // Setup the particle emitters for(auto& e : emitters){ e.setup(); } // Setup the curl noise, pass the emitter and // the number of particles we want curlNoise.setup(emitters, 1024*256); curlNoise.setTurbulence(0.3); renderShader.load("shaders/render_vert.glsl", "shaders/render_frag.glsl"); // Add 'lifespan' and 'emitterId' attributes to the particle vbo // (see the shaders for how to use these) curlNoise.setAttributes(renderShader); // Setup GUI parameters.add(curlNoise.parameters); for(auto& e : emitters){ parameters.add(e.parameters); } gui.setup(parameters); gui.add(fps.setup("Fps:", "")); gui.minimizeAll(); } void ofApp::update(){ fps = ofToString(ofGetFrameRate()); // Update emitters' positions for(uint i = 0; i < emitters.size(); ++i){ updateEmitter(i); } // Update curl noise curlNoise.update(); } void ofApp::updateEmitter(int i){ float t = ofGetElapsedTimef(); float r = 150.0; float theta = t + 4*M_PI*i/float(emitters.size()); float x = r*cos(theta) + r/2.0*cos(2*M_PI*i/float(emitters.size())); float y = r*sin(theta) + r/2.0*sin(2*M_PI*i/float(emitters.size())); emitters[i].update(x, y, 0); } void ofApp::draw(){ ofBackground(ofColor::lightGrey); ofEnableAlphaBlending(); cam.begin(); // Draw particles renderShader.begin(); curlNoise.draw(); renderShader.end(); cam.end(); // Draw GUI gui.draw(); } <|endoftext|>
<commit_before>#include <iostream> #include <vw/Image/ImageMath.h> #include <vw/Image/UtilityViews.h> #include <vw/Plate/PlateFile.h> #include <vw/Image/MaskViews.h> #include <mvp/Config.h> #include <mvp/MVPWorkspace.h> #include <mvp/MVPJob.h> #include <boost/program_options.hpp> using namespace vw; using namespace vw::cartography; using namespace vw::platefile; using namespace std; using namespace mvp; namespace po = boost::program_options; template <class BBoxT, class RealT, size_t DimN> void print_bbox_helper(math::BBoxBase<BBoxT, RealT, DimN> const& bbox) { cout << "BBox = " << bbox << endl; cout << "width, height = " << bbox.width() << ", " << bbox.height() << endl; } int main(int argc, char* argv[]) { #if MVP_ENABLE_OCTAVE_SUPPORT MVPJobOctave::start_interpreter(); #endif po::options_description cmd_opts("Command line options"); cmd_opts.add_options() ("help,h", "Print this message") ("silent", "Run without outputting status") ("config-file,f", po::value<string>()->default_value("mvp.conf"), "Specify a pipeline configuration file") ("print-workspace,p", "Print information about the workspace and exit") ("dump-job", "Dump a jobfile") ("col,c", po::value<int>(), "When dumping a jobfile, column of tile to dump") ("row,r", po::value<int>(), "When dumping a jobfile, row of tile to dump") ("level,l", po::value<int>(), "When dumping a jobfile or printing the workspace, level to operate at") ; po::options_description render_opts("Render Options"); render_opts.add_options() ("col-start", po::value<int>(), "Col to start rendering at") ("col-end", po::value<int>(), "One past last col to render") ("row-start", po::value<int>(), "Row to start rendering at") ("row-end", po::value<int>(), "One past last row to render") ("render-level", po::value<int>(), "Level to render at") ; po::options_description mvp_opts; mvp_opts.add(MVPWorkspace::program_options()).add(render_opts); po::options_description all_opts; all_opts.add(cmd_opts).add(mvp_opts); po::variables_map vm; store(po::command_line_parser(argc, argv).options(all_opts).run(), vm); if (vm.count("help")) { cout << all_opts << endl; return 0; } ifstream ifs(vm["config-file"].as<string>().c_str()); if (ifs) { store(parse_config_file(ifs, mvp_opts), vm); } notify(vm); MVPWorkspace work(MVPWorkspace::construct_from_program_options(vm)); if (!vm.count("silent")) { cout << boolalpha << endl; cout << "-------------------------------------" << endl; cout << "Welcome to the Multiple View Pipeline" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Number of images loaded = " << work.num_images() << endl; cout << " Equal resolution level = " << work.equal_resolution_level() << endl; cout << " Equal density level = " << work.equal_density_level() << endl; cout << endl; cout << "# Workspace lonlat BBox #" << endl; print_bbox_helper(work.lonlat_work_area()); cout << endl; cout << "# Workspace tile BBox (@ equal density level) #" << endl; print_bbox_helper(work.tile_work_area(work.equal_density_level())); if (vm.count("level")) { int print_level = vm["level"].as<int>(); cout << endl; cout << "# Workspace tile BBox (@ level " << print_level << ") #" << endl; print_bbox_helper(work.tile_work_area(print_level)); } cout << endl; } if (vm.count("print-workspace")) { return 0; } int render_level = work.equal_density_level(); if (vm.count("render-level")) { render_level = vm["render-level"].as<int>(); } BBox2i tile_bbox(work.tile_work_area(render_level)); if (vm.count("col-start")) { VW_ASSERT(vm.count("col-end"), ArgumentErr() << "col-start specified, but col-end not"); tile_bbox.min()[0] = vm["col-start"].as<int>(); tile_bbox.max()[0] = vm["col-end"].as<int>(); } if (vm.count("row-start")) { VW_ASSERT(vm.count("row-end"), ArgumentErr() << "row-start specified, but col-end not"); tile_bbox.min()[1] = vm["row-start"].as<int>(); tile_bbox.max()[1] = vm["row-end"].as<int>(); } if (!vm.count("silent")) { cout << "-------------------------------------" << endl; cout << " Rendering Information" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Render level = " << render_level << endl; cout << " Use octave = " << vm["use-octave"].as<bool>() << endl; cout << endl; cout << "# Render tile BBox #" << endl; print_bbox_helper(tile_bbox); cout << endl; cout << "-------------------------------------" << endl; cout << " Status" << endl; cout << "-------------------------------------" << endl; cout << endl; } boost::shared_ptr<PlateFile> pf(new PlateFile(work.result_platefile(), work.plate_georef().map_proj(), "MVP Result Plate", work.plate_georef().tile_size(), "tif", VW_PIXEL_GRAYA, VW_CHANNEL_FLOAT32)); Transaction tid = pf->transaction_request("Post Heights", -1); int curr_tile = 0; int num_tiles = tile_bbox.width() * tile_bbox.height(); float32 plate_min_val = numeric_limits<float32>::max(), plate_max_val = numeric_limits<float32>::min(); for (int col = tile_bbox.min().x(); col < tile_bbox.max().x(); col++) { for (int row = tile_bbox.min().y(); row < tile_bbox.max().y(); row++) { boost::shared_ptr<ProgressCallback> progress; if (!vm.count("silent")) { ostringstream status; status << "Tile: " << ++curr_tile << "/" << num_tiles << " Location: [" << col << ", " << row << "] @" << render_level << " "; progress.reset(new TerminalProgressCallback("mvp", status.str())); } else { progress.reset(new ProgressCallback); } MVPTileResult result = mvpjob_process_tile(work.assemble_job(col, row, render_level), *progress); ImageView<PixelGrayA<float32> > rendered_tile = mask_to_alpha(pixel_cast<PixelMask<PixelGray<float32> > >(result.post_height)); float32 tile_min_val, tile_max_val; min_max_channel_values(result.post_height, tile_min_val, tile_max_val); plate_min_val = min(plate_min_val, tile_min_val); plate_max_val = max(plate_max_val, tile_max_val); pf->write_request(); pf->write_update(rendered_tile, col, row, render_level, tid); pf->sync(); pf->write_complete(); } } // This way that tile is easy to find... for (int level = 2; level < render_level; level++) { int divisor = render_level - level; for (int col = tile_bbox.min().x() >> divisor; col <= tile_bbox.max().x() >> divisor; col++) { for (int row = tile_bbox.min().y() >> divisor; row <= tile_bbox.max().y() >> divisor; row++) { ImageView<PixelGrayA<float32> > rendered_tile(constant_view(PixelGrayA<float32>(), work.plate_georef().tile_size(), work.plate_georef().tile_size())); pf->write_request(); pf->write_update(rendered_tile, col, row, level, tid); pf->sync(); pf->write_complete(); } } } if (!vm.count("silent")) { cout << "Plate (min, max): (" << plate_min_val << ", " << plate_max_val << ")" << endl; cout << endl; } return 0; } <commit_msg>catch exception thrown when there are no valid samples<commit_after>#include <iostream> #include <vw/Image/ImageMath.h> #include <vw/Image/UtilityViews.h> #include <vw/Plate/PlateFile.h> #include <vw/Image/MaskViews.h> #include <mvp/Config.h> #include <mvp/MVPWorkspace.h> #include <mvp/MVPJob.h> #include <boost/program_options.hpp> using namespace vw; using namespace vw::cartography; using namespace vw::platefile; using namespace std; using namespace mvp; namespace po = boost::program_options; template <class BBoxT, class RealT, size_t DimN> void print_bbox_helper(math::BBoxBase<BBoxT, RealT, DimN> const& bbox) { cout << "BBox = " << bbox << endl; cout << "width, height = " << bbox.width() << ", " << bbox.height() << endl; } int main(int argc, char* argv[]) { #if MVP_ENABLE_OCTAVE_SUPPORT MVPJobOctave::start_interpreter(); #endif po::options_description cmd_opts("Command line options"); cmd_opts.add_options() ("help,h", "Print this message") ("silent", "Run without outputting status") ("config-file,f", po::value<string>()->default_value("mvp.conf"), "Specify a pipeline configuration file") ("print-workspace,p", "Print information about the workspace and exit") ("dump-job", "Dump a jobfile") ("col,c", po::value<int>(), "When dumping a jobfile, column of tile to dump") ("row,r", po::value<int>(), "When dumping a jobfile, row of tile to dump") ("level,l", po::value<int>(), "When dumping a jobfile or printing the workspace, level to operate at") ; po::options_description render_opts("Render Options"); render_opts.add_options() ("col-start", po::value<int>(), "Col to start rendering at") ("col-end", po::value<int>(), "One past last col to render") ("row-start", po::value<int>(), "Row to start rendering at") ("row-end", po::value<int>(), "One past last row to render") ("render-level", po::value<int>(), "Level to render at") ; po::options_description mvp_opts; mvp_opts.add(MVPWorkspace::program_options()).add(render_opts); po::options_description all_opts; all_opts.add(cmd_opts).add(mvp_opts); po::variables_map vm; store(po::command_line_parser(argc, argv).options(all_opts).run(), vm); if (vm.count("help")) { cout << all_opts << endl; return 0; } ifstream ifs(vm["config-file"].as<string>().c_str()); if (ifs) { store(parse_config_file(ifs, mvp_opts), vm); } notify(vm); MVPWorkspace work(MVPWorkspace::construct_from_program_options(vm)); if (!vm.count("silent")) { cout << boolalpha << endl; cout << "-------------------------------------" << endl; cout << "Welcome to the Multiple View Pipeline" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Number of images loaded = " << work.num_images() << endl; cout << " Equal resolution level = " << work.equal_resolution_level() << endl; cout << " Equal density level = " << work.equal_density_level() << endl; cout << endl; cout << "# Workspace lonlat BBox #" << endl; print_bbox_helper(work.lonlat_work_area()); cout << endl; cout << "# Workspace tile BBox (@ equal density level) #" << endl; print_bbox_helper(work.tile_work_area(work.equal_density_level())); if (vm.count("level")) { int print_level = vm["level"].as<int>(); cout << endl; cout << "# Workspace tile BBox (@ level " << print_level << ") #" << endl; print_bbox_helper(work.tile_work_area(print_level)); } cout << endl; } if (vm.count("print-workspace")) { return 0; } int render_level = work.equal_density_level(); if (vm.count("render-level")) { render_level = vm["render-level"].as<int>(); } BBox2i tile_bbox(work.tile_work_area(render_level)); if (vm.count("col-start")) { VW_ASSERT(vm.count("col-end"), ArgumentErr() << "col-start specified, but col-end not"); tile_bbox.min()[0] = vm["col-start"].as<int>(); tile_bbox.max()[0] = vm["col-end"].as<int>(); } if (vm.count("row-start")) { VW_ASSERT(vm.count("row-end"), ArgumentErr() << "row-start specified, but col-end not"); tile_bbox.min()[1] = vm["row-start"].as<int>(); tile_bbox.max()[1] = vm["row-end"].as<int>(); } if (!vm.count("silent")) { cout << "-------------------------------------" << endl; cout << " Rendering Information" << endl; cout << "-------------------------------------" << endl; cout << endl; cout << "Render level = " << render_level << endl; cout << " Use octave = " << vm["use-octave"].as<bool>() << endl; cout << endl; cout << "# Render tile BBox #" << endl; print_bbox_helper(tile_bbox); cout << endl; cout << "-------------------------------------" << endl; cout << " Status" << endl; cout << "-------------------------------------" << endl; cout << endl; } boost::shared_ptr<PlateFile> pf(new PlateFile(work.result_platefile(), work.plate_georef().map_proj(), "MVP Result Plate", work.plate_georef().tile_size(), "tif", VW_PIXEL_GRAYA, VW_CHANNEL_FLOAT32)); Transaction tid = pf->transaction_request("Post Heights", -1); int curr_tile = 0; int num_tiles = tile_bbox.width() * tile_bbox.height(); float32 plate_min_val = numeric_limits<float32>::max(), plate_max_val = numeric_limits<float32>::min(); for (int col = tile_bbox.min().x(); col < tile_bbox.max().x(); col++) { for (int row = tile_bbox.min().y(); row < tile_bbox.max().y(); row++) { boost::shared_ptr<ProgressCallback> progress; if (!vm.count("silent")) { ostringstream status; status << "Tile: " << ++curr_tile << "/" << num_tiles << " Location: [" << col << ", " << row << "] @" << render_level << " "; progress.reset(new TerminalProgressCallback("mvp", status.str())); } else { progress.reset(new ProgressCallback); } MVPTileResult result = mvpjob_process_tile(work.assemble_job(col, row, render_level), *progress); ImageView<PixelGrayA<float32> > rendered_tile = mask_to_alpha(pixel_cast<PixelMask<PixelGray<float32> > >(result.post_height)); float32 tile_min_val, tile_max_val; try { min_max_channel_values(result.post_height, tile_min_val, tile_max_val); } catch (ArgumentErr& e) { tile_min_val = numeric_limits<float32>::max(); tile_max_val = numeric_limits<float32>::min(); } plate_min_val = min(plate_min_val, tile_min_val); plate_max_val = max(plate_max_val, tile_max_val); pf->write_request(); pf->write_update(rendered_tile, col, row, render_level, tid); pf->sync(); pf->write_complete(); } } // This way that tile is easy to find... for (int level = 2; level < render_level; level++) { int divisor = render_level - level; for (int col = tile_bbox.min().x() >> divisor; col <= tile_bbox.max().x() >> divisor; col++) { for (int row = tile_bbox.min().y() >> divisor; row <= tile_bbox.max().y() >> divisor; row++) { ImageView<PixelGrayA<float32> > rendered_tile(constant_view(PixelGrayA<float32>(), work.plate_georef().tile_size(), work.plate_georef().tile_size())); pf->write_request(); pf->write_update(rendered_tile, col, row, level, tid); pf->sync(); pf->write_complete(); } } } if (!vm.count("silent")) { cout << "Plate (min, max): (" << plate_min_val << ", " << plate_max_val << ")" << endl; cout << endl; } return 0; } <|endoftext|>
<commit_before>#include "native.h" #include "vmstate.h" #include "verifier.h" #include "rtlibrary.h" #include "function.h" #include <iostream> #include <math.h> #include <string.h> extern VMState vmState; void NativeLibrary::print(int x) { std::cout << x; } void NativeLibrary::print(float x) { std::cout << x; } void NativeLibrary::print(bool x) { if (x) { std::cout << "true"; } else { std::cout << "false"; } } void NativeLibrary::print(char x) { std::cout << x; } void NativeLibrary::println(int x) { std::cout << x << std::endl; } void NativeLibrary::println(float x) { std::cout << x << std::endl; } void NativeLibrary::println(bool x) { print(x); std::cout << std::endl; } void NativeLibrary::println(char x) { std::cout << x << std::endl; } void NativeLibrary::println(RawArrayRef objRef) { if (objRef != nullptr) { ArrayRef<char> arrayRef(objRef); for (int i = 0; i < arrayRef.length(); i++) { std::cout << arrayRef.getElement(i); } std::cout << std::endl; } else { Runtime::nullReferenceError(); } } int NativeLibrary::abs(int x) { if (x < 0) { return -x; } else { return x; } } StringRef::StringRef(RawClassRef stringRef) { auto charsField = (char**)(stringRef + sCharsFieldOffset); ArrayRef<char> charsArray((unsigned char*)(*charsField)); mChars = charsArray.elementsPtr(); mLength = charsArray.length(); } void StringRef::setCharsField(RawClassRef stringRef, char* value) { *(char**)(stringRef + sCharsFieldOffset) = value; } //Returns the char at the given index char StringRef::charAt(int index) { return mChars[index]; } //Returns the length of the string int StringRef::length() const { return mLength; } std::size_t StringRef::sCharsFieldOffset; void StringRef::initialize(VMState& vmState) { auto& classMetadata = vmState.classProvider().getMetadata("std.String"); sCharsFieldOffset = classMetadata.fields().at("chars").offset(); } bool NativeLibrary::stringEquals(RawClassRef str1, RawClassRef str2) { if (str1 == nullptr || str2 == nullptr) { return false; } if (str1 == str2) { return true; } //Get references to the instances StringRef str1Ref(str1); StringRef str2Ref(str2); if (str1Ref.length() != str2Ref.length()) { return false; } for (int i = 0; i < str1Ref.length(); i++) { if (str1Ref.charAt(i) != str2Ref.charAt(i)) { return false; } } return true; } void NativeLibrary::add(VMState& vmState) { auto intType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Integer)); auto floatType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Float)); auto charType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Char)); auto boolType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Bool)); auto voidType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Void)); auto charArrayType = vmState.typeProvider().makeType(TypeSystem::arrayTypeName(charType)); auto& binder = vmState.binder(); //Print void(*printInt)(int) = &NativeLibrary::print; void(*printFloat)(float) = &NativeLibrary::print; void(*printBool)(bool) = &NativeLibrary::print; void(*printChar)(char) = &NativeLibrary::print; void(*printlnInt)(int) = &NativeLibrary::println; void(*printlnFloat)(float) = &NativeLibrary::println; void(*printlnBool)(bool) = &NativeLibrary::println; void(*printlnChar)(char) = &NativeLibrary::println; void(*printlnCharArray)(RawArrayRef) = &NativeLibrary::println; //IO binder.define(FunctionDefinition("std.print", { intType }, voidType, (unsigned char*)(printInt))); binder.define(FunctionDefinition("std.print", { floatType }, voidType, (unsigned char*)(printFloat))); binder.define(FunctionDefinition("std.print", { boolType }, voidType, (unsigned char*)(printBool))); binder.define(FunctionDefinition("std.printchar", { charType }, voidType, (unsigned char*)(printChar))); binder.define(FunctionDefinition("std.println", { intType }, voidType, (unsigned char*)(printlnInt))); binder.define(FunctionDefinition("std.println", { floatType }, voidType, (unsigned char*)(printlnFloat))); binder.define(FunctionDefinition("std.println", { boolType }, voidType, (unsigned char*)(printlnBool))); binder.define(FunctionDefinition("std.println", { charType }, voidType, (unsigned char*)(printlnChar))); binder.define(FunctionDefinition("std.println", { charArrayType }, voidType, (unsigned char*)(printlnCharArray))); //Math binder.define(FunctionDefinition("std.math.abs", { intType }, intType, (unsigned char*)(&abs))); binder.define(FunctionDefinition("std.math.sqrt", { floatType }, floatType, (unsigned char*)(&sqrtf))); binder.define(FunctionDefinition("std.math.sin", { floatType }, floatType, (unsigned char*)(&sinf))); binder.define(FunctionDefinition("std.math.cos", { floatType }, floatType, (unsigned char*)(&cosf))); //String auto stringType = vmState.typeProvider().makeType(TypeSystem::stringTypeName); if (stringType != nullptr) { StringRef::initialize(vmState); binder.define(FunctionDefinition("std.equals", { stringType, stringType }, boolType, (unsigned char*)(&stringEquals))); } }<commit_msg>Added null checks when creating string references.<commit_after>#include "native.h" #include "vmstate.h" #include "verifier.h" #include "rtlibrary.h" #include "function.h" #include <iostream> #include <math.h> #include <string.h> extern VMState vmState; void NativeLibrary::print(int x) { std::cout << x; } void NativeLibrary::print(float x) { std::cout << x; } void NativeLibrary::print(bool x) { if (x) { std::cout << "true"; } else { std::cout << "false"; } } void NativeLibrary::print(char x) { std::cout << x; } void NativeLibrary::println(int x) { std::cout << x << std::endl; } void NativeLibrary::println(float x) { std::cout << x << std::endl; } void NativeLibrary::println(bool x) { print(x); std::cout << std::endl; } void NativeLibrary::println(char x) { std::cout << x << std::endl; } void NativeLibrary::println(RawArrayRef objRef) { if (objRef != nullptr) { ArrayRef<char> arrayRef(objRef); for (int i = 0; i < arrayRef.length(); i++) { std::cout << arrayRef.getElement(i); } std::cout << std::endl; } else { Runtime::nullReferenceError(); } } int NativeLibrary::abs(int x) { if (x < 0) { return -x; } else { return x; } } StringRef::StringRef(RawClassRef stringRef) { auto charsField = (char**)(stringRef + sCharsFieldOffset); auto chars = *charsField; if (chars == nullptr) { Runtime::nullReferenceError(); } ArrayRef<char> charsArray((unsigned char*)(chars)); mChars = charsArray.elementsPtr(); mLength = charsArray.length(); } void StringRef::setCharsField(RawClassRef stringRef, char* value) { *(char**)(stringRef + sCharsFieldOffset) = value; } //Returns the char at the given index char StringRef::charAt(int index) { return mChars[index]; } //Returns the length of the string int StringRef::length() const { return mLength; } std::size_t StringRef::sCharsFieldOffset; void StringRef::initialize(VMState& vmState) { auto& classMetadata = vmState.classProvider().getMetadata("std.String"); sCharsFieldOffset = classMetadata.fields().at("chars").offset(); } bool NativeLibrary::stringEquals(RawClassRef str1, RawClassRef str2) { if (str1 == nullptr || str2 == nullptr) { return false; } if (str1 == str2) { return true; } //Get references to the instances StringRef str1Ref(str1); StringRef str2Ref(str2); if (str1Ref.length() != str2Ref.length()) { return false; } for (int i = 0; i < str1Ref.length(); i++) { if (str1Ref.charAt(i) != str2Ref.charAt(i)) { return false; } } return true; } void NativeLibrary::add(VMState& vmState) { auto intType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Integer)); auto floatType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Float)); auto charType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Char)); auto boolType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Bool)); auto voidType = vmState.typeProvider().makeType(TypeSystem::toString(PrimitiveTypes::Void)); auto charArrayType = vmState.typeProvider().makeType(TypeSystem::arrayTypeName(charType)); auto& binder = vmState.binder(); //Print void(*printInt)(int) = &NativeLibrary::print; void(*printFloat)(float) = &NativeLibrary::print; void(*printBool)(bool) = &NativeLibrary::print; void(*printChar)(char) = &NativeLibrary::print; void(*printlnInt)(int) = &NativeLibrary::println; void(*printlnFloat)(float) = &NativeLibrary::println; void(*printlnBool)(bool) = &NativeLibrary::println; void(*printlnChar)(char) = &NativeLibrary::println; void(*printlnCharArray)(RawArrayRef) = &NativeLibrary::println; //IO binder.define(FunctionDefinition("std.print", { intType }, voidType, (unsigned char*)(printInt))); binder.define(FunctionDefinition("std.print", { floatType }, voidType, (unsigned char*)(printFloat))); binder.define(FunctionDefinition("std.print", { boolType }, voidType, (unsigned char*)(printBool))); binder.define(FunctionDefinition("std.printchar", { charType }, voidType, (unsigned char*)(printChar))); binder.define(FunctionDefinition("std.println", { intType }, voidType, (unsigned char*)(printlnInt))); binder.define(FunctionDefinition("std.println", { floatType }, voidType, (unsigned char*)(printlnFloat))); binder.define(FunctionDefinition("std.println", { boolType }, voidType, (unsigned char*)(printlnBool))); binder.define(FunctionDefinition("std.println", { charType }, voidType, (unsigned char*)(printlnChar))); binder.define(FunctionDefinition("std.println", { charArrayType }, voidType, (unsigned char*)(printlnCharArray))); //Math binder.define(FunctionDefinition("std.math.abs", { intType }, intType, (unsigned char*)(&abs))); binder.define(FunctionDefinition("std.math.sqrt", { floatType }, floatType, (unsigned char*)(&sqrtf))); binder.define(FunctionDefinition("std.math.sin", { floatType }, floatType, (unsigned char*)(&sinf))); binder.define(FunctionDefinition("std.math.cos", { floatType }, floatType, (unsigned char*)(&cosf))); //String auto stringType = vmState.typeProvider().makeType(TypeSystem::stringTypeName); if (stringType != nullptr) { StringRef::initialize(vmState); binder.define(FunctionDefinition("std.equals", { stringType, stringType }, boolType, (unsigned char*)(&stringEquals))); } }<|endoftext|>
<commit_before>#include "installables.hh" #include "store-api.hh" #include "eval-inline.hh" #include "eval-cache.hh" #include "names.hh" #include "command.hh" #include "derivations.hh" namespace nix { struct InstallableDerivedPath : Installable { ref<Store> store; const DerivedPath derivedPath; InstallableDerivedPath(ref<Store> store, const DerivedPath & derivedPath) : store(store) , derivedPath(derivedPath) { } std::string what() const override { return derivedPath.to_string(*store); } DerivedPaths toDerivedPaths() override { return {derivedPath}; } std::optional<StorePath> getStorePath() override { return std::nullopt; } }; /** * Return the rewrites that are needed to resolve a string whose context is * included in `dependencies`. */ StringPairs resolveRewrites(Store & store, const BuiltPaths dependencies) { StringPairs res; for (auto & dep : dependencies) if (auto drvDep = std::get_if<BuiltPathBuilt>(&dep)) for (auto & [ outputName, outputPath ] : drvDep->outputs) res.emplace( downstreamPlaceholder(store, drvDep->drvPath, outputName), store.printStorePath(outputPath) ); return res; } /** * Resolve the given string assuming the given context. */ std::string resolveString(Store & store, const std::string & toResolve, const BuiltPaths dependencies) { auto rewrites = resolveRewrites(store, dependencies); return rewriteStrings(toResolve, rewrites); } UnresolvedApp Installable::toApp(EvalState & state) { auto cursor = getCursor(state); auto attrPath = cursor->getAttrPath(); auto type = cursor->getAttr("type")->getString(); std::string expected = !attrPath.empty() && state.symbols[attrPath[0]] == "apps" ? "app" : "derivation"; if (type != expected) throw Error("attribute '%s' should have type '%s'", cursor->getAttrPathStr(), expected); if (type == "app") { auto [program, context] = cursor->getAttr("program")->getStringWithContext(); std::vector<StorePathWithOutputs> context2; for (auto & [path, name] : context) context2.push_back({path, {name}}); return UnresolvedApp{App { .context = std::move(context2), .program = program, }}; } else if (type == "derivation") { auto drvPath = cursor->forceDerivation(); auto outPath = cursor->getAttr(state.sOutPath)->getString(); auto outputName = cursor->getAttr(state.sOutputName)->getString(); auto name = cursor->getAttr(state.sName)->getString(); auto aPname = cursor->maybeGetAttr("pname"); auto aMeta = cursor->maybeGetAttr(state.sMeta); auto aMainProgram = aMeta ? aMeta->maybeGetAttr("mainProgram") : nullptr; auto mainProgram = aMainProgram ? aMainProgram->getString() : aPname ? aPname->getString() : DrvName(name).name; auto program = outPath + "/bin/" + mainProgram; return UnresolvedApp { App { .context = { { drvPath, {outputName} } }, .program = program, }}; } else throw Error("attribute '%s' has unsupported type '%s'", cursor->getAttrPathStr(), type); } // FIXME: move to libcmd App UnresolvedApp::resolve(ref<Store> evalStore, ref<Store> store) { auto res = unresolved; std::vector<std::shared_ptr<Installable>> installableContext; for (auto & ctxElt : unresolved.context) installableContext.push_back( std::make_shared<InstallableDerivedPath>(store, ctxElt.toDerivedPath())); auto builtContext = Installable::build(evalStore, store, Realise::Outputs, installableContext); res.program = resolveString(*store, unresolved.program, builtContext); if (!store->isInStore(res.program)) throw Error("app program '%s' is not in the Nix store", res.program); return res; } } <commit_msg>nix run: fix "'defaultApp.x86_64-linux' should have type 'derivation'"<commit_after>#include "installables.hh" #include "store-api.hh" #include "eval-inline.hh" #include "eval-cache.hh" #include "names.hh" #include "command.hh" #include "derivations.hh" namespace nix { struct InstallableDerivedPath : Installable { ref<Store> store; const DerivedPath derivedPath; InstallableDerivedPath(ref<Store> store, const DerivedPath & derivedPath) : store(store) , derivedPath(derivedPath) { } std::string what() const override { return derivedPath.to_string(*store); } DerivedPaths toDerivedPaths() override { return {derivedPath}; } std::optional<StorePath> getStorePath() override { return std::nullopt; } }; /** * Return the rewrites that are needed to resolve a string whose context is * included in `dependencies`. */ StringPairs resolveRewrites(Store & store, const BuiltPaths dependencies) { StringPairs res; for (auto & dep : dependencies) if (auto drvDep = std::get_if<BuiltPathBuilt>(&dep)) for (auto & [ outputName, outputPath ] : drvDep->outputs) res.emplace( downstreamPlaceholder(store, drvDep->drvPath, outputName), store.printStorePath(outputPath) ); return res; } /** * Resolve the given string assuming the given context. */ std::string resolveString(Store & store, const std::string & toResolve, const BuiltPaths dependencies) { auto rewrites = resolveRewrites(store, dependencies); return rewriteStrings(toResolve, rewrites); } UnresolvedApp Installable::toApp(EvalState & state) { auto cursor = getCursor(state); auto attrPath = cursor->getAttrPath(); auto type = cursor->getAttr("type")->getString(); std::string expected = !attrPath.empty() && (state.symbols[attrPath[0]] == "apps" || state.symbols[attrPath[0]] == "defaultApp") ? "app" : "derivation"; if (type != expected) throw Error("attribute '%s' should have type '%s'", cursor->getAttrPathStr(), expected); if (type == "app") { auto [program, context] = cursor->getAttr("program")->getStringWithContext(); std::vector<StorePathWithOutputs> context2; for (auto & [path, name] : context) context2.push_back({path, {name}}); return UnresolvedApp{App { .context = std::move(context2), .program = program, }}; } else if (type == "derivation") { auto drvPath = cursor->forceDerivation(); auto outPath = cursor->getAttr(state.sOutPath)->getString(); auto outputName = cursor->getAttr(state.sOutputName)->getString(); auto name = cursor->getAttr(state.sName)->getString(); auto aPname = cursor->maybeGetAttr("pname"); auto aMeta = cursor->maybeGetAttr(state.sMeta); auto aMainProgram = aMeta ? aMeta->maybeGetAttr("mainProgram") : nullptr; auto mainProgram = aMainProgram ? aMainProgram->getString() : aPname ? aPname->getString() : DrvName(name).name; auto program = outPath + "/bin/" + mainProgram; return UnresolvedApp { App { .context = { { drvPath, {outputName} } }, .program = program, }}; } else throw Error("attribute '%s' has unsupported type '%s'", cursor->getAttrPathStr(), type); } // FIXME: move to libcmd App UnresolvedApp::resolve(ref<Store> evalStore, ref<Store> store) { auto res = unresolved; std::vector<std::shared_ptr<Installable>> installableContext; for (auto & ctxElt : unresolved.context) installableContext.push_back( std::make_shared<InstallableDerivedPath>(store, ctxElt.toDerivedPath())); auto builtContext = Installable::build(evalStore, store, Realise::Outputs, installableContext); res.program = resolveString(*store, unresolved.program, builtContext); if (!store->isInStore(res.program)) throw Error("app program '%s' is not in the Nix store", res.program); return res; } } <|endoftext|>
<commit_before>/*************************************************************************** This is a library for the MS5607-02BA03 barometric pressure sensor These sensors use I2C or SPI to communicate, though only I2C is implemented Written by Paul Guenette Apr 8, 2016 MIT License ***************************************************************************/ #include "Melon_MS5607.h" #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #ifdef __AVR_ATtiny85__ #include "TinyWireM.h" #define Wire TinyWireM #elif defined(TEENSYDUINO) #include <i2c_t3.h> #else #include <Wire.h> #endif Melon_MS5607::Melon_MS5607(void){ // i2c } /* Set the i2c address, reset the chip, and read the calibration values from PROM */ bool Melon_MS5607::begin(uint8_t addr) { Wire.begin(); this->_i2caddr = addr; // Send a software reset, per datasheet this->reset(); // Must delay before getting calibration data, or we read a bunch of ACKs as values delay(20); this->getCalibrationData(_calibData); setDelay(); _lastConversion = 0; startTemperatureConversion(); delayMicroseconds(_osrdelay); startPressureConversion(); delayMicroseconds(_osrdelay); return true; } /* Get the compensated temperature as a floating point value, in C */ int32_t Melon_MS5607::getTemperature(){ return TEMP; // TEMP is a fixed-point int - 2000 = 20.00C } /* Get the compensated pressure as a floating point value, in mbar */ int32_t Melon_MS5607::getPressure(){ return P; } void Melon_MS5607::getPressureBlocking(){ write8(MS5607_CONVERT_D2 + _oversamplingRate); // Start a temperature conversion setDelay(); delayMicroseconds(_osrdelay); D2 = read24(MS5607_ADC_READ); // Read and store the Digital temperature value dT = D2 - ((uint32_t)_calibData.C5*256); // D2 - T_ref TEMP = 2000 + ((dT * _calibData.C6) >> 23); // 20.00C + dT * TEMPSENS or 2000 + dT * C6 / 2^23 write8(MS5607_CONVERT_D1 + _oversamplingRate); delayMicroseconds(_osrdelay); D1 = read24(MS5607_ADC_READ); // Read and store the Digital pressure value OFF = (((int64_t)_calibData.C2) << 17) + ((dT * (int64_t)_calibData.C4) >> 6); // OFF = OFF_t1 + TCO * dT or OFF = C2 * 2^17 + (C4 * dT) / 2^6 SENS = ((int64_t)_calibData.C1 << 16) + ((dT * (int64_t)_calibData.C3) >> 7); // SENS = SENS_t1 + TCS * dT or SENS = C1 * 2^16 + (C3 * dT) / 2^7 int32_t T2 = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Low Temperature if (TEMP < 2000){ T2 = ((dT * dT) >> 31); // T2 = dT^2 / 2^31 OFF2 = 61 * (TEMP - 2000)*(TEMP - 2000) >> 4; // OFF2 = 61 * (TEMP-2000)^2 / 2^4 SENS2 = 2 * (TEMP - 2000)*(TEMP - 2000); // SENS2 = 2 * (TEMP-2000)^2 // Very Low Temperature if (TEMP < -1500) { OFF2 += 15 * (TEMP + 1500)*(TEMP + 1500); // OFF2 = OFF2 + 15 * (TEMP + 1500)^2 SENS2 += 8 * (TEMP + 1500)*(TEMP + 1500); // SENS2 = SENS2 + 8 * (TEMP + 1500)^2 } TEMP = TEMP - T2; OFF = OFF - OFF2; SENS = SENS - SENS2; } P = (((D1 * SENS) >> 21) - OFF) >> 15; // P = (D1 * SENS / 2^21 - OFF) / 2^15 } bool Melon_MS5607::startTemperatureConversion(){ if (micros() - _lastConversion > _osrdelay){ write8(MS5607_CONVERT_D2 + _oversamplingRate); // Start a temperature conversion with the specified oversampling rate setDelay(); _lastConversion = micros(); return true; } return false; } bool Melon_MS5607::startPressureConversion(){ if (micros() - _lastConversion > _osrdelay){ write8(MS5607_CONVERT_D1 + _oversamplingRate); // Start a pressure conversion with the speciifed oversampling rate setDelay(); _lastConversion = micros(); return true; } return false; } void Melon_MS5607::setOversamplingRate(uint8_t rate){ _oversamplingRate = rate; } void Melon_MS5607::setDelay(){ // Set the delay between conversion and ADC read to a value // just above the max conversion time for each oversampling rate switch (_oversamplingRate) { case 0: _osrdelay = 750; break; case 2: _osrdelay = 1250; break; case 4: _osrdelay = 2500; break; case 6: _osrdelay = 4750; break; case 8: _osrdelay = 9250; break; } } /* Write the reset command to the MS5607 */ void Melon_MS5607::reset(){ write8(MS5607_RESET); } /* Prints off the values stored in _calibdata */ void Melon_MS5607::printCalibData(){ Serial.print("C1: "); Serial.println(_calibData.C1); Serial.print("C2: "); Serial.println(_calibData.C2); Serial.print("C3: "); Serial.println(_calibData.C3); Serial.print("C4: "); Serial.println(_calibData.C4); Serial.print("C5: "); Serial.println(_calibData.C5); Serial.print("C6: "); Serial.println(_calibData.C6); } /*************************************************************************** PRIVATE FUNCTIONS ***************************************************************************/ /* Reads the PROM from the MS5607 and stores the values into a struct */ void Melon_MS5607::getCalibrationData(ms5607_calibration &calib){ calib.C1 = read16(MS5607_PROM_READ_C1); calib.C2 = read16(MS5607_PROM_READ_C2); calib.C3 = read16(MS5607_PROM_READ_C3); calib.C4 = read16(MS5607_PROM_READ_C4); calib.C5 = read16(MS5607_PROM_READ_C5); calib.C6 = read16(MS5607_PROM_READ_C6); } /* Read the ADC, store it into D2, and calculate TEMP from calibration data and D1 */ bool Melon_MS5607::readTemperature(){ if (micros() - _lastConversion > _osrdelay){ D2 = read24(MS5607_ADC_READ); // Read and store the Digital temperature value // Compensate for calibration data dT = D2 - ((uint32_t)_calibData.C5 << 8); // D2 - T_ref TEMP = 2000 + ((dT*(int64_t)_calibData.C6) >> 23); // 20.00C + dT * TEMPSENS or 2000 + dT * C6 / 2^23 return true; } else return false; } bool Melon_MS5607::readPressure(){ if (micros() - _lastConversion > _osrdelay){ D1 = read24(MS5607_ADC_READ); // Read and store the Digital pressure value OFF = ((int64_t)_calibData.C2 << 17) + ((dT * _calibData.C4) >> 6); // OFF = OFF_t1 + TCO * dT or OFF = C2 * 2^17 + (C4 * dT) / 2^6 SENS = ((int64_t)_calibData.C1 << 16) + ((dT * _calibData.C3) >> 7); // SENS = SENS_t1 + TCS * dT or SENS = C1 * 2^16 + (C3 * dT) / 2^7 compensateSecondOrder(); P = (((D1 * SENS) >> 21) - OFF) >> 15; // P = (D1 * SENS / 2^21 - OFF) / 2^15 return true; } else return false; } /* Run the 2nd order compensation tree (see datasheet) */ void Melon_MS5607::compensateSecondOrder() { int32_t T2 = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Low Temperature if (TEMP < 2000){ T2 = ((dT * dT) >> 31); // T2 = dT^2 / 2^31 OFF2 = 61 * (TEMP - 2000)*(TEMP - 2000) >> 4; // OFF2 = 61 * (TEMP-2000)^2 / 2^4 SENS2 = 2 * (TEMP - 2000)*(TEMP - 2000); // SENS2 = 2 * (TEMP-2000)^2 // Very Low Temperature if (TEMP < -1500) { OFF2 += 15 * (TEMP + 1500)*(TEMP + 1500); // OFF2 = OFF2 + 15 * (TEMP + 1500)^2 SENS2 += 8 * (TEMP + 1500)*(TEMP + 1500); // SENS2 = SENS2 + 8 * (TEMP + 1500)^2 } TEMP = TEMP - T2; OFF = OFF - OFF2; SENS = SENS - SENS2; } } /*************************************************************************** * i2c Communcation Functions ***************************************************************************/ /* Reads an 8-bit unsigned integer from the MS5607 */ uint8_t Melon_MS5607::read8(uint8_t reg){ uint8_t value; Wire.beginTransmission(_i2caddr); Wire.write(reg); Wire.endTransmission(_i2caddr); Wire.requestFrom(_i2caddr, (uint8_t)1); value = Wire.read(); return value; } /* Reads a 16-bit unsigned integer from the MS5607 */ uint16_t Melon_MS5607::read16(uint8_t reg){ uint16_t value; Wire.beginTransmission(_i2caddr); Wire.write(reg); Wire.endTransmission(); Wire.requestFrom(_i2caddr, (uint8_t)2); value = (Wire.read() << 8) | Wire.read(); // Big-Endian return value; } /* Reads a 24-bit unsigned integer from the MS5607 */ uint32_t Melon_MS5607::read24(uint8_t reg){ uint32_t value; Wire.beginTransmission(_i2caddr); Wire.write(reg); Wire.endTransmission(); Wire.requestFrom(_i2caddr, (uint8_t)3); value = (Wire.read() << 16) | (Wire.read() << 8) | Wire.read(); return value; } /* Write an 8-bit value to the device */ void Melon_MS5607::write8(uint8_t value){ Wire.beginTransmission(_i2caddr); Wire.write(value); Wire.endTransmission(); } <commit_msg>Remove blocking code when starting temp conversions<commit_after>/*************************************************************************** This is a library for the MS5607-02BA03 barometric pressure sensor These sensors use I2C or SPI to communicate, though only I2C is implemented Written by Paul Guenette Apr 8, 2016 MIT License ***************************************************************************/ #include "Melon_MS5607.h" #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #ifdef __AVR_ATtiny85__ #include "TinyWireM.h" #define Wire TinyWireM #elif defined(TEENSYDUINO) #include <i2c_t3.h> #else #include <Wire.h> #endif Melon_MS5607::Melon_MS5607(void){ // i2c } /* Set the i2c address, reset the chip, and read the calibration values from PROM */ bool Melon_MS5607::begin(uint8_t addr) { Wire.begin(); this->_i2caddr = addr; // Send a software reset, per datasheet this->reset(); // Must delay before getting calibration data, or we read a bunch of ACKs as values delay(20); this->getCalibrationData(_calibData); setDelay(); _lastConversion = 0; return true; } /* Get the compensated temperature as a floating point value, in C */ int32_t Melon_MS5607::getTemperature(){ return TEMP; // TEMP is a fixed-point int - 2000 = 20.00C } /* Get the compensated pressure as a floating point value, in mbar */ int32_t Melon_MS5607::getPressure(){ return P; } void Melon_MS5607::getPressureBlocking(){ write8(MS5607_CONVERT_D2 + _oversamplingRate); // Start a temperature conversion setDelay(); delayMicroseconds(_osrdelay); D2 = read24(MS5607_ADC_READ); // Read and store the Digital temperature value dT = D2 - ((uint32_t)_calibData.C5*256); // D2 - T_ref TEMP = 2000 + ((dT * _calibData.C6) >> 23); // 20.00C + dT * TEMPSENS or 2000 + dT * C6 / 2^23 write8(MS5607_CONVERT_D1 + _oversamplingRate); delayMicroseconds(_osrdelay); D1 = read24(MS5607_ADC_READ); // Read and store the Digital pressure value OFF = (((int64_t)_calibData.C2) << 17) + ((dT * (int64_t)_calibData.C4) >> 6); // OFF = OFF_t1 + TCO * dT or OFF = C2 * 2^17 + (C4 * dT) / 2^6 SENS = ((int64_t)_calibData.C1 << 16) + ((dT * (int64_t)_calibData.C3) >> 7); // SENS = SENS_t1 + TCS * dT or SENS = C1 * 2^16 + (C3 * dT) / 2^7 int32_t T2 = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Low Temperature if (TEMP < 2000){ T2 = ((dT * dT) >> 31); // T2 = dT^2 / 2^31 OFF2 = 61 * (TEMP - 2000)*(TEMP - 2000) >> 4; // OFF2 = 61 * (TEMP-2000)^2 / 2^4 SENS2 = 2 * (TEMP - 2000)*(TEMP - 2000); // SENS2 = 2 * (TEMP-2000)^2 // Very Low Temperature if (TEMP < -1500) { OFF2 += 15 * (TEMP + 1500)*(TEMP + 1500); // OFF2 = OFF2 + 15 * (TEMP + 1500)^2 SENS2 += 8 * (TEMP + 1500)*(TEMP + 1500); // SENS2 = SENS2 + 8 * (TEMP + 1500)^2 } TEMP = TEMP - T2; OFF = OFF - OFF2; SENS = SENS - SENS2; } P = (((D1 * SENS) >> 21) - OFF) >> 15; // P = (D1 * SENS / 2^21 - OFF) / 2^15 _lastConversion = micros(); } bool Melon_MS5607::startTemperatureConversion(){ write8(MS5607_CONVERT_D2 + _oversamplingRate); // Start a temperature conversion with the specified oversampling rate _lastConversion = micros(); return true; } bool Melon_MS5607::startPressureConversion(){ write8(MS5607_CONVERT_D1 + _oversamplingRate); // Start a pressure conversion with the speciifed oversampling rate _lastConversion = micros(); return true; } void Melon_MS5607::setOversamplingRate(uint8_t rate){ _oversamplingRate = rate; } void Melon_MS5607::setDelay(){ // Set the delay between conversion and ADC read to a value // just above the max conversion time for each oversampling rate switch (_oversamplingRate) { case 0: _osrdelay = 750; break; case 2: _osrdelay = 1250; break; case 4: _osrdelay = 2500; break; case 6: _osrdelay = 4750; break; case 8: _osrdelay = 9250; break; } } /* Write the reset command to the MS5607 */ void Melon_MS5607::reset(){ write8(MS5607_RESET); } /* Prints off the values stored in _calibdata */ void Melon_MS5607::printCalibData(){ Serial.print("C1: "); Serial.println(_calibData.C1); Serial.print("C2: "); Serial.println(_calibData.C2); Serial.print("C3: "); Serial.println(_calibData.C3); Serial.print("C4: "); Serial.println(_calibData.C4); Serial.print("C5: "); Serial.println(_calibData.C5); Serial.print("C6: "); Serial.println(_calibData.C6); } /*************************************************************************** PRIVATE FUNCTIONS ***************************************************************************/ /* Reads the PROM from the MS5607 and stores the values into a struct */ void Melon_MS5607::getCalibrationData(ms5607_calibration &calib){ calib.C1 = read16(MS5607_PROM_READ_C1); calib.C2 = read16(MS5607_PROM_READ_C2); calib.C3 = read16(MS5607_PROM_READ_C3); calib.C4 = read16(MS5607_PROM_READ_C4); calib.C5 = read16(MS5607_PROM_READ_C5); calib.C6 = read16(MS5607_PROM_READ_C6); } /* Read the ADC, store it into D2, and calculate TEMP from calibration data and D1 */ bool Melon_MS5607::readTemperature(){ if (micros() - _lastConversion > _osrdelay){ D2 = read24(MS5607_ADC_READ); // Read and store the Digital temperature value // Compensate for calibration data dT = D2 - ((uint32_t)_calibData.C5 << 8); // D2 - T_ref TEMP = 2000 + ((dT*(int64_t)_calibData.C6) >> 23); // 20.00C + dT * TEMPSENS or 2000 + dT * C6 / 2^23 return true; } else return false; } bool Melon_MS5607::readPressure(){ if (micros() - _lastConversion > _osrdelay){ D1 = read24(MS5607_ADC_READ); // Read and store the Digital pressure value OFF = ((int64_t)_calibData.C2 << 17) + ((dT * _calibData.C4) >> 6); // OFF = OFF_t1 + TCO * dT or OFF = C2 * 2^17 + (C4 * dT) / 2^6 SENS = ((int64_t)_calibData.C1 << 16) + ((dT * _calibData.C3) >> 7); // SENS = SENS_t1 + TCS * dT or SENS = C1 * 2^16 + (C3 * dT) / 2^7 compensateSecondOrder(); P = (((D1 * SENS) >> 21) - OFF) >> 15; // P = (D1 * SENS / 2^21 - OFF) / 2^15 return true; } else return false; } /* Run the 2nd order compensation tree (see datasheet) */ void Melon_MS5607::compensateSecondOrder() { int32_t T2 = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Low Temperature if (TEMP < 2000){ T2 = ((dT * dT) >> 31); // T2 = dT^2 / 2^31 OFF2 = 61 * (TEMP - 2000)*(TEMP - 2000) >> 4; // OFF2 = 61 * (TEMP-2000)^2 / 2^4 SENS2 = 2 * (TEMP - 2000)*(TEMP - 2000); // SENS2 = 2 * (TEMP-2000)^2 // Very Low Temperature if (TEMP < -1500) { OFF2 += 15 * (TEMP + 1500)*(TEMP + 1500); // OFF2 = OFF2 + 15 * (TEMP + 1500)^2 SENS2 += 8 * (TEMP + 1500)*(TEMP + 1500); // SENS2 = SENS2 + 8 * (TEMP + 1500)^2 } TEMP = TEMP - T2; OFF = OFF - OFF2; SENS = SENS - SENS2; } } /*************************************************************************** * i2c Communcation Functions ***************************************************************************/ /* Reads an 8-bit unsigned integer from the MS5607 */ uint8_t Melon_MS5607::read8(uint8_t reg){ uint8_t value; Wire.beginTransmission(_i2caddr); Wire.write(reg); Wire.endTransmission(_i2caddr); Wire.requestFrom(_i2caddr, (uint8_t)1); value = Wire.read(); return value; } /* Reads a 16-bit unsigned integer from the MS5607 */ uint16_t Melon_MS5607::read16(uint8_t reg){ uint16_t value; Wire.beginTransmission(_i2caddr); Wire.write(reg); Wire.endTransmission(); Wire.requestFrom(_i2caddr, (uint8_t)2); value = (Wire.read() << 8) | Wire.read(); // Big-Endian return value; } /* Reads a 24-bit unsigned integer from the MS5607 */ uint32_t Melon_MS5607::read24(uint8_t reg){ uint32_t value; Wire.beginTransmission(_i2caddr); Wire.write(reg); Wire.endTransmission(); Wire.requestFrom(_i2caddr, (uint8_t)3); value = (Wire.read() << 16) | (Wire.read() << 8) | Wire.read(); return value; } /* Write an 8-bit value to the device */ void Melon_MS5607::write8(uint8_t value){ Wire.beginTransmission(_i2caddr); Wire.write(value); Wire.endTransmission(); } <|endoftext|>
<commit_before> //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- #include "Effekseer.InstanceContainer.h" #include "Effekseer.Instance.h" #include "Effekseer.InstanceGlobal.h" #include "Effekseer.InstanceGroup.h" #include "Effekseer.ManagerImplemented.h" #include "Effekseer.Effect.h" #include "Effekseer.EffectNode.h" #include "Renderer/Effekseer.SpriteRenderer.h" //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- namespace Effekseer { //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceContainer::InstanceContainer(ManagerImplemented* pManager, EffectNode* pEffectNode, InstanceGlobal* pGlobal) : m_pManager(pManager) , m_pEffectNode((EffectNodeImplemented*)pEffectNode) , m_pGlobal(pGlobal) , m_headGroups(nullptr) , m_tailGroups(nullptr) { auto en = (EffectNodeImplemented*)pEffectNode; if (en->RenderingPriority >= 0) { pGlobal->RenderedInstanceContainers[en->RenderingPriority] = this; } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceContainer::~InstanceContainer() { RemoveForcibly(false); assert(m_headGroups == nullptr); assert(m_tailGroups == nullptr); for (auto child : m_Children) { m_pManager->ReleaseInstanceContainer(child); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::AddChild(InstanceContainer* pContainter) { m_Children.push_back(pContainter); } InstanceContainer* InstanceContainer::GetChild(int index) { assert(index < static_cast<int32_t>(m_Children.size())); auto it = m_Children.begin(); for (int i = 0; i < index; i++) { it++; } return *it; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::RemoveInvalidGroups() { /* 最後に存在する有効なグループ */ InstanceGroup* tailGroup = nullptr; for (InstanceGroup* group = m_headGroups; group != nullptr;) { if (!group->IsReferencedFromInstance && group->GetInstanceCount() == 0) { InstanceGroup* next = group->NextUsedByContainer; m_pManager->ReleaseGroup(group); if (m_headGroups == group) { m_headGroups = next; } group = next; if (tailGroup != nullptr) { tailGroup->NextUsedByContainer = next; } } else { tailGroup = group; group = group->NextUsedByContainer; } } m_tailGroups = tailGroup; assert(m_tailGroups == nullptr || m_tailGroups->NextUsedByContainer == nullptr); } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceGroup* InstanceContainer::CreateInstanceGroup() { InstanceGroup* group = m_pManager->CreateInstanceGroup(m_pEffectNode, this, m_pGlobal); if (group == nullptr) { return nullptr; } if (m_tailGroups != nullptr) { m_tailGroups->NextUsedByContainer = group; m_tailGroups = group; } else { assert(m_headGroups == nullptr); m_headGroups = group; m_tailGroups = group; } m_pEffectNode->InitializeRenderedInstanceGroup(*group, m_pManager); return group; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceGroup* InstanceContainer::GetFirstGroup() const { return m_headGroups; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::Update(bool recursive, bool shown) { // 更新 for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->Update(shown); } // 破棄 RemoveInvalidGroups(); if (recursive) { for (auto child : m_Children) { child->Update(recursive, shown); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::SetBaseMatrix(bool recursive, const SIMD::Mat43f& mat) { if (m_pEffectNode->GetType() != EFFECT_NODE_TYPE_ROOT) { for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->SetBaseMatrix(mat); } } if (recursive) { for (auto child : m_Children) { child->SetBaseMatrix(recursive, mat); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::RemoveForcibly(bool recursive) { KillAllInstances(false); for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->RemoveForcibly(); } RemoveInvalidGroups(); if (recursive) { for (auto child : m_Children) { child->RemoveForcibly(recursive); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::Draw(bool recursive) { if (m_pEffectNode->GetType() != EFFECT_NODE_TYPE_ROOT && m_pEffectNode->GetType() != EFFECT_NODE_TYPE_NONE) { /* 個数計測 */ int32_t count = 0; { for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { for (auto instance : group->m_instances) { if (instance->m_State == INSTANCE_STATE_ACTIVE) { count++; } } } } if (count > 0) { /* 描画 */ m_pEffectNode->BeginRendering(count, m_pManager); for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { m_pEffectNode->BeginRenderingGroup(group, m_pManager); if (m_pEffectNode->RenderingOrder == RenderingOrder_FirstCreatedInstanceIsFirst) { auto it = group->m_instances.begin(); while (it != group->m_instances.end()) { if ((*it)->m_State == INSTANCE_STATE_ACTIVE) { auto it_temp = it; it_temp++; if (it_temp != group->m_instances.end()) { (*it)->Draw((*it_temp)); } else { (*it)->Draw(nullptr); } } it++; } } else { auto it = group->m_instances.rbegin(); while (it != group->m_instances.rend()) { if ((*it)->m_State == INSTANCE_STATE_ACTIVE) { auto it_temp = it; it_temp++; if (it_temp != group->m_instances.rend()) { (*it)->Draw((*it_temp)); } else { (*it)->Draw(nullptr); } } it++; } } m_pEffectNode->EndRenderingGroup(group, m_pManager); } m_pEffectNode->EndRendering(m_pManager); } } if (recursive) { for (auto child : m_Children) { child->Draw(recursive); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::KillAllInstances(bool recursive) { for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->KillAllInstances(); } if (recursive) { for (auto child : m_Children) { child->KillAllInstances(recursive); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceGlobal* InstanceContainer::GetRootInstance() { return m_pGlobal; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- } // namespace Effekseer //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- <commit_msg>Fix a bug where invisible node allocates a memory<commit_after> //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- #include "Effekseer.InstanceContainer.h" #include "Effekseer.Instance.h" #include "Effekseer.InstanceGlobal.h" #include "Effekseer.InstanceGroup.h" #include "Effekseer.ManagerImplemented.h" #include "Effekseer.Effect.h" #include "Effekseer.EffectNode.h" #include "Renderer/Effekseer.SpriteRenderer.h" //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- namespace Effekseer { //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceContainer::InstanceContainer(ManagerImplemented* pManager, EffectNode* pEffectNode, InstanceGlobal* pGlobal) : m_pManager(pManager) , m_pEffectNode((EffectNodeImplemented*)pEffectNode) , m_pGlobal(pGlobal) , m_headGroups(nullptr) , m_tailGroups(nullptr) { auto en = (EffectNodeImplemented*)pEffectNode; if (en->RenderingPriority >= 0) { pGlobal->RenderedInstanceContainers[en->RenderingPriority] = this; } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceContainer::~InstanceContainer() { RemoveForcibly(false); assert(m_headGroups == nullptr); assert(m_tailGroups == nullptr); for (auto child : m_Children) { m_pManager->ReleaseInstanceContainer(child); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::AddChild(InstanceContainer* pContainter) { m_Children.push_back(pContainter); } InstanceContainer* InstanceContainer::GetChild(int index) { assert(index < static_cast<int32_t>(m_Children.size())); auto it = m_Children.begin(); for (int i = 0; i < index; i++) { it++; } return *it; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::RemoveInvalidGroups() { /* 最後に存在する有効なグループ */ InstanceGroup* tailGroup = nullptr; for (InstanceGroup* group = m_headGroups; group != nullptr;) { if (!group->IsReferencedFromInstance && group->GetInstanceCount() == 0) { InstanceGroup* next = group->NextUsedByContainer; m_pManager->ReleaseGroup(group); if (m_headGroups == group) { m_headGroups = next; } group = next; if (tailGroup != nullptr) { tailGroup->NextUsedByContainer = next; } } else { tailGroup = group; group = group->NextUsedByContainer; } } m_tailGroups = tailGroup; assert(m_tailGroups == nullptr || m_tailGroups->NextUsedByContainer == nullptr); } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceGroup* InstanceContainer::CreateInstanceGroup() { InstanceGroup* group = m_pManager->CreateInstanceGroup(m_pEffectNode, this, m_pGlobal); if (group == nullptr) { return nullptr; } if (m_tailGroups != nullptr) { m_tailGroups->NextUsedByContainer = group; m_tailGroups = group; } else { assert(m_headGroups == nullptr); m_headGroups = group; m_tailGroups = group; } m_pEffectNode->InitializeRenderedInstanceGroup(*group, m_pManager); return group; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceGroup* InstanceContainer::GetFirstGroup() const { return m_headGroups; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::Update(bool recursive, bool shown) { // 更新 for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->Update(shown); } // 破棄 RemoveInvalidGroups(); if (recursive) { for (auto child : m_Children) { child->Update(recursive, shown); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::SetBaseMatrix(bool recursive, const SIMD::Mat43f& mat) { if (m_pEffectNode->GetType() != EFFECT_NODE_TYPE_ROOT) { for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->SetBaseMatrix(mat); } } if (recursive) { for (auto child : m_Children) { child->SetBaseMatrix(recursive, mat); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::RemoveForcibly(bool recursive) { KillAllInstances(false); for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->RemoveForcibly(); } RemoveInvalidGroups(); if (recursive) { for (auto child : m_Children) { child->RemoveForcibly(recursive); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::Draw(bool recursive) { if (m_pEffectNode->GetType() != EFFECT_NODE_TYPE_ROOT && m_pEffectNode->GetType() != EFFECT_NODE_TYPE_NONE) { /* 個数計測 */ int32_t count = 0; { for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { for (auto instance : group->m_instances) { if (instance->m_State == INSTANCE_STATE_ACTIVE) { count++; } } } } if (count > 0 && m_pEffectNode->IsRendered) { m_pEffectNode->BeginRendering(count, m_pManager); for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { m_pEffectNode->BeginRenderingGroup(group, m_pManager); if (m_pEffectNode->RenderingOrder == RenderingOrder_FirstCreatedInstanceIsFirst) { auto it = group->m_instances.begin(); while (it != group->m_instances.end()) { if ((*it)->m_State == INSTANCE_STATE_ACTIVE) { auto it_temp = it; it_temp++; if (it_temp != group->m_instances.end()) { (*it)->Draw((*it_temp)); } else { (*it)->Draw(nullptr); } } it++; } } else { auto it = group->m_instances.rbegin(); while (it != group->m_instances.rend()) { if ((*it)->m_State == INSTANCE_STATE_ACTIVE) { auto it_temp = it; it_temp++; if (it_temp != group->m_instances.rend()) { (*it)->Draw((*it_temp)); } else { (*it)->Draw(nullptr); } } it++; } } m_pEffectNode->EndRenderingGroup(group, m_pManager); } m_pEffectNode->EndRendering(m_pManager); } } if (recursive) { for (auto child : m_Children) { child->Draw(recursive); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- void InstanceContainer::KillAllInstances(bool recursive) { for (InstanceGroup* group = m_headGroups; group != nullptr; group = group->NextUsedByContainer) { group->KillAllInstances(); } if (recursive) { for (auto child : m_Children) { child->KillAllInstances(recursive); } } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- InstanceGlobal* InstanceContainer::GetRootInstance() { return m_pGlobal; } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- } // namespace Effekseer //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- <|endoftext|>
<commit_before>#ifndef __FACTOR_MASTER_H__ #define __FACTOR_MASTER_H__ #ifndef WINCE #include <errno.h> #endif #ifdef FACTOR_DEBUG #include <assert.h> #endif /* C headers */ #include <fcntl.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* C++ headers */ #include <vector> #if __GNUC__ == 4 #include <tr1/unordered_map> #define unordered_map std::tr1::unordered_map #elif __GNUC__ == 3 #include <boost/unordered_map.hpp> #define unordered_map boost::unordered_map #else #error Factor requires GCC 3.x or later #endif /* Factor headers */ #include "layouts.hpp" #include "platform.hpp" #include "primitives.hpp" #include "stacks.hpp" #include "segments.hpp" #include "contexts.hpp" #include "run.hpp" #include "profiler.hpp" #include "errors.hpp" #include "bignumint.hpp" #include "bignum.hpp" #include "code_block.hpp" #include "data_heap.hpp" #include "write_barrier.hpp" #include "data_gc.hpp" #include "local_roots.hpp" #include "generic_arrays.hpp" #include "debug.hpp" #include "arrays.hpp" #include "strings.hpp" #include "booleans.hpp" #include "byte_arrays.hpp" #include "tuples.hpp" #include "words.hpp" #include "math.hpp" #include "float_bits.hpp" #include "io.hpp" #include "code_gc.hpp" #include "code_heap.hpp" #include "image.hpp" #include "callstack.hpp" #include "alien.hpp" #include "vm.hpp" #include "tagged.hpp" #include "inlineimpls.hpp" #include "jit.hpp" #include "quotations.hpp" #include "dispatch.hpp" #include "inline_cache.hpp" #include "factor.hpp" #include "utilities.hpp" #endif /* __FACTOR_MASTER_H__ */ <commit_msg>added threadsafe defines. Dunno if they do much<commit_after>#ifndef __FACTOR_MASTER_H__ #define __FACTOR_MASTER_H__ #define _THREAD_SAFE #define _REENTRANT #ifndef WINCE #include <errno.h> #endif #ifdef FACTOR_DEBUG #include <assert.h> #endif /* C headers */ #include <fcntl.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <setjmp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /* C++ headers */ #include <vector> #if __GNUC__ == 4 #include <tr1/unordered_map> #define unordered_map std::tr1::unordered_map #elif __GNUC__ == 3 #include <boost/unordered_map.hpp> #define unordered_map boost::unordered_map #else #error Factor requires GCC 3.x or later #endif /* Factor headers */ #include "layouts.hpp" #include "platform.hpp" #include "primitives.hpp" #include "stacks.hpp" #include "segments.hpp" #include "contexts.hpp" #include "run.hpp" #include "profiler.hpp" #include "errors.hpp" #include "bignumint.hpp" #include "bignum.hpp" #include "code_block.hpp" #include "data_heap.hpp" #include "write_barrier.hpp" #include "data_gc.hpp" #include "local_roots.hpp" #include "generic_arrays.hpp" #include "debug.hpp" #include "arrays.hpp" #include "strings.hpp" #include "booleans.hpp" #include "byte_arrays.hpp" #include "tuples.hpp" #include "words.hpp" #include "math.hpp" #include "float_bits.hpp" #include "io.hpp" #include "code_gc.hpp" #include "code_heap.hpp" #include "image.hpp" #include "callstack.hpp" #include "alien.hpp" #include "vm.hpp" #include "tagged.hpp" #include "inlineimpls.hpp" #include "jit.hpp" #include "quotations.hpp" #include "dispatch.hpp" #include "inline_cache.hpp" #include "factor.hpp" #include "utilities.hpp" #endif /* __FACTOR_MASTER_H__ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "sim/mem_system.hh" #include "mem/port_proxy.hh" #include "mem/dtu/tlb.hh" #include "params/MemSystem.hh" MemSystem::MemSystem(Params *p) : System(p), coreId(p->core_id), memFile(p->mem_file), memFileNum(p->mem_file_num) { } MemSystem::~MemSystem() { } void MemSystem::initState() { System::initState(); if(!memFile.empty() && memFileNum > 0) { FILE *f = fopen(memFile.c_str(), "r"); if(!f) panic("Unable to open '%s' for reading", memFile.c_str()); fseek(f, 0L, SEEK_END); size_t sz = ftell(f); fseek(f, 0L, SEEK_SET); const size_t BUF_SIZE = 1024 * 1024; auto data = new uint8_t[BUF_SIZE]; size_t rem = sz, off = 0; while (rem > 0) { size_t amount = std::min(rem, BUF_SIZE); if(fread(data, 1, amount, f) != amount) panic("Unable to read '%s'", memFile.c_str()); for(size_t i = 0; i < memFileNum; ++i) physProxy.writeBlob(i * sz + off, data, amount); off += amount; rem -= amount; } delete[] data; fclose(f); } } MemSystem * MemSystemParams::create() { return new MemSystem(this); } <commit_msg>DTU: improved error handling for FS image loading.<commit_after>/* * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "sim/mem_system.hh" #include "mem/port_proxy.hh" #include "mem/dtu/tlb.hh" #include "params/MemSystem.hh" MemSystem::MemSystem(Params *p) : System(p), coreId(p->core_id), memFile(p->mem_file), memFileNum(p->mem_file_num) { } MemSystem::~MemSystem() { } void MemSystem::initState() { System::initState(); if(!memFile.empty() && memFileNum > 0) { FILE *f = fopen(memFile.c_str(), "r"); if(!f) panic("Unable to open '%s' for reading", memFile.c_str()); fseek(f, 0L, SEEK_END); size_t sz = ftell(f); fseek(f, 0L, SEEK_SET); const size_t BUF_SIZE = 1024 * 1024; auto data = new uint8_t[BUF_SIZE]; size_t rem = sz, off = 0; while (rem > 0) { size_t amount = std::min(rem, BUF_SIZE); size_t res; if((res = fread(data, 1, amount, f)) != amount) panic("Unable to read '%s': %lu (expected %lu)", memFile.c_str(), res, amount); for(size_t i = 0; i < memFileNum; ++i) physProxy.writeBlob(i * sz + off, data, amount); off += amount; rem -= amount; } delete[] data; fclose(f); } } MemSystem * MemSystemParams::create() { return new MemSystem(this); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/rtl.h" #include <algorithm> #include "base/file_path.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/sys_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" namespace { base::i18n::TextDirection GetTextDirection(const char* locale_name) { return base::i18n::GetTextDirectionForLocale(locale_name); } } class RTLTest : public PlatformTest { }; TEST_F(RTLTest, GetFirstStrongCharacterDirection) { // Test pure LTR string. std::wstring string(L"foo bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type L. string.assign(L"foo \x05d0 bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type R. string.assign(L"\x05d0 foo bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string which starts with a character with weak directionality // and in which the first character with strong directionality is a character // with type L. string.assign(L"!foo \x05d0 bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string which starts with a character with weak directionality // and in which the first character with strong directionality is a character // with type R. string.assign(L",\x05d0 foo bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type LRE. string.assign(L"\x202a \x05d0 foo bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type LRO. string.assign(L"\x202d \x05d0 foo bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type RLE. string.assign(L"\x202b foo \x05d0 bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type RLO. string.assign(L"\x202e foo \x05d0 bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type AL. string.assign(L"\x0622 foo \x05d0 bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test a string without strong directionality characters. string.assign(L",!.{}"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test empty string. string.assign(L""); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test characters in non-BMP (e.g. Phoenician letters. Please refer to // http://demo.icu-project.org/icu-bin/ubrowse?scr=151&b=10910 for more // information). #if defined(WCHAR_T_IS_UTF32) string.assign(L" ! \x10910" L"abc 123"); #elif defined(WCHAR_T_IS_UTF16) string.assign(L" ! \xd802\xdd10" L"abc 123"); #else #error wchar_t should be either UTF-16 or UTF-32 #endif EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); #if defined(WCHAR_T_IS_UTF32) string.assign(L" ! \x10401" L"abc 123"); #elif defined(WCHAR_T_IS_UTF16) string.assign(L" ! \xd801\xdc01" L"abc 123"); #else #error wchar_t should be either UTF-16 or UTF-32 #endif EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); } TEST_F(RTLTest, WrapPathWithLTRFormatting) { const wchar_t* kTestData[] = { // Test common path, such as "c:\foo\bar". L"c:/foo/bar", // Test path with file name, such as "c:\foo\bar\test.jpg". L"c:/foo/bar/test.jpg", // Test path ending with punctuation, such as "c:\(foo)\bar.". L"c:/(foo)/bar.", // Test path ending with separator, such as "c:\foo\bar\". L"c:/foo/bar/", // Test path with RTL character. L"c:/\x05d0", // Test path with 2 level RTL directory names. L"c:/\x05d0/\x0622", // Test path with mixed RTL/LTR directory names and ending with punctuation. L"c:/\x05d0/\x0622/(foo)/b.a.r.", // Test path without driver name, such as "/foo/bar/test/jpg". L"/foo/bar/test.jpg", // Test path start with current directory, such as "./foo". L"./foo", // Test path start with parent directory, such as "../foo/bar.jpg". L"../foo/bar.jpg", // Test absolute path, such as "//foo/bar.jpg". L"//foo/bar.jpg", // Test path with mixed RTL/LTR directory names. L"c:/foo/\x05d0/\x0622/\x05d1.jpg", // Test empty path. L"" }; for (unsigned int i = 0; i < arraysize(kTestData); ++i) { FilePath path; #if defined(OS_WIN) std::wstring win_path(kTestData[i]); std::replace(win_path.begin(), win_path.end(), '/', '\\'); path = FilePath(win_path); #else path = FilePath(base::SysWideToNativeMB(kTestData[i])); #endif string16 localized_file_path_string; base::i18n::WrapPathWithLTRFormatting(path, &localized_file_path_string); std::wstring wrapped_expected = std::wstring(L"\x202a") + win_path + L"\x202c"; std::wstring wrapped_actual = UTF16ToWide(localized_file_path_string); EXPECT_EQ(wrapped_expected, wrapped_actual); } } typedef struct { std::wstring raw_filename; std::wstring display_string; } StringAndLTRString; TEST_F(RTLTest, GetDisplayStringInLTRDirectionality) { const StringAndLTRString test_data[] = { { L"test", L"\x202atest\x202c" }, { L"test.html", L"\x202atest.html\x202c" }, { L"\x05d0\x05d1\x05d2", L"\x202a\x05d0\x05d1\x05d2\x202c" }, { L"\x05d0\x05d1\x05d2.txt", L"\x202a\x05d0\x05d1\x05d2.txt\x202c" }, { L"\x05d0"L"abc", L"\x202a\x05d0"L"abc\x202c" }, { L"\x05d0"L"abc.txt", L"\x202a\x05d0"L"abc.txt\x202c" }, { L"abc\x05d0\x05d1", L"\x202a"L"abc\x05d0\x05d1\x202c" }, { L"abc\x05d0\x05d1.jpg", L"\x202a"L"abc\x05d0\x05d1.jpg\x202c" }, }; for (unsigned int i = 0; i < arraysize(test_data); ++i) { string16 input = WideToUTF16(test_data[i].raw_filename); string16 expected = base::i18n::GetDisplayStringInLTRDirectionality(input); if (base::i18n::IsRTL()) EXPECT_EQ(expected, WideToUTF16(test_data[i].display_string)); else EXPECT_EQ(expected, input); } } TEST_F(RTLTest, GetTextDirection) { EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("ar")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("ar_EG")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("he")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("he_IL")); // iw is an obsolete code for Hebrew. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("iw")); // Although we're not yet localized to Farsi and Urdu, we // do have the text layout direction information for them. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("fa")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("ur")); #if 0 // Enable these when we include the minimal locale data for Azerbaijani // written in Arabic and Dhivehi. At the moment, our copy of // ICU data does not have entries for them. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("az_Arab")); // Dhivehi that uses Thaana script. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("dv")); #endif EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("en")); // Chinese in China with '-'. EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("zh-CN")); // Filipino : 3-letter code EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("fil")); // Russian EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("ru")); // Japanese that uses multiple scripts EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("ja")); } <commit_msg>Retry on fix. I am a bad programmer.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/rtl.h" #include <algorithm> #include "base/file_path.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/sys_string_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" namespace { base::i18n::TextDirection GetTextDirection(const char* locale_name) { return base::i18n::GetTextDirectionForLocale(locale_name); } } class RTLTest : public PlatformTest { }; TEST_F(RTLTest, GetFirstStrongCharacterDirection) { // Test pure LTR string. std::wstring string(L"foo bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type L. string.assign(L"foo \x05d0 bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type R. string.assign(L"\x05d0 foo bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string which starts with a character with weak directionality // and in which the first character with strong directionality is a character // with type L. string.assign(L"!foo \x05d0 bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string which starts with a character with weak directionality // and in which the first character with strong directionality is a character // with type R. string.assign(L",\x05d0 foo bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type LRE. string.assign(L"\x202a \x05d0 foo bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type LRO. string.assign(L"\x202d \x05d0 foo bar"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type RLE. string.assign(L"\x202b foo \x05d0 bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type RLO. string.assign(L"\x202e foo \x05d0 bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test bidi string in which the first character with strong directionality // is a character with type AL. string.assign(L"\x0622 foo \x05d0 bar"); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test a string without strong directionality characters. string.assign(L",!.{}"); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test empty string. string.assign(L""); EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); // Test characters in non-BMP (e.g. Phoenician letters. Please refer to // http://demo.icu-project.org/icu-bin/ubrowse?scr=151&b=10910 for more // information). #if defined(WCHAR_T_IS_UTF32) string.assign(L" ! \x10910" L"abc 123"); #elif defined(WCHAR_T_IS_UTF16) string.assign(L" ! \xd802\xdd10" L"abc 123"); #else #error wchar_t should be either UTF-16 or UTF-32 #endif EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, base::i18n::GetFirstStrongCharacterDirection(string)); #if defined(WCHAR_T_IS_UTF32) string.assign(L" ! \x10401" L"abc 123"); #elif defined(WCHAR_T_IS_UTF16) string.assign(L" ! \xd801\xdc01" L"abc 123"); #else #error wchar_t should be either UTF-16 or UTF-32 #endif EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, base::i18n::GetFirstStrongCharacterDirection(string)); } TEST_F(RTLTest, WrapPathWithLTRFormatting) { const wchar_t* kTestData[] = { // Test common path, such as "c:\foo\bar". L"c:/foo/bar", // Test path with file name, such as "c:\foo\bar\test.jpg". L"c:/foo/bar/test.jpg", // Test path ending with punctuation, such as "c:\(foo)\bar.". L"c:/(foo)/bar.", // Test path ending with separator, such as "c:\foo\bar\". L"c:/foo/bar/", // Test path with RTL character. L"c:/\x05d0", // Test path with 2 level RTL directory names. L"c:/\x05d0/\x0622", // Test path with mixed RTL/LTR directory names and ending with punctuation. L"c:/\x05d0/\x0622/(foo)/b.a.r.", // Test path without driver name, such as "/foo/bar/test/jpg". L"/foo/bar/test.jpg", // Test path start with current directory, such as "./foo". L"./foo", // Test path start with parent directory, such as "../foo/bar.jpg". L"../foo/bar.jpg", // Test absolute path, such as "//foo/bar.jpg". L"//foo/bar.jpg", // Test path with mixed RTL/LTR directory names. L"c:/foo/\x05d0/\x0622/\x05d1.jpg", // Test empty path. L"" }; for (unsigned int i = 0; i < arraysize(kTestData); ++i) { FilePath path; #if defined(OS_WIN) std::wstring win_path(kTestData[i]); std::replace(win_path.begin(), win_path.end(), '/', '\\'); path = FilePath(win_path); std::wstring wrapped_expected = std::wstring(L"\x202a") + win_path + L"\x202c"; #else path = FilePath(base::SysWideToNativeMB(kTestData[i])); std::wstring wrapped_expected = std::wstring(L"\x202a") + kTestData[i] + L"\x202c"; #endif string16 localized_file_path_string; base::i18n::WrapPathWithLTRFormatting(path, &localized_file_path_string); std::wstring wrapped_actual = UTF16ToWide(localized_file_path_string); EXPECT_EQ(wrapped_expected, wrapped_actual); } } typedef struct { std::wstring raw_filename; std::wstring display_string; } StringAndLTRString; TEST_F(RTLTest, GetDisplayStringInLTRDirectionality) { const StringAndLTRString test_data[] = { { L"test", L"\x202atest\x202c" }, { L"test.html", L"\x202atest.html\x202c" }, { L"\x05d0\x05d1\x05d2", L"\x202a\x05d0\x05d1\x05d2\x202c" }, { L"\x05d0\x05d1\x05d2.txt", L"\x202a\x05d0\x05d1\x05d2.txt\x202c" }, { L"\x05d0"L"abc", L"\x202a\x05d0"L"abc\x202c" }, { L"\x05d0"L"abc.txt", L"\x202a\x05d0"L"abc.txt\x202c" }, { L"abc\x05d0\x05d1", L"\x202a"L"abc\x05d0\x05d1\x202c" }, { L"abc\x05d0\x05d1.jpg", L"\x202a"L"abc\x05d0\x05d1.jpg\x202c" }, }; for (unsigned int i = 0; i < arraysize(test_data); ++i) { string16 input = WideToUTF16(test_data[i].raw_filename); string16 expected = base::i18n::GetDisplayStringInLTRDirectionality(input); if (base::i18n::IsRTL()) EXPECT_EQ(expected, WideToUTF16(test_data[i].display_string)); else EXPECT_EQ(expected, input); } } TEST_F(RTLTest, GetTextDirection) { EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("ar")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("ar_EG")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("he")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("he_IL")); // iw is an obsolete code for Hebrew. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("iw")); // Although we're not yet localized to Farsi and Urdu, we // do have the text layout direction information for them. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("fa")); EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("ur")); #if 0 // Enable these when we include the minimal locale data for Azerbaijani // written in Arabic and Dhivehi. At the moment, our copy of // ICU data does not have entries for them. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("az_Arab")); // Dhivehi that uses Thaana script. EXPECT_EQ(base::i18n::RIGHT_TO_LEFT, GetTextDirection("dv")); #endif EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("en")); // Chinese in China with '-'. EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("zh-CN")); // Filipino : 3-letter code EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("fil")); // Russian EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("ru")); // Japanese that uses multiple scripts EXPECT_EQ(base::i18n::LEFT_TO_RIGHT, GetTextDirection("ja")); } <|endoftext|>
<commit_before>//===-- sanitizer_stoptheworld_mac.cc -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // See sanitizer_stoptheworld.h for details. // //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC && (defined(__x86_64__) || defined(__aarch64__) || \ defined(__i386)) #include <mach/mach.h> #include "sanitizer_stoptheworld.h" namespace __sanitizer { typedef struct { tid_t tid; thread_t thread; } SuspendedThreadInfo; class SuspendedThreadsListMac : public SuspendedThreadsList { public: SuspendedThreadsListMac() : threads_(1024) {} tid_t GetThreadID(uptr index) const; thread_t GetThread(uptr index) const; uptr ThreadCount() const; bool ContainsThread(thread_t thread) const; void Append(thread_t thread); PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer, uptr *sp) const; uptr RegisterCount() const; private: InternalMmapVector<SuspendedThreadInfo> threads_; }; void StopTheWorld(StopTheWorldCallback callback, void *argument) { CHECK(0 && "unimplemented"); } tid_t SuspendedThreadsListMac::GetThreadID(uptr index) const { CHECK_LT(index, threads_.size()); return threads_[index].tid; } thread_t SuspendedThreadsListMac::GetThread(uptr index) const { CHECK_LT(index, threads_.size()); return threads_[index].thread; } uptr SuspendedThreadsListMac::ThreadCount() const { return threads_.size(); } bool SuspendedThreadsListMac::ContainsThread(thread_t thread) const { for (uptr i = 0; i < threads_.size(); i++) { if (threads_[i].thread == thread) return true; } return false; } void SuspendedThreadsListMac::Append(thread_t thread) { thread_identifier_info_data_t info; mach_msg_type_number_t info_count = THREAD_IDENTIFIER_INFO_COUNT; kern_return_t err = thread_info(thread, THREAD_IDENTIFIER_INFO, (thread_info_t)&info, &info_count); if (err != KERN_SUCCESS) { VReport(1, "Error - unable to get thread ident for a thread\n"); return; } threads_.push_back({info.thread_id, thread}); } PtraceRegistersStatus SuspendedThreadsListMac::GetRegistersAndSP( uptr index, uptr *buffer, uptr *sp) const { CHECK(0 && "unimplemented"); return REGISTERS_UNAVAILABLE_FATAL; } uptr SuspendedThreadsListMac::RegisterCount() const { return MACHINE_THREAD_STATE_COUNT; } } // namespace __sanitizer #endif // SANITIZER_MAC && (defined(__x86_64__) || defined(__aarch64__)) || // defined(__i386)) <commit_msg>Implement function to get registers from suspended thread on darwin<commit_after>//===-- sanitizer_stoptheworld_mac.cc -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // See sanitizer_stoptheworld.h for details. // //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC && (defined(__x86_64__) || defined(__aarch64__) || \ defined(__i386)) #include <mach/mach.h> #include "sanitizer_stoptheworld.h" namespace __sanitizer { typedef struct { tid_t tid; thread_t thread; } SuspendedThreadInfo; class SuspendedThreadsListMac : public SuspendedThreadsList { public: SuspendedThreadsListMac() : threads_(1024) {} tid_t GetThreadID(uptr index) const; thread_t GetThread(uptr index) const; uptr ThreadCount() const; bool ContainsThread(thread_t thread) const; void Append(thread_t thread); PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer, uptr *sp) const; uptr RegisterCount() const; private: InternalMmapVector<SuspendedThreadInfo> threads_; }; void StopTheWorld(StopTheWorldCallback callback, void *argument) { CHECK(0 && "unimplemented"); } #if defined(__x86_64__) typedef x86_thread_state64_t regs_struct; #define SP_REG __rsp #elif defined(__aarch64__) typedef arm_thread_state64_t regs_struct; # if __DARWIN_UNIX03 # define SP_REG __sp # else # define SP_REG sp # endif #elif defined(__i386) typedef x86_thread_state32_t regs_struct; #define SP_REG __esp #else #error "Unsupported architecture" #endif tid_t SuspendedThreadsListMac::GetThreadID(uptr index) const { CHECK_LT(index, threads_.size()); return threads_[index].tid; } thread_t SuspendedThreadsListMac::GetThread(uptr index) const { CHECK_LT(index, threads_.size()); return threads_[index].thread; } uptr SuspendedThreadsListMac::ThreadCount() const { return threads_.size(); } bool SuspendedThreadsListMac::ContainsThread(thread_t thread) const { for (uptr i = 0; i < threads_.size(); i++) { if (threads_[i].thread == thread) return true; } return false; } void SuspendedThreadsListMac::Append(thread_t thread) { thread_identifier_info_data_t info; mach_msg_type_number_t info_count = THREAD_IDENTIFIER_INFO_COUNT; kern_return_t err = thread_info(thread, THREAD_IDENTIFIER_INFO, (thread_info_t)&info, &info_count); if (err != KERN_SUCCESS) { VReport(1, "Error - unable to get thread ident for a thread\n"); return; } threads_.push_back({info.thread_id, thread}); } PtraceRegistersStatus SuspendedThreadsListMac::GetRegistersAndSP( uptr index, uptr *buffer, uptr *sp) const { thread_t thread = GetThread(index); regs_struct regs; int err; mach_msg_type_number_t reg_count = MACHINE_THREAD_STATE_COUNT; err = thread_get_state(thread, MACHINE_THREAD_STATE, (thread_state_t)&regs, &reg_count); if (err != KERN_SUCCESS) { VReport(1, "Error - unable to get registers for a thread\n"); // KERN_INVALID_ARGUMENT indicates that either the flavor is invalid, // or the thread does not exist. The other possible error case, // MIG_ARRAY_TOO_LARGE, means that the state is too large, but it's // still safe to proceed. return err == KERN_INVALID_ARGUMENT ? REGISTERS_UNAVAILABLE_FATAL : REGISTERS_UNAVAILABLE; } internal_memcpy(buffer, &regs, sizeof(regs)); *sp = regs.SP_REG; return REGISTERS_AVAILABLE; } uptr SuspendedThreadsListMac::RegisterCount() const { return MACHINE_THREAD_STATE_COUNT; } } // namespace __sanitizer #endif // SANITIZER_MAC && (defined(__x86_64__) || defined(__aarch64__)) || // defined(__i386)) <|endoftext|>